context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using UnityEngine;
using System;
using System.Linq;
using System.Collections.Generic;
namespace NodeEditorFramework
{
public abstract class Node : ScriptableObject
{
public Rect rect = new Rect ();
internal Vector2 contentOffset = Vector2.zero;
[SerializeField]
public List<NodeKnob> nodeKnobs = new List<NodeKnob> ();
// Calculation graph
[SerializeField]
public List<NodeInput> Inputs = new List<NodeInput>();
[SerializeField]
public List<NodeOutput> Outputs = new List<NodeOutput>();
[HideInInspector]
[NonSerialized]
internal bool calculated = true;
#region General
/// <summary>
/// Init the Node Base after the Node has been created. This includes adding to canvas, and to calculate for the first time
/// </summary>
protected internal void InitBase ()
{
NodeEditor.RecalculateFrom (this);
if (!NodeEditor.curNodeCanvas.nodes.Contains (this))
NodeEditor.curNodeCanvas.nodes.Add (this);
#if UNITY_EDITOR
if (String.IsNullOrEmpty (name))
name = UnityEditor.ObjectNames.NicifyVariableName (GetID);
#endif
NodeEditor.RepaintClients ();
}
/// <summary>
/// Deletes this Node from curNodeCanvas and the save file
/// </summary>
public void Delete ()
{
if (!NodeEditor.curNodeCanvas.nodes.Contains (this))
throw new UnityException ("The Node " + name + " does not exist on the Canvas " + NodeEditor.curNodeCanvas.name + "!");
NodeEditorCallbacks.IssueOnDeleteNode (this);
NodeEditor.curNodeCanvas.nodes.Remove (this);
for (int outCnt = 0; outCnt < Outputs.Count; outCnt++)
{
NodeOutput output = Outputs [outCnt];
while (output.connections.Count != 0)
output.connections[0].RemoveConnection ();
DestroyImmediate (output, true);
}
for (int inCnt = 0; inCnt < Inputs.Count; inCnt++)
{
NodeInput input = Inputs [inCnt];
if (input.connection != null)
input.connection.connections.Remove (input);
DestroyImmediate (input, true);
}
for (int knobCnt = 0; knobCnt < nodeKnobs.Count; knobCnt++)
{ // Inputs/Outputs need specific treatment, unfortunately
if (nodeKnobs[knobCnt] != null)
DestroyImmediate (nodeKnobs[knobCnt], true);
}
DestroyImmediate (this, true);
}
/// <summary>
/// Create the a Node of the type specified by the nodeID at position
/// </summary>
public static Node Create (string nodeID, Vector2 position)
{
return Create (nodeID, position, null);
}
/// <summary>
/// Create the a Node of the type specified by the nodeID at position
/// Auto-connects the passed connectingOutput if not null to the first compatible input
/// </summary>
public static Node Create (string nodeID, Vector2 position, NodeOutput connectingOutput)
{
Node node = NodeTypes.getDefaultNode (nodeID);
if (node == null)
throw new UnityException ("Cannot create Node with id " + nodeID + " as no such Node type is registered!");
node = node.Create (position);
node.InitBase ();
if (connectingOutput != null)
{ // Handle auto-connection and link the output to the first compatible input
foreach (NodeInput input in node.Inputs)
{
if (input.TryApplyConnection (connectingOutput))
break;
}
}
NodeEditorCallbacks.IssueOnAddNode (node);
return node;
}
/// <summary>
/// Makes sure this Node has migrated from the previous save version of NodeKnobs to the current mixed and generic one
/// </summary>
internal void CheckNodeKnobMigration ()
{ // TODO: Migration from previous NodeKnob system; Remove later on
if (nodeKnobs.Count == 0 && (Inputs.Count != 0 || Outputs.Count != 0))
{
nodeKnobs.AddRange (Inputs.Cast<NodeKnob> ());
nodeKnobs.AddRange (Outputs.Cast<NodeKnob> ());
}
}
#endregion
#region Dynamic Members
#region Node Type Methods
/// <summary>
/// Get the ID of the Node
/// </summary>
public abstract string GetID { get; }
/// <summary>
/// Create an instance of this Node at the given position
/// </summary>
public abstract Node Create (Vector2 pos);
/// <summary>
/// Draw the Node immediately
/// </summary>
protected internal abstract void NodeGUI ();
/// <summary>
/// Used to display a custom node property editor in the side window of the NodeEditorWindow
/// Optionally override this to implement
/// </summary>
public virtual void DrawNodePropertyEditor () { }
/// <summary>
/// Calculate the outputs of this Node
/// Return Success/Fail
/// Might be dependant on previous nodes
/// </summary>
public virtual bool Calculate () { return true; }
#endregion
#region Node Type Properties
/// <summary>
/// Does this node allow recursion? Recursion is allowed if atleast a single Node in the loop allows for recursion
/// </summary>
public virtual bool AllowRecursion { get { return false; } }
/// <summary>
/// Should the following Nodes be calculated after finishing the Calculation function of this node?
/// </summary>
public virtual bool ContinueCalculation { get { return true; } }
#endregion
#region Protected Callbacks
/// <summary>
/// Callback when the node is deleted
/// </summary>
protected internal virtual void OnDelete () {}
/// <summary>
/// Callback when the NodeInput was assigned a new connection
/// </summary>
protected internal virtual void OnAddInputConnection (NodeInput input) {}
/// <summary>
/// Callback when the NodeOutput was assigned a new connection (the last in the list)
/// </summary>
protected internal virtual void OnAddOutputConnection (NodeOutput output) {}
#endregion
#region Additional Serialization
/// <summary>
/// Returns all additional ScriptableObjects this Node holds.
/// That means only the actual SOURCES, simple REFERENCES will not be returned
/// This means all SciptableObjects returned here do not have it's source elsewhere
/// </summary>
public virtual ScriptableObject[] GetScriptableObjects () { return new ScriptableObject[0]; }
/// <summary>
/// Replaces all REFERENCES aswell as SOURCES of any ScriptableObjects this Node holds with the cloned versions in the serialization process.
/// </summary>
protected internal virtual void CopyScriptableObjects (System.Func<ScriptableObject, ScriptableObject> replaceSerializableObject) {}
public void SerializeInputsAndOutputs(System.Func<ScriptableObject, ScriptableObject> replaceSerializableObject) {}
#endregion
#endregion
#region Drawing
#if UNITY_EDITOR
public virtual void OnSceneGUI()
{
}
#endif
/// <summary>
/// Draws the node frame and calls NodeGUI. Can be overridden to customize drawing.
/// </summary>
protected internal virtual void DrawNode ()
{
// TODO: Node Editor Feature: Custom Windowing System
// Create a rect that is adjusted to the editor zoom
Rect nodeRect = rect;
nodeRect.position += NodeEditor.curEditorState.zoomPanAdjust + NodeEditor.curEditorState.panOffset;
contentOffset = new Vector2 (0, 20);
// Create a headerRect out of the previous rect and draw it, marking the selected node as such by making the header bold
Rect headerRect = new Rect (nodeRect.x, nodeRect.y, nodeRect.width, contentOffset.y);
GUI.Label (headerRect, name, NodeEditor.curEditorState.selectedNode == this? NodeEditorGUI.nodeBoxBold : NodeEditorGUI.nodeBox);
// Begin the body frame around the NodeGUI
Rect bodyRect = new Rect (nodeRect.x, nodeRect.y + contentOffset.y, nodeRect.width, nodeRect.height - contentOffset.y);
GUI.BeginGroup (bodyRect, GUI.skin.box);
bodyRect.position = Vector2.zero;
GUILayout.BeginArea (bodyRect, GUI.skin.box);
// Call NodeGUI
GUI.changed = false;
NodeGUI ();
// End NodeGUI frame
GUILayout.EndArea ();
GUI.EndGroup ();
}
/// <summary>
/// Draws the nodeKnobs
/// </summary>
protected internal virtual void DrawKnobs ()
{
CheckNodeKnobMigration ();
for (int knobCnt = 0; knobCnt < nodeKnobs.Count; knobCnt++)
nodeKnobs[knobCnt].DrawKnob ();
}
/// <summary>
/// Draws the node curves
/// </summary>
protected internal virtual void DrawConnections ()
{
CheckNodeKnobMigration ();
if (Event.current.type != EventType.Repaint)
return;
for (int outCnt = 0; outCnt < Outputs.Count; outCnt++)
{
NodeOutput output = Outputs [outCnt];
Vector2 startPos = output.GetGUIKnob ().center;
Vector2 startDir = output.GetDirection ();
for (int conCnt = 0; conCnt < output.connections.Count; conCnt++)
{
NodeInput input = output.connections [conCnt];
NodeEditorGUI.DrawConnection (startPos,
startDir,
input.GetGUIKnob ().center,
input.GetDirection (),
output.typeData.Color);
}
}
}
#endregion
#region Calculation Utility
/// <summary>
/// Checks if there are no unassigned and no null-value inputs.
/// </summary>
protected internal bool allInputsReady ()
{
for (int inCnt = 0; inCnt < Inputs.Count; inCnt++)
{
if (Inputs[inCnt].connection == null || Inputs[inCnt].connection.IsValueNull)
return false;
}
return true;
}
/// <summary>
/// Checks if there are any unassigned inputs.
/// </summary>
protected internal bool hasUnassignedInputs ()
{
for (int inCnt = 0; inCnt < Inputs.Count; inCnt++)
if (Inputs [inCnt].connection == null)
return true;
return false;
}
/// <summary>
/// Returns whether every direct dexcendant has been calculated
/// </summary>
protected internal bool descendantsCalculated ()
{
for (int cnt = 0; cnt < Inputs.Count; cnt++)
{
if (Inputs [cnt].connection != null && !Inputs [cnt].connection.body.calculated)
return false;
}
return true;
}
/// <summary>
/// Returns whether the node acts as an input (no inputs or no inputs assigned)
/// </summary>
protected internal bool isInput ()
{
for (int cnt = 0; cnt < Inputs.Count; cnt++)
if (Inputs [cnt].connection != null)
return false;
return true;
}
#endregion
#region Knob Utility
// -- OUTPUTS --
/// <summary>
/// Creates and output on your Node of the given type.
/// </summary>
public NodeOutput CreateOutput (string outputName, string outputType)
{
return NodeOutput.Create (this, outputName, outputType);
}
/// <summary>
/// Creates and output on this Node of the given type at the specified NodeSide.
/// </summary>
public NodeOutput CreateOutput (string outputName, string outputType, NodeSide nodeSide)
{
return NodeOutput.Create (this, outputName, outputType, nodeSide);
}
/// <summary>
/// Creates and output on this Node of the given type at the specified NodeSide and position.
/// </summary>
public NodeOutput CreateOutput (string outputName, string outputType, NodeSide nodeSide, float sidePosition)
{
return NodeOutput.Create (this, outputName, outputType, nodeSide, sidePosition);
}
/// <summary>
/// Aligns the OutputKnob on it's NodeSide with the last GUILayout control drawn.
/// </summary>
/// <param name="outputIdx">The index of the output in the Node's Outputs list</param>
protected void OutputKnob (int outputIdx)
{
if (Event.current.type == EventType.Repaint)
Outputs[outputIdx].SetPosition ();
}
// -- INPUTS --
/// <summary>
/// Creates and input on your Node of the given type.
/// </summary>
public NodeInput CreateInput (string inputName, string inputType)
{
return NodeInput.Create (this, inputName, inputType);
}
/// <summary>
/// Creates and input on this Node of the given type at the specified NodeSide.
/// </summary>
public NodeInput CreateInput (string inputName, string inputType, NodeSide nodeSide)
{
return NodeInput.Create (this, inputName, inputType, nodeSide);
}
/// <summary>
/// Creates and input on this Node of the given type at the specified NodeSide and position.
/// </summary>
public NodeInput CreateInput (string inputName, string inputType, NodeSide nodeSide, float sidePosition)
{
return NodeInput.Create (this, inputName, inputType, nodeSide, sidePosition);
}
/// <summary>
/// Aligns the InputKnob on it's NodeSide with the last GUILayout control drawn.
/// </summary>
/// <param name="inputIdx">The index of the input in the Node's Inputs list</param>
protected void InputKnob (int inputIdx)
{
if (Event.current.type == EventType.Repaint)
Inputs[inputIdx].SetPosition ();
}
/// <summary>
/// Reassigns the type of the given output. This actually recreates it
/// </summary>
protected static void ReassignOutputType (ref NodeOutput output, Type newOutputType)
{
Node body = output.body;
string outputName = output.name;
// Store all valid connections that are not affected by the type change
IEnumerable<NodeInput> validConnections = output.connections.Where ((NodeInput connection) => connection.typeData.Type.IsAssignableFrom (newOutputType));
// Delete the output of the old type
output.Delete ();
// Create Output with new type
NodeEditorCallbacks.IssueOnAddNodeKnob (NodeOutput.Create (body, outputName, newOutputType.AssemblyQualifiedName));
output = body.Outputs[body.Outputs.Count-1];
// Restore the valid connections
foreach (NodeInput input in validConnections)
input.ApplyConnection (output);
}
/// <summary>
/// Reassigns the type of the given output. This actually recreates it
/// </summary>
protected static void ReassignInputType (ref NodeInput input, Type newInputType)
{
Node body = input.body;
string inputName = input.name;
// Store the valid connection if it's not affected by the type change
NodeOutput validConnection = null;
if (input.connection != null && newInputType.IsAssignableFrom (input.connection.typeData.Type))
validConnection = input.connection;
// Delete the input of the old type
input.Delete ();
// Create Output with new type
NodeEditorCallbacks.IssueOnAddNodeKnob (NodeInput.Create (body, inputName, newInputType.AssemblyQualifiedName));
input = body.Inputs[body.Inputs.Count-1];
// Restore the valid connections
if (validConnection != null)
input.ApplyConnection (validConnection);
}
#endregion
#region Node Utility
/// <summary>
/// Recursively checks whether this node is a child of the other node
/// </summary>
public bool isChildOf (Node otherNode)
{
if (otherNode == null || otherNode == this)
return false;
if (BeginRecursiveSearchLoop ()) return false;
for (int cnt = 0; cnt < Inputs.Count; cnt++)
{
NodeOutput connection = Inputs [cnt].connection;
if (connection != null)
{
if (connection.body != startRecursiveSearchNode)
{
if (connection.body == otherNode || connection.body.isChildOf (otherNode))
{
StopRecursiveSearchLoop ();
return true;
}
}
}
}
EndRecursiveSearchLoop ();
return false;
}
/// <summary>
/// Recursively checks whether this node is in a loop
/// </summary>
internal bool isInLoop ()
{
if (BeginRecursiveSearchLoop ()) return this == startRecursiveSearchNode;
for (int cnt = 0; cnt < Inputs.Count; cnt++)
{
NodeOutput connection = Inputs [cnt].connection;
if (connection != null && connection.body.isInLoop ())
{
StopRecursiveSearchLoop ();
return true;
}
}
EndRecursiveSearchLoop ();
return false;
}
/// <summary>
/// Recursively checks whether any node in the loop to be made allows recursion.
/// Other node is the node this node needs connect to in order to fill the loop (other node being the node coming AFTER this node).
/// That means isChildOf has to be confirmed before calling this!
/// </summary>
internal bool allowsLoopRecursion (Node otherNode)
{
if (AllowRecursion)
return true;
if (otherNode == null)
return false;
if (BeginRecursiveSearchLoop ()) return false;
for (int cnt = 0; cnt < Inputs.Count; cnt++)
{
NodeOutput connection = Inputs [cnt].connection;
if (connection != null && connection.body.allowsLoopRecursion (otherNode))
{
StopRecursiveSearchLoop ();
return true;
}
}
EndRecursiveSearchLoop ();
return false;
}
/// <summary>
/// A recursive function to clear all calculations depending on this node.
/// Usually does not need to be called manually
/// </summary>
public void ClearCalculation ()
{
if (BeginRecursiveSearchLoop ()) return;
calculated = false;
for (int outCnt = 0; outCnt < Outputs.Count; outCnt++)
{
NodeOutput output = Outputs [outCnt];
for (int conCnt = 0; conCnt < output.connections.Count; conCnt++)
output.connections [conCnt].body.ClearCalculation ();
}
EndRecursiveSearchLoop ();
}
#region Recursive Search Helpers
[NonSerialized] private List<Node> recursiveSearchSurpassed;
[NonSerialized] private Node startRecursiveSearchNode; // Temporary start node for recursive searches
/// <summary>
/// Begins the recursive search loop and returns whether this node has already been searched
/// </summary>
internal bool BeginRecursiveSearchLoop ()
{
if (startRecursiveSearchNode == null || recursiveSearchSurpassed == null)
{ // Start search
recursiveSearchSurpassed = new List<Node> ();
startRecursiveSearchNode = this;
}
if (recursiveSearchSurpassed.Contains (this))
return true;
recursiveSearchSurpassed.Add (this);
return false;
}
/// <summary>
/// Ends the recursive search loop if this was the start node
/// </summary>
internal void EndRecursiveSearchLoop ()
{
if (startRecursiveSearchNode == this)
{ // End search
recursiveSearchSurpassed = null;
startRecursiveSearchNode = null;
}
}
/// <summary>
/// Stops the recursive search loop immediately. Call when you found what you needed.
/// </summary>
internal void StopRecursiveSearchLoop ()
{
recursiveSearchSurpassed = null;
startRecursiveSearchNode = null;
}
#endregion
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// An embassy.
/// </summary>
public class Embassy_Core : TypeCore, IGovernmentBuilding
{
public Embassy_Core()
{
this._TypeId = 92;
this._Id = "Embassy";
this._Schema_Org_Url = "http://schema.org/Embassy";
string label = "";
GetLabel(out label, "Embassy", typeof(Embassy_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62,116};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{116};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareLessThanDouble()
{
var test = new SimpleBinaryOpTest__CompareLessThanDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareLessThanDouble
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__CompareLessThanDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareLessThanDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareLessThan(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareLessThan(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareLessThan(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareLessThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareLessThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareLessThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareLessThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareLessThanDouble();
var result = Sse2.CompareLessThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareLessThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] < right[0]) ? -1 : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] < right[i]) ? -1 : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareLessThan)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Collections.Generic;
using System.IO;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Text;
using System.Xml;
class BinaryMessageEncoderFactory : MessageEncoderFactory
{
const int maxPooledXmlReaderPerMessage = 2;
BinaryMessageEncoder messageEncoder;
MessageVersion messageVersion;
int maxReadPoolSize;
int maxWritePoolSize;
CompressionFormat compressionFormat;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile SynchronizedPool<XmlDictionaryWriter> streamedWriterPool;
volatile SynchronizedPool<XmlDictionaryReader> streamedReaderPool;
volatile SynchronizedPool<BinaryBufferedMessageData> bufferedDataPool;
volatile SynchronizedPool<BinaryBufferedMessageWriter> bufferedWriterPool;
volatile SynchronizedPool<RecycledMessageState> recycledStatePool;
object thisLock;
int maxSessionSize;
OnXmlDictionaryReaderClose onStreamedReaderClose;
XmlDictionaryReaderQuotas readerQuotas;
XmlDictionaryReaderQuotas bufferedReadReaderQuotas;
BinaryVersion binaryVersion;
public BinaryMessageEncoderFactory(MessageVersion messageVersion, int maxReadPoolSize, int maxWritePoolSize, int maxSessionSize,
XmlDictionaryReaderQuotas readerQuotas, long maxReceivedMessageSize, BinaryVersion version, CompressionFormat compressionFormat)
{
this.messageVersion = messageVersion;
this.maxReadPoolSize = maxReadPoolSize;
this.maxWritePoolSize = maxWritePoolSize;
this.maxSessionSize = maxSessionSize;
this.thisLock = new object();
this.onStreamedReaderClose = new OnXmlDictionaryReaderClose(ReturnStreamedReader);
this.readerQuotas = new XmlDictionaryReaderQuotas();
if (readerQuotas != null)
{
readerQuotas.CopyTo(this.readerQuotas);
}
this.bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(this.readerQuotas);
this.MaxReceivedMessageSize = maxReceivedMessageSize;
this.binaryVersion = version;
this.compressionFormat = compressionFormat;
this.messageEncoder = new BinaryMessageEncoder(this, false, 0);
}
public static IXmlDictionary XmlDictionary
{
get { return XD.Dictionary; }
}
public override MessageEncoder Encoder
{
get
{
return messageEncoder;
}
}
public override MessageVersion MessageVersion
{
get { return messageVersion; }
}
public int MaxWritePoolSize
{
get { return maxWritePoolSize; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return readerQuotas;
}
}
public int MaxReadPoolSize
{
get { return maxReadPoolSize; }
}
public int MaxSessionSize
{
get { return maxSessionSize; }
}
public CompressionFormat CompressionFormat
{
get { return this.compressionFormat; }
}
long MaxReceivedMessageSize
{
get;
set;
}
object ThisLock
{
get { return thisLock; }
}
SynchronizedPool<RecycledMessageState> RecycledStatePool
{
get
{
if (recycledStatePool == null)
{
lock (ThisLock)
{
if (recycledStatePool == null)
{
//running = true;
recycledStatePool = new SynchronizedPool<RecycledMessageState>(maxReadPoolSize);
}
}
}
return recycledStatePool;
}
}
public override MessageEncoder CreateSessionEncoder()
{
return new BinaryMessageEncoder(this, true, maxSessionSize);
}
XmlDictionaryWriter TakeStreamedWriter(Stream stream)
{
if (streamedWriterPool == null)
{
lock (ThisLock)
{
if (streamedWriterPool == null)
{
//running = true;
streamedWriterPool = new SynchronizedPool<XmlDictionaryWriter>(maxWritePoolSize);
}
}
}
XmlDictionaryWriter xmlWriter = streamedWriterPool.Take();
if (xmlWriter == null)
{
xmlWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, binaryVersion.Dictionary, null, false);
if (TD.WritePoolMissIsEnabled())
{
TD.WritePoolMiss(xmlWriter.GetType().Name);
}
}
else
{
((IXmlBinaryWriterInitializer)xmlWriter).SetOutput(stream, binaryVersion.Dictionary, null, false);
}
return xmlWriter;
}
void ReturnStreamedWriter(XmlDictionaryWriter xmlWriter)
{
xmlWriter.Close();
streamedWriterPool.Return(xmlWriter);
}
BinaryBufferedMessageWriter TakeBufferedWriter()
{
if (bufferedWriterPool == null)
{
lock (ThisLock)
{
if (bufferedWriterPool == null)
{
//running = true;
bufferedWriterPool = new SynchronizedPool<BinaryBufferedMessageWriter>(maxWritePoolSize);
}
}
}
BinaryBufferedMessageWriter messageWriter = bufferedWriterPool.Take();
if (messageWriter == null)
{
messageWriter = new BinaryBufferedMessageWriter(binaryVersion.Dictionary);
if (TD.WritePoolMissIsEnabled())
{
TD.WritePoolMiss(messageWriter.GetType().Name);
}
}
return messageWriter;
}
void ReturnMessageWriter(BinaryBufferedMessageWriter messageWriter)
{
bufferedWriterPool.Return(messageWriter);
}
XmlDictionaryReader TakeStreamedReader(Stream stream)
{
if (streamedReaderPool == null)
{
lock (ThisLock)
{
if (streamedReaderPool == null)
{
//running = true;
streamedReaderPool = new SynchronizedPool<XmlDictionaryReader>(maxReadPoolSize);
}
}
}
XmlDictionaryReader xmlReader = streamedReaderPool.Take();
if (xmlReader == null)
{
xmlReader = XmlDictionaryReader.CreateBinaryReader(stream,
binaryVersion.Dictionary,
readerQuotas,
null,
onStreamedReaderClose);
if (TD.ReadPoolMissIsEnabled())
{
TD.ReadPoolMiss(xmlReader.GetType().Name);
}
}
else
{
((IXmlBinaryReaderInitializer)xmlReader).SetInput(stream,
binaryVersion.Dictionary,
readerQuotas,
null,
onStreamedReaderClose);
}
return xmlReader;
}
void ReturnStreamedReader(XmlDictionaryReader xmlReader)
{
streamedReaderPool.Return(xmlReader);
}
BinaryBufferedMessageData TakeBufferedData(BinaryMessageEncoder messageEncoder)
{
if (bufferedDataPool == null)
{
lock (ThisLock)
{
if (bufferedDataPool == null)
{
//running = true;
bufferedDataPool = new SynchronizedPool<BinaryBufferedMessageData>(maxReadPoolSize);
}
}
}
BinaryBufferedMessageData messageData = bufferedDataPool.Take();
if (messageData == null)
{
messageData = new BinaryBufferedMessageData(this, maxPooledXmlReaderPerMessage);
if (TD.ReadPoolMissIsEnabled())
{
TD.ReadPoolMiss(messageData.GetType().Name);
}
}
messageData.SetMessageEncoder(messageEncoder);
return messageData;
}
void ReturnBufferedData(BinaryBufferedMessageData messageData)
{
messageData.SetMessageEncoder(null);
bufferedDataPool.Return(messageData);
}
class BinaryBufferedMessageData : BufferedMessageData
{
BinaryMessageEncoderFactory factory;
BinaryMessageEncoder messageEncoder;
Pool<XmlDictionaryReader> readerPool;
OnXmlDictionaryReaderClose onClose;
public BinaryBufferedMessageData(BinaryMessageEncoderFactory factory, int maxPoolSize)
: base(factory.RecycledStatePool)
{
this.factory = factory;
readerPool = new Pool<XmlDictionaryReader>(maxPoolSize);
onClose = new OnXmlDictionaryReaderClose(OnXmlReaderClosed);
}
public override MessageEncoder MessageEncoder
{
get { return messageEncoder; }
}
public override XmlDictionaryReaderQuotas Quotas
{
get { return factory.readerQuotas; }
}
public void SetMessageEncoder(BinaryMessageEncoder messageEncoder)
{
this.messageEncoder = messageEncoder;
}
protected override XmlDictionaryReader TakeXmlReader()
{
ArraySegment<byte> buffer = this.Buffer;
XmlDictionaryReader xmlReader = readerPool.Take();
if (xmlReader != null)
{
((IXmlBinaryReaderInitializer)xmlReader).SetInput(buffer.Array, buffer.Offset, buffer.Count,
factory.binaryVersion.Dictionary,
factory.bufferedReadReaderQuotas,
messageEncoder.ReaderSession,
onClose);
}
else
{
xmlReader = XmlDictionaryReader.CreateBinaryReader(buffer.Array, buffer.Offset, buffer.Count,
factory.binaryVersion.Dictionary,
factory.bufferedReadReaderQuotas,
messageEncoder.ReaderSession,
onClose);
if (TD.ReadPoolMissIsEnabled())
{
TD.ReadPoolMiss(xmlReader.GetType().Name);
}
}
return xmlReader;
}
protected override void ReturnXmlReader(XmlDictionaryReader reader)
{
readerPool.Return(reader);
}
protected override void OnClosed()
{
factory.ReturnBufferedData(this);
}
}
class BinaryBufferedMessageWriter : BufferedMessageWriter
{
XmlDictionaryWriter writer;
IXmlDictionary dictionary;
XmlBinaryWriterSession session;
public BinaryBufferedMessageWriter(IXmlDictionary dictionary)
{
this.dictionary = dictionary;
}
public BinaryBufferedMessageWriter(IXmlDictionary dictionary, XmlBinaryWriterSession session)
{
this.dictionary = dictionary;
this.session = session;
}
protected override XmlDictionaryWriter TakeXmlWriter(Stream stream)
{
XmlDictionaryWriter returnedWriter = writer;
if (returnedWriter == null)
{
returnedWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, dictionary, session, false);
}
else
{
writer = null;
((IXmlBinaryWriterInitializer)returnedWriter).SetOutput(stream, dictionary, session, false);
}
return returnedWriter;
}
protected override void ReturnXmlWriter(XmlDictionaryWriter writer)
{
writer.Close();
if (this.writer == null)
{
this.writer = writer;
}
}
}
class BinaryMessageEncoder : MessageEncoder, ICompressedMessageEncoder, ITraceSourceStringProvider
{
const string SupportedCompressionTypesMessageProperty = "BinaryMessageEncoder.SupportedCompressionTypes";
BinaryMessageEncoderFactory factory;
bool isSession;
XmlBinaryWriterSessionWithQuota writerSession;
BinaryBufferedMessageWriter sessionMessageWriter;
XmlBinaryReaderSession readerSession;
XmlBinaryReaderSession readerSessionForLogging;
bool readerSessionForLoggingIsInvalid = false;
int writeIdCounter;
int idCounter;
int maxSessionSize;
int remainingReaderSessionSize;
bool isReaderSessionInvalid;
MessagePatterns messagePatterns;
string contentType;
string normalContentType;
string gzipCompressedContentType;
string deflateCompressedContentType;
CompressionFormat sessionCompressionFormat;
readonly long maxReceivedMessageSize;
public BinaryMessageEncoder(BinaryMessageEncoderFactory factory, bool isSession, int maxSessionSize)
{
this.factory = factory;
this.isSession = isSession;
this.maxSessionSize = maxSessionSize;
this.remainingReaderSessionSize = maxSessionSize;
this.normalContentType = isSession ? factory.binaryVersion.SessionContentType : factory.binaryVersion.ContentType;
this.gzipCompressedContentType = isSession ? BinaryVersion.GZipVersion1.SessionContentType : BinaryVersion.GZipVersion1.ContentType;
this.deflateCompressedContentType = isSession ? BinaryVersion.DeflateVersion1.SessionContentType : BinaryVersion.DeflateVersion1.ContentType;
this.sessionCompressionFormat = this.factory.CompressionFormat;
this.maxReceivedMessageSize = this.factory.MaxReceivedMessageSize;
switch (this.factory.CompressionFormat)
{
case CompressionFormat.Deflate:
this.contentType = this.deflateCompressedContentType;
break;
case CompressionFormat.GZip:
this.contentType = this.gzipCompressedContentType;
break;
default:
this.contentType = this.normalContentType;
break;
}
}
public override string ContentType
{
get
{
return this.contentType;
}
}
public override MessageVersion MessageVersion
{
get { return factory.messageVersion; }
}
public override string MediaType
{
get { return this.contentType; }
}
public XmlBinaryReaderSession ReaderSession
{
get { return readerSession; }
}
public bool CompressionEnabled
{
get { return this.factory.CompressionFormat != CompressionFormat.None; }
}
ArraySegment<byte> AddSessionInformationToMessage(ArraySegment<byte> messageData, BufferManager bufferManager, int maxMessageSize)
{
int dictionarySize = 0;
byte[] buffer = messageData.Array;
if (writerSession.HasNewStrings)
{
IList<XmlDictionaryString> newStrings = writerSession.GetNewStrings();
for (int i = 0; i < newStrings.Count; i++)
{
int utf8ValueSize = Encoding.UTF8.GetByteCount(newStrings[i].Value);
dictionarySize += IntEncoder.GetEncodedSize(utf8ValueSize) + utf8ValueSize;
}
int messageSize = messageData.Offset + messageData.Count;
int remainingMessageSize = maxMessageSize - messageSize;
if (remainingMessageSize - dictionarySize < 0)
{
string excMsg = SR.GetString(SR.MaxSentMessageSizeExceeded, maxMessageSize);
if (TD.MaxSentMessageSizeExceededIsEnabled())
{
TD.MaxSentMessageSizeExceeded(excMsg);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(excMsg));
}
int requiredBufferSize = messageData.Offset + messageData.Count + dictionarySize;
if (buffer.Length < requiredBufferSize)
{
byte[] newBuffer = bufferManager.TakeBuffer(requiredBufferSize);
Buffer.BlockCopy(buffer, messageData.Offset, newBuffer, messageData.Offset, messageData.Count);
bufferManager.ReturnBuffer(buffer);
buffer = newBuffer;
}
Buffer.BlockCopy(buffer, messageData.Offset, buffer, messageData.Offset + dictionarySize, messageData.Count);
int offset = messageData.Offset;
for (int i = 0; i < newStrings.Count; i++)
{
string newString = newStrings[i].Value;
int utf8ValueSize = Encoding.UTF8.GetByteCount(newString);
offset += IntEncoder.Encode(utf8ValueSize, buffer, offset);
offset += Encoding.UTF8.GetBytes(newString, 0, newString.Length, buffer, offset);
}
writerSession.ClearNewStrings();
}
int headerSize = IntEncoder.GetEncodedSize(dictionarySize);
int newOffset = messageData.Offset - headerSize;
int newSize = headerSize + messageData.Count + dictionarySize;
IntEncoder.Encode(dictionarySize, buffer, newOffset);
return new ArraySegment<byte>(buffer, newOffset, newSize);
}
ArraySegment<byte> ExtractSessionInformationFromMessage(ArraySegment<byte> messageData)
{
if (isReaderSessionInvalid)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.GetString(SR.BinaryEncoderSessionInvalid)));
}
byte[] buffer = messageData.Array;
int dictionarySize;
int headerSize;
int newOffset;
int newSize;
bool throwing = true;
try
{
IntDecoder decoder = new IntDecoder();
headerSize = decoder.Decode(buffer, messageData.Offset, messageData.Count);
dictionarySize = decoder.Value;
if (dictionarySize > messageData.Count)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.GetString(SR.BinaryEncoderSessionMalformed)));
}
newOffset = messageData.Offset + headerSize + dictionarySize;
newSize = messageData.Count - headerSize - dictionarySize;
if (newSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.GetString(SR.BinaryEncoderSessionMalformed)));
}
if (dictionarySize > 0)
{
if (dictionarySize > remainingReaderSessionSize)
{
string message = SR.GetString(SR.BinaryEncoderSessionTooLarge, this.maxSessionSize);
if (TD.MaxSessionSizeReachedIsEnabled())
{
TD.MaxSessionSizeReached(message);
}
Exception inner = new QuotaExceededException(message);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner));
}
else
{
remainingReaderSessionSize -= dictionarySize;
}
int size = dictionarySize;
int offset = messageData.Offset + headerSize;
while (size > 0)
{
decoder.Reset();
int bytesDecoded = decoder.Decode(buffer, offset, size);
int utf8ValueSize = decoder.Value;
offset += bytesDecoded;
size -= bytesDecoded;
if (utf8ValueSize > size)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.GetString(SR.BinaryEncoderSessionMalformed)));
}
string value = Encoding.UTF8.GetString(buffer, offset, utf8ValueSize);
offset += utf8ValueSize;
size -= utf8ValueSize;
readerSession.Add(idCounter, value);
idCounter++;
}
}
throwing = false;
}
finally
{
if (throwing)
{
isReaderSessionInvalid = true;
}
}
return new ArraySegment<byte>(buffer, newOffset, newSize);
}
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
if (bufferManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bufferManager");
}
CompressionFormat compressionFormat = this.CheckContentType(contentType);
if (TD.BinaryMessageDecodingStartIsEnabled())
{
TD.BinaryMessageDecodingStart();
}
if (compressionFormat != CompressionFormat.None)
{
MessageEncoderCompressionHandler.DecompressBuffer(ref buffer, bufferManager, compressionFormat, this.maxReceivedMessageSize);
}
if (isSession)
{
if (readerSession == null)
{
readerSession = new XmlBinaryReaderSession();
messagePatterns = new MessagePatterns(factory.binaryVersion.Dictionary, readerSession, this.MessageVersion);
}
try
{
buffer = ExtractSessionInformationFromMessage(buffer);
}
catch (InvalidDataException)
{
MessageLogger.LogMessage(buffer, MessageLoggingSource.Malformed);
throw;
}
}
BinaryBufferedMessageData messageData = factory.TakeBufferedData(this);
Message message;
if (messagePatterns != null)
{
message = messagePatterns.TryCreateMessage(buffer.Array, buffer.Offset, buffer.Count, bufferManager, messageData);
}
else
{
message = null;
}
if (message == null)
{
messageData.Open(buffer, bufferManager);
RecycledMessageState messageState = messageData.TakeMessageState();
if (messageState == null)
{
messageState = new RecycledMessageState();
}
message = new BufferedMessage(messageData, messageState);
}
message.Properties.Encoder = this;
if (TD.MessageReadByEncoderIsEnabled() && buffer != null)
{
TD.MessageReadByEncoder(
EventTraceActivityHelper.TryExtractActivity(message, true),
buffer.Count,
this);
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
{
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
}
CompressionFormat compressionFormat = this.CheckContentType(contentType);
if (TD.BinaryMessageDecodingStartIsEnabled())
{
TD.BinaryMessageDecodingStart();
}
if (compressionFormat != CompressionFormat.None)
{
stream = new MaxMessageSizeStream(
MessageEncoderCompressionHandler.GetDecompressStream(stream, compressionFormat), this.maxReceivedMessageSize);
}
XmlDictionaryReader reader = factory.TakeStreamedReader(stream);
Message message = Message.CreateMessage(reader, maxSizeOfHeaders, factory.messageVersion);
message.Properties.Encoder = this;
if (TD.StreamedMessageReadByEncoderIsEnabled())
{
TD.StreamedMessageReadByEncoder(
EventTraceActivityHelper.TryExtractActivity(message, true));
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
if (bufferManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bufferManager");
}
if (maxMessageSize < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize,
SR.GetString(SR.ValueMustBeNonNegative)));
}
EventTraceActivity eventTraceActivity = null;
if (TD.BinaryMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.BinaryMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
if (isSession)
{
if (writerSession == null)
{
writerSession = new XmlBinaryWriterSessionWithQuota(maxSessionSize);
sessionMessageWriter = new BinaryBufferedMessageWriter(factory.binaryVersion.Dictionary, writerSession);
}
messageOffset += IntEncoder.MaxEncodedSize;
}
if (messageOffset < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset,
SR.GetString(SR.ValueMustBeNonNegative)));
}
if (messageOffset > maxMessageSize)
{
string excMsg = SR.GetString(SR.MaxSentMessageSizeExceeded, maxMessageSize);
if (TD.MaxSentMessageSizeExceededIsEnabled())
{
TD.MaxSentMessageSizeExceeded(excMsg);
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new QuotaExceededException(excMsg));
}
ThrowIfMismatchedMessageVersion(message);
BinaryBufferedMessageWriter messageWriter;
if (isSession)
{
messageWriter = sessionMessageWriter;
}
else
{
messageWriter = factory.TakeBufferedWriter();
}
ArraySegment<byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize);
if (MessageLogger.LogMessagesAtTransportLevel && !this.readerSessionForLoggingIsInvalid)
{
if (isSession)
{
if (this.readerSessionForLogging == null)
{
this.readerSessionForLogging = new XmlBinaryReaderSession();
}
if (this.writerSession.HasNewStrings)
{
foreach (XmlDictionaryString xmlDictionaryString in this.writerSession.GetNewStrings())
{
this.readerSessionForLogging.Add(this.writeIdCounter++, xmlDictionaryString.Value);
}
}
}
XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateBinaryReader(messageData.Array, messageData.Offset, messageData.Count, XD.Dictionary, XmlDictionaryReaderQuotas.Max, this.readerSessionForLogging, null);
MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend);
}
else
{
this.readerSessionForLoggingIsInvalid = true;
}
if (isSession)
{
messageData = AddSessionInformationToMessage(messageData, bufferManager, maxMessageSize);
}
else
{
factory.ReturnMessageWriter(messageWriter);
}
if (TD.MessageWrittenByEncoderIsEnabled() && messageData != null)
{
TD.MessageWrittenByEncoder(
eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message),
messageData.Count,
this);
}
CompressionFormat compressionFormat = this.CheckCompressedWrite(message);
if (compressionFormat != CompressionFormat.None)
{
MessageEncoderCompressionHandler.CompressBuffer(ref messageData, bufferManager, compressionFormat);
}
return messageData;
}
public override void WriteMessage(Message message, Stream stream)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
}
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
}
EventTraceActivity eventTraceActivity = null;
if (TD.BinaryMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.BinaryMessageEncodingStart(eventTraceActivity);
}
CompressionFormat compressionFormat = this.CheckCompressedWrite(message);
if (compressionFormat != CompressionFormat.None)
{
stream = MessageEncoderCompressionHandler.GetCompressStream(stream, compressionFormat);
}
ThrowIfMismatchedMessageVersion(message);
message.Properties.Encoder = this;
XmlDictionaryWriter xmlWriter = factory.TakeStreamedWriter(stream);
message.WriteMessage(xmlWriter);
xmlWriter.Flush();
if (TD.StreamedMessageWrittenByEncoderIsEnabled())
{
TD.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message));
}
factory.ReturnStreamedWriter(xmlWriter);
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend);
}
if (compressionFormat != CompressionFormat.None)
{
stream.Close();
}
}
public override bool IsContentTypeSupported(string contentType)
{
bool supported = true;
if (!base.IsContentTypeSupported(contentType))
{
if (this.CompressionEnabled)
{
supported = (this.factory.CompressionFormat == CompressionFormat.GZip &&
base.IsContentTypeSupported(contentType, this.gzipCompressedContentType, this.gzipCompressedContentType)) ||
(this.factory.CompressionFormat == CompressionFormat.Deflate &&
base.IsContentTypeSupported(contentType, this.deflateCompressedContentType, this.deflateCompressedContentType)) ||
base.IsContentTypeSupported(contentType, this.normalContentType, this.normalContentType);
}
else
{
supported = false;
}
}
return supported;
}
public void SetSessionContentType(string contentType)
{
if (base.IsContentTypeSupported(contentType, this.gzipCompressedContentType, this.gzipCompressedContentType))
{
this.sessionCompressionFormat = CompressionFormat.GZip;
}
else if (base.IsContentTypeSupported(contentType, this.deflateCompressedContentType, this.deflateCompressedContentType))
{
this.sessionCompressionFormat = CompressionFormat.Deflate;
}
else
{
this.sessionCompressionFormat = CompressionFormat.None;
}
}
public void AddCompressedMessageProperties(Message message, string supportedCompressionTypes)
{
message.Properties.Add(SupportedCompressionTypesMessageProperty, supportedCompressionTypes);
}
static bool ContentTypeEqualsOrStartsWith(string contentType, string supportedContentType)
{
return contentType == supportedContentType || contentType.StartsWith(supportedContentType, StringComparison.OrdinalIgnoreCase);
}
CompressionFormat CheckContentType(string contentType)
{
CompressionFormat compressionFormat = CompressionFormat.None;
if (contentType == null)
{
compressionFormat = this.sessionCompressionFormat;
}
else
{
if (!this.CompressionEnabled)
{
if (!ContentTypeEqualsOrStartsWith(contentType, this.ContentType))
{
throw FxTrace.Exception.AsError(new ProtocolException(SR.GetString(SR.EncoderUnrecognizedContentType, contentType, this.ContentType)));
}
}
else
{
if (this.factory.CompressionFormat == CompressionFormat.GZip && ContentTypeEqualsOrStartsWith(contentType, this.gzipCompressedContentType))
{
compressionFormat = CompressionFormat.GZip;
}
else if (this.factory.CompressionFormat == CompressionFormat.Deflate && ContentTypeEqualsOrStartsWith(contentType, this.deflateCompressedContentType))
{
compressionFormat = CompressionFormat.Deflate;
}
else if (ContentTypeEqualsOrStartsWith(contentType, this.normalContentType))
{
compressionFormat = CompressionFormat.None;
}
else
{
throw FxTrace.Exception.AsError(new ProtocolException(SR.GetString(SR.EncoderUnrecognizedContentType, contentType, this.ContentType)));
}
}
}
return compressionFormat;
}
CompressionFormat CheckCompressedWrite(Message message)
{
CompressionFormat compressionFormat = this.sessionCompressionFormat;
if (compressionFormat != CompressionFormat.None && !this.isSession)
{
string acceptEncoding;
if (message.Properties.TryGetValue<string>(SupportedCompressionTypesMessageProperty, out acceptEncoding) &&
acceptEncoding != null)
{
acceptEncoding = acceptEncoding.ToLowerInvariant();
if ((compressionFormat == CompressionFormat.GZip &&
!acceptEncoding.Contains(MessageEncoderCompressionHandler.GZipContentEncoding)) ||
(compressionFormat == CompressionFormat.Deflate &&
!acceptEncoding.Contains(MessageEncoderCompressionHandler.DeflateContentEncoding)))
{
compressionFormat = CompressionFormat.None;
}
}
}
return compressionFormat;
}
string ITraceSourceStringProvider.GetSourceString()
{
return base.GetTraceSourceString();
}
}
class XmlBinaryWriterSessionWithQuota : XmlBinaryWriterSession
{
int bytesRemaining;
List<XmlDictionaryString> newStrings;
public XmlBinaryWriterSessionWithQuota(int maxSessionSize)
{
bytesRemaining = maxSessionSize;
}
public bool HasNewStrings
{
get { return newStrings != null; }
}
public override bool TryAdd(XmlDictionaryString s, out int key)
{
if (bytesRemaining == 0)
{
key = -1;
return false;
}
int bytesRequired = Encoding.UTF8.GetByteCount(s.Value);
bytesRequired += IntEncoder.GetEncodedSize(bytesRequired);
if (bytesRequired > bytesRemaining)
{
key = -1;
bytesRemaining = 0;
return false;
}
if (base.TryAdd(s, out key))
{
if (newStrings == null)
{
newStrings = new List<XmlDictionaryString>();
}
newStrings.Add(s);
bytesRemaining -= bytesRequired;
return true;
}
else
{
return false;
}
}
public IList<XmlDictionaryString> GetNewStrings()
{
return newStrings;
}
public void ClearNewStrings()
{
newStrings = null;
}
}
}
class BinaryFormatBuilder
{
List<byte> bytes;
public BinaryFormatBuilder()
{
this.bytes = new List<byte>();
}
public int Count
{
get { return bytes.Count; }
}
public void AppendPrefixDictionaryElement(char prefix, int key)
{
this.AppendNode(XmlBinaryNodeType.PrefixDictionaryElementA + GetPrefixOffset(prefix));
this.AppendKey(key);
}
public void AppendDictionaryXmlnsAttribute(char prefix, int key)
{
this.AppendNode(XmlBinaryNodeType.DictionaryXmlnsAttribute);
this.AppendUtf8(prefix);
this.AppendKey(key);
}
public void AppendPrefixDictionaryAttribute(char prefix, int key, char value)
{
this.AppendNode(XmlBinaryNodeType.PrefixDictionaryAttributeA + GetPrefixOffset(prefix));
this.AppendKey(key);
if (value == '1')
{
this.AppendNode(XmlBinaryNodeType.OneText);
}
else
{
this.AppendNode(XmlBinaryNodeType.Chars8Text);
this.AppendUtf8(value);
}
}
public void AppendDictionaryAttribute(char prefix, int key, char value)
{
this.AppendNode(XmlBinaryNodeType.DictionaryAttribute);
this.AppendUtf8(prefix);
this.AppendKey(key);
this.AppendNode(XmlBinaryNodeType.Chars8Text);
this.AppendUtf8(value);
}
public void AppendDictionaryTextWithEndElement(int key)
{
this.AppendNode(XmlBinaryNodeType.DictionaryTextWithEndElement);
this.AppendKey(key);
}
public void AppendDictionaryTextWithEndElement()
{
this.AppendNode(XmlBinaryNodeType.DictionaryTextWithEndElement);
}
public void AppendUniqueIDWithEndElement()
{
this.AppendNode(XmlBinaryNodeType.UniqueIdTextWithEndElement);
}
public void AppendEndElement()
{
this.AppendNode(XmlBinaryNodeType.EndElement);
}
void AppendKey(int key)
{
if (key < 0 || key >= 0x4000)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("key", key,
SR.GetString(SR.ValueMustBeInRange, 0, 0x4000)));
}
if (key >= 0x80)
{
this.AppendByte((key & 0x7f) | 0x80);
this.AppendByte(key >> 7);
}
else
{
this.AppendByte(key);
}
}
void AppendNode(XmlBinaryNodeType value)
{
this.AppendByte((int)value);
}
void AppendByte(int value)
{
if (value < 0 || value > 0xFF)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeInRange, 0, 0xFF)));
}
this.bytes.Add((byte)value);
}
void AppendUtf8(char value)
{
AppendByte(1);
AppendByte((int)value);
}
public int GetStaticKey(int value)
{
return value * 2;
}
public int GetSessionKey(int value)
{
return value * 2 + 1;
}
int GetPrefixOffset(char prefix)
{
if (prefix < 'a' && prefix > 'z')
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("prefix", prefix,
SR.GetString(SR.ValueMustBeInRange, 'a', 'z')));
}
return prefix - 'a';
}
public byte[] ToByteArray()
{
byte[] array = this.bytes.ToArray();
this.bytes.Clear();
return array;
}
}
static class BinaryFormatParser
{
public static bool IsSessionKey(int value)
{
return (value & 1) != 0;
}
public static int GetSessionKey(int value)
{
return value / 2;
}
public static int GetStaticKey(int value)
{
return value / 2;
}
public static int ParseInt32(byte[] buffer, int offset, int size)
{
switch (size)
{
case 1:
return buffer[offset];
case 2:
return (buffer[offset] & 0x7f) + (buffer[offset + 1] << 7);
case 3:
return (buffer[offset] & 0x7f) + ((buffer[offset + 1] & 0x7f) << 7) + (buffer[offset + 2] << 14);
case 4:
return (buffer[offset] & 0x7f) + ((buffer[offset + 1] & 0x7f) << 7) + ((buffer[offset + 2] & 0x7f) << 14) + (buffer[offset + 3] << 21);
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("size", size,
SR.GetString(SR.ValueMustBeInRange, 1, 4)));
}
}
public static int ParseKey(byte[] buffer, int offset, int size)
{
return ParseInt32(buffer, offset, size);
}
public unsafe static UniqueId ParseUniqueID(byte[] buffer, int offset, int size)
{
return new UniqueId(buffer, offset);
}
public static int MatchBytes(byte[] buffer, int offset, int size, byte[] buffer2)
{
if (size < buffer2.Length)
{
return 0;
}
int j = offset;
for (int i = 0; i < buffer2.Length; i++, j++)
{
if (buffer2[i] != buffer[j])
{
return 0;
}
}
return buffer2.Length;
}
public static bool MatchAttributeNode(byte[] buffer, int offset, int size)
{
const XmlBinaryNodeType minAttribute = XmlBinaryNodeType.ShortAttribute;
const XmlBinaryNodeType maxAttribute = XmlBinaryNodeType.DictionaryAttribute;
if (size < 1)
{
return false;
}
XmlBinaryNodeType nodeType = (XmlBinaryNodeType)buffer[offset];
return nodeType >= minAttribute && nodeType <= maxAttribute;
}
public static int MatchKey(byte[] buffer, int offset, int size)
{
return MatchInt32(buffer, offset, size);
}
public static int MatchInt32(byte[] buffer, int offset, int size)
{
if (size > 0)
{
if ((buffer[offset] & 0x80) == 0)
{
return 1;
}
}
if (size > 1)
{
if ((buffer[offset + 1] & 0x80) == 0)
{
return 2;
}
}
if (size > 2)
{
if ((buffer[offset + 2] & 0x80) == 0)
{
return 3;
}
}
if (size > 3)
{
if ((buffer[offset + 3] & 0x80) == 0)
{
return 4;
}
}
return 0;
}
public static int MatchUniqueID(byte[] buffer, int offset, int size)
{
if (size < 16)
{
return 0;
}
return 16;
}
}
class MessagePatterns
{
static readonly byte[] commonFragment; // <Envelope><Headers><Action>
static readonly byte[] requestFragment1; // </Action><MessageID>
static readonly byte[] requestFragment2; // </MessageID><ReplyTo>...</ReplyTo><To>session-to-key</To></Headers><Body>
static readonly byte[] responseFragment1; // </Action><RelatesTo>
static readonly byte[] responseFragment2; // </RelatesTo><To>static-anonymous-key</To></Headers><Body>
static readonly byte[] bodyFragment; // <Envelope><Body>
const int ToValueSessionKey = 1;
IXmlDictionary dictionary;
XmlBinaryReaderSession readerSession;
ToHeader toHeader;
MessageVersion messageVersion;
static MessagePatterns()
{
BinaryFormatBuilder builder = new BinaryFormatBuilder();
MessageDictionary messageDictionary = XD.MessageDictionary;
Message12Dictionary message12Dictionary = XD.Message12Dictionary;
AddressingDictionary addressingDictionary = XD.AddressingDictionary;
Addressing10Dictionary addressing10Dictionary = XD.Addressing10Dictionary;
char messagePrefix = MessageStrings.Prefix[0];
char addressingPrefix = AddressingStrings.Prefix[0];
// <s:Envelope xmlns:s="soap-ns" xmlns="addressing-ns">
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Envelope.Key));
builder.AppendDictionaryXmlnsAttribute(messagePrefix, builder.GetStaticKey(message12Dictionary.Namespace.Key));
builder.AppendDictionaryXmlnsAttribute(addressingPrefix, builder.GetStaticKey(addressing10Dictionary.Namespace.Key));
// <s:Header>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Header.Key));
// <a:Action>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.Action.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement();
commonFragment = builder.ToByteArray();
// <a:MessageID>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.MessageId.Key));
builder.AppendUniqueIDWithEndElement();
requestFragment1 = builder.ToByteArray();
// <a:ReplyTo><a:Address>static-anonymous-key</a:Address></a:ReplyTo>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.ReplyTo.Key));
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.Address.Key));
builder.AppendDictionaryTextWithEndElement(builder.GetStaticKey(addressing10Dictionary.Anonymous.Key));
builder.AppendEndElement();
// <a:To>session-to-key</a:To>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.To.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement(builder.GetSessionKey(ToValueSessionKey));
// </s:Header>
builder.AppendEndElement();
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
requestFragment2 = builder.ToByteArray();
// <a:RelatesTo>...
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.RelatesTo.Key));
builder.AppendUniqueIDWithEndElement();
responseFragment1 = builder.ToByteArray();
// <a:To>static-anonymous-key</a:To>
builder.AppendPrefixDictionaryElement(addressingPrefix, builder.GetStaticKey(addressingDictionary.To.Key));
builder.AppendPrefixDictionaryAttribute(messagePrefix, builder.GetStaticKey(messageDictionary.MustUnderstand.Key), '1');
builder.AppendDictionaryTextWithEndElement(builder.GetStaticKey(addressing10Dictionary.Anonymous.Key));
// </s:Header>
builder.AppendEndElement();
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
responseFragment2 = builder.ToByteArray();
// <s:Envelope xmlns:s="soap-ns" xmlns="addressing-ns">
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Envelope.Key));
builder.AppendDictionaryXmlnsAttribute(messagePrefix, builder.GetStaticKey(message12Dictionary.Namespace.Key));
builder.AppendDictionaryXmlnsAttribute(addressingPrefix, builder.GetStaticKey(addressing10Dictionary.Namespace.Key));
// <s:Body>
builder.AppendPrefixDictionaryElement(messagePrefix, builder.GetStaticKey(messageDictionary.Body.Key));
bodyFragment = builder.ToByteArray();
}
public MessagePatterns(IXmlDictionary dictionary, XmlBinaryReaderSession readerSession, MessageVersion messageVersion)
{
this.dictionary = dictionary;
this.readerSession = readerSession;
this.messageVersion = messageVersion;
}
public Message TryCreateMessage(byte[] buffer, int offset, int size, BufferManager bufferManager, BufferedMessageData messageData)
{
RelatesToHeader relatesToHeader;
MessageIDHeader messageIDHeader;
XmlDictionaryString toString;
int currentOffset = offset;
int remainingSize = size;
int bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, commonFragment);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchKey(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int actionOffset = currentOffset;
int actionSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
int totalBytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, requestFragment1);
if (bytesMatched != 0)
{
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchUniqueID(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int messageIDOffset = currentOffset;
int messageIDSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, requestFragment2);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
if (BinaryFormatParser.MatchAttributeNode(buffer, currentOffset, remainingSize))
{
return null;
}
UniqueId messageId = BinaryFormatParser.ParseUniqueID(buffer, messageIDOffset, messageIDSize);
messageIDHeader = MessageIDHeader.Create(messageId, messageVersion.Addressing);
relatesToHeader = null;
if (!readerSession.TryLookup(ToValueSessionKey, out toString))
{
return null;
}
totalBytesMatched = requestFragment1.Length + messageIDSize + requestFragment2.Length;
}
else
{
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, responseFragment1);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchUniqueID(buffer, currentOffset, remainingSize);
if (bytesMatched == 0)
{
return null;
}
int messageIDOffset = currentOffset;
int messageIDSize = bytesMatched;
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
bytesMatched = BinaryFormatParser.MatchBytes(buffer, currentOffset, remainingSize, responseFragment2);
if (bytesMatched == 0)
{
return null;
}
currentOffset += bytesMatched;
remainingSize -= bytesMatched;
if (BinaryFormatParser.MatchAttributeNode(buffer, currentOffset, remainingSize))
{
return null;
}
UniqueId messageId = BinaryFormatParser.ParseUniqueID(buffer, messageIDOffset, messageIDSize);
relatesToHeader = RelatesToHeader.Create(messageId, messageVersion.Addressing);
messageIDHeader = null;
toString = XD.Addressing10Dictionary.Anonymous;
totalBytesMatched = responseFragment1.Length + messageIDSize + responseFragment2.Length;
}
totalBytesMatched += commonFragment.Length + actionSize;
int actionKey = BinaryFormatParser.ParseKey(buffer, actionOffset, actionSize);
XmlDictionaryString actionString;
if (!TryLookupKey(actionKey, out actionString))
{
return null;
}
ActionHeader actionHeader = ActionHeader.Create(actionString, messageVersion.Addressing);
if (toHeader == null)
{
toHeader = ToHeader.Create(new Uri(toString.Value), messageVersion.Addressing);
}
int abandonedSize = totalBytesMatched - bodyFragment.Length;
offset += abandonedSize;
size -= abandonedSize;
Buffer.BlockCopy(bodyFragment, 0, buffer, offset, bodyFragment.Length);
messageData.Open(new ArraySegment<byte>(buffer, offset, size), bufferManager);
PatternMessage patternMessage = new PatternMessage(messageData, this.messageVersion);
MessageHeaders headers = patternMessage.Headers;
headers.AddActionHeader(actionHeader);
if (messageIDHeader != null)
{
headers.AddMessageIDHeader(messageIDHeader);
headers.AddReplyToHeader(ReplyToHeader.AnonymousReplyTo10);
}
else
{
headers.AddRelatesToHeader(relatesToHeader);
}
headers.AddToHeader(toHeader);
return patternMessage;
}
bool TryLookupKey(int key, out XmlDictionaryString result)
{
if (BinaryFormatParser.IsSessionKey(key))
{
return readerSession.TryLookup(BinaryFormatParser.GetSessionKey(key), out result);
}
else
{
return dictionary.TryLookup(BinaryFormatParser.GetStaticKey(key), out result);
}
}
sealed class PatternMessage : ReceivedMessage
{
IBufferedMessageData messageData;
MessageHeaders headers;
RecycledMessageState recycledMessageState;
MessageProperties properties;
XmlDictionaryReader reader;
public PatternMessage(IBufferedMessageData messageData, MessageVersion messageVersion)
{
this.messageData = messageData;
recycledMessageState = messageData.TakeMessageState();
if (recycledMessageState == null)
{
recycledMessageState = new RecycledMessageState();
}
properties = recycledMessageState.TakeProperties();
if (properties == null)
{
this.properties = new MessageProperties();
}
headers = recycledMessageState.TakeHeaders();
if (headers == null)
{
headers = new MessageHeaders(messageVersion);
}
else
{
headers.Init(messageVersion);
}
XmlDictionaryReader reader = messageData.GetMessageReader();
reader.ReadStartElement();
VerifyStartBody(reader, messageVersion.Envelope);
ReadStartBody(reader);
this.reader = reader;
}
public PatternMessage(IBufferedMessageData messageData, MessageVersion messageVersion,
KeyValuePair<string, object>[] properties, MessageHeaders headers)
{
this.messageData = messageData;
this.messageData.Open();
this.recycledMessageState = this.messageData.TakeMessageState();
if (this.recycledMessageState == null)
{
this.recycledMessageState = new RecycledMessageState();
}
this.properties = recycledMessageState.TakeProperties();
if (this.properties == null)
{
this.properties = new MessageProperties();
}
if (properties != null)
{
this.properties.CopyProperties(properties);
}
this.headers = recycledMessageState.TakeHeaders();
if (this.headers == null)
{
this.headers = new MessageHeaders(messageVersion);
}
if (headers != null)
{
this.headers.CopyHeadersFrom(headers);
}
XmlDictionaryReader reader = messageData.GetMessageReader();
reader.ReadStartElement();
VerifyStartBody(reader, messageVersion.Envelope);
ReadStartBody(reader);
this.reader = reader;
}
public override MessageHeaders Headers
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return headers;
}
}
public override MessageProperties Properties
{
get
{
if (IsDisposed)
#pragma warning suppress 56503 // [....], Invalid State after dispose
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return properties;
}
}
public override MessageVersion Version
{
get
{
if (IsDisposed)
{
#pragma warning suppress 56503 // [....], Invalid State after dispose
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateMessageDisposedException());
}
return headers.MessageVersion;
}
}
internal override RecycledMessageState RecycledMessageState
{
get { return recycledMessageState; }
}
XmlDictionaryReader GetBufferedReaderAtBody()
{
XmlDictionaryReader reader = messageData.GetMessageReader();
reader.ReadStartElement();
reader.ReadStartElement();
return reader;
}
protected override void OnBodyToString(XmlDictionaryWriter writer)
{
using (XmlDictionaryReader reader = GetBufferedReaderAtBody())
{
while (reader.NodeType != XmlNodeType.EndElement)
{
writer.WriteNode(reader, false);
}
}
}
protected override void OnClose()
{
Exception ex = null;
try
{
base.OnClose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
ex = e;
}
try
{
properties.Dispose();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
try
{
if (reader != null)
{
reader.Close();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
try
{
recycledMessageState.ReturnHeaders(headers);
recycledMessageState.ReturnProperties(properties);
messageData.ReturnMessageState(recycledMessageState);
recycledMessageState = null;
messageData.Close();
messageData = null;
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
if (ex == null)
{
ex = e;
}
}
if (ex != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
}
}
protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize)
{
KeyValuePair<string, object>[] properties = new KeyValuePair<string, object>[Properties.Count];
((ICollection<KeyValuePair<string, object>>)Properties).CopyTo(properties, 0);
messageData.EnableMultipleUsers();
return new PatternMessageBuffer(this.messageData, this.Version, properties, this.headers);
}
protected override XmlDictionaryReader OnGetReaderAtBodyContents()
{
XmlDictionaryReader reader = this.reader;
this.reader = null;
return reader;
}
protected override string OnGetBodyAttribute(string localName, string ns)
{
return null;
}
}
class PatternMessageBuffer : MessageBuffer
{
bool closed;
MessageHeaders headers;
IBufferedMessageData messageDataAtBody;
MessageVersion messageVersion;
KeyValuePair<string, object>[] properties;
object thisLock = new object();
RecycledMessageState recycledMessageState;
public PatternMessageBuffer(IBufferedMessageData messageDataAtBody, MessageVersion messageVersion,
KeyValuePair<string, object>[] properties, MessageHeaders headers)
{
this.messageDataAtBody = messageDataAtBody;
this.messageDataAtBody.Open();
this.recycledMessageState = this.messageDataAtBody.TakeMessageState();
if (this.recycledMessageState == null)
{
this.recycledMessageState = new RecycledMessageState();
}
this.headers = this.recycledMessageState.TakeHeaders();
if (this.headers == null)
{
this.headers = new MessageHeaders(messageVersion);
}
this.headers.CopyHeadersFrom(headers);
this.properties = properties;
this.messageVersion = messageVersion;
}
public override int BufferSize
{
get
{
lock (this.ThisLock)
{
if (this.closed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException());
}
return messageDataAtBody.Buffer.Count;
}
}
}
object ThisLock
{
get
{
return this.thisLock;
}
}
public override void Close()
{
lock (this.thisLock)
{
if (!this.closed)
{
this.closed = true;
this.recycledMessageState.ReturnHeaders(this.headers);
this.messageDataAtBody.ReturnMessageState(this.recycledMessageState);
this.messageDataAtBody.Close();
this.recycledMessageState = null;
this.messageDataAtBody = null;
this.properties = null;
this.messageVersion = null;
this.headers = null;
}
}
}
public override Message CreateMessage()
{
lock (this.ThisLock)
{
if (this.closed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateBufferDisposedException());
}
return new PatternMessage(this.messageDataAtBody, this.messageVersion, this.properties,
this.headers);
}
}
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.AbstractDomains;
namespace Microsoft.Research.CodeAnalysis
{
class BooleanExpressionsSimplificator
{
public static BoxedExpression Simplify<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>
(
BoxedExpression exp,
INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> oracle,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver
)
where Expression : IEquatable<Expression>
where Variable : IEquatable<Variable>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
{
BoxedExpression simplified;
SimplifyInternal(exp, oracle, mdriver, out simplified);
return simplified;
}
private static ProofOutcome SimplifyInternal<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>
(
BoxedExpression exp,
INumericalAbstractDomain<BoxedVariable<Variable>, BoxedExpression> oracle,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
out BoxedExpression simplified
)
where Expression : IEquatable<Expression>
where Variable : IEquatable<Variable>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
{
BinaryOperator bop;
BoxedExpression left, right;
if (exp.IsBinaryExpression(out bop, out left, out right))
{
BoxedExpression simplifiedLeft, simplifiedRight;
switch (bop)
{
case BinaryOperator.LogicalAnd:
{
var tLeft = SimplifyInternal(left, oracle, mdriver, out simplifiedLeft);
if (tLeft == ProofOutcome.False)
{
simplified = BoxedExpression.Const(0, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.False;
}
var tRight = SimplifyInternal(right, oracle, mdriver, out simplifiedRight);
if (tRight == ProofOutcome.False)
{
simplified = BoxedExpression.Const(0, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.False;
}
if (tLeft == ProofOutcome.True)
{
simplified = simplifiedRight;
return tRight;
}
if (tRight == ProofOutcome.True)
{
simplified = simplifiedLeft;
return tLeft;
}
simplified = BoxedExpression.BinaryLogicalAnd(simplifiedLeft, simplifiedRight);
return ProofOutcome.Top;
}
case BinaryOperator.LogicalOr:
{
var tLeft = SimplifyInternal(left, oracle, mdriver, out simplifiedLeft);
if (tLeft == ProofOutcome.True)
{
simplified = BoxedExpression.Const(1, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.True;
}
var tRight = SimplifyInternal(right, oracle, mdriver, out simplifiedRight);
if (tRight == ProofOutcome.True)
{
simplified = BoxedExpression.Const(1, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.True;
}
if (tLeft == ProofOutcome.False)
{
simplified = simplifiedRight;
return tRight;
}
if (tRight == ProofOutcome.False)
{
simplified = simplifiedLeft;
return tLeft;
}
simplified = BoxedExpression.BinaryLogicalOr(simplifiedLeft, simplifiedRight);
return ProofOutcome.Top;
}
case BinaryOperator.Ceq:
{
var r = oracle.CheckIfEqual(left, right);
return ProcessOutcome(r, exp, mdriver, out simplified);
}
case BinaryOperator.Cge:
case BinaryOperator.Cge_Un:
{
var r = oracle.CheckIfLessEqualThan(right, left);
return ProcessOutcome(r, exp, mdriver, out simplified);
}
case BinaryOperator.Cgt:
case BinaryOperator.Cgt_Un:
{
var r = oracle.CheckIfLessThan(right, left);
return ProcessOutcome(r, exp, mdriver, out simplified);
}
case BinaryOperator.Cle:
case BinaryOperator.Cle_Un:
{
var r = oracle.CheckIfLessEqualThan(left, right);
return ProcessOutcome(r, exp, mdriver, out simplified);
}
case BinaryOperator.Clt:
case BinaryOperator.Clt_Un:
{
var r = oracle.CheckIfLessThan(left, right);
return ProcessOutcome(r, exp, mdriver, out simplified);
}
case BinaryOperator.Cne_Un:
{
var r1 = oracle.CheckIfLessThan(left, right);
if (r1.IsNormal())
{
simplified = BoxedExpression.Const(1, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.True;
}
var r2 = oracle.CheckIfLessThan(right, left);
if (r2.IsNormal())
{
simplified = BoxedExpression.Const(1, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.True;
}
simplified = exp;
return ProofOutcome.Top;
}
}
}
if (exp.IsUnary)
{
var r = oracle.CheckIfHolds(exp);
if (r.IsTrue())
{
simplified = BoxedExpression.Const(1, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.True;
}
if (r.IsFalse())
{
simplified = BoxedExpression.Const(0, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.False;
}
}
simplified = exp;
return ProofOutcome.Top;
}
private static ProofOutcome ProcessOutcome<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>
(
FlatAbstractDomain<bool> result,
BoxedExpression exp,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mdriver,
out BoxedExpression simplified
)
where Expression : IEquatable<Expression>
where Variable : IEquatable<Variable>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
{
if (result.IsTrue())
{
simplified = BoxedExpression.Const(1, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.True;
}
if (result.IsFalse())
{
simplified = BoxedExpression.Const(0, mdriver.MetaDataDecoder.System_Boolean, mdriver.MetaDataDecoder);
return ProofOutcome.False;
}
simplified = exp;
return ProofOutcome.Top;
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class StartRecordingRequestEncoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 4;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private StartRecordingRequestEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public StartRecordingRequestEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public StartRecordingRequestEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public StartRecordingRequestEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public StartRecordingRequestEncoder ControlSessionId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public StartRecordingRequestEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int StreamIdEncodingOffset()
{
return 16;
}
public static int StreamIdEncodingLength()
{
return 4;
}
public static int StreamIdNullValue()
{
return -2147483648;
}
public static int StreamIdMinValue()
{
return -2147483647;
}
public static int StreamIdMaxValue()
{
return 2147483647;
}
public StartRecordingRequestEncoder StreamId(int value)
{
_buffer.PutInt(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int SourceLocationEncodingOffset()
{
return 20;
}
public static int SourceLocationEncodingLength()
{
return 4;
}
public StartRecordingRequestEncoder SourceLocation(SourceLocation value)
{
_buffer.PutInt(_offset + 20, (int)value, ByteOrder.LittleEndian);
return this;
}
public static int ChannelId()
{
return 5;
}
public static string ChannelCharacterEncoding()
{
return "US-ASCII";
}
public static string ChannelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static int ChannelHeaderLength()
{
return 4;
}
public StartRecordingRequestEncoder PutChannel(IDirectBuffer src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public StartRecordingRequestEncoder PutChannel(byte[] src, int srcOffset, int length)
{
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutBytes(limit + headerLength, src, srcOffset, length);
return this;
}
public StartRecordingRequestEncoder Channel(string value)
{
int length = value.Length;
if (length > 1073741824)
{
throw new InvalidOperationException("length > maxValue for type: " + length);
}
int headerLength = 4;
int limit = _parentMessage.Limit();
_parentMessage.Limit(limit + headerLength + length);
_buffer.PutInt(limit, unchecked((int)length), ByteOrder.LittleEndian);
_buffer.PutStringWithoutLengthAscii(limit + headerLength, value);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
StartRecordingRequestDecoder writer = new StartRecordingRequestDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
using System.Linq;
using System.Reactive.Subjects;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Shapes;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class ComboBoxTests
{
MouseTestHelper _helper = new MouseTestHelper();
[Fact]
public void Clicking_On_Control_Toggles_IsDropDownOpen()
{
var target = new ComboBox
{
Items = new[] { "Foo", "Bar" },
};
_helper.Down(target);
_helper.Up(target);
Assert.True(target.IsDropDownOpen);
_helper.Down(target);
_helper.Up(target);
Assert.False(target.IsDropDownOpen);
}
[Fact]
public void SelectionBoxItem_Is_Rectangle_With_VisualBrush_When_Selection_Is_Control()
{
var items = new[] { new Canvas() };
var target = new ComboBox
{
Items = items,
SelectedIndex = 0,
};
var root = new TestRoot(target);
var rectangle = target.GetValue(ComboBox.SelectionBoxItemProperty) as Rectangle;
Assert.NotNull(rectangle);
var brush = rectangle.Fill as VisualBrush;
Assert.NotNull(brush);
Assert.Same(items[0], brush.Visual);
}
[Fact]
public void SelectionBoxItem_Rectangle_Is_Removed_From_Logical_Tree()
{
var target = new ComboBox
{
Items = new[] { new Canvas() },
SelectedIndex = 0,
Template = GetTemplate(),
};
var root = new TestRoot { Child = target };
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var rectangle = target.GetValue(ComboBox.SelectionBoxItemProperty) as Rectangle;
Assert.True(((ILogical)target).IsAttachedToLogicalTree);
Assert.True(((ILogical)rectangle).IsAttachedToLogicalTree);
rectangle.DetachedFromLogicalTree += (s, e) => { };
root.Child = null;
Assert.False(((ILogical)target).IsAttachedToLogicalTree);
Assert.False(((ILogical)rectangle).IsAttachedToLogicalTree);
}
private FuncControlTemplate GetTemplate()
{
return new FuncControlTemplate<ComboBox>((parent, scope) =>
{
return new Panel
{
Name = "container",
Children =
{
new ContentControl
{
[!ContentControl.ContentProperty] = parent[!ComboBox.SelectionBoxItemProperty],
},
new ToggleButton
{
Name = "toggle",
}.RegisterInNameScope(scope),
new Popup
{
Name = "PART_Popup",
Child = new ItemsPresenter
{
Name = "PART_ItemsPresenter",
[!ItemsPresenter.ItemsProperty] = parent[!ComboBox.ItemsProperty],
}.RegisterInNameScope(scope)
}.RegisterInNameScope(scope)
}
};
});
}
[Fact]
public void Detaching_Closed_ComboBox_Keeps_Current_Focus()
{
using (UnitTestApplication.Start(TestServices.RealFocus))
{
var target = new ComboBox
{
Items = new[] { new Canvas() },
SelectedIndex = 0,
Template = GetTemplate(),
};
var other = new Control { Focusable = true };
StackPanel panel;
var root = new TestRoot { Child = panel = new StackPanel { Children = { target, other } } };
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
other.Focus();
Assert.True(other.IsFocused);
panel.Children.Remove(target);
Assert.True(other.IsFocused);
}
}
[Theory]
[InlineData(-1, 2, "c", "A item", "B item", "C item")]
[InlineData(0, 1, "b", "A item", "B item", "C item")]
[InlineData(2, 2, "x", "A item", "B item", "C item")]
public void TextSearch_Should_Have_Expected_SelectedIndex(
int initialSelectedIndex,
int expectedSelectedIndex,
string searchTerm,
params string[] items)
{
using (UnitTestApplication.Start(TestServices.MockThreadingInterface))
{
var target = new ComboBox
{
Template = GetTemplate(),
Items = items.Select(x => new ComboBoxItem { Content = x })
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
target.SelectedIndex = initialSelectedIndex;
var args = new TextInputEventArgs
{
Text = searchTerm,
RoutedEvent = InputElement.TextInputEvent
};
target.RaiseEvent(args);
Assert.Equal(expectedSelectedIndex, target.SelectedIndex);
}
}
[Fact]
public void SelectedItem_Validation()
{
using (UnitTestApplication.Start(TestServices.MockThreadingInterface))
{
var target = new ComboBox
{
Template = GetTemplate(),
VirtualizationMode = ItemVirtualizationMode.None
};
target.ApplyTemplate();
target.Presenter.ApplyTemplate();
var exception = new System.InvalidCastException("failed validation");
var textObservable = new BehaviorSubject<BindingNotification>(new BindingNotification(exception, BindingErrorType.DataValidationError));
target.Bind(ComboBox.SelectedItemProperty, textObservable);
Assert.True(DataValidationErrors.GetHasErrors(target));
Assert.True(DataValidationErrors.GetErrors(target).SequenceEqual(new[] { exception }));
}
}
[Fact]
public void Close_Window_On_Alt_F4_When_ComboBox_Is_Focus()
{
var inputManagerMock = new Moq.Mock<IInputManager>();
var services = TestServices.StyledWindow.With(inputManager: inputManagerMock.Object);
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var window = new Window();
window.KeyDown += (s, e) =>
{
if (e.Handled == false
&& e.KeyModifiers.HasAllFlags(KeyModifiers.Alt) == true
&& e.Key == Key.F4 )
{
e.Handled = true;
window.Close();
}
};
var count = 0;
var target = new ComboBox
{
Items = new[] { new Canvas() },
SelectedIndex = 0,
Template = GetTemplate(),
};
window.Content = target;
window.Closing +=
(sender, e) =>
{
count++;
};
window.Show();
target.Focus();
_helper.Down(target);
_helper.Up(target);
Assert.True(target.IsDropDownOpen);
target.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
KeyModifiers = KeyModifiers.Alt,
Key = Key.F4
});
Assert.Equal(1, count);
}
}
}
}
| |
//
// 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.WindowsAzure.Management.Store;
using Microsoft.WindowsAzure.Management.Store.Models;
namespace Microsoft.WindowsAzure.Management.Store
{
/// <summary>
/// Provides REST operations for working with Store add-ins from the
/// Windows Azure store service.
/// </summary>
public static partial class AddOnOperationsExtensions
{
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The add on name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static AddOnOperationStatusResponse BeginCreating(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
try
{
return operations.BeginCreatingAsync(cloudServiceName, resourceName, addOnName, parameters).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 1)
{
throw;
}
else
{
throw ex.InnerException;
}
}
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The add on name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<AddOnOperationStatusResponse> BeginCreatingAsync(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
return operations.BeginCreatingAsync(cloudServiceName, resourceName, addOnName, parameters, CancellationToken.None);
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Store entries
/// that re provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static AddOnOperationStatusResponse BeginDeleting(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
try
{
return operations.BeginDeletingAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 1)
{
throw;
}
else
{
throw ex.InnerException;
}
}
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Store entries
/// that re provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<AddOnOperationStatusResponse> BeginDeletingAsync(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
return operations.BeginDeletingAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName, CancellationToken.None);
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The add on name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static AddOnOperationStatusResponse Create(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
try
{
return operations.CreateAsync(cloudServiceName, resourceName, addOnName, parameters).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 1)
{
throw;
}
else
{
throw ex.InnerException;
}
}
}
/// <summary>
/// The Create Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The add on name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<AddOnOperationStatusResponse> CreateAsync(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnCreateParameters parameters)
{
return operations.CreateAsync(cloudServiceName, resourceName, addOnName, parameters, CancellationToken.None);
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Storeentries
/// that are provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static AddOnOperationStatusResponse Delete(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
try
{
return operations.DeleteAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 1)
{
throw;
}
else
{
throw ex.InnerException;
}
}
}
/// <summary>
/// The Delete Store Item operation deletes Windows Azure Storeentries
/// that are provisioned for a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceProviderNamespace'>
/// The namespace in which this store item resides.
/// </param>
/// <param name='resourceProviderType'>
/// The type of store item to be deleted.
/// </param>
/// <param name='resourceProviderName'>
/// The name of this resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<AddOnOperationStatusResponse> DeleteAsync(this IAddOnOperations operations, string cloudServiceName, string resourceProviderNamespace, string resourceProviderType, string resourceProviderName)
{
return operations.DeleteAsync(cloudServiceName, resourceProviderNamespace, resourceProviderType, resourceProviderName, CancellationToken.None);
}
/// <summary>
/// The Update Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The addon name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static AddOnOperationStatusResponse Update(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnUpdateParameters parameters)
{
try
{
return operations.UpdateAsync(cloudServiceName, resourceName, addOnName, parameters).Result;
}
catch (AggregateException ex)
{
if (ex.InnerExceptions.Count > 1)
{
throw;
}
else
{
throw ex.InnerException;
}
}
}
/// <summary>
/// The Update Store Item operation creates Windows Azure Store entries
/// in a Windows Azure subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Store.IAddOnOperations.
/// </param>
/// <param name='cloudServiceName'>
/// The name of the cloud service to which this store item will be
/// assigned.
/// </param>
/// <param name='resourceName'>
/// The name of this resource.
/// </param>
/// <param name='addOnName'>
/// The addon name.
/// </param>
/// <param name='parameters'>
/// Parameters used to specify how the Create procedure will function.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public static Task<AddOnOperationStatusResponse> UpdateAsync(this IAddOnOperations operations, string cloudServiceName, string resourceName, string addOnName, AddOnUpdateParameters parameters)
{
return operations.UpdateAsync(cloudServiceName, resourceName, addOnName, parameters, CancellationToken.None);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Cassandra.Mapping.Utils;
using Cassandra.Serialization;
namespace Cassandra.Mapping.Statements
{
/// <summary>
/// A utility class capable of generating CQL statements for a POCO.
/// </summary>
internal class CqlGenerator
{
private const string CannotGenerateStatementForPoco = "Cannot create {0} statement for POCO of type {1}";
private const string NoColumns = CannotGenerateStatementForPoco + " because it has no columns";
private const string MissingPkColumns = CannotGenerateStatementForPoco + " because it is missing PK columns {2}. " +
"Are you missing a property/field on the POCO or did you forget to specify " +
"the PK columns in the mapping?";
private static readonly Regex SelectRegex = new Regex(@"\A\s*SELECT\s", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex FromRegex = new Regex(@"\A\s*FROM\s", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly PocoDataFactory _pocoDataFactory;
private static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
public CqlGenerator(PocoDataFactory pocoDataFactory)
{
if (pocoDataFactory == null) throw new ArgumentNullException("pocoDataFactory");
_pocoDataFactory = pocoDataFactory;
}
/// <summary>
/// Adds "SELECT columnlist" and "FROM tablename" to a CQL statement if they don't already exist for a POCO of Type T.
/// </summary>
public void AddSelect<T>(Cql cql)
{
// If it's already got a SELECT clause, just bail
if (SelectRegex.IsMatch(cql.Statement))
return;
// Get the PocoData so we can generate a list of columns
var pocoData = _pocoDataFactory.GetPocoData<T>();
var allColumns = pocoData.Columns.Select(Escape(pocoData)).ToCommaDelimitedString();
// If it's got the from clause, leave FROM intact, otherwise add it
cql.SetStatement(FromRegex.IsMatch(cql.Statement)
? string.Format("SELECT {0} {1}", allColumns, cql.Statement)
: string.Format("SELECT {0} FROM {1} {2}", allColumns, Escape(pocoData.TableName, pocoData), cql.Statement));
}
/// <summary>
/// Escapes an identier if necessary
/// </summary>
private static string Escape(string identifier, PocoData pocoData)
{
if (!pocoData.CaseSensitive)
{
return identifier;
}
return "\"" + identifier + "\"";
}
private static Func<PocoColumn, string> Escape(PocoData pocoData)
{
Func<PocoColumn, string> f = c => Escape(c.ColumnName, pocoData);
return f;
}
private static Func<PocoColumn, string> Escape(PocoData pocoData, string format)
{
Func<PocoColumn, string> f = c => String.Format(format, Escape(c.ColumnName, pocoData));
return f;
}
/// <summary>
/// Generates an "INSERT INTO tablename (columns) VALUES (?...)" statement for a POCO of Type T.
/// </summary>
/// <param name="insertNulls">When set to <c>true</c>, it will only generate columns which POCO members are not null</param>
/// <param name="pocoValues">The parameters of this query, it will only be used if <c>insertNulls</c> is set to <c>true</c></param>
/// <param name="queryParameters">The parameters for this query. When insertNulls is <c>true</c>, the <c>pocoValues</c>
/// is the <c>queryParameters</c>, when set to <c>false</c> the <c>queryParameters do not include <c>null</c> values</c></param>
/// <param name="ifNotExists">Determines if it should add the IF NOT EXISTS at the end of the query</param>
/// <param name="ttl">Amount of seconds for the data to expire (TTL)</param>
/// <param name="timestamp">Data timestamp</param>
/// <param name="tableName">Table name. If null, it will use table name based on Poco Data</param>
/// <returns></returns>
public string GenerateInsert<T>(bool insertNulls, object[] pocoValues, out object[] queryParameters,
bool ifNotExists = false, int? ttl = null, DateTimeOffset? timestamp = null, string tableName = null)
{
var pocoData = _pocoDataFactory.GetPocoData<T>();
if (pocoData.Columns.Count == 0)
{
throw new InvalidOperationException(string.Format(NoColumns, "INSERT", typeof(T).Name));
}
string columns;
string placeholders;
var parameterList = new List<object>();
if (!insertNulls)
{
if (pocoValues == null)
{
throw new ArgumentNullException("pocoValues");
}
if (pocoValues.Length != pocoData.Columns.Count)
{
throw new ArgumentException("Values array should contain the same amount of items as POCO columns");
}
//only include columns which value is not null
var columnsBuilder = new StringBuilder();
var placeholdersBuilder = new StringBuilder();
for (var i = 0; i < pocoData.Columns.Count; i++)
{
var value = pocoValues[i];
if (value == null)
{
continue;
}
if (i > 0)
{
columnsBuilder.Append(", ");
placeholdersBuilder.Append(", ");
}
columnsBuilder.Append(Escape(pocoData)(pocoData.Columns[i]));
placeholdersBuilder.Append("?");
parameterList.Add(value);
}
columns = columnsBuilder.ToString();
placeholders = placeholdersBuilder.ToString();
}
else
{
//Include all columns defined in the Poco
columns = pocoData.Columns.Select(Escape(pocoData)).ToCommaDelimitedString();
placeholders = Enumerable.Repeat("?", pocoData.Columns.Count).ToCommaDelimitedString();
parameterList.AddRange(pocoValues);
}
var queryBuilder = new StringBuilder();
queryBuilder.Append("INSERT INTO ");
queryBuilder.Append(tableName ?? Escape(pocoData.TableName, pocoData));
queryBuilder.Append(" (");
queryBuilder.Append(columns);
queryBuilder.Append(") VALUES (");
queryBuilder.Append(placeholders);
queryBuilder.Append(")");
if (ifNotExists)
{
queryBuilder.Append(" IF NOT EXISTS");
}
if (ttl != null || timestamp != null)
{
queryBuilder.Append(" USING");
if (ttl != null)
{
queryBuilder.Append(" TTL ?");
parameterList.Add(ttl.Value);
if (timestamp != null)
{
queryBuilder.Append(" AND");
}
}
if (timestamp != null)
{
queryBuilder.Append(" TIMESTAMP ?");
parameterList.Add((timestamp.Value - UnixEpoch).Ticks / 10);
}
}
queryParameters = parameterList.ToArray();
return queryBuilder.ToString();
}
/// <summary>
/// Generates an "UPDATE tablename SET columns = ? WHERE pkColumns = ?" statement for a POCO of Type T.
/// </summary>
public string GenerateUpdate<T>()
{
var pocoData = _pocoDataFactory.GetPocoData<T>();
if (pocoData.Columns.Count == 0)
throw new InvalidOperationException(string.Format(NoColumns, "UPDATE", typeof(T).Name));
if (pocoData.MissingPrimaryKeyColumns.Count > 0)
{
throw new InvalidOperationException(string.Format(MissingPkColumns, "UPDATE", typeof(T).Name,
pocoData.MissingPrimaryKeyColumns.ToCommaDelimitedString()));
}
var nonPkColumns = pocoData.GetNonPrimaryKeyColumns().Select(Escape(pocoData, "{0} = ?")).ToCommaDelimitedString();
var pkColumns = string.Join(" AND ", pocoData.GetPrimaryKeyColumns().Select(Escape(pocoData, "{0} = ?")));
return string.Format("UPDATE {0} SET {1} WHERE {2}", Escape(pocoData.TableName, pocoData), nonPkColumns, pkColumns);
}
/// <summary>
/// Prepends the CQL statement specified with "UPDATE tablename " for a POCO of Type T.
/// </summary>
public void PrependUpdate<T>(Cql cql)
{
var pocoData = _pocoDataFactory.GetPocoData<T>();
cql.SetStatement(string.Format("UPDATE {0} {1}", Escape(pocoData.TableName, pocoData), cql.Statement));
}
/// <summary>
/// Generates a "DELETE FROM tablename WHERE pkcolumns = ?" statement for a POCO of Type T.
/// </summary>
public string GenerateDelete<T>()
{
var pocoData = _pocoDataFactory.GetPocoData<T>();
if (pocoData.Columns.Count == 0)
{
throw new InvalidOperationException(string.Format(NoColumns, "DELETE", typeof(T).Name));
}
if (pocoData.MissingPrimaryKeyColumns.Count > 0)
{
throw new InvalidOperationException(string.Format(MissingPkColumns, "DELETE", typeof(T).Name,
pocoData.MissingPrimaryKeyColumns.ToCommaDelimitedString()));
}
var pkColumns = String.Join(" AND ", pocoData.GetPrimaryKeyColumns().Select(Escape(pocoData, "{0} = ?")));
return string.Format("DELETE FROM {0} WHERE {1}", Escape(pocoData.TableName, pocoData), pkColumns);
}
/// <summary>
/// Prepends the CQL statement specified with "DELETE FROM tablename " for a POCO of Type T.
/// </summary>
public void PrependDelete<T>(Cql cql)
{
PocoData pocoData = _pocoDataFactory.GetPocoData<T>();
cql.SetStatement(string.Format("DELETE FROM {0} {1}", pocoData.TableName, cql.Statement));
}
private static string GetTypeString(Serializer serializer, PocoColumn column)
{
if (column.IsCounter)
{
return "counter";
}
IColumnInfo typeInfo;
var typeCode = serializer.GetCqlType(column.ColumnType, out typeInfo);
var typeName = GetTypeString(column, typeCode, typeInfo);
if (column.IsStatic)
{
return typeName + " static";
}
return typeName;
}
/// <summary>
/// Gets the CQL queries involved in a table creation (CREATE TABLE, CREATE INDEX)
/// </summary>
public static List<string> GetCreate(Serializer serializer, PocoData pocoData, string tableName, string keyspaceName, bool ifNotExists)
{
if (pocoData == null)
{
throw new ArgumentNullException("pocoData");
}
if (pocoData.MissingPrimaryKeyColumns.Count > 0)
{
throw new InvalidOperationException(string.Format(MissingPkColumns, "CREATE", pocoData.PocoType.Name,
pocoData.MissingPrimaryKeyColumns.ToCommaDelimitedString()));
}
var commands = new List<string>();
var secondaryIndexes = new List<string>();
var createTable = new StringBuilder("CREATE TABLE ");
tableName = Escape(tableName, pocoData);
if (keyspaceName != null)
{
//Use keyspace.tablename notation
tableName = Escape(keyspaceName, pocoData) + "." + tableName;
}
createTable.Append(tableName);
createTable.Append(" (");
foreach (var column in pocoData.Columns)
{
var columnName = Escape(column.ColumnName, pocoData);
createTable
.Append(columnName)
.Append(" ");
var columnType = GetTypeString(serializer, column);
createTable
.Append(columnType);
createTable
.Append(", ");
if (column.SecondaryIndex)
{
secondaryIndexes.Add(columnName);
}
}
createTable.Append("PRIMARY KEY (");
if (pocoData.PartitionKeys.Count == 0)
{
throw new InvalidOperationException("No partition key defined");
}
if (pocoData.PartitionKeys.Count == 1)
{
createTable.Append(Escape(pocoData.PartitionKeys[0].ColumnName, pocoData));
}
else
{
//tupled partition keys
createTable
.Append("(")
.Append(String.Join(", ", pocoData.PartitionKeys.Select(Escape(pocoData))))
.Append(")");
}
if (pocoData.ClusteringKeys.Count > 0)
{
createTable.Append(", ");
createTable.Append(String.Join(", ", pocoData.ClusteringKeys.Select(k => Escape(k.Item1.ColumnName, pocoData))));
}
//close primary keys
createTable.Append(")");
//close table column definition
createTable.Append(")");
var clusteringOrder = String.Join(", ", pocoData.ClusteringKeys
.Where(k => k.Item2 != SortOrder.Unspecified)
.Select(k => Escape(k.Item1.ColumnName, pocoData) + " " + (k.Item2 == SortOrder.Ascending ? "ASC" : "DESC")));
if (!String.IsNullOrEmpty(clusteringOrder))
{
createTable
.Append(" WITH CLUSTERING ORDER BY (")
.Append(clusteringOrder)
.Append(")");
}
if (pocoData.CompactStorage)
{
createTable.Append(" WITH COMPACT STORAGE");
}
commands.Add(createTable.ToString());
//Secondary index definitions
commands.AddRange(secondaryIndexes.Select(name => "CREATE INDEX ON " + tableName + " (" + name + ")"));
return commands;
}
private static string GetTypeString(PocoColumn column, ColumnTypeCode typeCode, IColumnInfo typeInfo)
{
if (typeInfo == null)
{
//Is a single type
return typeCode.ToString().ToLower();
}
string typeName = null;
var frozenKey = column != null && column.HasFrozenKey;
var frozenValue = column != null && column.HasFrozenValue;
if (typeInfo is MapColumnInfo)
{
var mapInfo = (MapColumnInfo) typeInfo;
typeName = "map<" +
WrapFrozen(frozenKey, GetTypeString(null, mapInfo.KeyTypeCode, mapInfo.KeyTypeInfo)) +
", " +
WrapFrozen(frozenValue, GetTypeString(null, mapInfo.ValueTypeCode, mapInfo.ValueTypeInfo)) +
">";
}
else if (typeInfo is SetColumnInfo)
{
var setInfo = (SetColumnInfo) typeInfo;
typeName = "set<" +
WrapFrozen(frozenKey, GetTypeString(null, setInfo.KeyTypeCode, setInfo.KeyTypeInfo)) +
">";
}
else if (typeInfo is ListColumnInfo)
{
var setInfo = (ListColumnInfo) typeInfo;
typeName = "list<" +
WrapFrozen(frozenValue, GetTypeString(null, setInfo.ValueTypeCode, setInfo.ValueTypeInfo)) +
">";
}
else if (typeInfo is TupleColumnInfo)
{
var tupleInfo = (TupleColumnInfo) typeInfo;
typeName = "tuple<" +
string.Join(", ", tupleInfo.Elements.Select(e => GetTypeString(null, e.TypeCode, e.TypeInfo))) +
">";
}
else if (typeInfo is UdtColumnInfo)
{
var udtInfo = (UdtColumnInfo) typeInfo;
typeName = udtInfo.Name;
}
if (typeName == null)
{
throw new NotSupportedException(string.Format("Type {0} is not supported", typeCode));
}
return WrapFrozen(column != null && column.IsFrozen, typeName);
}
private static string WrapFrozen(bool condition, string typeName)
{
if (condition)
{
return "frozen<" + typeName + ">";
}
return typeName;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace VehicleStatisticsApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Lists;
namespace osu.Framework.Graphics.Transforms
{
/// <summary>
/// Tracks the lifetime of transforms for one specified target member.
/// </summary>
internal class TargetGroupingTransformTracker
{
/// <summary>
/// A list of <see cref="Transform"/>s associated with the <see cref="TargetGrouping"/>.
/// </summary>
public IEnumerable<Transform> Transforms => transforms;
/// <summary>
/// The member this instance is tracking.
/// </summary>
public readonly string TargetGrouping;
private readonly SortedList<Transform> transforms = new SortedList<Transform>(Transform.COMPARER);
private readonly Transformable transformable;
private readonly Queue<Action> removalActions = new Queue<Action>();
/// <summary>
/// Used to assign a monotonically increasing ID to <see cref="Transform"/>s as they are added. This member is
/// incremented whenever a <see cref="Transform"/> is added.
/// </summary>
private ulong currentTransformID;
/// <summary>
/// The index of the last transform in <see cref="transforms"/> to be applied to completion.
/// </summary>
private readonly Dictionary<string, int> lastAppliedTransformIndices = new Dictionary<string, int>();
/// <summary>
/// All <see cref="Transform.TargetMember"/>s which are handled by this tracker.
/// </summary>
public IEnumerable<string> TargetMembers => targetMembers;
private readonly HashSet<string> targetMembers = new HashSet<string>();
public TargetGroupingTransformTracker(Transformable transformable, string targetGrouping)
{
TargetGrouping = targetGrouping;
this.transformable = transformable;
}
public void UpdateTransforms(in double time, bool rewinding)
{
if (rewinding && !transformable.RemoveCompletedTransforms)
{
resetLastAppliedCache();
var appliedToEndReverts = new List<string>();
// Under the case that completed transforms are not removed, reversing the clock is permitted.
// We need to first look back through all the transforms and apply the start values of the ones that were previously
// applied, but now exist in the future relative to the current time.
for (int i = transforms.Count - 1; i >= 0; i--)
{
var t = transforms[i];
// rewind logic needs to only run on transforms which have been applied at least once.
if (!t.Applied)
continue;
// some specific transforms can be marked as non-rewindable.
if (!t.Rewindable)
continue;
if (time >= t.StartTime)
{
// we are in the middle of this transform, so we want to mark as not-completely-applied.
// note that we should only do this for the last transform of each TargetMember to avoid incorrect application order.
// the actual application will be in the main loop below now that AppliedToEnd is false.
if (!appliedToEndReverts.Contains(t.TargetMember))
{
t.AppliedToEnd = false;
appliedToEndReverts.Add(t.TargetMember);
}
}
else
{
// we are before the start time of this transform, so we want to eagerly apply the value at current time and mark as not-yet-applied.
// this transform will not be applied again unless we play forward in the future.
t.Apply(time);
t.Applied = false;
t.AppliedToEnd = false;
}
}
}
for (int i = getLastAppliedIndex(); i < transforms.Count; ++i)
{
var t = transforms[i];
var tCanRewind = !transformable.RemoveCompletedTransforms && t.Rewindable;
bool flushAppliedCache = false;
if (time < t.StartTime)
break;
if (!t.Applied)
{
// This is the first time we are updating this transform.
// We will find other still active transforms which act on the same target member and remove them.
// Since following transforms acting on the same target member are immediately removed when a
// new one is added, we can be sure that previous transforms were added before this one and can
// be safely removed.
for (int j = getLastAppliedIndex(t.TargetMember); j < i; ++j)
{
var u = transforms[j];
if (u.TargetMember != t.TargetMember) continue;
if (!u.AppliedToEnd)
// we may have applied the existing transforms too far into the future.
// we want to prepare to potentially read into the newly activated transform's StartTime,
// so we should re-apply using its StartTime as a basis.
u.Apply(t.StartTime);
if (!tCanRewind)
{
transforms.RemoveAt(j--);
flushAppliedCache = true;
i--;
if (u.OnAbort != null)
removalActions.Enqueue(u.OnAbort);
}
else
u.AppliedToEnd = true;
}
}
if (!t.HasStartValue)
{
t.ReadIntoStartValue();
t.HasStartValue = true;
}
if (!t.AppliedToEnd)
{
t.Apply(time);
t.AppliedToEnd = time >= t.EndTime;
if (t.AppliedToEnd)
{
if (!tCanRewind)
{
transforms.RemoveAt(i--);
flushAppliedCache = true;
}
if (t.IsLooping)
{
if (tCanRewind)
{
t.IsLooping = false;
t = t.Clone();
}
t.AppliedToEnd = false;
t.Applied = false;
t.HasStartValue = false;
t.IsLooping = true;
t.StartTime += t.LoopDelay;
t.EndTime += t.LoopDelay;
// this could be added back at a lower index than where we are currently iterating, but
// running the same transform twice isn't a huge deal.
transforms.Add(t);
flushAppliedCache = true;
}
else if (t.OnComplete != null)
removalActions.Enqueue(t.OnComplete);
}
}
if (flushAppliedCache)
resetLastAppliedCache();
// if this transform is applied to end, we can be sure that all previous transforms have been completed.
else if (t.AppliedToEnd)
setLastAppliedIndex(t.TargetMember, i + 1);
}
invokePendingRemovalActions();
}
/// <summary>
/// Adds to this object a <see cref="Transform"/> which was previously populated using this object via
/// <see cref="TransformableExtensions.PopulateTransform{TValue, TEasing, TThis}"/>.
/// Added <see cref="Transform"/>s are immediately applied, and therefore have an immediate effect on this object if the current time of this
/// object falls within <see cref="Transform.StartTime"/> and <see cref="Transform.EndTime"/>.
/// If <see cref="Transformable.Clock"/> is null, e.g. because this object has just been constructed, then the given transform will be finished instantaneously.
/// </summary>
/// <param name="transform">The <see cref="Transform"/> to be added.</param>
/// <param name="customTransformID">When not null, the <see cref="Transform.TransformID"/> to assign for ordering.</param>
public void AddTransform(Transform transform, ulong? customTransformID = null)
{
Debug.Assert(!(transform.TransformID == 0 && transforms.Contains(transform)), $"Zero-id {nameof(Transform)}s should never be contained already.");
if (transform.TargetGrouping != TargetGrouping)
throw new ArgumentException($"Target grouping \"{transform.TargetGrouping}\" does not match this tracker's grouping \"{TargetGrouping}\".", nameof(transform));
targetMembers.Add(transform.TargetMember);
// This contains check may be optimized away in the future, should it become a bottleneck
if (transform.TransformID != 0 && transforms.Contains(transform))
throw new InvalidOperationException($"{nameof(Transformable)} may not contain the same {nameof(Transform)} more than once.");
transform.TransformID = customTransformID ?? ++currentTransformID;
int insertionIndex = transforms.Add(transform);
resetLastAppliedCache();
// Remove all existing following transforms touching the same property as this one.
for (int i = insertionIndex + 1; i < transforms.Count; ++i)
{
var t = transforms[i];
if (t.TargetMember == transform.TargetMember)
{
transforms.RemoveAt(i--);
if (t.OnAbort != null)
removalActions.Enqueue(t.OnAbort);
}
}
invokePendingRemovalActions();
}
/// <summary>
/// Removes a <see cref="Transform"/>.
/// </summary>
/// <param name="toRemove">The <see cref="Transform"/> to remove.</param>
public void RemoveTransform(Transform toRemove)
{
transforms.Remove(toRemove);
resetLastAppliedCache();
}
/// <summary>
/// Removes <see cref="Transform"/>s that start after <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to clear <see cref="Transform"/>s after.</param>
/// <param name="targetMember">
/// An optional <see cref="Transform.TargetMember"/> name of <see cref="Transform"/>s to clear.
/// Null for clearing all <see cref="Transform"/>s.
/// </param>
public virtual void ClearTransformsAfter(double time, string targetMember = null)
{
resetLastAppliedCache();
Transform[] toAbort;
if (targetMember == null)
{
toAbort = transforms.Where(t => t.StartTime >= time).ToArray();
transforms.RemoveAll(t => t.StartTime >= time);
}
else
{
toAbort = transforms.Where(t => t.TargetMember == targetMember && t.StartTime >= time).ToArray();
transforms.RemoveAll(t => t.TargetMember == targetMember && t.StartTime >= time);
}
foreach (var t in toAbort)
t.OnAbort?.Invoke();
}
/// <summary>
/// Finishes specified <see cref="Transform"/>s, using their <see cref="Transform{TValue}.EndValue"/>.
/// </summary>
/// <param name="targetMember">
/// An optional <see cref="Transform.TargetMember"/> name of <see cref="Transform"/>s to finish.
/// Null for finishing all <see cref="Transform"/>s.
/// </param>
public virtual void FinishTransforms(string targetMember = null)
{
Func<Transform, bool> toFlushPredicate;
if (targetMember == null)
toFlushPredicate = t => !t.IsLooping;
else
toFlushPredicate = t => !t.IsLooping && t.TargetMember == targetMember;
// Flush is undefined for endlessly looping transforms
var toFlush = transforms.Where(toFlushPredicate).ToArray();
transforms.RemoveAll(t => toFlushPredicate(t));
resetLastAppliedCache();
foreach (Transform t in toFlush)
{
if (!t.HasStartValue)
{
t.ReadIntoStartValue();
t.HasStartValue = true;
}
t.Apply(t.EndTime);
t.OnComplete?.Invoke();
}
}
private void invokePendingRemovalActions()
{
while (removalActions.TryDequeue(out var action))
action();
}
/// <summary>
/// Retrieve the last transform index that was <see cref="Transform.AppliedToEnd"/>.
/// </summary>
/// <param name="targetMember">An optional target member. If null, the lowest common last application is returned.</param>
private int getLastAppliedIndex(string targetMember = null)
{
if (targetMember == null)
{
int min = int.MaxValue;
foreach (int i in lastAppliedTransformIndices.Values)
{
if (i < min)
min = i;
}
return min;
}
if (lastAppliedTransformIndices.TryGetValue(targetMember, out int val))
return val;
return 0;
}
/// <summary>
/// Set the last transform index that was <see cref="Transform.AppliedToEnd"/> for a specific target member.
/// </summary>
/// <param name="targetMember">The target member to set the index of.</param>
/// <param name="index">The index of the transform in <see cref="transforms"/>.</param>
private void setLastAppliedIndex(string targetMember, int index)
{
lastAppliedTransformIndices[targetMember] = index;
}
/// <summary>
/// Reset the last applied index cache completely.
/// </summary>
private void resetLastAppliedCache()
{
foreach (var tracked in targetMembers)
lastAppliedTransformIndices[tracked] = 0;
}
}
}
| |
// Copyright 2011, 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.
// Author: api.anash@gmail.com (Anash P. Oommen)
using System;
using System.IO;
using System.Net;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.Services.Configuration;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Serialization;
namespace Google.Api.Ads.Common.Lib {
/// <summary>
/// Base class for all SOAP services supported by this library.
/// </summary>
[System.ComponentModel.DesignerCategoryAttribute("code")]
public abstract class AdsSoapClient : SoapHttpClientProtocol, AdsClient {
/// <summary>
/// The user that created this service instance.
/// </summary>
private AdsUser user;
/// <summary>
/// The signature for this service.
/// </summary>
private ServiceSignature signature;
/// <summary>
/// The WebRequest that was used by the last API call from this service.
/// </summary>
private WebRequest lastRequest;
/// <summary>
/// The WebResponse for the last API call from this service.
/// </summary>
private WebResponse lastResponse;
/// <summary>
/// An internal delegate to the method that makes the SOAP API call.
/// </summary>
/// <param name="methodName">The name of the SOAP API method.</param>
/// <param name="parameters">The list of parameters for the SOAP API
/// method.</param>
/// <returns>The results from calling the SOAP API method.</returns>
private delegate object[] CallMethod(string methodName, object[] parameters);
/// <summary>
/// Gets or sets the AdsUser object that created this
/// service.
/// </summary>
public AdsUser User {
get {
return user;
}
set {
user = value;
}
}
/// <summary>
/// Gets or sets the signature for this service.
/// </summary>
public ServiceSignature Signature {
get {
return signature;
}
set {
signature = value;
}
}
/// <summary>
/// Gets or sets the web request associated with this service's
/// last API call.
/// </summary>
public WebRequest LastRequest {
get {
return lastRequest;
}
set {
lastRequest = value;
}
}
/// <summary>
/// Gets or sets the web response associated with this service's
/// last API call.
/// </summary>
public WebResponse LastResponse {
get {
return lastResponse;
}
set {
lastResponse = value;
}
}
/// <summary>
/// Invokes a SOAP service method synchronously using SOAP.
/// </summary>
/// <param name="methodName">The name of the SOAP service method
/// in the derived class that is invoking BeginInvoke. </param>
/// <param name="parameters">An array of objects containing the
/// parameters to pass to the SOAP service. The order of the
/// values in the array correspond to the order of the parameters
/// in the calling method of the derived class.</param>
/// <returns>An array of objects containing the return value and any
/// by reference or out parameters of the derived class method.</returns>
protected new object[] Invoke(string methodName, object[] parameters) {
return MakeApiCall(methodName, parameters);
}
/// <summary>
/// Starts an asynchronous invocation of a SOAP service method
/// using SOAP.
/// </summary>
/// <param name="methodName">The name of the SOAP service method
/// in the derived class that is invoking BeginInvoke. </param>
/// <param name="parameters">An array of objects containing the
/// parameters to pass to the SOAP service. The order of the
/// values in the array correspond to the order of the parameters
/// in the calling method of the derived class.</param>
/// <param name="callback">The delegate to call when the asynchronous
/// invoke is complete.</param>
/// <param name="asyncState">Extra information supplied by the caller.
/// </param>
/// <returns>An IAsyncResult which is passed to EndInvoke to obtain
/// the return values from the remote method call.</returns>
protected new IAsyncResult BeginInvoke(string methodName, object[] parameters,
AsyncCallback callback, object asyncState) {
CallMethod apiFunction = new CallMethod(MakeApiCall);
return apiFunction.BeginInvoke(methodName, parameters, callback, apiFunction);
}
/// <summary>
/// Ends an asynchronous invocation of a SOAP service method using
/// SOAP.
/// </summary>
/// <param name="asyncResult">The IAsyncResult returned from BeginInvoke.
/// </param>
/// <returns>An array of objects containing the return value and any
/// by-reference or out parameters of the derived class method.</returns>
/// <exception cref="ArgumentNullException">Thrown if
/// <paramref name="asyncResult"/> is null.</exception>
protected new object[] EndInvoke(IAsyncResult asyncResult) {
if (asyncResult == null) {
throw new ArgumentNullException("asyncResult");
}
CallMethod apiFunction = (CallMethod) asyncResult.AsyncState;
return apiFunction.EndInvoke(asyncResult);
}
/// <summary>
/// Initializes the service before MakeApiCall.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <param name="parameters">The method parameters.</param>
protected virtual void InitForCall(string methodName, object[] parameters) {
if (!IsSoapListenerLoaded()) {
throw new ApplicationException(CommonErrorMessages.SoapListenerExtensionNotLoaded);
}
ContextStore.AddKey("SoapService", this);
ContextStore.AddKey("SoapMethod", methodName);
this.user.InitListeners();
}
/// <summary>
/// Cleans up the service after MakeApiCall.
/// </summary>
/// <param name="methodName">Name of the method.</param>
/// <param name="parameters">The method parameters.</param>
protected virtual void CleanupAfterCall(string methodName, object[] parameters) {
this.user.CleanupListeners();
ContextStore.RemoveKey("SoapService");
ContextStore.RemoveKey("SoapMethod");
this.lastRequest = null;
this.lastResponse = null;
}
/// <summary>
/// This method makes the actual SOAP API call. It is a thin wrapper
/// over SOAPHttpClientProtocol:Invoke, and provide things like
/// protection from race condition.
/// </summary>
/// <param name="methodName">The name of the SOAP API method.</param>
/// <param name="parameters">The list of parameters for the SOAP API
/// method.</param>
/// <returns>The results from calling the SOAP API method.</returns>
protected virtual object[] MakeApiCall(string methodName, object[] parameters) {
ErrorHandler errorHandler = CreateErrorHandler();
while (true) {
try {
InitForCall(methodName, parameters);
return base.Invoke(methodName, parameters);
} catch (SoapException ex) {
Exception customException = GetCustomException(ex);
if (errorHandler.ShouldRetry(customException)) {
errorHandler.PrepareForRetry(customException);
} else {
throw customException;
}
} finally {
CleanupAfterCall(methodName, parameters);
}
}
throw new ArgumentOutOfRangeException("Retry count cannot be negative.");
}
/// <summary>
/// Creates the error handler.
/// </summary>
/// <returns>The error handler instance.</returns>
protected virtual ErrorHandler CreateErrorHandler() {
return new ErrorHandler(this.User.Config);
}
/// <summary>
/// Determines whether SOAP listener extension is loaded.
/// </summary>
/// <returns>True, if SoapListenerExtension is loaded as a SOAP extension.
/// </returns>
private static bool IsSoapListenerLoaded() {
foreach (SoapExtensionTypeElement extensionElement in
WebServicesSection.Current.SoapExtensionTypes) {
if (extensionElement.Type == typeof(SoapListenerExtension)) {
return true;
}
}
return false;
}
/// <summary>
/// Gets a custom exception that wraps the SOAP exception thrown
/// by the server.
/// </summary>
/// <param name="ex">SOAPException that was thrown by the server.</param>
/// <returns>A custom exception object that wraps the SOAP exception.
/// </returns>
/// <remarks>Any service that wishes to provide a custom exception
/// should override this method.</remarks>
protected virtual Exception GetCustomException(SoapException ex) {
return ex;
}
/// <summary>
/// Creates a WebRequest instance for the specified url.
/// </summary>
/// <param name="uri">The Uri to use when creating the WebRequest.</param>
/// <returns>The WebRequest instance.</returns>
protected override WebRequest GetWebRequest(Uri uri) {
// Store the base WebRequest in the member variable for future access.
this.lastRequest = base.GetWebRequest(uri);
if (this.lastRequest is HttpWebRequest) {
(this.lastRequest as HttpWebRequest).ServicePoint.Expect100Continue = false;
}
return this.lastRequest;
}
/// <summary>
/// Returns a response from a synchronous request to an XML Web
/// service method.
/// </summary>
/// <param name="request">The System.Net.WebRequest from which
/// to get the response.</param>
/// <returns>The web response.</returns>
protected override WebResponse GetWebResponse(WebRequest request) {
// Store the base WebResponse in the member variable for future access.
this.lastResponse = base.GetWebResponse(request);
return this.lastResponse;
}
/// <summary>
/// Returns a response from an asynchronous request to a SOAP service
/// method.
/// </summary>
/// <param name="request">The System.Net.WebRequest from which to get the
/// response.</param>
/// <param name="result">The System.IAsyncResult to pass to System.Net.
/// HttpWebRequest.EndGetResponse(System.IAsyncResult) when the response
/// has completed.</param>
/// <returns>The web response.</returns>
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result) {
// Store the base WebResponse in the member variable for future access.
lastResponse = base.GetWebResponse(request, result);
return lastResponse;
}
/// <summary>
/// Gets the default XML namespace, based on the type of this object.
/// </summary>
/// <returns>The XML namespace to which this object is serialized, or an
/// empty string if the method fails to retrieve the default namespace.
/// </returns>
/// <remarks>
/// All the services making use of the XML Serialization framework
/// (including ones generated by wsdl.exe and xsd.exe) will have
/// a WebServiceBindingAttribute decoration, something like:
///
/// [System.Web.Services.WebServiceBindingAttribute(
/// Name = "SomeServiceSoapBinding",
/// Namespace = "https://the_xml_namespace_for_serializing")]
/// public partial class SomeService : SoapHttpClientProtocol {
/// ...
/// }
///
/// The only exception to this rule is when we choose to write our own
/// serialization framework, by implementing IXmlSerializable on
/// AdsSoapClient. If and when someone does that, and someone were to
/// call this method, then he/she will get an empty string from this
/// method.
/// </remarks>
protected string GetDefaultNamespace() {
object[] attributes = this.GetType().GetCustomAttributes(false);
foreach (object attribute in attributes) {
if (attribute is WebServiceBindingAttribute) {
return ((WebServiceBindingAttribute) attribute).Namespace;
}
}
return String.Empty;
}
/// <summary>
/// Extracts the fault xml node from soap exception.
/// </summary>
/// <param name="exception">The SOAP exception corresponding to the SOAP
/// fault.</param>
/// <param name="ns">The xml namespace for the fault node.</param>
/// <param name="nodeName">The root node name for fault node.</param>
/// <returns>The fault node.</returns>
protected static XmlElement GetFaultNode(SoapException exception, string ns,
string nodeName) {
// Issue 1: Exception.Detail could be null. Can happen if SoapException
// is a SoapHeaderException.
if (exception.Detail == null) {
return null;
} else {
XmlNamespaceManager xmlns =
new XmlNamespaceManager(exception.Detail.OwnerDocument.NameTable);
xmlns.AddNamespace("api", ns);
return (XmlElement) exception.Detail.SelectSingleNode("api:" + nodeName, xmlns);
}
}
}
}
| |
// All code copyright Chris West 2011.
// If you make any improvements please send them back to me at chris@west-racing.com so I can update the package.
#if !UNITY_FLASH && !UNITY_METRO && !UNITY_WP8
using UnityEngine;
using System.IO;
using System;
using System.Collections;
using System.Collections.Generic;
public enum IMGFormat
{
Tga,
Jpg,
}
//[ExecuteInEditMode]
public class MegaGrab : MonoBehaviour
{
public Camera SrcCamera = null; // camera to use for screenshot
public KeyCode GrabKey = KeyCode.S; // Key to grab the screenshot
public int ResUpscale = 1; // How much to increase the screen shot res by
public float Blur = 1.0f; // Pixel oversampling
public int AASamples = 8; // Anti aliasing samples
public AnisotropicFiltering FilterMode = AnisotropicFiltering.ForceEnable; // Filter mode
public bool UseJitter = false; // use random jitter for AA sampling
public string SaveName = "Grab"; // Base name for grabs
public string Format = "dddd MMM dd yyyy HH_mm_ss"; // format string for date time info
public string Enviro = ""; // Enviro variable to use ie USERPROFILE
public string Path = "";
public bool UseDOF = false; // Use Dof grab
public float focalDistance = 8.0f; // DOF focal distance
public int totalSegments = 8; // How many DOF samples
public float sampleRadius = 1.0f; // Amount of DOF effect
//public float sampleBias = 1.0f;
public bool CalcFromSize = false; // Let grab calc res from dpi and Width(in inches)
public int Dpi = 300; // Number of Dots per inch required
public float Width = 24.0f; // Final physical size of grab using Dpi
public int NumberOfGrabs = 0; // Read only of how many grabs will happen
public float EstimatedTime = 0.0f; // Guide to show how long a grab will take in Seconds
public int GrabWidthWillBe = 0; // Width of final image
public int GrabHeightWillBe = 0; // Height of final IMage
public bool UseCoroutine = false; // Use coroutine method, needed for later versions of unity
float mleft;
float mright;
float mtop;
float mbottom;
int sampcount;
Vector2[] poisson;
Texture2D grabtex;
Color[,] accbuf;
Color[,] blendbuf;
byte[] output1;
Color[] outputjpg;
AnisotropicFiltering filtering;
MGBlendTable blendtable;
int DOFSamples;
//float DOFJitter = 5.0f;
Vector3 camfor;
Vector3 campos;
Matrix4x4 camtm;
// Calc the camera offsets and rots in init
void CalcDOFInfo(Camera camera)
{
camtm = camera.transform.localToWorldMatrix;
campos = camera.transform.position;
camfor = camera.transform.forward;
}
void ChangeDOFPos(int segment)
{
float theta = (float)segment / (float)(totalSegments) * Mathf.PI * 2.0f;
float radius = sampleRadius;
float uOffset = radius * Mathf.Cos(theta);
float vOffset = radius * Mathf.Sin(theta);
Vector3 newCameraLocation = new Vector3(uOffset, vOffset, 0.0f);
Vector3 initialTargetLocation = camfor * focalDistance; //new Vector3(0.0f, 0.0f, -focalDistance);
Vector3 tpos = initialTargetLocation + campos; //srcCamera.transform.TransformPoint(initialTargetLocation);
SrcCamera.transform.position = camtm.MultiplyPoint3x4(newCameraLocation);
SrcCamera.transform.LookAt(tpos);
}
static Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far)
{
Matrix4x4 m = Matrix4x4.identity;
m[0, 0] = (2.0f * near) / (right - left);
m[1, 1] = (2.0f * near) / (top - bottom);
m[0, 2] = (right + left) / (right - left);
m[1, 2] = (top + bottom) / (top - bottom);
m[2, 2] = -(far + near) / (far - near);
m[2, 3] = -(2.0f * far * near) / (far - near);
m[3, 2] = -1.0f;
m[3, 3] = 0.0f;
return m;
}
Matrix4x4 CalcProjectionMatrix(float left, float right, float bottom, float top, float near, float far, float xoff, float yoff)
{
float scalex = (right - left) / (float)Screen.width;
float scaley = (top - bottom) / (float)Screen.height;
return PerspectiveOffCenter(left - xoff * scalex, right - xoff * scalex, bottom - yoff * scaley, top - yoff * scaley, near, far);
}
void Cleanup()
{
QualitySettings.anisotropicFiltering = filtering;
}
bool InitGrab(int width, int height, int aasamples)
{
blendtable = new MGBlendTable(32, 32, totalSegments, 0.4f, true);
if ( ResUpscale < 1 )
ResUpscale = 1;
if ( AASamples < 1 )
AASamples = 1;
if ( SrcCamera == null )
SrcCamera = Camera.main;
if ( SrcCamera == null )
{
Debug.Log("No Camera set as source and no main camera found in the scene");
return false;
}
CalcDOFInfo(SrcCamera);
if ( OutputFormat == IMGFormat.Tga )
output1 = new byte[(width * ResUpscale) * (height * ResUpscale) * 3];
else
outputjpg = new Color[(width * ResUpscale) * (height * ResUpscale)];
if ( output1 != null || outputjpg != null )
{
filtering = QualitySettings.anisotropicFiltering;
QualitySettings.anisotropicFiltering = FilterMode;
grabtex = new Texture2D(width, height, TextureFormat.RGB24, false);
if ( grabtex != null )
{
accbuf = new Color[width, height];
blendbuf = new Color[width, height];
if ( accbuf != null )
{
float l = (1.0f - Blur) * 0.5f;
float h = 1.0f + ((Blur - 1.0f) * 0.5f);
if ( UseJitter)
{
poisson = new Vector2[aasamples];
sampcount = aasamples;
for ( int i = 0; i < aasamples; i++ )
{
Vector2 pos = new Vector2();
pos.x = Mathf.Lerp(l, h, UnityEngine.Random.value);
pos.y = Mathf.Lerp(l, h, UnityEngine.Random.value);
poisson[i] = pos;
}
}
else
{
int samples = (int)Mathf.Sqrt((float)aasamples);
if ( samples < 1 )
samples = 1;
sampcount = samples * samples;
poisson = new Vector2[samples * samples];
int i = 0;
for ( int ya = 0; ya < samples; ya++ )
{
for ( int xa = 0; xa < samples; xa++ )
{
float xa1 = ((float)xa / (float)samples);
float ya1 = ((float)ya / (float)samples);
Vector2 pos = new Vector2();
pos.x = Mathf.Lerp(l, h, xa1);
pos.y = Mathf.Lerp(l, h, ya1);
poisson[i++] = pos;
}
}
}
return true;
}
}
}
Debug.Log("Cant create a large enough texture, Try lower ResUpscale value");
return false;
}
Texture2D GrabImage(int samples, float x, float y)
{
float ps = 1.0f / (float)ResUpscale;
for ( int i = 0; i < sampcount; i++ )
{
float xa = poisson[i].x * ps;
float ya = poisson[i].y * ps;
// Move view and grab
float xo = x + xa;
float yo = y + ya;
SrcCamera.projectionMatrix = CalcProjectionMatrix(mleft, mright, mbottom, mtop, SrcCamera.nearClipPlane, SrcCamera.farClipPlane, xo, yo);
SrcCamera.Render();
// Read screen contents into the texture
grabtex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
grabtex.Apply();
if ( i == 0 )
{
for ( int ty = 0; ty < Screen.height; ty++ )
{
for ( int tx = 0; tx < Screen.width; tx++ )
accbuf[tx, ty] = grabtex.GetPixel(tx, ty);
}
}
else
{
for ( int ty = 0; ty < Screen.height; ty++ )
{
for ( int tx = 0; tx < Screen.width; tx++ )
accbuf[tx, ty] += grabtex.GetPixel(tx, ty);
}
}
}
for ( int ty = 0; ty < Screen.height; ty++ )
{
for ( int tx = 0; tx < Screen.width; tx++ )
grabtex.SetPixel(tx, ty, accbuf[tx, ty] / sampcount);
}
grabtex.Apply();
return grabtex;
}
void GrabAA(float x, float y)
{
float ps = 1.0f / (float)ResUpscale;
for ( int ty = 0; ty < Screen.height; ty++ )
{
for ( int tx = 0; tx < Screen.width; tx++ )
accbuf[tx, ty] = Color.black;
}
for ( int i = 0; i < sampcount; i++ )
{
float xa = poisson[i].x * ps;
float ya = poisson[i].y * ps;
// Move view and grab
float xo = x + xa;
float yo = y + ya;
SrcCamera.projectionMatrix = CalcProjectionMatrix(mleft, mright, mbottom, mtop, SrcCamera.nearClipPlane, SrcCamera.farClipPlane, xo, yo);
SrcCamera.Render();
// Read screen contents into the texture
grabtex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
grabtex.Apply();
for ( int ty = 0; ty < Screen.height; ty++ )
{
for ( int tx = 0; tx < Screen.width; tx++ )
accbuf[tx, ty] += grabtex.GetPixel(tx, ty);
}
}
for ( int ty = 0; ty < Screen.height; ty++ )
{
for ( int tx = 0; tx < Screen.width; tx++ )
accbuf[tx, ty] = accbuf[tx, ty] / sampcount;
}
}
// return accbuf here
Texture2D GrabImageDOF(int samples, float x, float y)
{
//float ps = 1.0f / (float)ResUpscale;
for ( int ty = 0; ty < Screen.height; ty++ )
{
for ( int tx = 0; tx < Screen.width; tx++ )
blendbuf[tx, ty] = Color.black;
}
for ( int d = 0; d < totalSegments; d++ )
{
ChangeDOFPos(d);
//SrcCamera.transform.localToWorldMatrix = ChangeCameraDOF(d);
GrabAA(x, y);
// Blend image
blendtable.BlendImages(blendbuf, accbuf, Screen.width, Screen.height, d);
}
return grabtex;
}
void DoGrabTGA()
{
if ( InitGrab(Screen.width, Screen.height, AASamples) )
{
mtop = SrcCamera.nearClipPlane * Mathf.Tan(SrcCamera.fieldOfView * 0.5f * Mathf.Deg2Rad);
mbottom = -mtop;
mleft = mbottom * SrcCamera.aspect;
mright = mtop * SrcCamera.aspect;
//float mWidth = SrcCamera.nearClipPlane / SrcCamera.projectionMatrix.m00;
//float mHeight = SrcCamera.nearClipPlane / SrcCamera.projectionMatrix.m11;
//float spox = mWidth / (Screen.width * ResUpscale * 1.0f);
//float spoy = mHeight / (Screen.height * ResUpscale * 1.0f);
int width = Screen.width;
int height = Screen.height;
if ( AASamples < 1 )
AASamples = 1;
//int total = ResUpscale * ResUpscale;
int count = 0;
for ( int y = 0; y < ResUpscale; y++ )
{
float yo = (float)y / (float)ResUpscale;
for ( int x = 0; x < ResUpscale; x++ )
{
//MyDebug.Log("Doing Grab " + count + " of " + total);
count++;
float xo = (float)x / (float)ResUpscale;
Texture2D tex;
if ( UseDOF )
{
tex = GrabImageDOF(AASamples, xo, yo);
for ( int h = 0; h < Screen.height; h++ )
{
int index = ((ResUpscale - y) + (h * ResUpscale) - 1) * (width * ResUpscale);
for ( int w = 0; w < Screen.width; w++ )
{
Color col = blendbuf[w, h]; //tex.GetPixel(w, h);
int ix = (index + ((ResUpscale - x) + (w * ResUpscale) - 1)) * 3;
output1[ix + 0] = (byte)(col.b * 255.0f);
output1[ix + 1] = (byte)(col.g * 255.0f);
output1[ix + 2] = (byte)(col.r * 255.0f);
}
}
}
else
{
tex = GrabImage(AASamples, xo, yo);
for ( int h = 0; h < Screen.height; h++ )
{
int index = ((ResUpscale - y) + (h * ResUpscale) - 1) * (width * ResUpscale);
for ( int w = 0; w < Screen.width; w++ )
{
Color col = tex.GetPixel(w, h);
int ix = (index + ((ResUpscale - x) + (w * ResUpscale) - 1)) * 3;
output1[ix + 0] = (byte)(col.b * 255.0f);
output1[ix + 1] = (byte)(col.g * 255.0f);
output1[ix + 2] = (byte)(col.r * 255.0f);
}
}
}
}
}
string epath = "";
if ( Enviro != null && Enviro.Length > 0 )
epath = System.Environment.GetEnvironmentVariable(Enviro);
//string fname = epath + Path + SaveName + " " + (width * ResUpscale) + "x" + (height * ResUpscale) + " " + System.DateTime.Now.ToString(Format);
// Save big version
//if ( uploadGrabs )
//{
// string fname = SaveName + " " + (width * ResUpscale) + "x" + (height * ResUpscale) + " " + System.DateTime.Now.ToString(Format);
// UploadTGA(fname + ".tga", (width * ResUpscale), (height * ResUpscale), output1);
//}
//else
//{
string fname = epath + Path + SaveName + " " + (width * ResUpscale) + "x" + (height * ResUpscale) + " " + System.DateTime.Now.ToString(Format);
SaveTGA(fname + ".tga", (width * ResUpscale), (height * ResUpscale), output1);
//}
//SaveTGA(fname + ".tga", (width * ResUpscale), (height * ResUpscale), output1);
//SrcCamera.camera.worldToCameraMatrix = cameraMat;
//SrcCamera.ResetWorldToCameraMatrix();
SrcCamera.ResetProjectionMatrix();
Cleanup();
}
}
public IMGFormat OutputFormat = IMGFormat.Jpg;
public float Quality = 75.0f;
void DoGrabJPG()
{
if ( InitGrab(Screen.width, Screen.height, AASamples) )
{
mtop = SrcCamera.nearClipPlane * Mathf.Tan(SrcCamera.fieldOfView * 0.5f * Mathf.Deg2Rad);
mbottom = -mtop;
mleft = mbottom * SrcCamera.aspect;
mright = mtop * SrcCamera.aspect;
//float mWidth = SrcCamera.nearClipPlane / SrcCamera.projectionMatrix.m00;
//float mHeight = SrcCamera.nearClipPlane / SrcCamera.projectionMatrix.m11;
//float spox = mWidth / (Screen.width * ResUpscale * 1.0f);
//float spoy = mHeight / (Screen.height * ResUpscale * 1.0f);
int width = Screen.width;
int height = Screen.height;
if ( AASamples < 1 )
AASamples = 1;
//int total = ResUpscale * ResUpscale;
int count = 0;
for ( int y = 0; y < ResUpscale; y++ )
{
float yo = (float)y / (float)ResUpscale;
for ( int x = 0; x < ResUpscale; x++ )
{
//MyDebug.Log("Doing Grab " + count + " of " + total);
count++;
float xo = (float)x / (float)ResUpscale;
Texture2D tex;
if ( UseDOF )
{
tex = GrabImageDOF(AASamples, xo, yo);
for ( int h = 0; h < Screen.height; h++ )
{
int index = ((ResUpscale - y) + (h * ResUpscale) - 1) * (width * ResUpscale);
for ( int w = 0; w < Screen.width; w++ )
{
Color col = blendbuf[w, h]; //tex.GetPixel(w, h);
int ix = (index + ((ResUpscale - x) + (w * ResUpscale) - 1));
outputjpg[ix] = col;
}
}
}
else
{
tex = GrabImage(AASamples, xo, yo);
for ( int h = 0; h < Screen.height; h++ )
{
int index = ((ResUpscale - y) + (h * ResUpscale) - 1) * (width * ResUpscale);
for ( int w = 0; w < Screen.width; w++ )
{
Color col = tex.GetPixel(w, h);
int ix = (index + ((ResUpscale - x) + (w * ResUpscale) - 1));
outputjpg[ix] = col;
}
}
}
}
}
string epath = "";
if ( Enviro != null && Enviro.Length > 0 )
epath = System.Environment.GetEnvironmentVariable(Enviro);
//string fname = epath + Path + SaveName + " " + (width * ResUpscale) + "x" + (height * ResUpscale) + " " + System.DateTime.Now.ToString(Format);
// Save big version
if ( uploadGrabs )
{
string fname = SaveName + " " + (width * ResUpscale) + "x" + (height * ResUpscale) + " " + System.DateTime.Now.ToString(Format);
UploadJPG(fname + ".jpg", (width * ResUpscale), (height * ResUpscale), outputjpg);
}
else
{
string fname = epath + Path + SaveName + " " + (width * ResUpscale) + "x" + (height * ResUpscale) + " " + System.DateTime.Now.ToString(Format);
SaveJPG(fname + ".jpg", (width * ResUpscale), (height * ResUpscale), outputjpg);
}
//SrcCamera.camera.worldToCameraMatrix = cameraMat;
//SrcCamera.ResetWorldToCameraMatrix();
SrcCamera.ResetProjectionMatrix();
Cleanup();
}
}
public bool uploadGrabs = false;
void SaveJPG(string filename, int width, int height, Color[] pixels)
{
FileStream fs = new FileStream(filename, FileMode.Create);
if ( fs != null )
{
BinaryWriter bw = new BinaryWriter(fs);
if ( bw != null )
{
Quality = Mathf.Clamp(Quality, 0.0f, 100.0f);
JPGEncoder NewEncoder = new JPGEncoder(pixels, width, height, Quality);
NewEncoder.doEncoding();
byte[] TexData = NewEncoder.GetBytes();
bw.Write(TexData);
bw.Close();
}
fs.Close();
}
}
void UploadJPG(string filename, int width, int height, Color[] pixels)
{
Quality = Mathf.Clamp(Quality, 0.0f, 100.0f);
JPGEncoder NewEncoder = new JPGEncoder(pixels, width, height, Quality);
NewEncoder.doEncoding();
byte[] TexData = NewEncoder.GetBytes();
UploadFile(TexData, m_URL, filename);
}
#if false
void UploadTGA(string filename, int width, int height, byte[] pixels)
{
//byte[] data = new byte[output1.Length * 4];
//Buffer.BlockCopy(output1, 0, data, 0, data.Length);
UploadFile(pixels, m_URL, filename);
}
#endif
void SaveTGA(string filename, int width, int height, byte[] pixels)
{
FileStream fs = new FileStream(filename, FileMode.Create);
if ( fs != null )
{
BinaryWriter bw = new BinaryWriter(fs);
if ( bw != null )
{
bw.Write((short)0);
bw.Write((byte)2);
bw.Write((int)0);
bw.Write((int)0);
bw.Write((byte)0);
bw.Write((short)width);
bw.Write((short)height);
bw.Write((byte)24);
bw.Write((byte)0);
for ( int h = 0; h < pixels.Length; h++ )
bw.Write(pixels[h]);
bw.Close();
}
fs.Close();
}
}
void CalcUpscale()
{
float w = Width / ((float)Screen.width / (float)Dpi); // * Width;
ResUpscale = (int)(w);
GrabWidthWillBe = Screen.width * ResUpscale;
GrabHeightWillBe = Screen.height * ResUpscale;
}
void CalcEstimate()
{
NumberOfGrabs = ResUpscale * ResUpscale * AASamples;
if ( UseDOF )
{
NumberOfGrabs *= totalSegments;
}
EstimatedTime = NumberOfGrabs * 0.41f;
}
IEnumerator GrabCoroutine()
{
yield return new WaitForEndOfFrame();
if ( OutputFormat == IMGFormat.Tga )
DoGrabTGA();
else
DoGrabJPG();
yield return null;
}
void LateUpdate()
{
if ( Input.GetKeyDown(GrabKey) )
{
#if UNITY_IPHONE
Path = Application.persistentDataPath + "/";
#endif
//StartCoroutine(GrabCoroutine());
if ( CalcFromSize )
CalcUpscale();
CalcEstimate();
if ( UseCoroutine )
{
StartCoroutine(GrabCoroutine());
}
else
{
float t = Time.realtimeSinceStartup;
//DoGrabTGA();
if ( OutputFormat == IMGFormat.Tga )
DoGrabTGA();
else
DoGrabJPG();
float time = Time.realtimeSinceStartup - t;
Debug.Log("Took " + time.ToString("0.00000000") + "s");
}
}
}
void OnDrawGizmos()
{
if ( CalcFromSize )
CalcUpscale();
CalcEstimate();
}
//using UnityEngine;
//using System.Collections;
//public class FileUpload : MonoBehaviour
//{
public string m_URL = "http://www.west-racing.com/uploadtest1.php";
IEnumerator UploadFileCo(byte[] data, string uploadURL, string filename)
{
WWWForm postForm = new WWWForm();
// version 1
//postForm.AddBinaryData("theFile",localFile.bytes);
Debug.Log("uploading " + filename);
// version 2
postForm.AddField("action", "Upload Image");
postForm.AddBinaryData("theFile", data, filename, "images/jpg"); //text/plain");
Debug.Log("url " + uploadURL);
WWW upload = new WWW(uploadURL, postForm);
yield return upload;
//if ( upload.error == null )
Debug.Log("upload done :" + upload.text);
//else
Debug.Log("Error during upload: " + upload.error);
}
void UploadFile(byte[] data, string uploadURL, string filename)
{
Debug.Log("Start upload");
//StartCoroutine(UploadFileCo(data, uploadURL, filename));
StartCoroutine(UploadLevel(data, uploadURL, filename));
Debug.Log("len " + data.Length);
}
IEnumerator UploadLevel(byte[] data, string uploadURL, string filename)
{
WWWForm form = new WWWForm();
form.AddField("action", "level upload");
form.AddField("file", "file");
form.AddBinaryData("file", data, filename, "images/jpg");
Debug.Log("url " + uploadURL);
WWW w = new WWW(uploadURL, form);
yield return w;
if ( w.error != null )
{
print("error");
print(w.error);
}
else
{
if ( w.uploadProgress == 1 && w.isDone )
{
yield return new WaitForSeconds(5);
}
}
}
#if false
<?
if ( isset ($_POST['action']) ) {
if($_POST['action'] == "Upload Image") {
unset($imagename);
if(!isset($_FILES) && isset($HTTP_POST_FILES)) $_FILES = $HTTP_POST_FILES;
if(!isset($_FILES['fileUpload'])) $error["image_file"] = "An image was not found.";
$imagename = basename($_FILES['fileUpload']['name']);
if(empty($imagename)) $error["imagename"] = "The name of the image was not found.";
if(empty($error)) {
$newimage = "images/" . $imagename;
//echo $newimage;
$result = @move_uploaded_file($_FILES['fileUpload']['tmp_name'], $newimage);
if ( empty($result) ) $error["result"] = "There was an error moving the uploaded file.";
}
}
} else {
echo "no form data found";
}
?>
#endif
}
// Example php code to take uploaded jog images
#if false
// Php Code, upload this to your server
<?php
//check if something its being sent to this script
if ($_POST)
{
//check if theres a field called action in the sent data
if ( isset ($_POST['action']) )
{
//if it indeed theres an field called action. check if its value its level upload
if($_POST['action'] === 'level upload')
{
if(!isset($_FILES) && isset($HTTP_POST_FILES))
{
$_FILES = $HTTP_POST_FILES;
}
if ($_FILES['file']['error'] === UPLOAD_ERR_OK)
{
//check if the file has a name, in this script it has to have a name to be stored, the file name is sent by unity
if ($_FILES['file']['name'] !== "")
{
//this checks the file mime type, to filter the kind of files you want to accept, this script is configured to accept only jpg files
if ($_FILES['file']['type'] === 'images/jpg')
{
$uploadfile = $_FILES['file']['name'];
$newimage = "images/" . $uploadfile;
move_uploaded_file($_FILES['file']['tmp_name'], $newimage);
}
}
}
}
}
}
?>
#endif
#endif
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Reflection.Emit;
namespace AutoMapper.Mappers
{
public class DataReaderMapper : IObjectMapper
{
private static ConcurrentDictionary<BuilderKey, Build> _builderCache = new ConcurrentDictionary<BuilderKey, Build>();
public object Map(ResolutionContext context, IMappingEngineRunner mapper)
{
if (IsDataReader(context))
{
var dataReader = (IDataReader)context.SourceValue;
var destinationElementType = TypeHelper.GetElementType(context.DestinationType);
var resolveUsingContext = context;
if (context.TypeMap == null)
{
var configurationProvider = mapper.ConfigurationProvider;
TypeMap typeMap = configurationProvider.FindTypeMapFor(context.SourceValue, context.SourceType, destinationElementType);
resolveUsingContext = new ResolutionContext(typeMap, context.SourceValue, context.SourceType, destinationElementType, new MappingOperationOptions());
}
var buildFrom = CreateBuilder(destinationElementType, dataReader);
var results = ObjectCreator.CreateList(destinationElementType);
while (dataReader.Read())
{
var result = buildFrom(dataReader);
MapPropertyValues(resolveUsingContext, mapper, result);
results.Add(result);
}
return results;
}
if (IsDataRecord(context))
{
var dataRecord = context.SourceValue as IDataRecord;
var buildFrom = CreateBuilder(context.DestinationType, dataRecord);
var result = buildFrom(dataRecord);
MapPropertyValues(context, mapper, result);
return result;
}
return null;
}
public bool IsMatch(ResolutionContext context)
{
return IsDataReader(context) || IsDataRecord(context);
}
private static bool IsDataReader(ResolutionContext context)
{
return typeof(IDataReader).IsAssignableFrom(context.SourceType) &&
context.DestinationType.IsEnumerableType();
}
private static bool IsDataRecord(ResolutionContext context)
{
return typeof(IDataRecord).IsAssignableFrom(context.SourceType);
}
private static Build CreateBuilder(Type destinationType, IDataRecord dataRecord)
{
Build builder;
BuilderKey builderKey = new BuilderKey(destinationType, dataRecord);
if (_builderCache.TryGetValue(builderKey, out builder))
{
return builder;
}
var method = new DynamicMethod("DynamicCreate", destinationType, new[] { typeof(IDataRecord) }, destinationType, true);
var generator = method.GetILGenerator();
var result = generator.DeclareLocal(destinationType);
generator.Emit(OpCodes.Newobj, destinationType.GetConstructor(Type.EmptyTypes));
generator.Emit(OpCodes.Stloc, result);
for (var i = 0; i < dataRecord.FieldCount; i++)
{
var propertyInfo = destinationType.GetProperty(dataRecord.GetName(i), BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance);
var endIfLabel = generator.DefineLabel();
if (propertyInfo != null && propertyInfo.GetSetMethod(true) != null)
{
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Callvirt, isDBNullMethod);
generator.Emit(OpCodes.Brtrue, endIfLabel);
generator.Emit(OpCodes.Ldloc, result);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Callvirt, getValueMethod);
if (propertyInfo.PropertyType.IsGenericType
&& propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))
)
{
var nullableType = propertyInfo.PropertyType.GetGenericTypeDefinition().GetGenericArguments()[0];
if (!nullableType.IsEnum)
generator.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType);
else
{
generator.Emit(OpCodes.Unbox_Any, nullableType);
generator.Emit(OpCodes.Newobj, propertyInfo.PropertyType);
}
}
else
{
generator.Emit(OpCodes.Unbox_Any, dataRecord.GetFieldType(i));
}
generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod(true));
generator.MarkLabel(endIfLabel);
}
}
generator.Emit(OpCodes.Ldloc, result);
generator.Emit(OpCodes.Ret);
builder = (Build)method.CreateDelegate(typeof(Build));
_builderCache[builderKey] = builder;
return builder;
}
private static void MapPropertyValues(ResolutionContext context, IMappingEngineRunner mapper, object result)
{
if (context.TypeMap == null)
throw new AutoMapperMappingException(context, "Missing type map configuration or unsupported mapping.");
foreach (var propertyMap in context.TypeMap.GetPropertyMaps())
{
MapPropertyValue(context, mapper, result, propertyMap);
}
}
private static void MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper,
object mappedObject, PropertyMap propertyMap)
{
if (!propertyMap.CanResolveValue())
return;
var result = propertyMap.ResolveValue(context);
var newContext = context.CreateMemberContext(null, result.Value, null, result.Type, propertyMap);
if (!propertyMap.ShouldAssignValue(newContext))
return;
try
{
var propertyValueToAssign = mapper.Map(newContext);
if (propertyMap.CanBeSet)
propertyMap.DestinationProperty.SetValue(mappedObject, propertyValueToAssign);
}
catch (AutoMapperMappingException)
{
throw;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(newContext, ex);
}
}
private delegate object Build(IDataRecord dataRecord);
private static readonly MethodInfo parseMethod =
typeof(Enum).GetMethod("get_Item", new[] { typeof(int) });
private static readonly MethodInfo getValueMethod =
typeof(IDataRecord).GetMethod("get_Item", new[] { typeof(int) });
private static readonly MethodInfo isDBNullMethod =
typeof(IDataRecord).GetMethod("IsDBNull", new[] { typeof(int) });
private class BuilderKey
{
private readonly List<string> _dataRecordNames;
private readonly Type _destinationType;
public BuilderKey(Type destinationType, IDataRecord record)
{
_destinationType = destinationType;
_dataRecordNames = new List<string>(record.FieldCount);
for (int i = 0; i < record.FieldCount; i++)
{
_dataRecordNames.Add(record.GetName(i));
}
}
public override int GetHashCode()
{
int hash = _destinationType.GetHashCode();
foreach (var name in _dataRecordNames)
{
hash = hash * 37 + name.GetHashCode();
}
return hash;
}
public override bool Equals(object obj)
{
var builderKey = obj as BuilderKey;
if (builderKey == null)
return false;
if (this._dataRecordNames.Count != builderKey._dataRecordNames.Count)
return false;
for (int i = 0; i < _dataRecordNames.Count; i++)
{
if (this._dataRecordNames[i] != builderKey._dataRecordNames[i])
return false;
}
return true;
}
}
}
}
| |
using Signum.Entities.Workflow;
using Signum.Entities;
using Signum.Engine.Operations;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Linq.Expressions;
namespace Signum.Engine.Workflow
{
public partial class WorkflowBuilder
{
internal partial class LaneBuilder
{
public XmlEntity<WorkflowLaneEntity> lane;
private Dictionary<string, XmlEntity<WorkflowEventEntity>> events;
private Dictionary<string, XmlEntity<WorkflowActivityEntity>> activities;
private Dictionary<string, XmlEntity<WorkflowGatewayEntity>> gateways;
private Dictionary<string, XmlEntity<WorkflowConnectionEntity>> connections;
private Dictionary<Lite<IWorkflowNodeEntity>, List<XmlEntity<WorkflowConnectionEntity>>> incoming;
private Dictionary<Lite<IWorkflowNodeEntity>, List<XmlEntity<WorkflowConnectionEntity>>> outgoing;
public LaneBuilder(WorkflowLaneEntity l,
IEnumerable<WorkflowActivityEntity> activities,
IEnumerable<WorkflowEventEntity> events,
IEnumerable<WorkflowGatewayEntity> gateways,
IEnumerable<XmlEntity<WorkflowConnectionEntity>> connections)
{
this.lane = new XmlEntity<WorkflowLaneEntity>(l);
this.events = events.Select(a => new XmlEntity<WorkflowEventEntity>(a)).ToDictionary(x => x.bpmnElementId);
this.activities = activities.Select(a => new XmlEntity<WorkflowActivityEntity>(a)).ToDictionary(x => x.bpmnElementId);
this.gateways = gateways.Select(a => new XmlEntity<WorkflowGatewayEntity>(a)).ToDictionary(x => x.bpmnElementId);
this.connections = connections.ToDictionary(a => a.bpmnElementId);
this.outgoing = this.connections.Values.GroupToDictionary(a => a.Entity.From.ToLite());
this.incoming = this.connections.Values.GroupToDictionary(a => a.Entity.To.ToLite());
}
public void ApplyChanges(XElement processElement, XElement laneElement, Locator locator)
{
var laneIds = laneElement.Elements(bpmn + "flowNodeRef").Select(a => a.Value).ToHashSet();
var laneElements = processElement.Elements().Where(a => laneIds.Contains(a.Attribute("id")?.Value!));
var events = laneElements.Where(a => WorkflowEventTypes.Where(kvp => !kvp.Key.IsBoundaryTimer()).ToDictionary().Values.Contains(a.Name.LocalName)).ToDictionary(a => a.Attribute("id")!.Value);
var oldEvents = this.events.Values.Where(a => a.Entity.BoundaryOf == null).ToDictionaryEx(a => a.bpmnElementId, "events");
Synchronizer.Synchronize(events, oldEvents,
(id, e) =>
{
var already = (WorkflowEventEntity?)locator.FindEntity(id);
if (already != null)
{
locator.FindLane(already.Lane).events.Remove(id);
already.Lane = this.lane.Entity;
}
var we = (already ?? new WorkflowEventEntity { Xml = new WorkflowXmlEmbedded(), Lane = this.lane.Entity }).ApplyXml(e, locator);
this.events.Add(id, new XmlEntity<WorkflowEventEntity>(we));
},
(id, oe) =>
{
if (!locator.ExistDiagram(id))
{
this.events.Remove(id);
if (oe.Entity.Type == WorkflowEventType.IntermediateTimer)
MoveCasesAndDelete(oe.Entity, locator);
else
oe.Entity.Delete(WorkflowEventOperation.Delete);
};
},
(id, e, oe) =>
{
var we = oe.Entity.ApplyXml(e, locator);
});
var activities = laneElements.Where(a => WorkflowActivityTypes.Values.Contains(a.Name.LocalName)).ToDictionary(a => a.Attribute("id")!.Value);
var oldActivities = this.activities.Values.ToDictionaryEx(a => a.bpmnElementId, "activities");
Synchronizer.Synchronize(activities, oldActivities,
(id, a) =>
{
var already = (WorkflowActivityEntity?)locator.FindEntity(id);
if (already != null)
{
locator.FindLane(already.Lane).activities.Remove(id);
already.Lane = this.lane.Entity;
}
var wa = (already ?? new WorkflowActivityEntity { Xml = new WorkflowXmlEmbedded(), Lane = this.lane.Entity }).ApplyXml(a, locator, this.events);
this.activities.Add(id, new XmlEntity<WorkflowActivityEntity>(wa));
},
(id, oa) =>
{
if (!locator.ExistDiagram(id))
{
this.activities.Remove(id);
MoveCasesAndDelete(oa.Entity, locator);
};
},
(id, a, oa) =>
{
var we = oa.Entity.ApplyXml(a, locator, this.events);
});
var gateways = laneElements
.Where(a => WorkflowGatewayTypes.Values.Contains(a.Name.LocalName))
.ToDictionary(a => a.Attribute("id")!.Value);
var oldGateways = this.gateways.Values.ToDictionaryEx(a => a.bpmnElementId, "gateways");
Synchronizer.Synchronize(gateways, oldGateways,
(id, g) =>
{
var already = (WorkflowGatewayEntity?)locator.FindEntity(id);
if (already != null)
{
locator.FindLane(already.Lane).gateways.Remove(id);
already.Lane = this.lane.Entity;
}
var wg = (already ?? new WorkflowGatewayEntity { Xml = new WorkflowXmlEmbedded(), Lane = this.lane.Entity }).ApplyXml(g, locator);
this.gateways.Add(id, new XmlEntity<WorkflowGatewayEntity>(wg));
},
(id, og) =>
{
if (!locator.ExistDiagram(id))
{
this.gateways.Remove(id);
og.Entity.Delete(WorkflowGatewayOperation.Delete);
};
},
(id, g, og) =>
{
var we = og.Entity.ApplyXml(g, locator);
});
}
public IWorkflowNodeEntity? FindEntity(string bpmElementId)
{
return this.events.TryGetC(bpmElementId)?.Entity ??
this.activities.TryGetC(bpmElementId)?.Entity ??
(IWorkflowNodeEntity?)this.gateways.TryGetC(bpmElementId)?.Entity;
}
internal IEnumerable<XmlEntity<WorkflowEventEntity>> GetEvents()
{
return this.events.Values;
}
internal IEnumerable<XmlEntity<WorkflowActivityEntity>> GetActivities()
{
return this.activities.Values;
}
internal IEnumerable<XmlEntity<WorkflowGatewayEntity>> GetGateways()
{
return this.gateways.Values;
}
internal IEnumerable<XmlEntity<WorkflowConnectionEntity>> GetConnections()
{
return this.connections.Values;
}
internal bool IsEmpty()
{
return (!this.GetActivities().Any() && !this.GetEvents().Any() && !this.GetGateways().Any());
}
internal string GetBpmnElementId(IWorkflowNodeEntity node)
{
return (node is WorkflowEventEntity) ? events.Values.Single(a => a.Entity.Is(node)).bpmnElementId :
(node is WorkflowActivityEntity) ? activities.Values.Single(a => a.Entity.Is(node)).bpmnElementId :
(node is WorkflowGatewayEntity) ? gateways.Values.Single(a => a.Entity.Is(node)).bpmnElementId :
throw new InvalidOperationException(WorkflowValidationMessage.NodeType0WithId1IsInvalid.NiceToString(node.GetType().NiceName(), node.Id.ToString()));
}
internal XElement GetLaneSetElement()
{
return new XElement(bpmn + "lane",
new XAttribute("id", lane.bpmnElementId),
new XAttribute("name", lane.Entity.Name),
events.Values.Select(e => GetLaneFlowNodeRefElement(e.bpmnElementId)),
activities.Values.Select(e => GetLaneFlowNodeRefElement(e.bpmnElementId)),
gateways.Values.Select(e => GetLaneFlowNodeRefElement(e.bpmnElementId)));
}
private XElement GetLaneFlowNodeRefElement(string bpmnElementId)
{
return new XElement(bpmn + "flowNodeRef", bpmnElementId);
}
internal List<XElement> GetNodesElement()
{
return events.Values.Select(e => GetEventProcessElement(e))
.Concat(activities.Values.Select(e => GetActivityProcessElement(e)))
.Concat(gateways.Values.Select(e => GetGatewayProcessElement(e))).ToList();
}
internal List<XElement> GetDiagramElement()
{
List<XElement> res = new List<XElement>();
res.Add(lane.Element);
res.AddRange(events.Values.Select(a => a.Element)
.Concat(activities.Values.Select(a => a.Element))
.Concat(gateways.Values.Select(a => a.Element)));
return res;
}
public static Dictionary<WorkflowEventType, string> WorkflowEventTypes = new Dictionary<WorkflowEventType, string>()
{
{ WorkflowEventType.Start, "startEvent" },
{ WorkflowEventType.ScheduledStart, "startEvent" },
{ WorkflowEventType.Finish, "endEvent" },
{ WorkflowEventType.BoundaryForkTimer, "boundaryEvent" },
{ WorkflowEventType.BoundaryInterruptingTimer, "boundaryEvent" },
{ WorkflowEventType.IntermediateTimer, "intermediateCatchEvent" },
};
public static Dictionary<WorkflowActivityType, string> WorkflowActivityTypes = new Dictionary<WorkflowActivityType, string>()
{
{ WorkflowActivityType.Task, "task" },
{ WorkflowActivityType.Decision, "userTask" },
{ WorkflowActivityType.CallWorkflow, "callActivity" },
{ WorkflowActivityType.DecompositionWorkflow, "callActivity" },
{ WorkflowActivityType.Script, "scriptTask" },
};
public static Dictionary<WorkflowGatewayType, string> WorkflowGatewayTypes = new Dictionary<WorkflowGatewayType, string>()
{
{ WorkflowGatewayType.Inclusive, "inclusiveGateway" },
{ WorkflowGatewayType.Parallel, "parallelGateway" },
{ WorkflowGatewayType.Exclusive, "exclusiveGateway" },
};
private XElement GetEventProcessElement(XmlEntity<WorkflowEventEntity> e)
{
var activity = e.Entity.BoundaryOf?.Let(lite => this.activities.Values.SingleEx(a => lite.Is(a.Entity))).Entity;
return new XElement(bpmn + WorkflowEventTypes.GetOrThrow(e.Entity.Type),
new XAttribute("id", e.bpmnElementId),
activity != null ? new XAttribute("attachedToRef", activity.BpmnElementId) : null!,
e.Entity.Type == WorkflowEventType.BoundaryForkTimer ? new XAttribute("cancelActivity", false) : null!,
e.Entity.Name.HasText() ? new XAttribute("name", e.Entity.Name) : null!,
e.Entity.Type.IsScheduledStart() || e.Entity.Type.IsTimer() ?
new XElement(bpmn + ((((WorkflowEventModel)e.Entity.GetModel()).Task?.TriggeredOn == TriggeredOn.Always || (e.Entity.Type.IsTimer() && e.Entity.Timer!.Duration != null)) ?
"timerEventDefinition" : "conditionalEventDefinition")) : null!,
GetConnections(e.Entity.ToLite()));
}
private XElement GetActivityProcessElement(XmlEntity<WorkflowActivityEntity> a)
{
return new XElement(bpmn + WorkflowActivityTypes.GetOrThrow(a.Entity.Type),
new XAttribute("id", a.bpmnElementId),
new XAttribute("name", a.Entity.Name),
GetConnections(a.Entity.ToLite()));
}
private XElement GetGatewayProcessElement(XmlEntity<WorkflowGatewayEntity> g)
{
return new XElement(bpmn + WorkflowGatewayTypes.GetOrThrow(g.Entity.Type),
new XAttribute("id", g.bpmnElementId),
g.Entity.Name.HasText() ? new XAttribute("name", g.Entity.Name) : null!,
GetConnections(g.Entity.ToLite()));
}
private IEnumerable<XElement> GetConnections(Lite<IWorkflowNodeEntity> lite)
{
List<XElement> result = new List<XElement>();
result.AddRange(incoming.TryGetC(lite).EmptyIfNull().Select(c => new XElement(bpmn + "incoming", c.bpmnElementId)));
result.AddRange(outgoing.TryGetC(lite).EmptyIfNull().Select(c => new XElement(bpmn + "outgoing", c.bpmnElementId)));
return result;
}
internal void DeleteAll(Locator? locator)
{
foreach (var e in events.Values.Select(a => a.Entity))
{
if (e.Type == WorkflowEventType.IntermediateTimer)
{
if (locator != null)
MoveCasesAndDelete(e, locator);
else
{
DeleteCaseActivities(e, c => true);
e.Delete(WorkflowEventOperation.Delete);
}
}
else
e.Delete(WorkflowEventOperation.Delete);
}
foreach (var g in gateways.Values.Select(a => a.Entity))
{
g.Delete(WorkflowGatewayOperation.Delete);
}
foreach (var ac in activities.Values.Select(a => a.Entity))
{
if (locator != null)
MoveCasesAndDelete(ac, locator);
else
{
DeleteCaseActivities(ac, c => true);
ac.Delete(WorkflowActivityOperation.Delete);
}
}
this.lane.Entity.Delete(WorkflowLaneOperation.Delete);
}
internal void DeleteCaseActivities(Expression<Func<CaseEntity, bool>> filter)
{
foreach (var ac in activities.Values.Select(a => a.Entity))
DeleteCaseActivities(ac, filter);
}
private static void DeleteCaseActivities(IWorkflowNodeEntity node, Expression<Func<CaseEntity, bool>> filter)
{
if (node is WorkflowActivityEntity wa && (wa.Type == WorkflowActivityType.DecompositionWorkflow || wa.Type == WorkflowActivityType.CallWorkflow))
{
var sw = wa.SubWorkflow!.Workflow;
var wb = new WorkflowBuilder(sw);
wb.DeleteCases(c => filter.Evaluate(c.ParentCase!) && c.ParentCase!.Workflow == wa.Lane.Pool.Workflow);
}
var caseActivities = node.CaseActivities().Where(ca => filter.Evaluate(ca.Case));
if (caseActivities.Any())
{
caseActivities.SelectMany(a => a.Notifications()).UnsafeDelete();
Database.Query<CaseActivityEntity>()
.Where(ca => ca.Previous!.Entity.WorkflowActivity.Is(node) && filter.Evaluate(ca.Previous.Entity.Case))
.UnsafeUpdate()
.Set(ca => ca.Previous, ca => ca.Previous!.Entity.Previous)
.Execute();
var running = caseActivities.Where(a => a.State == CaseActivityState.Pending).ToList();
running.ForEach(a => {
if (a.Previous == null)
throw new ApplicationException(CaseActivityMessage.ImpossibleToDeleteCaseActivity0OnWorkflowActivity1BecauseHasNoPreviousActivity.NiceToString(a.Id, a.WorkflowActivity));
a.Previous.ExecuteLite(CaseActivityOperation.Undo);
});
caseActivities.UnsafeDelete();
}
}
private static void MoveCasesAndDelete(IWorkflowNodeEntity node, Locator? locator)
{
if (node.CaseActivities().Any())
{
if (locator!.HasReplacement(node.ToLite()))
{
var replacement = locator.GetReplacement(node.ToLite())!;
node.CaseActivities()
.Where(a => a.State == CaseActivityState.Done)
.UnsafeUpdate()
.Set(ca => ca.WorkflowActivity, ca => replacement)
.Execute();
var running = node.CaseActivities().Where(a => a.State == CaseActivityState.Pending).ToList();
running.ForEach(a =>
{
a.Notifications().UnsafeDelete();
a.WorkflowActivity = replacement;
a.Save();
CaseActivityLogic.InsertCaseActivityNotifications(a);
});
}
else
{
DeleteCaseActivities(node, a => true);
}
}
if (node is WorkflowActivityEntity wa)
wa.Delete(WorkflowActivityOperation.Delete);
else
((WorkflowEventEntity)node).Delete(WorkflowEventOperation.Delete);
}
internal void Clone(WorkflowPoolEntity pool, Dictionary<IWorkflowNodeEntity, IWorkflowNodeEntity> nodes)
{
var oldLane = this.lane.Entity;
WorkflowLaneEntity newLane = new WorkflowLaneEntity
{
Pool = pool,
Name = oldLane.Name,
BpmnElementId = oldLane.BpmnElementId,
Actors = oldLane.Actors.ToMList(),
ActorsEval = oldLane.ActorsEval?.Clone(),
Xml = oldLane.Xml,
}.Save();
var newEvents = this.events.Values.Select(e => e.Entity).ToDictionary(e => e, e => new WorkflowEventEntity
{
Lane = newLane,
Name = e.Name,
BpmnElementId = e.BpmnElementId,
Timer = e.Timer?.Clone(),
Type = e.Type,
Xml = e.Xml,
});
newEvents.Values.SaveList();
nodes.AddRange(newEvents.ToDictionary(kvp => (IWorkflowNodeEntity)kvp.Key, kvp => (IWorkflowNodeEntity)kvp.Value));
var newActivities = this.activities.Values.Select(a => a.Entity).ToDictionary(a => a, a =>
{
var na = new WorkflowActivityEntity
{
Lane = newLane,
Name = a.Name,
BpmnElementId = a.BpmnElementId,
Xml = a.Xml,
Type = a.Type,
ViewName = a.ViewName,
ViewNameProps = a.ViewNameProps.Select(p=> new ViewNamePropEmbedded
{
Name = p.Name,
Expression = p.Expression
}).ToMList(),
RequiresOpen = a.RequiresOpen,
EstimatedDuration = a.EstimatedDuration,
Script = a.Script?.Clone(),
SubWorkflow = a.SubWorkflow?.Clone(),
UserHelp = a.UserHelp,
Comments = a.Comments,
};
na.BoundaryTimers = a.BoundaryTimers.Select(t => newEvents.GetOrThrow(t)).ToMList();
return na;
});
newActivities.Values.SaveList();
nodes.AddRange(newActivities.ToDictionary(kvp => (IWorkflowNodeEntity)kvp.Key, kvp => (IWorkflowNodeEntity)kvp.Value));
var newGateways = this.gateways.Values.Select(g => g.Entity).ToDictionary(g => g, g => new WorkflowGatewayEntity
{
Lane = newLane,
Name = g.Name,
BpmnElementId = g.BpmnElementId,
Type = g.Type,
Direction = g.Direction,
Xml = g.Xml,
});
newGateways.Values.SaveList();
nodes.AddRange(newGateways.ToDictionary(kvp => (IWorkflowNodeEntity)kvp.Key, kvp => (IWorkflowNodeEntity)kvp.Value));
}
}
}
}
| |
#region license
//
// Linkage - a multi-broker .NET messaging API
// Copyright (c) 2004, 2011 Stephan D. Cote
//
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// Contributors:
// Stephan D. Cote
// - Initial API and implementation
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace Coyote.DataFrame {
/// <summary>
/// A hierarchical unit of data.
/// </summary>
/// <remarks>
/// <para>DataFrame models a unit of data that can be exchanged over a variety of transports for a variety communications needs.</para>
/// <para>This is a surprisingly efficient transmission scheme as all field values and child frames are stored in their wire format as byte arrays. They are then marshaled only when accessed and are ready for transmission.</para>
/// <para>The DataFrame class was conceived to implement the Data Transfer Object (DTO) design pattern in distributed applications. Passing a DataFrame as both argument and return values in remote service calls. Using this implementation of a DTO allows for more efficient transfer of data between distributed components, reducing latency, improving throughput and decoupling not only the components of the system, but moving business logic out of the data model.</para>
/// <para>More recently, this class ha proven to be an effective implementation of the Value Object pattern and has made representing database rows and objects relatively easy to code. It has several features which make this class more feature rich than implementing VOs with Maps or other map-based structures such as properties. Most of the recent upgrades have been directly related to VO implementations.</para>
/// </remarks>
public class DataFrame : ICloneable {
#region Attributes
/// The array of fields this frame holds
protected internal List<DataField> fields = new List<DataField>();
/// Flag indicating the top-level elements of this frame has been changed.
protected internal volatile bool modified = false;
#endregion
#region Properties
/// <summary>
/// Flag indicating this frame was modified since being constructed.
/// </summary>
public bool IsModified {
get {
return modified;
}
}
/// <summary>
/// Generate a digest fingerprint for this DataFrame based soley on the wire format of this and all fields contained therein.
/// </summary>
/// <remarks>
/// <para>This performs a SHA-1 digest on the payload to help determine a unique identifier for the DataFrame. Note: the digest can be used to help determine equivalance between DataFrames.</para>
/// </remarks>
/// <returns>A digest fingerprint of the payload.</returns>
public byte[] Digest {
get {
return new SHA1CryptoServiceProvider().ComputeHash( this.Bytes );
}
}
/// <summary>
/// Return the wire format of this frame.
/// </summary>
public byte[] Bytes {
get {
lock ( this ) {
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter( ms );
try {
for ( int i = 0; i < fields.Count; i++ ) {
bw.Write( (byte[])((DataField)fields[i]).Bytes );
}
} catch ( IOException ) {
//Log.Error( e.StackTrace );
}
return ms.ToArray();
}
}
}
/// <summary>
/// Generate a digest fingerprint for this message based solely on the wire format of the payload and returns it as a Hex string.
/// </summary>
/// <remarks>
/// <para>NOTE: This is a very expensive function and should not be used without due consideration.</para>
/// </remarks>
public virtual string DigestString {
get {
return ByteUtil.BytesToHex( Digest );
}
}
/// <summary>
/// Access the number of types supported
/// </summary>
public virtual int TypeCount {
get {
return DataField.TypeCount;
}
}
/// <summary>
/// Flag indicating if the frame contains no fields.
/// </summary>
public virtual bool IsEmpty {
get {
return fields.Count == 0;
}
}
/// <summary>
/// Returns true if all the children are un-named and therefore is considered to be an array.
/// </summary>
public virtual bool IsArray {
get {
bool retval = true;
foreach ( DataField field in fields ) {
if ( field.name != null ) {
return false;
}
}
return retval;
}
}
/// <summary>
/// Convenience method to return the number of fields in this frame to make code a little more readable.
/// </summary>
public virtual int Size { get { return fields.Count; } }
#endregion
#region Indexed Properties
/// <summary>The collection of fields in this frame.</summary>
public FieldCollection Field;
/// <summary>Type allowing the frame to be viewed like an array of fields.</summary>
public class FieldCollection {
readonly DataFrame frame; // The containing object
/// <summary>Private constructor tying this collection to a frame.</summary>
/// <param name="f">The frame owning this collection.</param>
internal FieldCollection( DataFrame f ) {
frame = f;
}
/// <summary>Indexer to get and set field values.</summary>
/// <param name="index"></param>
/// <returns></returns>
public DataField this[int index] {
get {
lock ( frame ) {
if ( index >= 0 && index < frame.fields.Count ) {
return frame.fields[index];
} else {
throw new IndexOutOfRangeException();
}
}
}
set {
lock ( frame ) {
if ( index >= 0 && index < frame.fields.Count ) {
frame.fields[index] = value;
} else {
throw new IndexOutOfRangeException();
}
}
}
}
/// <summary>Indexer to get and set field values by field name.</summary>
/// <param name="fname"></param>
/// <returns></returns>
public DataField this[string fname] {
get {
lock ( frame ) {
foreach ( DataField field in frame.fields ) {
if ( field.Name.Equals( fname ) )
return field;
}
}
return null; //cfg.fields....
}
set {
lock ( frame ) {
foreach ( DataField field in frame.fields ) {
if ( field.Name.Equals( fname ) ) {
field.Type = value.Type;
Array.Copy( value.Value, field.Value, value.Value.Length );
}
}
frame.fields.Add( (DataField)value.Clone() );
}
}
}
/// <summary>Get the count of fields in the frame.</summary>
public int Count {
get {
lock ( frame ) {
return frame.fields.Count;
}
}
}
/// <summary>Check to see if the give name is a name of one of the fields.</summary>
/// <remarks><para>This is a linear search across all the field names returning when the first match is encountered.</para></remarks>
/// <param name="name">The name to check</param>
/// <returns>True if there is a field which exactly matches the given name, false otherwise.</returns>
public bool Contains( string name ) {
lock ( frame ) {
foreach ( DataField field in frame.fields ) {
if ( field.Name.Equals( name ) )
return true;
}
return false;
}
}
/// <summary>Enumerate over all the fields in this frame; required by foreach loops.</summary>
/// <returns>An enumerator over all the fields in this frame.</returns>
public IEnumerator<DataField> GetEnumerator() {
return frame.fields.GetEnumerator();
}
}
#endregion
#region Constructors
/// <summary>
/// Empty constructor for Clone operations
/// </summary>
static DataFrame() {
}
/// <summary>
/// Construct an empty frame.
/// </summary>
public DataFrame() {
Field = new FieldCollection( this );
}
/// <summary>
/// Convenience constructor for a frame wrapping the given field.
/// </summary>
/// <param name="field">the field to place in this frame </param>
public DataFrame( DataField field ) : this() {
fields.Add( field );
}
/// <summary>
/// Construct a frame simultaneously populating a data field.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public DataFrame( string name, object value ) : this() {
Add( name, value );
modified = false;
}
/// <summary>
/// Construct the frame with the given bytes.
/// </summary>
/// <param name="data">The byte array from which to construct the frame.</param>
/// <exception cref="DecodeException">If there were problems decoding the byte array</exception>
public DataFrame( byte[] data ) : this() {
if ( data != null && data.Length > 0 ) {
int loc = 0;
int ploc = 0;
using ( MemoryStream stream = new MemoryStream( data ) ) {
using ( BinaryReader reader = new BinaryReader( stream ) ) {
while ( reader.BaseStream.Position != reader.BaseStream.Length ) {
ploc = loc;
loc = (int)reader.BaseStream.Position;
try {
Add( new DataField( reader ) );
} catch ( EndOfStreamException eof ) {
throw new DecodeException( "Data underflow adding field", eof, loc, ploc, (fields.Count + 1), (fields.Count > 0) ? fields[fields.Count - 1] : null );
} catch ( IOException ioe ) {
throw new DecodeException( "Problems decoding field", ioe, loc, ploc, (fields.Count + 1), (fields.Count > 0) ? fields[fields.Count - 1] : null );
} catch ( DecodeException de ) {
throw new DecodeException( "DF:" + de.Message, de.InnerException, loc, ploc, de.FieldIndex, de.LastField );
}
}
}
}
}
}
/// <summary>Construct a frame copying the fields from the given frame. Since this is a constructor, the modified flag remains unset.</summary>
/// <param name="source">The frame from which data is copied.</param>
public DataFrame( DataFrame source )
: this() {
Copy( source );
modified = false;
}
#endregion
#region Methods
/// <summary>Deep copy all the fields of the given frame into this frame. The result includes setting the modified flag of this frame to true.</summary>
/// <param name="source">The frame from which data is copied.</param>
protected void Copy( DataFrame source ) {
for ( int i = 0; i < source.fields.Count; i++ ) {
fields.Insert( i, (DataField)((DataField)source.fields[i]).Clone() );
}
}
/// <summary>
/// Convenience method to check if this frame contains a field with the given name.
/// </summary>
/// <param name="name">The name of the field to check</param>
/// <returns>true if this frame contains a field with the given name, false otherwise.</returns>
public bool Contains( string name ) {
if ( name != null ) {
foreach ( DataField field in fields ) {
if ( String.Equals( name, field.Name, StringComparison.Ordinal ) ) {
return true;
}
}
}
return false;
}
/// <summary>
/// Find the first field with the given name - Case insensitive.
/// </summary>
/// <param name="name">The name of the field to find</param>
/// <returns>The first field with the given name, or null if no matching field was found.</returns>
public DataField Find( string name ) {
if ( name != null ) {
foreach ( DataField field in fields ) {
if ( String.Equals( name, field.Name, StringComparison.OrdinalIgnoreCase ) ) {
return field;
}
}
}
return null;
}
/// <summary>Add the given name-value pair to the frame.</summary>
/// <param name="name">Name of the field to add; if null, the value will only be accessible by its returned index.</param>
/// <param name="value">The value to place in the frame.</param>
/// <returns>The index of the placed value which can be used to later retrieve the value.</returns>
public int Add( string name, object value ) {
modified = true;
if ( value is DataField )
fields.Add( (DataField)value );
else
fields.Add( new DataField( name, value ) );
return fields.Count - 1;
}
/// <summary>Place the (anonymous)object in the frame without a name.</summary>
/// <param name="obj">Value of the field.</param>
/// <returns>The index in the list of message fields this value was placed.</returns>
public int Add( object obj ) {
modified = true;
if ( obj is DataField ) {
fields.Add( (DataField)obj );
} else {
fields.Add( new DataField( obj ) );
}
return fields.Count - 1;
}
/// <summary>Place the object in the DataFrame under the given name, overwriting any existing object with the same name.</summary>
/// <remarks><para>Note this is different from Add(String,Object) in that this method will eliminate duplicate names.</para></remarks>
/// <param name="name">Name of the field.</param>
/// <param name="obj">Value of the field.</param>
/// <returns></returns>
public int Put( string name, object obj ) {
lock ( fields ) {
if ( name != null ) {
for ( int i = 0; i < fields.Count; i++ ) {
DataField field = (DataField)fields[i];
if ( (field.Name != null) && field.Name.Equals( name ) ) {
// This is less than optimal! Why can't we do an in-place substitution/overwrite?
fields.Insert( i, new DataField( name, obj ) );
fields.RemoveAt( i + 1 );
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
modified = true;
return i;
}
}
return Add( name, obj );
} else {
return Add( obj );
}
}
}
/// <summary>Remove the first occurence of a DataField with the given name.</summary>
/// <param name="name">The name of the field to remove.</param>
public DataField Remove( string name ) {
if ( name != null ) {
for ( int i = 0; i < fields.Count; i++ ) {
DataField field = (DataField)fields[i];
if ( (field.Name != null) && field.Name.Equals( name ) ) {
fields.RemoveAt( i );
modified = true;
return field;
}
}
}
return null;
}
/// <summary>Remove all occurences of DataFields with the given name.</summary>
/// <param name="name">name of the fields to remove.</param>
/// <returns>A list of all the fields removed. Will never be null but may be empty if no fields with the given name were not found.</returns>
public List<DataField> RemoveAll( string name ) {
modified = true;
List<DataField> retval = new List<DataField>();
if ( name != null ) {
for ( int i = 0; i < fields.Count; i++ ) {
DataField field = (DataField)fields[i];
if ( (field.Name != null) && field.Name.Equals( name ) ) {
retval.Add( field );
fields.RemoveAt( i );
}
}
}
return retval;
}
/// <summary>
/// Remove the first field with the given name and add a new field with the given name and new object value.
/// </summary>
/// <remarks>
/// <para>This is equivalent to calling Remove(name); and then Add(name,obj);.</para>
/// <para>A check of the given type is performed before the remove method is called to throw an exception before removing any data.</para>
/// </remarks>
/// <param name="name">Name of the field to replace and then add.</param>
/// <param name="obj">The value of the object to set in the new field.</param>
/// <exception cref="ArgumetException">if the given object is not of a supported type.</exception>"
public void Replace( string name, object obj ) {
// check if the type is supported first
DataField.GetType( obj );
Remove( name );
Add( name, obj );
}
/// <summary>
/// Remove all the fields with the given name and add a single new field with the given name and new object value.
/// </summary>
/// <remarks>
/// <para>This is equivalent to calling RemoveAll(name); and then Add(name,obj);.</para>
/// <para>A check of the given type is performed before the remove method is called to throw an exception before removing any data.</para>
/// </remarks>
/// <param name="name">Name of the field to replace and then add.</param>
/// <param name="obj">The value of the object to set in the new field.</param>
/// <exception cref="ArgumetException">if the given object is not of a supported type.</exception>"
public void ReplaceAll( string name, object obj ) {
// check if the type is supported first
DataField.GetType( obj );
RemoveAll( name );
Add( name, obj );
}
/// <summary>Create a deep-copy of this DataFrame.</summary>
/// <returns>A copy of this data frame.</returns>
public virtual object Clone() {
DataFrame retval = new DataFrame();
// Clone all the fields
for ( int i = 0; i < fields.Count; i++ ) {
retval.fields.Insert( i, (DataField)((DataField)fields[i]).Clone() );
}
retval.modified = false;
return retval;
}
/// <summary>
/// Remove all the fields from this frame.
/// </summary>
/// <remarks>
/// <para>The frame will be empty after this method is called.</para>
/// </remarks>
public virtual void Clear() {
fields.Clear();
}
/// <summary>
/// This will return a list of unique field names in this data frame.
/// </summary>
/// <remarks>
/// <para>Note that fields are not required to have names. They can be anonymous and accessed by their index in the frame. Therefore it is possible that some fields will be inaccessible by name and will not be represented in the returned list of names.</para>
/// </remarks>
/// <returns>a list of field names in this frame.</returns>
public virtual List<string> GetNames() {
List<string> retval = new List<string>();
// get a list of unique field names
HashSet<string> names = new HashSet<string>();
for ( int i = 0; i < fields.Count; names.Add( fields[i++].Name ) ) ;
retval.AddRange( names );
return retval;
}
/// <summary>This is a very simple string representation of this data frame.</summary>
/// <returns>Human readable representation of this frame.</returns>
public override string ToString() {
StringBuilder b = new StringBuilder();
if ( fields.Count > 0 ) {
bool isArray = this.IsArray;
if ( isArray )
b.Append( "[" );
else
b.Append( "{" );
foreach ( DataField field in fields ) {
if ( !isArray ) {
b.Append( '"' );
b.Append( field.Name );
b.Append( "\":" );
}
if ( field.Type == DataField.UDEF ) {
b.Append( "null" );
} else if ( field.Type == DataField.BOOLEAN ) {
b.Append( field.StringValue.ToLower() );
} else if ( field.IsNumeric ) {
b.Append( field.StringValue );
} else if ( field.Type == DataField.STRING ) {
b.Append( '"' );
b.Append( field.StringValue );
b.Append( '"' );
} else if ( field.Type == DataField.DATE ) {
b.Append( '"' );
b.Append( field.StringValue );
b.Append( '"' );
} else if ( field.Type != DataField.FRAME ) {
if ( field.ObjectValue != null ) {
b.Append( '"' );
b.Append( field.ObjectValue.ToString() );
b.Append( '"' );
}
} else {
if ( field.IsNull ) {
b.Append( "null" );
} else {
b.Append( field.ObjectValue.ToString() );
}
}
b.Append( "," );
}
b.Remove( b.Length - 1, 1 );
if ( isArray )
b.Append( "]" );
else
b.Append( "}" );
} else {
b.Append( "{}" );
}
return b.ToString();
}
/// <summary>
/// Places all of the fields in the given frame in this frame, overwriting the values with the same name.
/// </summary>
/// <remarks>
/// <para>This is essentially a Put operation for all the fields in the given frame. Contrast this Populate(DataFrame).</para>
/// </remarks>
/// <param name="frame">The frame from which the fields are read.</param>
public virtual void Merge( DataFrame frame ) {
foreach ( DataField field in frame.Field ) {
this.Put( field.Name, field.ObjectValue );
}
}
/// <summary>
/// Places all of the fields in the given frame in this frame.
/// </summary>
/// <remarks>
/// <para>Overwriting does not occur. This is a straight addition of fields. It is possible that multiple fields with the same name may exist after this operation. Contrast this to Merge(DataFrame).</para>
/// <para>This is essentially an Add operation for all the fields in the given frame.</para>
/// </remarks>
/// <param name="frame">The frame from which the fields are read.</param>
public virtual void Populate( DataFrame frame ) {
foreach ( DataField field in frame.Field ) {
Add( field );
}
}
#endregion
}
}
| |
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2011 Anders Moeller
* All rights reserved.
* http://github.com/moodmosaic/Fare/
* Original Java code:
* http://www.brics.dk/automaton/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Collections.Generic;
using System.Linq;
namespace Ploeh.AutoFixture.DataAnnotations
{
internal static class MinimizationOperations
{
/// <summary>
/// Minimizes (and determinizes if not already deterministic) the given automaton.
/// </summary>
/// <param name="a">The automaton.</param>
internal static void Minimize(Automaton a)
{
if (!a.IsSingleton)
{
switch (Automaton.Minimization)
{
case Automaton.MinimizeHuffman:
MinimizationOperations.MinimizeHuffman(a);
break;
case Automaton.MinimizeBrzozowski:
MinimizationOperations.MinimizeBrzozowski(a);
break;
default:
MinimizationOperations.MinimizeHopcroft(a);
break;
}
}
a.RecomputeHashCode();
}
/// <summary>
/// Minimizes the given automaton using Brzozowski's algorithm.
/// </summary>
/// <param name="a">The automaton.</param>
internal static void MinimizeBrzozowski(Automaton a)
{
if (a.IsSingleton)
{
return;
}
BasicOperations.Determinize(a, SpecialOperations.Reverse(a).ToList());
BasicOperations.Determinize(a, SpecialOperations.Reverse(a).ToList());
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1814:PreferJaggedArraysOverMultidimensional", Justification = "This method has been ported as-is.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This method has been ported as-is.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1809:AvoidExcessiveLocals", Justification = "This method has been ported as-is.")]
internal static void MinimizeHopcroft(Automaton a)
{
a.Determinize();
IList<Transition> tr = a.Initial.Transitions;
if (tr.Count == 1)
{
Transition t = tr[0];
if (t.To == a.Initial && t.Min == char.MinValue && t.Max == char.MaxValue)
{
return;
}
}
a.Totalize();
// Make arrays for numbered states and effective alphabet.
HashSet<State> ss = a.GetStates();
var states = new State[ss.Count];
int number = 0;
foreach (State q in ss)
{
states[number] = q;
q.Number = number++;
}
char[] sigma = a.GetStartPoints();
// Initialize data structures.
var reverse = new List<List<LinkedList<State>>>();
foreach (State s in states)
{
var v = new List<LinkedList<State>>();
Initialize(ref v, sigma.Length);
reverse.Add(v);
}
var reverseNonempty = new bool[states.Length, sigma.Length];
var partition = new List<LinkedList<State>>();
Initialize(ref partition, states.Length);
var block = new int[states.Length];
var active = new StateList[states.Length, sigma.Length];
var active2 = new StateListNode[states.Length, sigma.Length];
var pending = new LinkedList<IntPair>();
var pending2 = new bool[sigma.Length, states.Length];
var split = new List<State>();
var split2 = new bool[states.Length];
var refine = new List<int>();
var refine2 = new bool[states.Length];
var splitblock = new List<List<State>>();
Initialize(ref splitblock, states.Length);
for (int q = 0; q < states.Length; q++)
{
splitblock[q] = new List<State>();
partition[q] = new LinkedList<State>();
for (int x = 0; x < sigma.Length; x++)
{
reverse[q][x] = new LinkedList<State>();
active[q, x] = new StateList();
}
}
// Find initial partition and reverse edges.
foreach (State qq in states)
{
int j = qq.Accept ? 0 : 1;
partition[j].AddLast(qq);
block[qq.Number] = j;
for (int x = 0; x < sigma.Length; x++)
{
char y = sigma[x];
State p = qq.Step(y);
reverse[p.Number][x].AddLast(qq);
reverseNonempty[p.Number, x] = true;
}
}
// Initialize active sets.
for (int j = 0; j <= 1; j++)
{
for (int x = 0; x < sigma.Length; x++)
{
foreach (State qq in partition[j])
{
if (reverseNonempty[qq.Number, x])
{
active2[qq.Number, x] = active[j, x].Add(qq);
}
}
}
}
// Initialize pending.
for (int x = 0; x < sigma.Length; x++)
{
int a0 = active[0, x].Size;
int a1 = active[1, x].Size;
int j = a0 <= a1 ? 0 : 1;
pending.AddLast(new IntPair(j, x));
pending2[x, j] = true;
}
// Process pending until fixed point.
int k = 2;
while (pending.Count > 0)
{
IntPair ip = pending.RemoveAndReturnFirst();
int p = ip.N1;
int x = ip.N2;
pending2[x, p] = false;
// Find states that need to be split off their blocks.
for (StateListNode m = active[p, x].First; m != null; m = m.Next)
{
foreach (State s in reverse[m.State.Number][x])
{
if (!split2[s.Number])
{
split2[s.Number] = true;
split.Add(s);
int j = block[s.Number];
splitblock[j].Add(s);
if (!refine2[j])
{
refine2[j] = true;
refine.Add(j);
}
}
}
}
// Refine blocks.
foreach (int j in refine)
{
if (splitblock[j].Count < partition[j].Count)
{
LinkedList<State> b1 = partition[j];
LinkedList<State> b2 = partition[k];
foreach (State s in splitblock[j])
{
b1.Remove(s);
b2.AddLast(s);
block[s.Number] = k;
for (int c = 0; c < sigma.Length; c++)
{
StateListNode sn = active2[s.Number, c];
if (sn != null && sn.StateList == active[j, c])
{
sn.Remove();
active2[s.Number, c] = active[k, c].Add(s);
}
}
}
// Update pending.
for (int c = 0; c < sigma.Length; c++)
{
int aj = active[j, c].Size;
int ak = active[k, c].Size;
if (!pending2[c, j] && 0 < aj && aj <= ak)
{
pending2[c, j] = true;
pending.AddLast(new IntPair(j, c));
}
else
{
pending2[c, k] = true;
pending.AddLast(new IntPair(k, c));
}
}
k++;
}
foreach (State s in splitblock[j])
{
split2[s.Number] = false;
}
refine2[j] = false;
splitblock[j].Clear();
}
split.Clear();
refine.Clear();
}
// Make a new state for each equivalence class, set initial state.
var newstates = new State[k];
for (int n = 0; n < newstates.Length; n++)
{
var s = new State();
newstates[n] = s;
foreach (State q in partition[n])
{
if (q == a.Initial)
{
a.Initial = s;
}
s.Accept = q.Accept;
s.Number = q.Number; // Select representative.
q.Number = n;
}
}
// Build transitions and set acceptance.
foreach (State s in newstates)
{
s.Accept = states[s.Number].Accept;
foreach (Transition t in states[s.Number].Transitions)
{
s.Transitions.Add(new Transition(t.Min, t.Max, newstates[t.To.Number]));
}
}
a.RemoveDeadTransitions();
}
/// <summary>
/// Minimizes the given automaton using Huffman's algorithm.
/// </summary>
/// <param name="a">The automaton.</param>
internal static void MinimizeHuffman(Automaton a)
{
a.Determinize();
a.Totalize();
HashSet<State> ss = a.GetStates();
var transitions = new Transition[ss.Count][];
State[] states = ss.ToArray();
var mark = new List<List<bool>>();
var triggers = new List<List<HashSet<IntPair>>>();
foreach (State t in states)
{
var v = new List<HashSet<IntPair>>();
Initialize(ref v, states.Length);
triggers.Add(v);
}
// Initialize marks based on acceptance status and find transition arrays.
for (int n1 = 0; n1 < states.Length; n1++)
{
states[n1].Number = n1;
transitions[n1] = states[n1].GetSortedTransitions(false).ToArray();
for (int n2 = n1 + 1; n2 < states.Length; n2++)
{
if (states[n1].Accept != states[n2].Accept)
{
mark[n1][n2] = true;
}
}
}
// For all pairs, see if states agree.
for (int n1 = 0; n1 < states.Length; n1++)
{
for (int n2 = n1 + 1; n2 < states.Length; n2++)
{
if (!mark[n1][n2])
{
if (MinimizationOperations.StatesAgree(transitions, mark, n1, n2))
{
MinimizationOperations.AddTriggers(transitions, triggers, n1, n2);
}
else
{
MinimizationOperations.MarkPair(mark, triggers, n1, n2);
}
}
}
}
// Assign equivalence class numbers to states.
int numclasses = 0;
foreach (State t in states)
{
t.Number = -1;
}
for (int n1 = 0; n1 < states.Length; n1++)
{
if (states[n1].Number == -1)
{
states[n1].Number = numclasses;
for (int n2 = n1 + 1; n2 < states.Length; n2++)
{
if (!mark[n1][n2])
{
states[n2].Number = numclasses;
}
}
numclasses++;
}
}
// Make a new state for each equivalence class.
var newstates = new State[numclasses];
for (int n = 0; n < numclasses; n++)
{
newstates[n] = new State();
}
// Select a class representative for each class and find the new initial state.
for (int n = 0; n < states.Length; n++)
{
newstates[states[n].Number].Number = n;
if (states[n] == a.Initial)
{
a.Initial = newstates[states[n].Number];
}
}
// Build transitions and set acceptance.
for (int n = 0; n < numclasses; n++)
{
State s = newstates[n];
s.Accept = states[s.Number].Accept;
foreach (Transition t in states[s.Number].Transitions)
{
s.Transitions.Add(new Transition(t.Min, t.Max, newstates[t.To.Number]));
}
}
a.RemoveDeadTransitions();
}
private static void Initialize<T>(ref List<T> list, int size)
{
for (int i = 0; i < size; i++)
{
list.Add(default(T));
}
}
private static void AddTriggers(Transition[][] transitions, IList<List<HashSet<IntPair>>> triggers, int n1, int n2)
{
Transition[] t1 = transitions[n1];
Transition[] t2 = transitions[n2];
for (int k1 = 0, k2 = 0; k1 < t1.Length && k2 < t2.Length;)
{
if (t1[k1].Max < t2[k2].Min)
{
k1++;
}
else if (t2[k2].Max < t1[k1].Min)
{
k2++;
}
else
{
if (t1[k1].To != t2[k2].To)
{
int m1 = t1[k1].To.Number;
int m2 = t2[k2].To.Number;
if (m1 > m2)
{
int t = m1;
m1 = m2;
m2 = t;
}
if (triggers[m1][m2] == null)
{
triggers[m1].Insert(m2, new HashSet<IntPair>());
}
triggers[m1][m2].Add(new IntPair(n1, n2));
}
if (t1[k1].Max < t2[k2].Max)
{
k1++;
}
else
{
k2++;
}
}
}
}
private static void MarkPair(List<List<bool>> mark, IList<List<HashSet<IntPair>>> triggers, int n1, int n2)
{
mark[n1][n2] = true;
if (triggers[n1][n2] != null)
{
foreach (IntPair p in triggers[n1][n2])
{
int m1 = p.N1;
int m2 = p.N2;
if (m1 > m2)
{
int t = m1;
m1 = m2;
m2 = t;
}
if (!mark[m1][m2])
{
MarkPair(mark, triggers, m1, m2);
}
}
}
}
private static bool StatesAgree(Transition[][] transitions, List<List<bool>> mark, int n1, int n2)
{
Transition[] t1 = transitions[n1];
Transition[] t2 = transitions[n2];
for (int k1 = 0, k2 = 0; k1 < t1.Length && k2 < t2.Length;)
{
if (t1[k1].Max < t2[k2].Min)
{
k1++;
}
else if (t2[k2].Max < t1[k1].Min)
{
k2++;
}
else
{
int m1 = t1[k1].To.Number;
int m2 = t2[k2].To.Number;
if (m1 > m2)
{
int t = m1;
m1 = m2;
m2 = t;
}
if (mark[m1][m2])
{
return false;
}
if (t1[k1].Max < t2[k2].Max)
{
k1++;
}
else
{
k2++;
}
}
}
return true;
}
#region Nested type: IntPair
private sealed class IntPair
{
internal IntPair(int n1, int n2)
{
this.N1 = n1;
this.N2 = n2;
}
internal int N1 { get; }
internal int N2 { get; }
}
#endregion
#region Nested type: StateList
private sealed class StateList
{
internal int Size { get; set; }
internal StateListNode First { get; set; }
internal StateListNode Last { get; set; }
internal StateListNode Add(State q)
{
return new StateListNode(q, this);
}
}
#endregion
#region Nested type: StateListNode
private sealed class StateListNode
{
internal StateListNode(State q, StateList sl)
{
State = q;
StateList = sl;
if (sl.Size++ == 0)
{
sl.First = sl.Last = this;
}
else
{
sl.Last.Next = this;
Prev = sl.Last;
sl.Last = this;
}
}
internal StateListNode Next { get; private set; }
private StateListNode Prev { get; set; }
internal StateList StateList { get; private set; }
internal State State { get; private set; }
internal void Remove()
{
StateList.Size--;
if (StateList.First == this)
{
StateList.First = Next;
}
else
{
Prev.Next = Next;
}
if (StateList.Last == this)
{
StateList.Last = Prev;
}
else
{
Next.Prev = Prev;
}
}
}
#endregion
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
namespace Valle.TpvFinal
{
public partial class Herramientas
{
private global::Gtk.VBox vbox1;
private global::Valle.GtkUtilidades.MiLabel lblTitulo;
private global::Gtk.VBox hbox1;
private global::Valle.GtkUtilidades.MiLabel lblImprimir;
private global::Valle.GtkUtilidades.MiLabel lblAdminitrador;
private global::Gtk.HButtonBox hbuttonbox1;
private global::Gtk.Button btnImprimir;
private global::Gtk.VBox vbox2;
private global::Gtk.Image imgImprimir;
private global::Gtk.Label lblBtnImprimir;
private global::Gtk.Button btnBorrarZ;
private global::Gtk.VBox vbox3;
private global::Gtk.Image image130;
private global::Gtk.Label label2;
private global::Gtk.Button btnArqueoCaja;
private global::Gtk.VBox vboxArqueoCaja;
private global::Gtk.Image imageArqueoCaja;
private global::Gtk.Label labelArqueoCaja;
private global::Gtk.Button btnTrimestres;
private global::Gtk.VBox vbox4;
private global::Gtk.Image image131;
private global::Gtk.Label label3;
private global::Gtk.Button btnListado;
private global::Gtk.VBox vbox5;
private global::Gtk.Image image132;
private global::Gtk.Label label4;
private global::Gtk.Button btnSalir;
private global::Gtk.VBox vbox6;
private global::Gtk.Image image133;
private global::Gtk.Label label5;
private global::Gtk.HButtonBox hbuttonbox2;
private global::Gtk.Button btnCambiar;
private global::Gtk.VBox vbox7;
private global::Gtk.Image image134;
private global::Gtk.Label label6;
private global::Gtk.Button btnReiniciar;
private global::Gtk.VBox vbox8;
private global::Gtk.Image image135;
private global::Gtk.Label label7;
private global::Gtk.Button btnMinimizar;
private global::Gtk.VBox vbox9;
private global::Gtk.Image image136;
private global::Gtk.Label label8;
private global::Gtk.Button btnComfiguracion;
private global::Gtk.VBox vbox10;
private global::Gtk.Image image137;
private global::Gtk.Label label9;
private global::Gtk.Button btnBloquear;
private global::Gtk.VBox vbox11;
private global::Gtk.Image imgKey;
private global::Gtk.Label lblBtnBloquear;
protected virtual void Init ()
{
global::Stetic.Gui.Initialize (this);
// Widget Valle.TpvFinal.Herramientas
this.Name ="Valle.Tpv.iconos.Herramientas";
this.Title = global::Mono.Unix.Catalog.GetString ("Herramientas");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child Valle.TpvFinal.Herramientas.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
this.vbox1.BorderWidth = ((uint)(12));
// Container child vbox1.Gtk.Box+BoxChild
this.lblTitulo = new global::Valle.GtkUtilidades.MiLabel ();
this.lblTitulo.HeightRequest = 25;
this.lblTitulo.Events = ((global::Gdk.EventMask)(256));
this.lblTitulo.Name = "lblTitulo";
this.vbox1.Add (this.lblTitulo);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.lblTitulo]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.VBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.lblImprimir = new global::Valle.GtkUtilidades.MiLabel ();
this.lblImprimir.HeightRequest = 25;
this.lblImprimir.Events = ((global::Gdk.EventMask)(256));
this.lblImprimir.Name = "lblImprimir";
this.hbox1.Add (this.lblImprimir);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.lblImprimir]));
w2.Position = 0;
// Container child hbox1.Gtk.Box+BoxChild
this.lblAdminitrador = new global::Valle.GtkUtilidades.MiLabel ();
this.lblAdminitrador.HeightRequest = 25;
this.lblAdminitrador.Events = ((global::Gdk.EventMask)(256));
this.lblAdminitrador.Name = "lblAdminitrador";
this.hbox1.Add (this.lblAdminitrador);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.lblAdminitrador]));
w3.Position = 1;
this.vbox1.Add (this.hbox1);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox1]));
w4.Position = 1;
w4.Expand = true;
w4.Fill = true;
// Container child vbox1.Gtk.Box+BoxChild
this.hbuttonbox1 = new global::Gtk.HButtonBox ();
this.hbuttonbox1.Name = "hbuttonbox1";
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnImprimir = new global::Gtk.Button ();
this.btnImprimir.WidthRequest = 100;
this.btnImprimir.HeightRequest = 100;
this.btnImprimir.CanFocus = true;
this.btnImprimir.Name = "btnImprimir";
// Container child btnImprimir.Gtk.Container+ContainerChild
this.vbox2 = new global::Gtk.VBox ();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 6;
// Container child vbox2.Gtk.Box+BoxChild
this.imgImprimir = new global::Gtk.Image ();
this.imgImprimir.Name = "imgImprimir";
this.imgImprimir.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-print", global::Gtk.IconSize.Dialog);
this.vbox2.Add (this.imgImprimir);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.imgImprimir]));
w5.Position = 0;
// Container child vbox2.Gtk.Box+BoxChild
this.lblBtnImprimir = new global::Gtk.Label ();
this.lblBtnImprimir.Name = "lblBtnImprimir";
this.lblBtnImprimir.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Imrpimir</big>");
this.lblBtnImprimir.UseMarkup = true;
this.vbox2.Add (this.lblBtnImprimir);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.lblBtnImprimir]));
w6.Position = 1;
w6.Expand = false;
w6.Fill = false;
this.btnImprimir.Add (this.vbox2);
this.btnImprimir.Label = null;
this.hbuttonbox1.Add (this.btnImprimir);
global::Gtk.ButtonBox.ButtonBoxChild w8 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnImprimir]));
w8.Expand = false;
w8.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnBorrarZ = new global::Gtk.Button ();
this.btnBorrarZ.CanFocus = true;
this.btnBorrarZ.Name = "btnBorrarZ";
// Container child btnBorrarZ.Gtk.Container+ContainerChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.image130 = new global::Gtk.Image ();
this.image130.Name = "image130";
this.image130.Pixbuf = Gdk.Pixbuf.LoadFromResource("Valle.Tpv.iconos.euro.png");
this.vbox3.Add (this.image130);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.image130]));
w9.Position = 0;
// Container child vbox3.Gtk.Box+BoxChild
this.label2 = new global::Gtk.Label ();
this.label2.Name = "label2";
this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("<big> Borrar </big>\n<big>Contador Z</big>");
this.label2.UseMarkup = true;
this.vbox3.Add (this.label2);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.label2]));
w10.Position = 1;
w10.Expand = false;
w10.Fill = false;
this.btnBorrarZ.Add (this.vbox3);
this.btnBorrarZ.Label = null;
this.hbuttonbox1.Add (this.btnBorrarZ);
global::Gtk.ButtonBox.ButtonBoxChild w12 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnBorrarZ]));
w12.Position = 1;
w12.Expand = false;
w12.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnArqueoCaja = new global::Gtk.Button ();
this.btnArqueoCaja.CanFocus = true;
this.btnArqueoCaja.Name = "btnArqueoCaja";
// Container child btnBorrarZ.Gtk.Container+ContainerChild
this.vboxArqueoCaja = new global::Gtk.VBox ();
this.vboxArqueoCaja.Name = "vboxArqueoCaja";
this.vboxArqueoCaja.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.imageArqueoCaja = new global::Gtk.Image ();
this.imageArqueoCaja.Name = "imageArqueoCaja";
this.imageArqueoCaja.Pixbuf = Gdk.Pixbuf.LoadFromResource("Valle.Tpv.iconos.cajonMonedas.jpeg");
this.vboxArqueoCaja.Add (this.imageArqueoCaja);
global::Gtk.Box.BoxChild wAr = ((global::Gtk.Box.BoxChild)(this.vboxArqueoCaja[this.imageArqueoCaja]));
wAr.Position = 0;
// Container child vbox3.Gtk.Box+BoxChild
this.labelArqueoCaja = new global::Gtk.Label ();
this.labelArqueoCaja.Name = "labelArqueoCaja";
this.labelArqueoCaja.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>ArqueoCaja</big>");
this.labelArqueoCaja.UseMarkup = true;
this.vboxArqueoCaja.Add (this.labelArqueoCaja);
global::Gtk.Box.BoxChild wAr1 = ((global::Gtk.Box.BoxChild)(this.vboxArqueoCaja[this.labelArqueoCaja]));
wAr1.Position = 1;
wAr1.Expand = false;
wAr1.Fill = false;
this.btnArqueoCaja.Add (this.vboxArqueoCaja);
this.btnArqueoCaja.Label = null;
this.hbuttonbox1.Add (this.btnArqueoCaja);
global::Gtk.ButtonBox.ButtonBoxChild wAr12 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnArqueoCaja]));
wAr12.Position = 2;
wAr12.Expand = false;
wAr12.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnTrimestres = new global::Gtk.Button ();
this.btnTrimestres.CanFocus = true;
this.btnTrimestres.Name = "btnTrimestres";
// Container child btnTrimestres.Gtk.Container+ContainerChild
this.vbox4 = new global::Gtk.VBox ();
this.vbox4.Name = "vbox4";
this.vbox4.Spacing = 6;
// Container child vbox4.Gtk.Box+BoxChild
this.image131 = new global::Gtk.Image ();
this.image131.Name = "image131";
this.image131.Pixbuf = Gdk.Pixbuf.LoadFromResource("Valle.Tpv.iconos.valances.jpeg");
this.vbox4.Add (this.image131);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.image131]));
w13.Position = 0;
// Container child vbox4.Gtk.Box+BoxChild
this.label3 = new global::Gtk.Label ();
this.label3.Name = "label3";
this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Dias, Meses</big>\n<big> trimestres </big>");
this.label3.UseMarkup = true;
this.vbox4.Add (this.label3);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label3]));
w14.Position = 1;
w14.Expand = false;
w14.Fill = false;
this.btnTrimestres.Add (this.vbox4);
this.btnTrimestres.Label = null;
this.hbuttonbox1.Add (this.btnTrimestres);
global::Gtk.ButtonBox.ButtonBoxChild w16 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnTrimestres]));
w16.Position = 3;
w16.Expand = false;
w16.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnListado = new global::Gtk.Button ();
this.btnListado.CanFocus = true;
this.btnListado.Name = "btnListado";
// Container child btnListado.Gtk.Container+ContainerChild
this.vbox5 = new global::Gtk.VBox ();
this.vbox5.Name = "vbox5";
this.vbox5.Spacing = 6;
// Container child vbox5.Gtk.Box+BoxChild
this.image132 = new global::Gtk.Image ();
this.image132.Name = "image132";
this.image132.Pixbuf = Gdk.Pixbuf.LoadFromResource("Valle.Tpv.iconos.OFFCE02C.ICO");
this.vbox5.Add (this.image132);
global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.image132]));
w17.Position = 0;
// Container child vbox5.Gtk.Box+BoxChild
this.label4 = new global::Gtk.Label ();
this.label4.Name = "label4";
this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Listado</big>\n<big>Cierres</big>");
this.label4.UseMarkup = true;
this.vbox5.Add (this.label4);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.vbox5[this.label4]));
w18.Position = 1;
w18.Expand = false;
w18.Fill = false;
this.btnListado.Add (this.vbox5);
this.btnListado.Label = null;
this.hbuttonbox1.Add (this.btnListado);
global::Gtk.ButtonBox.ButtonBoxChild w20 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnListado]));
w20.Position = 4;
w20.Expand = false;
w20.Fill = false;
// Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild
this.btnSalir = new global::Gtk.Button ();
this.btnSalir.CanFocus = true;
this.btnSalir.Name = "btnSalir";
// Container child btnSalir.Gtk.Container+ContainerChild
this.vbox6 = new global::Gtk.VBox ();
this.vbox6.Name = "vbox6";
this.vbox6.Spacing = 6;
// Container child vbox6.Gtk.Box+BoxChild
this.image133 = new global::Gtk.Image ();
this.image133.Name = "image133";
this.image133.Pixbuf = Gdk.Pixbuf.LoadFromResource("Valle.Tpv.iconos.~APP21MB.ICO");
this.vbox6.Add (this.image133);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.vbox6[this.image133]));
w21.Position = 0;
// Container child vbox6.Gtk.Box+BoxChild
this.label5 = new global::Gtk.Label ();
this.label5.Name = "label5";
this.label5.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Salir</big>");
this.label5.UseMarkup = true;
this.vbox6.Add (this.label5);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox6[this.label5]));
w22.Position = 1;
w22.Expand = false;
w22.Fill = false;
this.btnSalir.Add (this.vbox6);
this.btnSalir.Label = null;
this.hbuttonbox1.Add (this.btnSalir);
global::Gtk.ButtonBox.ButtonBoxChild w24 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btnSalir]));
w24.Position = 5;
w24.Expand = false;
w24.Fill = false;
this.vbox1.Add (this.hbuttonbox1);
global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbuttonbox1]));
w25.Position = 2;
w25.Expand = false;
w25.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbuttonbox2 = new global::Gtk.HButtonBox ();
this.hbuttonbox2.Name = "hbuttonbox2";
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnCambiar = new global::Gtk.Button ();
this.btnCambiar.WidthRequest = 100;
this.btnCambiar.HeightRequest = 100;
this.btnCambiar.CanFocus = true;
this.btnCambiar.Name = "btnCambiar";
// Container child btnCambiar.Gtk.Container+ContainerChild
this.vbox7 = new global::Gtk.VBox ();
this.vbox7.Name = "vbox7";
this.vbox7.Spacing = 6;
// Container child vbox7.Gtk.Box+BoxChild
this.image134 = new global::Gtk.Image ();
this.image134.Name = "image134";
this.image134.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-jump-to", global::Gtk.IconSize.Dialog);
this.vbox7.Add (this.image134);
global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.image134]));
w26.Position = 0;
// Container child vbox7.Gtk.Box+BoxChild
this.label6 = new global::Gtk.Label ();
this.label6.Name = "label6";
this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Cambiar</big>\n<big> TPV </big>");
this.label6.UseMarkup = true;
this.vbox7.Add (this.label6);
global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.vbox7[this.label6]));
w27.Position = 1;
w27.Expand = false;
w27.Fill = false;
this.btnCambiar.Add (this.vbox7);
this.btnCambiar.Label = null;
this.hbuttonbox2.Add (this.btnCambiar);
global::Gtk.ButtonBox.ButtonBoxChild w29 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnCambiar]));
w29.Expand = false;
w29.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnReiniciar = new global::Gtk.Button ();
this.btnReiniciar.CanFocus = true;
this.btnReiniciar.Name = "btnReiniciar";
// Container child btnReiniciar.Gtk.Container+ContainerChild
this.vbox8 = new global::Gtk.VBox ();
this.vbox8.Name = "vbox8";
this.vbox8.Spacing = 6;
// Container child vbox8.Gtk.Box+BoxChild
this.image135 = new global::Gtk.Image ();
this.image135.Name = "image135";
this.image135.Pixbuf = Gdk.Pixbuf.LoadFromResource("Valle.Tpv.iconos.CONVERT2.ICO");
this.vbox8.Add (this.image135);
global::Gtk.Box.BoxChild w30 = ((global::Gtk.Box.BoxChild)(this.vbox8[this.image135]));
w30.Position = 0;
// Container child vbox8.Gtk.Box+BoxChild
this.label7 = new global::Gtk.Label ();
this.label7.Name = "label7";
this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Reiniciar</big>\n<big> TPV </big>");
this.label7.UseMarkup = true;
this.vbox8.Add (this.label7);
global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.vbox8[this.label7]));
w31.Position = 1;
w31.Expand = false;
w31.Fill = false;
this.btnReiniciar.Add (this.vbox8);
this.btnReiniciar.Label = null;
this.hbuttonbox2.Add (this.btnReiniciar);
global::Gtk.ButtonBox.ButtonBoxChild w33 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnReiniciar]));
w33.Position = 1;
w33.Expand = false;
w33.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnMinimizar = new global::Gtk.Button ();
this.btnMinimizar.CanFocus = true;
this.btnMinimizar.Name = "btnMinimizar";
// Container child btnMinimizar.Gtk.Container+ContainerChild
this.vbox9 = new global::Gtk.VBox ();
this.vbox9.Name = "vbox9";
this.vbox9.Spacing = 6;
// Container child vbox9.Gtk.Box+BoxChild
this.image136 = new global::Gtk.Image ();
this.image136.Name = "image136";
this.image136.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-media-stop", global::Gtk.IconSize.Dialog);
this.vbox9.Add (this.image136);
global::Gtk.Box.BoxChild w34 = ((global::Gtk.Box.BoxChild)(this.vbox9[this.image136]));
w34.Position = 0;
// Container child vbox9.Gtk.Box+BoxChild
this.label8 = new global::Gtk.Label ();
this.label8.Name = "label8";
this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Minimizar</big>");
this.label8.UseMarkup = true;
this.vbox9.Add (this.label8);
global::Gtk.Box.BoxChild w35 = ((global::Gtk.Box.BoxChild)(this.vbox9[this.label8]));
w35.Position = 1;
w35.Expand = false;
w35.Fill = false;
this.btnMinimizar.Add (this.vbox9);
this.btnMinimizar.Label = null;
this.hbuttonbox2.Add (this.btnMinimizar);
global::Gtk.ButtonBox.ButtonBoxChild w37 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnMinimizar]));
w37.Position = 2;
w37.Expand = false;
w37.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnComfiguracion = new global::Gtk.Button ();
this.btnComfiguracion.CanFocus = true;
this.btnComfiguracion.Name = "btnComfiguracion";
// Container child btnComfiguracion.Gtk.Container+ContainerChild
this.vbox10 = new global::Gtk.VBox ();
this.vbox10.Name = "vbox10";
this.vbox10.Spacing = 6;
// Container child vbox10.Gtk.Box+BoxChild
this.image137 = new global::Gtk.Image ();
this.image137.Name = "image137";
this.image137.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-preferences", global::Gtk.IconSize.Dialog);
this.vbox10.Add (this.image137);
global::Gtk.Box.BoxChild w38 = ((global::Gtk.Box.BoxChild)(this.vbox10[this.image137]));
w38.Position = 0;
// Container child vbox10.Gtk.Box+BoxChild
this.label9 = new global::Gtk.Label ();
this.label9.Name = "label9";
this.label9.LabelProp = global::Mono.Unix.Catalog.GetString ("Configuracion");
this.label9.UseMarkup = true;
this.vbox10.Add (this.label9);
global::Gtk.Box.BoxChild w39 = ((global::Gtk.Box.BoxChild)(this.vbox10[this.label9]));
w39.Position = 1;
w39.Expand = false;
w39.Fill = false;
this.btnComfiguracion.Add (this.vbox10);
this.btnComfiguracion.Label = null;
this.hbuttonbox2.Add (this.btnComfiguracion);
global::Gtk.ButtonBox.ButtonBoxChild w41 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnComfiguracion]));
w41.Position = 3;
w41.Expand = false;
w41.Fill = false;
// Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild
this.btnBloquear = new global::Gtk.Button ();
this.btnBloquear.CanFocus = true;
this.btnBloquear.Name = "btnBloquear";
// Container child btnBloquear.Gtk.Container+ContainerChild
this.vbox11 = new global::Gtk.VBox ();
this.vbox11.Name = "vbox11";
this.vbox11.Spacing = 6;
// Container child vbox11.Gtk.Box+BoxChild
this.imgKey = new global::Gtk.Image ();
this.imgKey.Name = "image138";
this.imgKey.Pixbuf = Gdk.Pixbuf.LoadFromResource("Valle.Tpv.iconos.MUNECO_CANDAO_03.png");
this.vbox11.Add (this.imgKey);
global::Gtk.Box.BoxChild w42 = ((global::Gtk.Box.BoxChild)(this.vbox11[this.imgKey]));
w42.Position = 0;
// Container child vbox11.Gtk.Box+BoxChild
this.lblBtnBloquear = new global::Gtk.Label ();
this.lblBtnBloquear.Name = "lblBtnBloquear";
this.lblBtnBloquear.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Bloquear</big>");
this.lblBtnBloquear.UseMarkup = true;
this.vbox11.Add (this.lblBtnBloquear);
global::Gtk.Box.BoxChild w43 = ((global::Gtk.Box.BoxChild)(this.vbox11[this.lblBtnBloquear]));
w43.Position = 1;
w43.Expand = false;
w43.Fill = false;
this.btnBloquear.Add (this.vbox11);
this.btnBloquear.Label = null;
this.hbuttonbox2.Add (this.btnBloquear);
global::Gtk.ButtonBox.ButtonBoxChild w45 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btnBloquear]));
w45.Position = 4;
w45.Expand = false;
w45.Fill = false;
this.vbox1.Add (this.hbuttonbox2);
global::Gtk.Box.BoxChild w46 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbuttonbox2]));
w46.Position = 3;
w46.Expand = false;
w46.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 601;
this.DefaultHeight = 322;
this.btnImprimir.Clicked += new global::System.EventHandler (this.btnModoImp_Click);
this.btnBorrarZ.Clicked += new global::System.EventHandler (this.btnCajaDia_Click);
this.btnTrimestres.Clicked += new global::System.EventHandler (this.btnMesesTrim_Click);
this.btnListado.Clicked += new global::System.EventHandler (this.BtnListCierresClick);
this.btnSalir.Clicked += new global::System.EventHandler (this.btnSalir_Click);
this.btnCambiar.Clicked += new global::System.EventHandler (this.btnCambiarTpv_Click);
this.btnReiniciar.Clicked += new global::System.EventHandler (this.btnReiniciar_Click);
this.btnComfiguracion.Clicked += new global::System.EventHandler (this.BtnConfigClienteClick);
this.btnBloquear.Clicked += new global::System.EventHandler (this.btnBloqueo_Click);
this.btnMinimizar.Clicked += new global::System.EventHandler (this.BtnMinimizarClick);
}
}
}
| |
// 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.Linq.ParallelEnumerable.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.Linq
{
#if NETFRAMEWORK_4_0
static public partial class ParallelEnumerable
{
#region Methods and constructors
[Pure]
public static TResult Aggregate<TSource, TAccumulate, TResult>(
ParallelQuery<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func,
Func<TAccumulate, TResult> resultSelector)
{
Contract.Requires(source != null);
Contract.Requires(func != null);
Contract.Requires(resultSelector != null);
return default(TResult);
}
[Pure]
public static TResult Aggregate<TSource, TAccumulate, TResult>(
ParallelQuery<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc,
Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc,
Func<TAccumulate, TResult> resultSelector)
{
Contract.Requires(source != null);
Contract.Requires(combineAccumulatorsFunc != null);
Contract.Requires(resultSelector != null);
return default(TResult);
}
[Pure]
public static TResult Aggregate<TSource, TAccumulate, TResult>(
ParallelQuery<TSource> source,
Func<TAccumulate> seedFactory,
Func<TAccumulate, TSource, TAccumulate> updateAccumulatorFunc,
Func<TAccumulate, TAccumulate, TAccumulate> combineAccumulatorsFunc,
Func<TAccumulate, TResult> resultSelector)
{
Contract.Requires(source != null);
Contract.Requires(seedFactory != null);
Contract.Requires(updateAccumulatorFunc != null);
Contract.Requires(combineAccumulatorsFunc != null);
Contract.Requires(resultSelector != null);
return default(TResult);
}
[Pure]
public static TSource Aggregate<TSource>(ParallelQuery<TSource> source, Func<TSource, TSource, TSource> func)
{
Contract.Requires(source != null);
Contract.Requires(func != null);
return default(TSource);
}
[Pure]
public static TAccumulate Aggregate<TSource, TAccumulate>(
ParallelQuery<TSource> source,
TAccumulate seed,
Func<TAccumulate, TSource, TAccumulate> func)
{
Contract.Requires(source != null);
Contract.Requires(func != null);
return default(TAccumulate);
}
[Pure]
public static bool All<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
return default(bool);
}
[Pure]
public static bool Any<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(bool);
}
[Pure]
public static bool Any<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
return default(bool);
}
[Pure]
public static IEnumerable<TSource> AsEnumerable<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<TSource>>() != null);
return default(IEnumerable<TSource>);
}
[Pure]
public static ParallelQuery<TSource> AsOrdered<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery AsOrdered(ParallelQuery source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery>() != null);
return default(ParallelQuery);
}
[Pure]
public static ParallelQuery<TSource> AsParallel<TSource>(IEnumerable<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery AsParallel(System.Collections.IEnumerable source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery>() != null);
return default(ParallelQuery);
}
[Pure]
public static IEnumerable<TSource> AsSequential<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<IEnumerable<TSource>>() != null);
return default(IEnumerable<TSource>);
}
[Pure]
public static ParallelQuery<TSource> AsUnordered<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static Decimal Average(ParallelQuery<Decimal> source)
{
Contract.Requires(source != null);
return default(Decimal);
}
[Pure]
public static Nullable<double> Average(ParallelQuery<Nullable<double>> source)
{
Contract.Requires(source != null);
return default(Nullable<double>);
}
[Pure]
public static double Average(ParallelQuery<double> source)
{
Contract.Requires(source != null);
return default(double);
}
[Pure]
public static Nullable<double> Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<double>);
}
[Pure]
public static double Average<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(double);
}
[Pure]
public static Nullable<Decimal> Average(ParallelQuery<Nullable<Decimal>> source)
{
Contract.Requires(source != null);
return default(Nullable<Decimal>);
}
[Pure]
public static double Average(ParallelQuery<long> source)
{
Contract.Requires(source != null);
return default(double);
}
[Pure]
public static Nullable<double> Average(ParallelQuery<Nullable<int>> source)
{
Contract.Requires(source != null);
return default(Nullable<double>);
}
[Pure]
public static double Average(ParallelQuery<int> source)
{
Contract.Requires(source != null);
return default(double);
}
[Pure]
public static Nullable<float> Average(ParallelQuery<Nullable<float>> source)
{
Contract.Requires(source != null);
return default(Nullable<float>);
}
[Pure]
public static float Average(ParallelQuery<float> source)
{
Contract.Requires(source != null);
return default(float);
}
[Pure]
public static Nullable<double> Average(ParallelQuery<Nullable<long>> source)
{
Contract.Requires(source != null);
return default(Nullable<double>);
}
[Pure]
public static double Average<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(double);
}
[Pure]
public static Nullable<double> Average<TSource>(
ParallelQuery<TSource> source,
Func<TSource, Nullable<double>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<double>);
}
[Pure]
public static Decimal Average<TSource>(
ParallelQuery<TSource> source,
Func<TSource, Decimal> selector)
{
Contract.Requires(source != null);
return default(Decimal);
}
[Pure]
public static Nullable<Decimal> Average<TSource>(
ParallelQuery<TSource> source,
Func<TSource, Nullable<Decimal>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<Decimal>);
}
[Pure]
public static double Average<TSource>(
ParallelQuery<TSource> source,
Func<TSource, int> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(double);
}
[Pure]
public static Nullable<double> Average<TSource>(
ParallelQuery<TSource> source,
Func<TSource, Nullable<long>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<double>);
}
[Pure]
public static float Average<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(float);
}
[Pure]
public static Nullable<float> Average<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<float>);
}
[Pure]
public static ParallelQuery<TResult> Cast<TResult>(ParallelQuery source)
{
Contract.Requires(source != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TSource> Concat<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Concat<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static bool Contains<TSource>(ParallelQuery<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
{
Contract.Requires(source != null);
return default(bool);
}
[Pure]
public static bool Contains<TSource>(ParallelQuery<TSource> source, TSource value)
{
Contract.Requires(source != null);
return default(bool);
}
[Pure]
public static int Count<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<int>() >= 0);
return default(int);
}
[Pure]
public static int Count<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<int>() >= 0);
return default(int);
}
[Pure]
public static ParallelQuery<TSource> DefaultIfEmpty<TSource>(ParallelQuery<TSource> source, TSource defaultValue)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>().Any());
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> DefaultIfEmpty<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>().Any());
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Distinct<TSource>(ParallelQuery<TSource> source, IEqualityComparer<TSource> comparer)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Distinct<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static TSource ElementAt<TSource>(ParallelQuery<TSource> source, int index)
{
Contract.Requires(source != null);
Contract.Requires(index >= 0);
return default(TSource);
}
[Pure]
public static TSource ElementAtOrDefault<TSource>(ParallelQuery<TSource> source, int index)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static ParallelQuery<TResult> Empty<TResult>()
{
Contract.Ensures(Contract.Result<ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Except<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static TSource First<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Requires(ParallelEnumerable.Count<TSource>(source) > 0);
return default(TSource);
}
[Pure]
public static TSource First<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
Contract.Requires(ParallelEnumerable.Count<TSource>(source) > 0);
return default(TSource);
}
[Pure]
public static TSource FirstOrDefault<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static TSource FirstOrDefault<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
return default(TSource);
}
public static void ForAll<TSource>(ParallelQuery<TSource> source, Action<TSource> action)
{
Contract.Requires(source != null);
Contract.Requires(action != null);
}
[Pure]
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TElement, TResult>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
Func<TKey, IEnumerable<TElement>, TResult> resultSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TSource>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TSource>>);
}
[Pure]
public static ParallelQuery<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TSource>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TSource>>);
}
[Pure]
public static ParallelQuery<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TElement>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TElement>>);
}
[Pure]
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TResult>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TKey, IEnumerable<TSource>, TResult> resultSelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TElement, TResult>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<System.Linq.IGrouping<TKey, TElement>>>() != null);
return default(ParallelQuery<IGrouping<TKey, TElement>>);
}
[Pure]
public static ParallelQuery<TResult> GroupBy<TSource, TKey, TResult>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TKey, IEnumerable<TSource>, TResult> resultSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
ParallelQuery<TOuter> outer,
ParallelQuery<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
{
Contract.Requires(outer != null);
Contract.Requires(inner != null);
Contract.Requires(outerKeySelector != null);
Contract.Requires(innerKeySelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
ParallelQuery<TOuter> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
ParallelQuery<TOuter> outer,
ParallelQuery<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(outer != null);
Contract.Requires(inner != null);
Contract.Requires(outerKeySelector != null);
Contract.Requires(innerKeySelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(
ParallelQuery<TOuter> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, IEnumerable<TInner>, TResult> resultSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TSource> Intersect<TSource>(
ParallelQuery<TSource> first,
ParallelQuery<TSource> second)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Intersect<TSource>(
ParallelQuery<TSource> first,
IEnumerable<TSource> second)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Intersect<TSource>(
ParallelQuery<TSource> first,
IEnumerable<TSource> second,
IEqualityComparer<TSource> comparer)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Intersect<TSource>(
ParallelQuery<TSource> first,
ParallelQuery<TSource> second,
IEqualityComparer<TSource> comparer)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(
ParallelQuery<TOuter> outer,
ParallelQuery<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, TInner, TResult> resultSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(outer != null);
Contract.Requires(inner != null);
Contract.Requires(outerKeySelector != null);
Contract.Requires(innerKeySelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(
ParallelQuery<TOuter> outer,
IEnumerable<TInner> inner,
Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(ParallelQuery<TOuter> outer, IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, Func<TInner, TKey> innerKeySelector, Func<TOuter, TInner, TResult> resultSelector)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> Join<TOuter, TInner, TKey, TResult>(
ParallelQuery<TOuter> outer,
ParallelQuery<TInner> inner,
Func<TOuter, TKey> outerKeySelector,
Func<TInner, TKey> innerKeySelector,
Func<TOuter, TInner, TResult> resultSelector)
{
Contract.Requires(outer != null);
Contract.Requires(inner != null);
Contract.Requires(outerKeySelector != null);
Contract.Requires(innerKeySelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static TSource Last<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
Contract.Requires(Count(source) > 0);
return default(TSource);
}
[Pure]
public static TSource Last<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Requires(Count(source) > 0);
return default(TSource);
}
[Pure]
public static TSource LastOrDefault<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
return default(TSource);
}
[Pure]
public static TSource LastOrDefault<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static long LongCount<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(long);
}
[Pure]
public static long LongCount<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
return default(long);
}
[Pure]
public static TSource Max<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static Nullable<Decimal> Max(ParallelQuery<Nullable<Decimal>> source)
{
Contract.Requires(source != null);
return default(Nullable<Decimal>);
}
[Pure]
public static int Max<TSource>(ParallelQuery<TSource> source, Func<TSource, int> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(int);
}
[Pure]
public static Nullable<int> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<int>);
}
[Pure]
public static Decimal Max(ParallelQuery<Decimal> source)
{
Contract.Requires(source != null);
return default(Decimal);
}
[Pure]
public static Nullable<float> Max(ParallelQuery<Nullable<float>> source)
{
Contract.Requires(source != null);
return default(Nullable<float>);
}
[Pure]
public static float Max(ParallelQuery<float> source)
{
Contract.Requires(source != null);
return default(float);
}
[Pure]
public static Nullable<double> Max(ParallelQuery<Nullable<double>> source)
{
Contract.Requires(source != null);
return default(Nullable<double>);
}
[Pure]
public static double Max(ParallelQuery<double> source)
{
Contract.Requires(source != null);
return default(double);
}
[Pure]
public static Decimal Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Decimal> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Decimal);
}
[Pure]
public static Nullable<double> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<double>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<double>);
}
[Pure]
public static Nullable<Decimal> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<Decimal>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<Decimal>);
}
[Pure]
public static Nullable<int> Max(ParallelQuery<Nullable<int>> source)
{
Contract.Requires(source != null);
return default(Nullable<int>);
}
[Pure]
public static TResult Max<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, TResult> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(TResult);
}
[Pure]
public static Nullable<long> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<long>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<long>);
}
[Pure]
public static long Max<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(long);
}
[Pure]
public static float Max<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(float);
}
[Pure]
public static double Max<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(double);
}
[Pure]
public static Nullable<float> Max<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<float>);
}
[Pure]
public static int Max(ParallelQuery<int> source)
{
Contract.Requires(source != null);
return default(int);
}
[Pure]
public static long Max(ParallelQuery<long> source)
{
Contract.Requires(source != null);
return default(long);
}
[Pure]
public static Nullable<long> Max(ParallelQuery<Nullable<long>> source)
{
Contract.Requires(source != null);
return default(Nullable<long>);
}
[Pure]
public static Nullable<double> Min(ParallelQuery<Nullable<double>> source)
{
Contract.Requires(source != null);
return default(Nullable<double>);
}
[Pure]
public static double Min(ParallelQuery<double> source)
{
Contract.Requires(source != null);
return default(double);
}
[Pure]
public static Decimal Min(ParallelQuery<Decimal> source)
{
Contract.Requires(source != null);
return default(Decimal);
}
[Pure]
public static TSource Min<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static Nullable<Decimal> Min(ParallelQuery<Nullable<Decimal>> source)
{
Contract.Requires(source != null);
return default(Nullable<Decimal>);
}
[Pure]
public static int Min(ParallelQuery<int> source)
{
Contract.Requires(source != null);
return default(int);
}
[Pure]
public static float Min(ParallelQuery<float> source)
{
Contract.Requires(source != null);
return default(float);
}
[Pure]
public static Nullable<long> Min(ParallelQuery<Nullable<long>> source)
{
Contract.Requires(source != null);
return default(Nullable<long>);
}
[Pure]
public static Nullable<float> Min(ParallelQuery<Nullable<float>> source)
{
Contract.Requires(source != null);
return default(Nullable<float>);
}
[Pure]
public static Nullable<int> Min(ParallelQuery<Nullable<int>> source)
{
Contract.Requires(source != null);
return default(Nullable<int>);
}
[Pure]
public static long Min(ParallelQuery<long> source)
{
Contract.Requires(source != null);
return default(long);
}
[Pure]
public static Nullable<float> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<float>);
}
[Pure]
public static TResult Min<TSource, TResult>(ParallelQuery<TSource> source, Func<TSource, TResult> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(TResult);
}
[Pure]
public static float Min<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(float);
}
[Pure]
public static double Min<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(double);
}
[Pure]
public static Nullable<Decimal> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<Decimal>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<Decimal>);
}
[Pure]
public static Decimal Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Decimal> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Decimal);
}
[Pure]
public static Nullable<double> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<double>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<double>);
}
[Pure]
public static Nullable<long> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<long>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<long>);
}
[Pure]
public static int Min<TSource>(ParallelQuery<TSource> source, Func<TSource, int> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(int);
}
[Pure]
public static Nullable<int> Min<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<int>);
}
[Pure]
public static long Min<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(long);
}
[Pure]
public static ParallelQuery<TResult> OfType<TResult>(ParallelQuery source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static OrderedParallelQuery<TSource> OrderBy<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static OrderedParallelQuery<TSource> OrderBy<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static OrderedParallelQuery<TSource> OrderByDescending<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
IComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static OrderedParallelQuery<TSource> OrderByDescending<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<int> Range(int start, int count)
{
Contract.Requires(count >= 0);
Contract.Requires(0x7fffffff >= start + count - 1);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<int>>() != null);
return default(ParallelQuery<int>);
}
[Pure]
public static ParallelQuery<TResult> Repeat<TResult>(TResult element, int count)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TSource> Reverse<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TResult> Select<TSource, TResult>(
ParallelQuery<TSource> source,
Func<TSource, TResult> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> Select<TSource, TResult>(
ParallelQuery<TSource> source,
Func<TSource, int, TResult> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> SelectMany<TSource, TResult>(
ParallelQuery<TSource> source,
Func<TSource, IEnumerable<TResult>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> SelectMany<TSource, TCollection, TResult>(
ParallelQuery<TSource> source,
Func<TSource, int, IEnumerable<TCollection>> collectionSelector,
Func<TSource, TCollection, TResult> resultSelector)
{
Contract.Requires(source != null);
Contract.Requires(collectionSelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> SelectMany<TSource, TResult>(
ParallelQuery<TSource> source,
Func<TSource, int, IEnumerable<TResult>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> SelectMany<TSource, TCollection, TResult>(
ParallelQuery<TSource> source,
Func<TSource, IEnumerable<TCollection>> collectionSelector,
Func<TSource, TCollection, TResult> resultSelector)
{
Contract.Requires(source != null);
Contract.Requires(collectionSelector != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static bool SequenceEqual<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
return default(bool);
}
[Pure]
public static bool SequenceEqual<TSource>(
ParallelQuery<TSource> first,
IEnumerable<TSource> second,
IEqualityComparer<TSource> comparer)
{
Contract.Ensures(false);
return default(bool);
}
[Pure]
public static bool SequenceEqual<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
return default(bool);
}
[Pure]
public static bool SequenceEqual<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(bool);
}
[Pure]
public static TSource Single<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
return default(TSource);
}
[Pure]
public static TSource Single<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static TSource SingleOrDefault<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static TSource SingleOrDefault<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(TSource);
}
[Pure]
public static ParallelQuery<TSource> Skip<TSource>(ParallelQuery<TSource> source, int count)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> SkipWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, int, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> SkipWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static Nullable<long> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<long>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<long>);
}
[Pure]
public static Nullable<float> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<float>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<float>);
}
[Pure]
public static float Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, float> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(float);
}
[Pure]
public static double Sum(ParallelQuery<double> source)
{
Contract.Requires(source != null);
return default(double);
}
[Pure]
public static long Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, long> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(long);
}
[Pure]
public static Decimal Sum(ParallelQuery<Decimal> source)
{
Contract.Requires(source != null);
return default(Decimal);
}
[Pure]
public static Nullable<double> Sum(ParallelQuery<Nullable<double>> source)
{
Contract.Requires(source != null);
return default(Nullable<double>);
}
[Pure]
public static Nullable<Decimal> Sum(ParallelQuery<Nullable<Decimal>> source)
{
Contract.Requires(source != null);
return default(Nullable<Decimal>);
}
[Pure]
public static Nullable<int> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<int>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<int>);
}
[Pure]
public static int Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, int> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(int);
}
[Pure]
public static Nullable<int> Sum(ParallelQuery<Nullable<int>> source)
{
Contract.Requires(source != null);
return default(Nullable<int>);
}
[Pure]
public static int Sum(ParallelQuery<int> source)
{
Contract.Requires(source != null);
return default(int);
}
[Pure]
public static Nullable<double> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<double>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<double>);
}
[Pure]
public static Nullable<long> Sum(ParallelQuery<Nullable<long>> source)
{
Contract.Requires(source != null);
return default(Nullable<long>);
}
[Pure]
public static long Sum(ParallelQuery<long> source)
{
Contract.Requires(source != null);
return default(long);
}
[Pure]
public static float Sum(ParallelQuery<float> source)
{
Contract.Requires(source != null);
return default(float);
}
[Pure]
public static Nullable<float> Sum(ParallelQuery<Nullable<float>> source)
{
Contract.Requires(source != null);
return default(Nullable<float>);
}
[Pure]
public static Nullable<Decimal> Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Nullable<Decimal>> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Nullable<Decimal>);
}
[Pure]
public static Decimal Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, Decimal> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(Decimal);
}
[Pure]
public static double Sum<TSource>(ParallelQuery<TSource> source, Func<TSource, double> selector)
{
Contract.Requires(source != null);
Contract.Requires(selector != null);
return default(double);
}
[Pure]
public static ParallelQuery<TSource> Take<TSource>(ParallelQuery<TSource> source, int count)
{
Contract.Requires(source != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> TakeWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> TakeWhile<TSource>(ParallelQuery<TSource> source, Func<TSource, int, bool> predicate)
{
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static OrderedParallelQuery<TSource> ThenBy<TSource, TKey>(
OrderedParallelQuery<TSource> source,
Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(comparer != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static OrderedParallelQuery<TSource> ThenBy<TSource, TKey>(
OrderedParallelQuery<TSource> source,
Func<TSource, TKey> keySelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static OrderedParallelQuery<TSource> ThenByDescending<TSource, TKey>(
OrderedParallelQuery<TSource> source,
Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static OrderedParallelQuery<TSource> ThenByDescending<TSource, TKey>(
OrderedParallelQuery<TSource> source, Func<TSource, TKey> keySelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.OrderedParallelQuery<TSource>>() != null);
return default(OrderedParallelQuery<TSource>);
}
[Pure]
public static TSource[] ToArray<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
return default(TSource[]);
}
[Pure]
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TSource>>() != null);
return default(Dictionary<TKey, TSource>);
}
[Pure]
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TSource>>() != null);
return default(Dictionary<TKey, TSource>);
}
[Pure]
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TElement>>() != null);
return default(Dictionary<TKey, TElement>);
}
[Pure]
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Ensures(Contract.Result<System.Collections.Generic.Dictionary<TKey, TElement>>() != null);
return default(Dictionary<TKey, TElement>);
}
[Pure]
public static List<TSource> ToList<TSource>(ParallelQuery<TSource> source)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Collections.Generic.List<TSource>>() != null);
return default(List<TSource>);
}
[Pure]
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TElement>>() != null);
return default(ILookup<TKey, TElement>);
}
[Pure]
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Requires(elementSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TElement>>() != null);
return default(ILookup<TKey, TElement>);
}
[Pure]
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector,
IEqualityComparer<TKey> comparer)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TSource>>() != null);
return default(ILookup<TKey, TSource>);
}
[Pure]
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(
ParallelQuery<TSource> source,
Func<TSource, TKey> keySelector)
{
Contract.Requires(source != null);
Contract.Requires(keySelector != null);
Contract.Ensures(Contract.Result<System.Linq.ILookup<TKey, TSource>>() != null);
return default(ILookup<TKey, TSource>);
}
[Pure]
public static ParallelQuery<TSource> Union<TSource>(ParallelQuery<TSource> first, ParallelQuery<TSource> second)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Union<TSource>(
ParallelQuery<TSource> first, ParallelQuery<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Union<TSource>(
ParallelQuery<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Union<TSource>(ParallelQuery<TSource> first, IEnumerable<TSource> second)
{
Contract.Ensures(false);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Where<TSource>(
ParallelQuery<TSource> source, Func<TSource, int, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> Where<TSource>(ParallelQuery<TSource> source, Func<TSource, bool> predicate)
{
Contract.Requires(source != null);
Contract.Requires(predicate != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> WithCancellation<TSource>(
ParallelQuery<TSource> source, System.Threading.CancellationToken cancellationToken)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> WithDegreeOfParallelism<TSource>(
ParallelQuery<TSource> source, int degreeOfParallelism)
{
Contract.Requires(source != null);
Contract.Requires(degreeOfParallelism >= 0);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> WithExecutionMode<TSource>(ParallelQuery<TSource> source, ParallelExecutionMode executionMode)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TSource> WithMergeOptions<TSource>(ParallelQuery<TSource> source, ParallelMergeOptions mergeOptions)
{
Contract.Requires(source != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TSource>>() != null);
return default(ParallelQuery<TSource>);
}
[Pure]
public static ParallelQuery<TResult> Zip<TFirst, TSecond, TResult>(
ParallelQuery<TFirst> first, ParallelQuery<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
Contract.Requires(first != null);
Contract.Requires(second != null);
Contract.Requires(resultSelector != null);
Contract.Ensures(Contract.Result<System.Linq.ParallelQuery<TResult>>() != null);
return default(ParallelQuery<TResult>);
}
[Pure]
public static ParallelQuery<TResult> Zip<TFirst, TSecond, TResult>(
ParallelQuery<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> resultSelector)
{
Contract.Ensures(false);
return default(ParallelQuery<TResult>);
}
#endregion
}
#endif
}
| |
/*
Copyright 2018 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.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using System.Collections.Generic;
using ArcGIS.Desktop.Core.Events;
using ArcGIS.Core.Events;
using ArcGIS.Desktop.Mapping.Events;
using System.Linq;
namespace Framework.Snippets {
internal class Dockpane1ViewModel : ArcGIS.Desktop.Framework.Contracts.DockPane
{
#region How to subscribe and unsubscribe to events when the dockpane is visible or hidden
private SubscriptionToken _eventToken = null;
// Called when the visibility of the DockPane changes.
protected override void OnShow(bool isVisible)
{
if (isVisible && _eventToken == null) //Subscribe to event when dockpane is visible
{
_eventToken = MapSelectionChangedEvent.Subscribe(OnMapSelectionChangedEvent);
}
if (!isVisible && _eventToken != null) //Unsubscribe as the dockpane closes.
{
MapSelectionChangedEvent.Unsubscribe(_eventToken);
_eventToken = null;
}
}
//Event handler when the MapSelection event is triggered.
private void OnMapSelectionChangedEvent(MapSelectionChangedEventArgs obj)
{
MessageBox.Show("Selection has changed");
}
#endregion
}
internal class ProSnippets2
{
public void Snippets()
{
#region Execute a command
IPlugInWrapper wrapper = FrameworkApplication.GetPlugInWrapper("esri_editing_ShowAttributes");
var command = wrapper as ICommand; // tool and command(Button) supports this
if ((command != null) && command.CanExecute(null))
command.Execute(null);
#endregion
#region Set the current tool
// use SetCurrentToolAsync
FrameworkApplication.SetCurrentToolAsync("esri_mapping_selectByRectangleTool");
// or use ICommand.Execute
ICommand cmd = FrameworkApplication.GetPlugInWrapper("esri_mapping_selectByRectangleTool") as ICommand;
if ((cmd != null) && cmd.CanExecute(null))
cmd.Execute(null);
#endregion
#region Activate a tab
FrameworkApplication.ActivateTab("esri_mapping_insertTab");
#endregion
bool activate = true;
#region Activate/Deactivate a state - to modify a condition
// Define the condition in the DAML file based on the state
if (activate)
FrameworkApplication.State.Activate("someState");
else
FrameworkApplication.State.Deactivate("someState");
#endregion
#region Determine if the application is busy
// The application is considered busy if a task is currently running on the main worker thread or any
// pane or dock pane reports that it is busy or intiializing.
// Many Pro styles (such as Esri_SimpleButton) ensure that a button is disabled when FrameworkApplication.IsBusy is true
// You would use this property to bind to the IsEnabled property of a control (such as a listbox) on a dockpane or pane in order
// to disable it from user interaction while the application is busy.
bool isbusy = FrameworkApplication.IsBusy;
#endregion
#region Get the Application main window
System.Windows.Window window = FrameworkApplication.Current.MainWindow;
// center it
Rect rect = System.Windows.SystemParameters.WorkArea;
FrameworkApplication.Current.MainWindow.Left = rect.Left + (rect.Width - FrameworkApplication.Current.MainWindow.ActualWidth) / 2;
FrameworkApplication.Current.MainWindow.Top = rect.Top + (rect.Height - FrameworkApplication.Current.MainWindow.ActualHeight) / 2;
#endregion
#region Close ArcGIS Pro
FrameworkApplication.Close();
#endregion
#region Get ArcGIS Pro version
//"GetEntryAssembly" should be ArcGISPro.exe
string version = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString();
#endregion
#region Close a specific pane
string _viewPaneID = "my pane"; //DAML ID of your pane
//You could have multiple instances (InstanceIDs) of your pane.
//So you can iterate through the Panes to get "your" panes only
IList<uint> myPaneInstanceIDs = new List<uint>();
foreach (Pane pane in FrameworkApplication.Panes)
{
if (pane.ContentID == _viewPaneID)
{
myPaneInstanceIDs.Add(pane.InstanceID); //InstanceID of your pane, could be multiple, so build the collection
}
}
foreach (var instanceID in myPaneInstanceIDs) //close each of "your" panes.
{
FrameworkApplication.Panes.ClosePane(instanceID);
}
#endregion
#region Activate a pane
var mapPanes = ProApp.Panes.OfType<IMapPane>();
foreach (Pane pane in mapPanes)
{
if (pane.Caption == "MyMap")
{
pane.Activate();
break;
}
}
#endregion
}
public void Foo()
{
#region Get Information on the Currently Installed Add-ins
var addin_infos = FrameworkApplication.GetAddInInfos();
StringBuilder sb = new StringBuilder();
foreach(var info in addin_infos)
{
if (info == null)
break;//no addins probed
sb.AppendLine($"Addin: {info.Name}");
sb.AppendLine($"Description {info.Description}");
sb.AppendLine($"ImagePath {info.ImagePath}");
sb.AppendLine($"Author {info.Author}");
sb.AppendLine($"Company {info.Company}");
sb.AppendLine($"Date {info.Date}");
sb.AppendLine($"Version {info.Version}");
sb.AppendLine($"FullPath {info.FullPath}");
sb.AppendLine($"DigitalSignature {info.DigitalSignature}");
sb.AppendLine($"IsCompatible {info.IsCompatible}");
sb.AppendLine($"IsDeleted {info.IsDeleted}");
sb.AppendLine($"TargetVersion {info.TargetVersion}");
sb.AppendLine($"ErrorMsg {info.ErrorMsg}");
sb.AppendLine($"ID {info.ID}");
sb.AppendLine("");
}
System.Diagnostics.Debug.WriteLine(sb.ToString());
MessageBox.Show(sb.ToString(), "Addin Infos");
#endregion
}
public void Dockpane1()
{
#region Find a dockpane
// in order to find a dockpane you need to know it's DAML id
var pane = FrameworkApplication.DockPaneManager.Find("esri_core_ProjectDockPane");
#endregion
}
public void Dockpane2()
{
#region Dockpane properties and methods
// in order to find a dockpane you need to know it's DAML id
var pane = FrameworkApplication.DockPaneManager.Find("esri_core_ProjectDockPane");
// determine visibility
bool visible = pane.IsVisible;
// activate it
pane.Activate();
// determine dockpane state
DockPaneState state = pane.DockState;
// pin it
pane.Pin();
// hide it
pane.Hide();
#endregion
}
public async void Dockpane3()
{
#region Dockpane undo / redo
// in order to find a dockpane you need to know it's DAML id
var pane = FrameworkApplication.DockPaneManager.Find("esri_core_contentsDockPane");
// get the undo stack
OperationManager manager = pane.OperationManager;
if (manager != null)
{
// undo an operation
if (manager.CanUndo)
await manager.UndoAsync();
// redo an operation
if (manager.CanRedo)
await manager.RedoAsync();
// clear the undo and redo stack of operations of a particular category
manager.ClearUndoCategory("Some category");
manager.ClearRedoCategory("Some category");
}
#endregion
}
public void Dockpane4()
{
#region Find a dockpane and obtain its ViewModel
// in order to find a dockpane you need to know it's DAML id.
// Here is a DAML example with a dockpane defined. Once you have found the dockpane you can cast it
// to the dockpane viewModel which is defined by the className attribute.
//
//<dockPanes>
// <dockPane id="MySample_Dockpane" caption="Dockpane 1" className="Dockpane1ViewModel" dock="bottom" height="5">
// <content className="Dockpane1View" />
// </dockPane>
//</dockPanes>
Dockpane1ViewModel vm = FrameworkApplication.DockPaneManager.Find("MySample_Dockpane") as Dockpane1ViewModel;
#endregion
#region Open the Backstage tab
//Opens the Backstage to the "About ArcGIS Pro" tab.
FrameworkApplication.OpenBackstage("esri_core_aboutTab");
#endregion
#region Access the current theme
//Gets the application's theme
var theme = FrameworkApplication.ApplicationTheme;
//ApplicationTheme enumeration
if (FrameworkApplication.ApplicationTheme == ApplicationTheme.Dark) {
//Dark theme
}
if (FrameworkApplication.ApplicationTheme == ApplicationTheme.HighContrast){
//High Contrast
}
if (FrameworkApplication.ApplicationTheme == ApplicationTheme.Default) {
//Light/Default theme
}
#endregion
}
public void SnippetsAdvanced()
{
#region Display a Pro MessageBox
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Some Message", "Some title", MessageBoxButton.YesNo, MessageBoxImage.Information, MessageBoxResult.Yes);
#endregion
#region Add a toast notification
Notification notification = new Notification();
notification.Title = FrameworkApplication.Title;
notification.Message = "Notification 1";
notification.ImageUrl = @"pack://application:,,,/ArcGIS.Desktop.Resources;component/Images/ToastLicensing32.png";
ArcGIS.Desktop.Framework.FrameworkApplication.AddNotification(notification);
#endregion
}
#region Change a buttons caption or image
private void ChangeCaptionImage()
{
IPlugInWrapper wrapper = FrameworkApplication.GetPlugInWrapper("MyAddin_MyCustomButton");
if (wrapper != null)
{
wrapper.Caption = "new caption";
// ensure that T-Rex16 and T-Rex32 are included in your add-in under the images folder and have
// BuildAction = Resource and Copy to OutputDirectory = Do not copy
wrapper.SmallImage = BuildImage("T-Rex16.png");
wrapper.LargeImage = BuildImage("T-Rex32.png");
}
}
private ImageSource BuildImage(string imageName)
{
return new BitmapImage(PackUriForResource(imageName));
}
private Uri PackUriForResource(string resourceName)
{
string asm = System.IO.Path.GetFileNameWithoutExtension(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
return new Uri(string.Format("pack://application:,,,/{0};component/Images/{1}", asm, resourceName), UriKind.Absolute);
}
#endregion
private void GetButtonTooltipHeading()
{
#region Get a button's tooltip heading
//Pass in the daml id of your button. Or pass in any Pro button ID.
IPlugInWrapper wrapper = FrameworkApplication.GetPlugInWrapper("button_id_from daml");
var buttonTooltipHeading = wrapper.TooltipHeading;
#endregion
}
#region Subscribe to Active Tool Changed Event
private void SubscribeEvent()
{
ArcGIS.Desktop.Framework.Events.ActiveToolChangedEvent.Subscribe(OnActiveToolChanged);
}
private void UnSubscribeEvent()
{
ArcGIS.Desktop.Framework.Events.ActiveToolChangedEvent.Unsubscribe(OnActiveToolChanged);
}
private void OnActiveToolChanged(ArcGIS.Desktop.Framework.Events.ToolEventArgs args)
{
string prevTool = args.PreviousID;
string newTool = args.CurrentID;
}
#endregion
#region Progressor - Simple and non-cancelable
public async Task Progressor_NonCancelable()
{
ArcGIS.Desktop.Framework.Threading.Tasks.ProgressorSource ps = new ArcGIS.Desktop.Framework.Threading.Tasks.ProgressorSource("Doing my thing...", false);
int numSecondsDelay = 5;
//If you run this in the DEBUGGER you will NOT see the dialog
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => Task.Delay(numSecondsDelay * 1000).Wait(), ps.Progressor);
}
#endregion
#region Progressor - Cancelable
public async Task Progressor_Cancelable()
{
ArcGIS.Desktop.Framework.Threading.Tasks.CancelableProgressorSource cps =
new ArcGIS.Desktop.Framework.Threading.Tasks.CancelableProgressorSource("Doing my thing - cancelable", "Canceled");
int numSecondsDelay = 5;
//If you run this in the DEBUGGER you will NOT see the dialog
//simulate doing some work which can be canceled
await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
cps.Progressor.Max = (uint)numSecondsDelay;
//check every second
while (!cps.Progressor.CancellationToken.IsCancellationRequested) {
cps.Progressor.Value += 1;
cps.Progressor.Status = "Status " + cps.Progressor.Value;
cps.Progressor.Message = "Message " + cps.Progressor.Value;
if (System.Diagnostics.Debugger.IsAttached) {
System.Diagnostics.Debug.WriteLine(string.Format("RunCancelableProgress Loop{0}", cps.Progressor.Value));
}
//are we done?
if (cps.Progressor.Value == cps.Progressor.Max) break;
//block the CIM for a second
Task.Delay(1000).Wait();
}
System.Diagnostics.Debug.WriteLine(string.Format("RunCancelableProgress: Canceled {0}",
cps.Progressor.CancellationToken.IsCancellationRequested));
}, cps.Progressor);
}
#endregion
}
#region customize the disabedText property of a button or tool
//Set the tool's loadOnClick attribute to "false" in the config.daml.
//This will allow the tool to be created when Pro launches, so that the disabledText property can display customized text at startup.
//Remove the "condition" attribute from the tool. Use the OnUpdate method(below) to set the enable\disable state of the tool.
//Add the OnUpdate method to the tool.
//Note: since OnUpdate is called very frequently, you should avoid lengthy operations in this method
//as this would reduce the responsiveness of the application user interface.
internal class SnippetButton : ArcGIS.Desktop.Framework.Contracts.Button
{
protected override void OnUpdate()
{
bool enableSate = true; //TODO: Code your enabled state
bool criteria = true; //TODO: Evaluate criteria for disabledText
if (enableSate)
{
this.Enabled = true; //tool is enabled
}
else
{
this.Enabled = false; //tool is disabled
//customize your disabledText here
if (criteria)
this.DisabledTooltip = "Missing criteria 1";
}
}
}
#endregion
internal class ProSnippets1
{
#region Get an Image Resource from the Current Assembly
public static void ExampleUsage() {
//Image 'Dino32.png' is added as Build Action: Resource, 'Do not copy'
var img = ForImage("Dino32.png");
//Use the image...
}
public static BitmapImage ForImage(string imageName) {
return new BitmapImage(PackUriForResource(imageName));
}
public static Uri PackUriForResource(string resourceName, string folderName = "Images") {
string asm = System.IO.Path.GetFileNameWithoutExtension(
System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string uriString = folderName.Length > 0
? string.Format("pack://application:,,,/{0};component/{1}/{2}", asm, folderName, resourceName)
: string.Format("pack://application:,,,/{0};component/{1}", asm, resourceName);
return new Uri(uriString, UriKind.Absolute);
}
#endregion
}
#region Prevent ArcGIS Pro from Closing
// There are two ways to prevent ArcGIS Pro from closing
// 1. Override the CanUnload method on your add-in's module and return false.
// 2. Subscribe to the ApplicationClosing event and cancel the event when you receive it
internal class Module1 : Module
{
// Called by Framework when ArcGIS Pro is closing
protected override bool CanUnload()
{
//return false to ~cancel~ Application close
return false;
}
internal class Module2 : Module
{
public Module2()
{
ArcGIS.Desktop.Framework.Events.ApplicationClosingEvent.Subscribe(OnApplicationClosing);
}
~Module2()
{
ArcGIS.Desktop.Framework.Events.ApplicationClosingEvent.Unsubscribe(OnApplicationClosing);
}
private Task OnApplicationClosing(System.ComponentModel.CancelEventArgs args)
{
args.Cancel = true;
return Task.FromResult(0);
}
#region How to determine when a project is opened
protected override bool Initialize() //Called when the Module is initialized.
{
ProjectOpenedEvent.Subscribe(OnProjectOpened); //subscribe to Project opened event
return base.Initialize();
}
private void OnProjectOpened(ProjectEventArgs obj) //Project Opened event handler
{
MessageBox.Show($"{Project.Current} has opened"); //show your message box
}
protected override void Uninitialize() //unsubscribe to the project opened event
{
ProjectOpenedEvent.Unsubscribe(OnProjectOpened); //unsubscribe
return;
}
#endregion
}
}
#endregion
internal class ProSnippetMapTool : MapTool
{
#region How to position an embeddable control inside a MapView
public ProSnippetMapTool()
{
//Set the MapTool base class' OverlayControlID to the DAML id of your embeddable control in the constructor
this.OverlayControlID = "ProAppModule1_EmbeddableControl1";
}
protected override void OnToolMouseDown(MapViewMouseButtonEventArgs e)
{
if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
e.Handled = true;
}
protected override Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e)
{
return QueuedTask.Run(() =>
{
//assign the screen coordinate clicked point to the MapTool base class' OverlayControlLocation property.
this.OverlayControlPositionRatio = e.ClientPoint;
});
}
#endregion
}
}
internal class Module1 : Module
{
#region Suggested command options in CommandSearch when a tab is activated.
//In the module class..
public override string[] GetSuggestedCMDIDs(string activeTabID)
{
//Return the static list of daml ids you want to be the (suggested)
//defaults relevant to the given tab. It can be none, some, or all of the
//commands associated with the activeTabID.
//In this example, there are two tabs. This example arbitrarily
//identifies just one command on each tab to be a default to show in the
//command search list (when _that_ particular tab is active)
switch (activeTabID)
{
case "CommandSearch_Example_Tab1":
return new string[] { "CommandSearch_Example_Button2" };
case "CommandSearch_Example_Tab2":
return new string[] { "CommandSearch_Example_Button4" };
}
return new string[] { "" };
}
#endregion
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email info@fyireporting.com |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using Reporting.Rdl;
namespace Reporting.Rdl
{
/// <summary>
/// Process a custom instance method request.
/// </summary>
[Serializable]
internal class FunctionCustomInstance : IExpr
{
string _Cls; // class name
string _Func; // function/operator
IExpr[] _Args; // arguments
ReportClass _Rc; // ReportClass
TypeCode _ReturnTypeCode; // the return type
Type[] _ArgTypes; // argument types
/// <summary>
/// passed ReportClass, function name, and args for evaluation
/// </summary>
public FunctionCustomInstance(ReportClass rc, string f, IExpr[] a, TypeCode type)
{
_Cls = null;
_Func = f;
_Args = a;
_Rc = rc;
_ReturnTypeCode = type;
_ArgTypes = new Type[a.Length];
int i=0;
foreach (IExpr ex in a)
{
_ArgTypes[i++] = Utility.Assembly.GetTypeFromTypeCode(ex.GetTypeCode());
}
}
public TypeCode GetTypeCode()
{
return _ReturnTypeCode;
}
public bool IsConstant()
{
return false; // Can't know what the function does
}
public IExpr ConstantOptimization()
{
// Do constant optimization on all the arguments
for (int i=0; i < _Args.GetLength(0); i++)
{
IExpr e = (IExpr)_Args[i];
_Args[i] = e.ConstantOptimization();
}
// Can't assume that the function doesn't vary
// based on something other than the args e.g. Now()
return this;
}
// Evaluate is for interpretation (and is relatively slow)
public object Evaluate(Report rpt, Row row)
{
// get the results
object[] argResults = new object[_Args.Length];
int i=0;
bool bUseArg=true;
bool bNull = false;
foreach(IExpr a in _Args)
{
argResults[i] = a.Evaluate(rpt, row);
if (argResults[i] == null)
bNull = true;
else if (argResults[i].GetType() != _ArgTypes[i])
bUseArg = false;
i++;
}
// we build the arguments based on the type
Type[] argTypes = bUseArg || bNull? _ArgTypes: Type.GetTypeArray(argResults);
// We can definitely optimize this by caching some info TODO
// Get ready to call the function
Object returnVal;
object inst = _Rc.Instance(rpt);
Type theClassType=inst.GetType();
MethodInfo mInfo = Utility.Assembly.GetMethod(theClassType, _Func, argTypes);
if (mInfo == null)
{
throw new Exception(string.Format("{0} method not found in class {1}", _Func, _Cls));
}
returnVal = mInfo.Invoke(inst, argResults);
return returnVal;
}
public double EvaluateDouble(Report rpt, Row row)
{
return Convert.ToDouble(Evaluate(rpt, row));
}
public decimal EvaluateDecimal(Report rpt, Row row)
{
return Convert.ToDecimal(Evaluate(rpt, row));
}
public int EvaluateInt32(Report rpt, Row row)
{
return Convert.ToInt32(Evaluate(rpt, row));
}
public string EvaluateString(Report rpt, Row row)
{
return Convert.ToString(Evaluate(rpt, row));
}
public DateTime EvaluateDateTime(Report rpt, Row row)
{
return Convert.ToDateTime(Evaluate(rpt, row));
}
public bool EvaluateBoolean(Report rpt, Row row)
{
return Convert.ToBoolean(Evaluate(rpt, row));
}
public string Cls
{
get { return _Cls; }
set { _Cls = value; }
}
public string Func
{
get { return _Func; }
set { _Func = value; }
}
public IExpr[] Args
{
get { return _Args; }
set { _Args = value; }
}
}
#if DEBUG
internal class TestFunction // for testing CodeModules, Classes, and the Function class
{
int counter=0;
public TestFunction()
{
counter=0;
}
public int count()
{
return counter++;
}
public int count(string s)
{
counter++;
return Convert.ToInt32(s) + counter;
}
static public double sqrt(double x)
{
return Math.Sqrt(x);
}
}
#endif
}
| |
//-----------------------------------------------------------------------
// <copyright file="MethodCaller.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Provides methods to dynamically find and call methods.</summary>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Csla.Properties;
using Csla.Server;
using Csla;
using System.Globalization;
using System.Threading.Tasks;
namespace Csla.Reflection
{
/// <summary>
/// Provides methods to dynamically find and call methods.
/// </summary>
public static class MethodCaller
{
private const BindingFlags allLevelFlags
= BindingFlags.FlattenHierarchy
| BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic
;
private const BindingFlags oneLevelFlags
= BindingFlags.DeclaredOnly
| BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic
;
private const BindingFlags ctorFlags
= BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic
;
private const BindingFlags factoryFlags =
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.FlattenHierarchy;
private const BindingFlags privateMethodFlags =
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.FlattenHierarchy;
#region Dynamic Method Cache
private static Dictionary<MethodCacheKey, DynamicMethodHandle> _methodCache = new Dictionary<MethodCacheKey, DynamicMethodHandle>();
private static DynamicMethodHandle GetCachedMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters)
{
var key = new MethodCacheKey(obj.GetType().FullName, info.Name, GetParameterTypes(parameters));
DynamicMethodHandle mh = null;
var found = false;
try
{
found = _methodCache.TryGetValue(key, out mh);
}
catch
{ /* failure will drop into !found block */ }
if (!found)
{
lock (_methodCache)
{
if (!_methodCache.TryGetValue(key, out mh))
{
mh = new DynamicMethodHandle(info, parameters);
_methodCache.Add(key, mh);
}
}
}
return mh;
}
private static DynamicMethodHandle GetCachedMethod(object obj, string method)
{
return GetCachedMethod(obj, method, false, null);
}
private static DynamicMethodHandle GetCachedMethod(object obj, string method, params object[] parameters)
{
return GetCachedMethod(obj, method, true, parameters);
}
private static DynamicMethodHandle GetCachedMethod(object obj, string method, bool hasParameters, params object[] parameters)
{
var key = new MethodCacheKey(obj.GetType().FullName, method, GetParameterTypes(hasParameters, parameters));
DynamicMethodHandle mh = null;
if (!_methodCache.TryGetValue(key, out mh))
{
lock (_methodCache)
{
if (!_methodCache.TryGetValue(key, out mh))
{
var info = GetMethod(obj.GetType(), method, hasParameters, parameters);
mh = new DynamicMethodHandle(info, parameters);
_methodCache.Add(key, mh);
}
}
}
return mh;
}
#endregion
#region Dynamic Constructor Cache
private static Dictionary<Type, DynamicCtorDelegate> _ctorCache = new Dictionary<Type, DynamicCtorDelegate>();
private static DynamicCtorDelegate GetCachedConstructor(Type objectType)
{
if (objectType == null)
throw new ArgumentNullException(nameof(objectType));
DynamicCtorDelegate result = null;
var found = false;
try
{
found = _ctorCache.TryGetValue(objectType, out result);
}
catch
{ /* failure will drop into !found block */ }
if (!found)
{
lock (_ctorCache)
{
if (!_ctorCache.TryGetValue(objectType, out result))
{
#if NETFX_CORE
ConstructorInfo info = objectType.GetConstructor(ctorFlags, null, new Type[] { }, null);
#else
ConstructorInfo info = objectType.GetConstructor(ctorFlags, null, Type.EmptyTypes, null);
#endif
if (info == null)
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
"Cannot create instance of Type '{0}'. No public parameterless constructor found.",
objectType));
result = DynamicMethodHandlerFactory.CreateConstructor(info);
_ctorCache.Add(objectType, result);
}
}
}
return result;
}
#endregion
#region GetType
/// <summary>
/// Gets a Type object based on the type name.
/// </summary>
/// <param name="typeName">Type name including assembly name.</param>
/// <param name="throwOnError">true to throw an exception if the type can't be found.</param>
/// <param name="ignoreCase">true for a case-insensitive comparison of the type name.</param>
public static Type GetType(string typeName, bool throwOnError, bool ignoreCase)
{
string fullTypeName;
#if NETFX_CORE
if (typeName.Contains("Version="))
fullTypeName = typeName;
else
fullTypeName = typeName + ", Version=..., Culture=neutral, PublicKeyToken=null";
#else
fullTypeName = typeName;
#endif
#if NETFX_CORE
if (throwOnError)
return Type.GetType(fullTypeName);
else
try
{
return Type.GetType(fullTypeName);
}
catch
{
return null;
}
#else
return Type.GetType(fullTypeName, throwOnError, ignoreCase);
#endif
}
/// <summary>
/// Gets a Type object based on the type name.
/// </summary>
/// <param name="typeName">Type name including assembly name.</param>
/// <param name="throwOnError">true to throw an exception if the type can't be found.</param>
public static Type GetType(string typeName, bool throwOnError)
{
return GetType(typeName, throwOnError, false);
}
/// <summary>
/// Gets a Type object based on the type name.
/// </summary>
/// <param name="typeName">Type name including assembly name.</param>
public static Type GetType(string typeName)
{
return GetType(typeName, true, false);
}
#endregion
#region Create Instance
/// <summary>
/// Uses reflection to create an object using its
/// default constructor.
/// </summary>
/// <param name="objectType">Type of object to create.</param>
public static object CreateInstance(Type objectType)
{
var ctor = GetCachedConstructor(objectType);
if (ctor == null)
throw new NotImplementedException(objectType.Name + " " + Resources.DefaultConstructor + Resources.MethodNotImplemented);
return ctor.Invoke();
}
/// <summary>
/// Creates an instance of a generic type
/// using its default constructor.
/// </summary>
/// <param name="type">Generic type to create</param>
/// <param name="paramTypes">Type parameters</param>
/// <returns></returns>
public static object CreateGenericInstance(Type type, params Type[] paramTypes)
{
var genericType = type.GetGenericTypeDefinition();
var gt = genericType.MakeGenericType(paramTypes);
return Activator.CreateInstance(gt);
}
#endregion
private const BindingFlags propertyFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
private const BindingFlags fieldFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
private static readonly Dictionary<MethodCacheKey, DynamicMemberHandle> _memberCache = new Dictionary<MethodCacheKey, DynamicMemberHandle>();
internal static DynamicMemberHandle GetCachedProperty(Type objectType, string propertyName)
{
var key = new MethodCacheKey(objectType.FullName, propertyName, GetParameterTypes(null));
DynamicMemberHandle mh = null;
if (!_memberCache.TryGetValue(key, out mh))
{
lock (_memberCache)
{
if (!_memberCache.TryGetValue(key, out mh))
{
PropertyInfo info = objectType.GetProperty(propertyName, propertyFlags);
if (info == null)
throw new InvalidOperationException(
string.Format(Resources.MemberNotFoundException, propertyName));
mh = new DynamicMemberHandle(info);
_memberCache.Add(key, mh);
}
}
}
return mh;
}
internal static DynamicMemberHandle GetCachedField(Type objectType, string fieldName)
{
var key = new MethodCacheKey(objectType.FullName, fieldName, GetParameterTypes(null));
DynamicMemberHandle mh = null;
if (!_memberCache.TryGetValue(key, out mh))
{
lock (_memberCache)
{
if (!_memberCache.TryGetValue(key, out mh))
{
FieldInfo info = objectType.GetField(fieldName, fieldFlags);
if (info == null)
throw new InvalidOperationException(
string.Format(Resources.MemberNotFoundException, fieldName));
mh = new DynamicMemberHandle(info);
_memberCache.Add(key, mh);
}
}
}
return mh;
}
/// <summary>
/// Invokes a property getter using dynamic
/// method invocation.
/// </summary>
/// <param name="obj">Target object.</param>
/// <param name="property">Property to invoke.</param>
/// <returns></returns>
public static object CallPropertyGetter(object obj, string property)
{
if (ApplicationContext.UseReflectionFallback)
{
#if NET40
throw new NotSupportedException("CallPropertyGetter + UseReflectionFallback");
#else
var propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj);
#endif
}
else
{
if (obj == null)
throw new ArgumentNullException("obj");
if (string.IsNullOrEmpty(property))
throw new ArgumentException("Argument is null or empty.", "property");
var mh = GetCachedProperty(obj.GetType(), property);
if (mh.DynamicMemberGet == null)
{
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
"The property '{0}' on Type '{1}' does not have a public getter.",
property,
obj.GetType()));
}
return mh.DynamicMemberGet(obj);
}
}
/// <summary>
/// Invokes a property setter using dynamic
/// method invocation.
/// </summary>
/// <param name="obj">Target object.</param>
/// <param name="property">Property to invoke.</param>
/// <param name="value">New value for property.</param>
public static void CallPropertySetter(object obj, string property, object value)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (string.IsNullOrEmpty(property))
throw new ArgumentException("Argument is null or empty.", "property");
if (ApplicationContext.UseReflectionFallback)
{
#if NET40
throw new NotSupportedException("CallPropertySetter + UseReflectionFallback");
#else
var propertyInfo = obj.GetType().GetProperty(property);
propertyInfo.SetValue(obj, value);
#endif
}
else
{
var mh = GetCachedProperty(obj.GetType(), property);
if (mh.DynamicMemberSet == null)
{
throw new NotSupportedException(string.Format(
CultureInfo.CurrentCulture,
"The property '{0}' on Type '{1}' does not have a public setter.",
property,
obj.GetType()));
}
mh.DynamicMemberSet(obj, value);
}
}
#region Call Method
/// <summary>
/// Uses reflection to dynamically invoke a method
/// if that method is implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
public static object CallMethodIfImplemented(object obj, string method)
{
return CallMethodIfImplemented(obj, method, false, null);
}
/// <summary>
/// Uses reflection to dynamically invoke a method
/// if that method is implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static object CallMethodIfImplemented(object obj, string method, params object[] parameters)
{
return CallMethodIfImplemented(obj, method, true, parameters);
}
private static object CallMethodIfImplemented(object obj, string method, bool hasParameters, params object[] parameters)
{
if (ApplicationContext.UseReflectionFallback)
{
var found = (FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters)) != null);
if (found)
return CallMethod(obj, method, parameters);
else
return null;
}
else
{
var mh = GetCachedMethod(obj, method, parameters);
if (mh == null || mh.DynamicMethod == null)
return null;
return CallMethod(obj, mh, hasParameters, parameters);
}
}
/// <summary>
/// Detects if a method matching the name and parameters is implemented on the provided object.
/// </summary>
/// <param name="obj">The object implementing the method.</param>
/// <param name="method">The name of the method to find.</param>
/// <param name="parameters">The parameters matching the parameters types of the method to match.</param>
/// <returns>True obj implements a matching method.</returns>
public static bool IsMethodImplemented(object obj, string method, params object[] parameters)
{
var mh = GetCachedMethod(obj, method, parameters);
return mh != null && mh.DynamicMethod != null;
}
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
public static object CallMethod(object obj, string method)
{
return CallMethod(obj, method, false, null);
}
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static object CallMethod(object obj, string method, params object[] parameters)
{
return CallMethod(obj, method, true, parameters);
}
private static object CallMethod(object obj, string method, bool hasParameters, params object[] parameters)
{
if (ApplicationContext.UseReflectionFallback)
{
System.Reflection.MethodInfo info = GetMethod(obj.GetType(), method, hasParameters, parameters);
if (info == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
return CallMethod(obj, info, hasParameters, parameters);
}
else
{
var mh = GetCachedMethod(obj, method, hasParameters, parameters);
if (mh == null || mh.DynamicMethod == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
return CallMethod(obj, mh, hasParameters, parameters);
}
}
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="info">
/// System.Reflection.MethodInfo for the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static object CallMethod(object obj, System.Reflection.MethodInfo info, params object[] parameters)
{
return CallMethod(obj, info, true, parameters);
}
private static object CallMethod(object obj, System.Reflection.MethodInfo info, bool hasParameters, params object[] parameters)
{
if (ApplicationContext.UseReflectionFallback)
{
#if PCL46 || PCL259
throw new NotSupportedException("CallMethod + UseReflectionFallback");
#else
var infoParams = info.GetParameters();
var infoParamsCount = infoParams.Length;
bool hasParamArray = infoParamsCount > 0 && infoParams[infoParamsCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0;
bool specialParamArray = false;
if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(string[])))
specialParamArray = true;
if (hasParamArray && infoParams[infoParamsCount - 1].ParameterType.Equals(typeof(object[])))
specialParamArray = true;
object[] par = null;
if (infoParamsCount == 1 && specialParamArray)
{
par = new object[] { parameters };
}
else if (infoParamsCount > 1 && hasParamArray && specialParamArray)
{
par = new object[infoParamsCount];
for (int i = 0; i < infoParamsCount - 1; i++)
par[i] = parameters[i];
par[infoParamsCount - 1] = parameters[infoParamsCount - 1];
}
else
{
par = parameters;
}
object result = null;
try
{
result = info.Invoke(obj, par);
}
catch (Exception e)
{
Exception inner = null;
if (e.InnerException == null)
inner = e;
else
inner = e.InnerException;
throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner);
}
return result;
#endif
}
else
{
var mh = GetCachedMethod(obj, info, parameters);
if (mh == null || mh.DynamicMethod == null)
throw new NotImplementedException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodNotImplemented);
return CallMethod(obj, mh, hasParameters, parameters);
}
}
private static object CallMethod(object obj, DynamicMethodHandle methodHandle, bool hasParameters, params object[] parameters)
{
object result = null;
var method = methodHandle.DynamicMethod;
object[] inParams = null;
if (parameters == null)
inParams = new object[] { null };
else
inParams = parameters;
if (methodHandle.HasFinalArrayParam)
{
// last param is a param array or only param is an array
var pCount = methodHandle.MethodParamsLength;
var inCount = inParams.Length;
if (inCount == pCount - 1)
{
// no paramter was supplied for the param array
// copy items into new array with last entry null
object[] paramList = new object[pCount];
for (var pos = 0; pos <= pCount - 2; pos++)
paramList[pos] = parameters[pos];
paramList[paramList.Length - 1] = hasParameters && inParams.Length == 0 ? inParams : null;
// use new array
inParams = paramList;
}
else if ((inCount == pCount && inParams[inCount - 1] != null && !inParams[inCount - 1].GetType().IsArray) || inCount > pCount)
{
// 1 or more params go in the param array
// copy extras into an array
var extras = inParams.Length - (pCount - 1);
object[] extraArray = GetExtrasArray(extras, methodHandle.FinalArrayElementType);
Array.Copy(inParams, pCount - 1, extraArray, 0, extras);
// copy items into new array
object[] paramList = new object[pCount];
for (var pos = 0; pos <= pCount - 2; pos++)
paramList[pos] = parameters[pos];
paramList[paramList.Length - 1] = extraArray;
// use new array
inParams = paramList;
}
}
try
{
result = methodHandle.DynamicMethod(obj, inParams);
}
catch (Exception ex)
{
throw new CallMethodException(obj.GetType().Name + "." + methodHandle.MethodName + " " + Resources.MethodCallFailed, ex);
}
return result;
}
private static object[] GetExtrasArray(int count, Type arrayType)
{
return (object[])(System.Array.CreateInstance(arrayType.GetElementType(), count));
}
#endregion
#region Get/Find Method
/// <summary>
/// Uses reflection to locate a matching method
/// on the target object.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
public static System.Reflection.MethodInfo GetMethod(Type objectType, string method)
{
return GetMethod(objectType, method, true, false, null);
}
/// <summary>
/// Uses reflection to locate a matching method
/// on the target object.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static System.Reflection.MethodInfo GetMethod(Type objectType, string method, params object[] parameters)
{
return GetMethod(objectType, method, true, parameters);
}
private static System.Reflection.MethodInfo GetMethod(Type objectType, string method, bool hasParameters, params object[] parameters)
{
System.Reflection.MethodInfo result = null;
object[] inParams = null;
if (!hasParameters)
inParams = new object[] { };
else if (parameters == null)
inParams = new object[] { null };
else
inParams = parameters;
// try to find a strongly typed match
// first see if there's a matching method
// where all params match types
result = FindMethod(objectType, method, GetParameterTypes(hasParameters, inParams));
if (result == null)
{
// no match found - so look for any method
// with the right number of parameters
try
{
result = FindMethod(objectType, method, inParams.Length);
}
catch (AmbiguousMatchException)
{
// we have multiple methods matching by name and parameter count
result = FindMethodUsingFuzzyMatching(objectType, method, inParams);
}
}
// no strongly typed match found, get default based on name only
if (result == null)
{
result = objectType.GetMethod(method, allLevelFlags);
}
return result;
}
private static System.Reflection.MethodInfo FindMethodUsingFuzzyMatching(Type objectType, string method, object[] parameters)
{
System.Reflection.MethodInfo result = null;
Type currentType = objectType;
do
{
System.Reflection.MethodInfo[] methods = currentType.GetMethods(oneLevelFlags);
int parameterCount = parameters.Length;
// Match based on name and parameter types and parameter arrays
foreach (System.Reflection.MethodInfo m in methods)
{
if (m.Name == method)
{
var infoParams = m.GetParameters();
var pCount = infoParams.Length;
if (pCount > 0)
{
if (pCount == 1 && infoParams[0].ParameterType.IsArray)
{
// only param is an array
if (parameters.GetType().Equals(infoParams[0].ParameterType))
{
// got a match so use it
result = m;
break;
}
}
#if NETFX_CORE
if (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0)
#else
if (infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0)
#endif
{
// last param is a param array
if (parameterCount == pCount && parameters[pCount - 1].GetType().Equals(infoParams[pCount - 1].ParameterType))
{
// got a match so use it
result = m;
break;
}
}
}
}
}
if (result == null)
{
// match based on parameter name and number of parameters
foreach (System.Reflection.MethodInfo m in methods)
{
if (m.Name == method && m.GetParameters().Length == parameterCount)
{
result = m;
break;
}
}
}
if (result != null)
break;
#if NETFX_CORE
currentType = currentType.BaseType();
#else
currentType = currentType.BaseType;
#endif
} while (currentType != null);
return result;
}
/// <summary>
/// Returns information about the specified
/// method, even if the parameter types are
/// generic and are located in an abstract
/// generic base class.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="types">
/// Parameter types to pass to method.
/// </param>
public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, Type[] types)
{
System.Reflection.MethodInfo info = null;
do
{
// find for a strongly typed match
info = objectType.GetMethod(method, oneLevelFlags, null, types, null);
if (info != null)
{
break; // match found
}
#if NETFX_CORE
objectType = objectType.BaseType();
#else
objectType = objectType.BaseType;
#endif
} while (objectType != null);
return info;
}
/// <summary>
/// Returns information about the specified
/// method, finding the method based purely
/// on the method name and number of parameters.
/// </summary>
/// <param name="objectType">
/// Type of object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameterCount">
/// Number of parameters to pass to method.
/// </param>
public static System.Reflection.MethodInfo FindMethod(Type objectType, string method, int parameterCount)
{
// walk up the inheritance hierarchy looking
// for a method with the right number of
// parameters
System.Reflection.MethodInfo result = null;
Type currentType = objectType;
do
{
System.Reflection.MethodInfo info = currentType.GetMethod(method, oneLevelFlags);
if (info != null)
{
var infoParams = info.GetParameters();
var pCount = infoParams.Length;
if (pCount > 0 &&
((pCount == 1 && infoParams[0].ParameterType.IsArray) ||
#if NETFX_CORE
(infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Count() > 0)))
#else
(infoParams[pCount - 1].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length > 0)))
#endif
{
// last param is a param array or only param is an array
if (parameterCount >= pCount - 1)
{
// got a match so use it
result = info;
break;
}
}
else if (pCount == parameterCount)
{
// got a match so use it
result = info;
break;
}
}
#if NETFX_CORE
currentType = currentType.BaseType();
#else
currentType = currentType.BaseType;
#endif
} while (currentType != null);
return result;
}
#endregion
/// <summary>
/// Returns an array of Type objects corresponding
/// to the type of parameters provided.
/// </summary>
public static Type[] GetParameterTypes()
{
return GetParameterTypes(false, null);
}
/// <summary>
/// Returns an array of Type objects corresponding
/// to the type of parameters provided.
/// </summary>
/// <param name="parameters">
/// Parameter values.
/// </param>
public static Type[] GetParameterTypes(object[] parameters)
{
return GetParameterTypes(true, parameters);
}
private static Type[] GetParameterTypes(bool hasParameters, object[] parameters)
{
if (!hasParameters)
return new Type[] { };
List<Type> result = new List<Type>();
if (parameters == null)
{
result.Add(typeof(object));
}
else
{
foreach (object item in parameters)
{
if (item == null)
{
result.Add(typeof(object));
}
else
{
result.Add(item.GetType());
}
}
}
return result.ToArray();
}
#if !NETFX_CORE
/// <summary>
/// Gets a property type descriptor by name.
/// </summary>
/// <param name="t">Type of object containing the property.</param>
/// <param name="propertyName">Name of the property.</param>
public static PropertyDescriptor GetPropertyDescriptor(Type t, string propertyName)
{
var propertyDescriptors = TypeDescriptor.GetProperties(t);
PropertyDescriptor result = null;
foreach (PropertyDescriptor desc in propertyDescriptors)
if (desc.Name == propertyName)
{
result = desc;
break;
}
return result;
}
#endif
/// <summary>
/// Gets information about a property.
/// </summary>
/// <param name="objectType">Object containing the property.</param>
/// <param name="propertyName">Name of the property.</param>
public static PropertyInfo GetProperty(Type objectType, string propertyName)
{
return objectType.GetProperty(propertyName, propertyFlags);
}
/// <summary>
/// Gets a property value.
/// </summary>
/// <param name="obj">Object containing the property.</param>
/// <param name="info">Property info object for the property.</param>
/// <returns>The value of the property.</returns>
public static object GetPropertyValue(object obj, PropertyInfo info)
{
object result = null;
try
{
result = info.GetValue(obj, null);
}
catch (Exception e)
{
Exception inner = null;
if (e.InnerException == null)
inner = e;
else
inner = e.InnerException;
throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner);
}
return result;
}
/// <summary>
/// Invokes an instance method on an object.
/// </summary>
/// <param name="obj">Object containing method.</param>
/// <param name="info">Method info object.</param>
/// <returns>Any value returned from the method.</returns>
public static object CallMethod(object obj, System.Reflection.MethodInfo info)
{
object result = null;
try
{
result = info.Invoke(obj, null);
}
catch (Exception e)
{
Exception inner = null;
if (e.InnerException == null)
inner = e;
else
inner = e.InnerException;
throw new CallMethodException(obj.GetType().Name + "." + info.Name + " " + Resources.MethodCallFailed, inner);
}
return result;
}
/// <summary>
/// Uses reflection to dynamically invoke a method,
/// throwing an exception if it is not
/// implemented on the target object.
/// </summary>
/// <param name="obj">
/// Object containing method.
/// </param>
/// <param name="method">
/// Name of the method.
/// </param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method, params object[] parameters)
{
return await CallMethodTryAsync(obj, method, true, parameters);
}
/// <summary>
/// Invokes an instance method on an object. If the method
/// is async returning Task of object it will be invoked using an await statement.
/// </summary>
/// <param name="obj">Object containing method.</param>
/// <param name="method">
/// Name of the method.
/// </param>
public async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method)
{
return await CallMethodTryAsync(obj, method, false, null);
}
private async static System.Threading.Tasks.Task<object> CallMethodTryAsync(object obj, string method, bool hasParameters, params object[] parameters)
{
try
{
if (ApplicationContext.UseReflectionFallback)
{
#if PCL46 || PCL259
throw new NotSupportedException("CallMethod + UseReflectionFallback");
#else
var info = FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters));
if (info == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
var isAsyncTask = (info.ReturnType == typeof(System.Threading.Tasks.Task));
var isAsyncTaskObject = (info.ReturnType.IsGenericType && (info.ReturnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>)));
if (isAsyncTask)
{
await (System.Threading.Tasks.Task)CallMethod(obj, method, hasParameters, parameters);
return null;
}
else if (isAsyncTaskObject)
{
return await (System.Threading.Tasks.Task<object>)CallMethod(obj, method, hasParameters, parameters);
}
else
{
return CallMethod(obj, method, hasParameters, parameters);
}
#endif
}
else
{
var mh = GetCachedMethod(obj, method, hasParameters, parameters);
if (mh == null || mh.DynamicMethod == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
if (mh.IsAsyncTask)
{
await (System.Threading.Tasks.Task)CallMethod(obj, mh, hasParameters, parameters);
return null;
}
else if (mh.IsAsyncTaskObject)
{
return await (System.Threading.Tasks.Task<object>)CallMethod(obj, mh, hasParameters, parameters);
}
else
{
return CallMethod(obj, mh, hasParameters, parameters);
}
}
}
catch (InvalidCastException ex)
{
throw new NotSupportedException(
string.Format(Resources.TaskOfObjectException, obj.GetType().Name + "." + method),
ex);
}
}
/// <summary>
/// Returns true if the method provided is an async method returning a Task object.
/// </summary>
/// <param name="obj">Object containing method.</param>
/// <param name="method">Name of the method.</param>
public static bool IsAsyncMethod(object obj, string method)
{
return IsAsyncMethod(obj, method, false, null);
}
/// <summary>
/// Returns true if the method provided is an async method returning a Task object.
/// </summary>
/// <param name="obj">Object containing method.</param>
/// <param name="method">Name of the method.</param>
/// <param name="parameters">
/// Parameters to pass to method.
/// </param>
public static bool IsAsyncMethod(object obj, string method, params object[] parameters)
{
return IsAsyncMethod(obj, method, true, parameters);
}
private static bool IsAsyncMethod(object obj, string method, bool hasParameters, params object[] parameters)
{
if (ApplicationContext.UseReflectionFallback)
{
#if PCL46 || PCL259
throw new NotSupportedException("CallMethod + UseReflectionFallback");
#else
var info = FindMethod(obj.GetType(), method, GetParameterTypes(hasParameters, parameters));
if (info == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
var isAsyncTask = (info.ReturnType == typeof(System.Threading.Tasks.Task));
var isAsyncTaskObject = (info.ReturnType.IsGenericType && (info.ReturnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>)));
return isAsyncTask || isAsyncTaskObject;
#endif
}
else
{
var mh = GetCachedMethod(obj, method, hasParameters, parameters);
if (mh == null || mh.DynamicMethod == null)
throw new NotImplementedException(obj.GetType().Name + "." + method + " " + Resources.MethodNotImplemented);
return mh.IsAsyncTask || mh.IsAsyncTaskObject;
}
}
#if !NETFX_CORE
/// <summary>
/// Invokes a generic async static method by name
/// </summary>
/// <param name="objectType">Class containing static method</param>
/// <param name="method">Method to invoke</param>
/// <param name="typeParams">Type parameters for method</param>
/// <param name="hasParameters">Flag indicating whether method accepts parameters</param>
/// <param name="parameters">Parameters for method</param>
/// <returns></returns>
public static Task<object> CallGenericStaticMethodAsync(Type objectType, string method, Type[] typeParams, bool hasParameters, params object[] parameters)
{
var tcs = new TaskCompletionSource<object>();
try
{
Task task = null;
if (hasParameters)
{
var pTypes = GetParameterTypes(parameters);
var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, pTypes, null);
if (methodReference == null)
methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public);
if (methodReference == null)
throw new InvalidOperationException(objectType.Name + "." + method);
var gr = methodReference.MakeGenericMethod(typeParams);
task = (Task)gr.Invoke(null, parameters);
}
else
{
var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, System.Type.EmptyTypes, null);
var gr = methodReference.MakeGenericMethod(typeParams);
task = (Task)gr.Invoke(null, null);
}
task.Wait();
if (task.Exception != null)
tcs.SetException(task.Exception);
else
tcs.SetResult(Csla.Reflection.MethodCaller.CallPropertyGetter(task, "Result"));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
return tcs.Task;
}
#endif
/// <summary>
/// Invokes a generic method by name
/// </summary>
/// <param name="target">Object containing method to invoke</param>
/// <param name="method">Method to invoke</param>
/// <param name="typeParams">Type parameters for method</param>
/// <param name="hasParameters">Flag indicating whether method accepts parameters</param>
/// <param name="parameters">Parameters for method</param>
/// <returns></returns>
public static object CallGenericMethod(object target, string method, Type[] typeParams, bool hasParameters, params object[] parameters)
{
var objectType = target.GetType();
object result = null;
if (hasParameters)
{
var pTypes = GetParameterTypes(parameters);
#if NETFX_CORE
var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, pTypes, null);
#else
var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.Any, pTypes, null);
#endif
if (methodReference == null)
methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public);
if (methodReference == null)
throw new InvalidOperationException(objectType.Name + "." + method);
var gr = methodReference.MakeGenericMethod(typeParams);
result = gr.Invoke(target, parameters);
}
else
{
#if PCL46 || PCL259
var emptyTypes = new Type[] { };
var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, emptyTypes, null);
#elif NETFX_CORE
var methodReference = objectType.GetMethod(method, BindingFlags.Instance | BindingFlags.Public, null, System.Type.EmptyTypes, null);
#else
var methodReference = objectType.GetMethod(method, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, System.Type.EmptyTypes, null);
#endif
if (methodReference == null)
throw new InvalidOperationException(objectType.Name + "." + method);
var gr = methodReference.MakeGenericMethod(typeParams);
result = gr.Invoke(target, null);
}
return result;
}
/// <summary>
/// Invokes a static factory method.
/// </summary>
/// <param name="objectType">Business class where the factory is defined.</param>
/// <param name="method">Name of the factory method</param>
/// <param name="parameters">Parameters passed to factory method.</param>
/// <returns>Result of the factory method invocation.</returns>
public static object CallFactoryMethod(Type objectType, string method, params object[] parameters)
{
object returnValue;
System.Reflection.MethodInfo factory = objectType.GetMethod(
method, factoryFlags, null,
MethodCaller.GetParameterTypes(parameters), null);
if (factory == null)
{
// strongly typed factory couldn't be found
// so find one with the correct number of
// parameters
int parameterCount = parameters.Length;
System.Reflection.MethodInfo[] methods = objectType.GetMethods(factoryFlags);
foreach (System.Reflection.MethodInfo oneMethod in methods)
if (oneMethod.Name == method && oneMethod.GetParameters().Length == parameterCount)
{
factory = oneMethod;
break;
}
}
if (factory == null)
{
// no matching factory could be found
// so throw exception
throw new InvalidOperationException(
string.Format(Resources.NoSuchFactoryMethod, method));
}
try
{
returnValue = factory.Invoke(null, parameters);
}
catch (Exception ex)
{
Exception inner = null;
if (ex.InnerException == null)
inner = ex;
else
inner = ex.InnerException;
throw new CallMethodException(objectType.Name + "." + factory.Name + " " + Resources.MethodCallFailed, inner);
}
return returnValue;
}
/// <summary>
/// Gets a System.Reflection.MethodInfo object corresponding to a
/// non-public method.
/// </summary>
/// <param name="objectType">Object containing the method.</param>
/// <param name="method">Name of the method.</param>
public static System.Reflection.MethodInfo GetNonPublicMethod(Type objectType, string method)
{
System.Reflection.MethodInfo result = null;
result = FindMethod(objectType, method, privateMethodFlags);
return result;
}
#if !NETFX_CORE
/// <summary>
/// Returns information about the specified
/// method.
/// </summary>
/// <param name="objType">Type of object.</param>
/// <param name="method">Name of the method.</param>
/// <param name="flags">Flag values.</param>
public static System.Reflection.MethodInfo FindMethod(Type objType, string method, BindingFlags flags)
{
System.Reflection.MethodInfo info = null;
do
{
// find for a strongly typed match
info = objType.GetMethod(method, flags);
if (info != null)
break; // match found
objType = objType.BaseType;
} while (objType != null);
return info;
}
#else
/// <summary>
/// Returns information about the specified
/// method.
/// </summary>
/// <param name="objType">Type of object.</param>
/// <param name="method">Name of the method.</param>
/// <param name="flags">Flag values.</param>
public static System.Reflection.MethodInfo FindMethod(Type objType, string method, BindingFlags flags)
{
var info = objType.GetMethod(method);
return info;
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.ApplicationParts;
using Orleans.Hosting;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Extensions for working with <see cref="ApplicationPartManager"/>.
/// </summary>
public static class ApplicationPartManagerExtensions
{
private static readonly string CoreAssemblyName = typeof(RuntimeVersion).Assembly.GetName().Name;
private static readonly string AbstractionsAssemblyName = typeof(IGrain).Assembly.GetName().Name;
private static readonly IEnumerable<string> NoReferenceComplaint = new[] { $"Assembly does not reference {CoreAssemblyName} or {AbstractionsAssemblyName}" };
private static readonly object ApplicationPartsKey = new object();
/// <summary>
/// Returns the <see cref="ApplicationPartManager"/> for the provided context.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>The <see cref="ApplicationPartManager"/> belonging to the provided context.</returns>
public static ApplicationPartManager GetApplicationPartManager(this HostBuilderContext context) => GetApplicationPartManager(context.Properties);
/// <summary>
/// Adds default application parts if no non-framework parts have been added.
/// </summary>
/// <param name="applicationPartManager">The application part manager.</param>
/// <returns>The application part manager.</returns>
public static IApplicationPartManager ConfigureDefaults(this IApplicationPartManager applicationPartsManager)
{
var hasApplicationParts = applicationPartsManager.ApplicationParts.OfType<AssemblyPart>()
.Any(part => !part.IsFrameworkAssembly);
if (!hasApplicationParts)
{
applicationPartsManager.AddFromDependencyContext();
applicationPartsManager.AddFromAppDomain();
applicationPartsManager.AddFromApplicationBaseDirectory();
}
return applicationPartsManager;
}
/// <summary>
/// Creates and populates a feature.
/// </summary>
/// <typeparam name="TFeature">The feature.</typeparam>
/// <param name="applicationPartManager">The application part manager.</param>
/// <returns>The populated feature.</returns>
public static TFeature CreateAndPopulateFeature<TFeature>(this IApplicationPartManager applicationPartManager) where TFeature : new()
{
var result = new TFeature();
applicationPartManager.PopulateFeature(result);
return result;
}
/// <summary>
/// Adds the provided assembly to the builder as a framework assembly.
/// </summary>
/// <param name="manager">The builder.</param>
/// <param name="assembly">The assembly.</param>
/// <returns>The builder with the additionally added assembly.</returns>
public static IApplicationPartManagerWithAssemblies AddFrameworkPart(this IApplicationPartManager manager, Assembly assembly)
{
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
return new ApplicationPartManagerWithAssemblies(
manager.AddApplicationPart(
new AssemblyPart(assembly) {IsFrameworkAssembly = true}),
new[] {assembly});
}
/// <summary>
/// Adds the provided assembly to the builder.
/// </summary>
/// <param name="manager">The builder.</param>
/// <param name="assembly">The assembly.</param>
/// <returns>The builder with the additionally added assembly.</returns>
public static IApplicationPartManagerWithAssemblies AddApplicationPart(this IApplicationPartManager manager, Assembly assembly)
{
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
return new ApplicationPartManagerWithAssemblies(manager.AddApplicationPart(new AssemblyPart(assembly)), new[] { assembly });
}
/// <summary>
/// Adds assemblies from the current <see cref="AppDomain.BaseDirectory"/> to the builder.
/// </summary>
/// <param name="manager">The builder.</param>
/// <returns>The builder with the additionally added assemblies.</returns>
public static IApplicationPartManagerWithAssemblies AddFromApplicationBaseDirectory(this IApplicationPartManager manager)
{
var appDomainBase = AppDomain.CurrentDomain.BaseDirectory;
if (string.IsNullOrWhiteSpace(appDomainBase) || !Directory.Exists(appDomainBase)) return new ApplicationPartManagerWithAssemblies(manager, Enumerable.Empty<Assembly>());
var dirs = new Dictionary<string, SearchOption> { [appDomainBase] = SearchOption.TopDirectoryOnly };
AssemblyLoaderPathNameCriterion[] excludeCriteria =
{
AssemblyLoaderCriteria.ExcludeResourceAssemblies
};
AssemblyLoaderReflectionCriterion[] loadCriteria =
{
AssemblyLoaderReflectionCriterion.NewCriterion(ReferencesOrleansOrAbstractionsAssemblyPredicate)
};
var loadedAssemblies = AssemblyLoader.LoadAssemblies(dirs, excludeCriteria, loadCriteria, NullLogger.Instance);
foreach (var assembly in loadedAssemblies)
{
manager.AddApplicationPart(new AssemblyPart(assembly));
}
return new ApplicationPartManagerWithAssemblies(manager, loadedAssemblies);
// Returns true if the provided assembly references the Orleans core or abstractions assembly.
bool ReferencesOrleansOrAbstractionsAssemblyPredicate(Assembly assembly, out IEnumerable<string> complaints)
{
var referencesOrleans = assembly.GetReferencedAssemblies().Any(ReferencesOrleansOrAbstractions);
complaints = referencesOrleans ? null : NoReferenceComplaint;
return referencesOrleans;
bool ReferencesOrleansOrAbstractions(AssemblyName reference)
{
return string.Equals(reference.Name, CoreAssemblyName, StringComparison.OrdinalIgnoreCase)
|| string.Equals(reference.Name, AbstractionsAssemblyName, StringComparison.OrdinalIgnoreCase);
}
}
}
/// <summary>
/// Adds assemblies from the current <see cref="AppDomain"/> to the builder.
/// </summary>
/// <param name="manager">The builder.</param>
/// <returns>The builder with the added assemblies.</returns>
public static IApplicationPartManagerWithAssemblies AddFromAppDomain(this IApplicationPartManager manager)
{
if (manager == null)
{
throw new ArgumentNullException(nameof(manager));
}
var processedAssemblies = new HashSet<Assembly>(AppDomain.CurrentDomain.GetAssemblies());
foreach (var assembly in processedAssemblies)
{
manager.AddApplicationPart(new AssemblyPart(assembly));
}
return new ApplicationPartManagerWithAssemblies(manager, processedAssemblies);
}
/// <summary>
/// Adds all assemblies referenced by the assemblies in the builder's <see cref="IApplicationPartManagerWithAssemblies.Assemblies"/> property.
/// </summary>
/// <param name="manager">The builder.</param>
/// <returns>The builder with the additionally included assemblies.</returns>
public static IApplicationPartManagerWithAssemblies WithReferences(this IApplicationPartManagerWithAssemblies manager)
{
var referencedAssemblies = new HashSet<Assembly>(manager.Assemblies);
foreach (var scopedAssembly in manager.Assemblies)
{
LoadReferencedAssemblies(scopedAssembly, referencedAssemblies);
}
foreach (var includedAsm in referencedAssemblies)
{
manager.AddApplicationPart(new AssemblyPart(includedAsm));
}
return new ApplicationPartManagerWithAssemblies(manager, referencedAssemblies);
void LoadReferencedAssemblies(Assembly asm, HashSet<Assembly> includedAssemblies)
{
if (asm == null)
{
throw new ArgumentNullException(nameof(asm));
}
if (includedAssemblies == null)
{
throw new ArgumentNullException(nameof(includedAssemblies));
}
var referenced = asm.GetReferencedAssemblies();
foreach (var asmName in referenced)
{
try
{
var refAsm = Assembly.Load(asmName);
if (includedAssemblies.Add(refAsm)) LoadReferencedAssemblies(refAsm, includedAssemblies);
}
catch
{
// Ignore loading exceptions.
}
}
}
}
/// <summary>
/// Adds all assemblies referencing Orleans found in the application's <see cref="DependencyContext"/>.
/// </summary>
/// <param name="manager">The builder.</param>
/// <returns>The builder with the additionally included assemblies.</returns>
public static IApplicationPartManagerWithAssemblies AddFromDependencyContext(this IApplicationPartManager manager)
{
return manager.AddFromDependencyContext(Assembly.GetCallingAssembly())
.AddFromDependencyContext(Assembly.GetEntryAssembly())
.AddFromDependencyContext(Assembly.GetExecutingAssembly());
}
/// <summary>
/// Adds all assemblies referencing Orleans found in the provided assembly's <see cref="DependencyContext"/>.
/// </summary>
/// <param name="manager">The builder.</param>
/// <returns>The builder with the additionally included assemblies.</returns>
public static IApplicationPartManagerWithAssemblies AddFromDependencyContext(this IApplicationPartManager manager, Assembly entryAssembly)
{
entryAssembly = entryAssembly ?? Assembly.GetCallingAssembly();
var dependencyContext = DependencyContext.Default;
if (entryAssembly != null)
{
dependencyContext = DependencyContext.Load(entryAssembly) ?? DependencyContext.Default;
manager = manager.AddApplicationPart(entryAssembly);
}
if (dependencyContext == null) return new ApplicationPartManagerWithAssemblies(manager, Array.Empty<Assembly>());
var assemblies = new List<Assembly>();
foreach (var lib in dependencyContext.RuntimeLibraries)
{
if (!lib.Dependencies.Any(dep => dep.Name.Contains("Orleans"))) continue;
try
{
var asm = Assembly.Load(lib.Name);
manager.AddApplicationPart(new AssemblyPart(asm));
assemblies.Add(asm);
}
catch
{
// Ignore any exceptions thrown during non-explicit assembly loading.
}
}
return new ApplicationPartManagerWithAssemblies(manager, assemblies);
}
/// <summary>
/// Returns the <see cref="ApplicationPartManager"/> for the provided properties.
/// </summary>
/// <param name="properties">The properties.</param>
/// <returns>The <see cref="ApplicationPartManager"/> belonging to the provided properties.</returns>
internal static ApplicationPartManager GetApplicationPartManager(IDictionary<object, object> properties)
{
ApplicationPartManager result;
if (properties.TryGetValue(ApplicationPartsKey, out var value))
{
result = value as ApplicationPartManager;
if (result == null) throw new InvalidOperationException($"The ApplicationPartManager value is of the wrong type {value.GetType()}. It should be {nameof(ApplicationPartManager)}");
}
else
{
properties[ApplicationPartsKey] = result = new ApplicationPartManager();
}
return result;
}
private class ApplicationPartManagerWithAssemblies : IApplicationPartManagerWithAssemblies
{
private readonly IApplicationPartManager manager;
public ApplicationPartManagerWithAssemblies(IApplicationPartManager manager, IEnumerable<Assembly> additionalAssemblies)
{
if (manager is ApplicationPartManagerWithAssemblies builderWithAssemblies)
{
this.manager = builderWithAssemblies.manager;
this.Assemblies = builderWithAssemblies.Assemblies.Concat(additionalAssemblies).Distinct().ToList();
}
else
{
this.manager = manager;
this.Assemblies = additionalAssemblies;
}
}
public IEnumerable<Assembly> Assemblies { get; }
public IReadOnlyList<IApplicationFeatureProvider> FeatureProviders => this.manager.FeatureProviders;
public IReadOnlyList<IApplicationPart> ApplicationParts => this.manager.ApplicationParts;
public IApplicationPartManager AddApplicationPart(IApplicationPart part)
{
this.manager.AddApplicationPart(part);
return this;
}
public IApplicationPartManager AddFeatureProvider(IApplicationFeatureProvider featureProvider)
{
this.manager.AddFeatureProvider(featureProvider);
return this;
}
public void PopulateFeature<TFeature>(TFeature feature) => this.manager.PopulateFeature(feature);
}
}
}
| |
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// Copyright (c) 2011 Andy Pickett
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace YamlDotNet.RepresentationModel
{
/// <summary>
/// Represents a mapping node in the YAML document.
/// </summary>
[Serializable]
public sealed class YamlMappingNode : YamlNode, IEnumerable<KeyValuePair<YamlNode, YamlNode>>, IYamlConvertible
{
private readonly IDictionary<YamlNode, YamlNode> children = new Dictionary<YamlNode, YamlNode>();
/// <summary>
/// Gets the children of the current node.
/// </summary>
/// <value>The children.</value>
public IDictionary<YamlNode, YamlNode> Children
{
get
{
return children;
}
}
/// <summary>
/// Gets or sets the style of the node.
/// </summary>
/// <value>The style.</value>
public MappingStyle Style { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
internal YamlMappingNode(IParser parser, DocumentLoadingState state)
{
Load(parser, state);
}
private void Load(IParser parser, DocumentLoadingState state)
{
var mapping = parser.Expect<MappingStart>();
Load(mapping, state);
Style = mapping.Style;
bool hasUnresolvedAliases = false;
while (!parser.Accept<MappingEnd>())
{
var key = ParseNode(parser, state);
var value = ParseNode(parser, state);
try
{
children.Add(key, value);
}
catch (ArgumentException err)
{
throw new YamlException(key.Start, key.End, "Duplicate key", err);
}
hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode;
}
if (hasUnresolvedAliases)
{
state.AddNodeWithUnresolvedAliases(this);
}
parser.Expect<MappingEnd>();
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
public YamlMappingNode()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
public YamlMappingNode(params KeyValuePair<YamlNode, YamlNode>[] children)
: this((IEnumerable<KeyValuePair<YamlNode, YamlNode>>)children)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
public YamlMappingNode(IEnumerable<KeyValuePair<YamlNode, YamlNode>> children)
{
foreach (var child in children)
{
this.children.Add(child);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
/// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param>
public YamlMappingNode(params YamlNode[] children)
: this((IEnumerable<YamlNode>)children)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="YamlMappingNode"/> class.
/// </summary>
/// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param>
public YamlMappingNode(IEnumerable<YamlNode> children)
{
using (var enumerator = children.GetEnumerator())
{
while (enumerator.MoveNext())
{
var key = enumerator.Current;
if (!enumerator.MoveNext())
{
throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even.");
}
Add(key, enumerator.Current);
}
}
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(YamlNode key, YamlNode value)
{
children.Add(key, value);
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(string key, YamlNode value)
{
children.Add(new YamlScalarNode(key), value);
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(YamlNode key, string value)
{
children.Add(key, new YamlScalarNode(value));
}
/// <summary>
/// Adds the specified mapping to the <see cref="Children"/> collection.
/// </summary>
/// <param name="key">The key node.</param>
/// <param name="value">The value node.</param>
public void Add(string key, string value)
{
children.Add(new YamlScalarNode(key), new YamlScalarNode(value));
}
/// <summary>
/// Resolves the aliases that could not be resolved when the node was created.
/// </summary>
/// <param name="state">The state of the document.</param>
internal override void ResolveAliases(DocumentLoadingState state)
{
Dictionary<YamlNode, YamlNode> keysToUpdate = null;
Dictionary<YamlNode, YamlNode> valuesToUpdate = null;
foreach (var entry in children)
{
if (entry.Key is YamlAliasNode)
{
if (keysToUpdate == null)
{
keysToUpdate = new Dictionary<YamlNode, YamlNode>();
}
keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End));
}
if (entry.Value is YamlAliasNode)
{
if (valuesToUpdate == null)
{
valuesToUpdate = new Dictionary<YamlNode, YamlNode>();
}
valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End));
}
}
if (valuesToUpdate != null)
{
foreach (var entry in valuesToUpdate)
{
children[entry.Key] = entry.Value;
}
}
if (keysToUpdate != null)
{
foreach (var entry in keysToUpdate)
{
YamlNode value = children[entry.Key];
children.Remove(entry.Key);
children.Add(entry.Value, value);
}
}
}
/// <summary>
/// Saves the current node to the specified emitter.
/// </summary>
/// <param name="emitter">The emitter where the node is to be saved.</param>
/// <param name="state">The state.</param>
internal override void Emit(IEmitter emitter, EmitterState state)
{
emitter.Emit(new MappingStart(Anchor, Tag, true, Style));
foreach (var entry in children)
{
entry.Key.Save(emitter, state);
entry.Value.Save(emitter, state);
}
emitter.Emit(new MappingEnd());
}
/// <summary>
/// Accepts the specified visitor by calling the appropriate Visit method on it.
/// </summary>
/// <param name="visitor">
/// A <see cref="IYamlVisitor"/>.
/// </param>
public override void Accept(IYamlVisitor visitor)
{
visitor.Visit(this);
}
/// <summary />
public override bool Equals(object obj)
{
var other = obj as YamlMappingNode;
if (other == null || !Equals(other) || children.Count != other.children.Count)
{
return false;
}
foreach (var entry in children)
{
YamlNode otherNode;
if (!other.children.TryGetValue(entry.Key, out otherNode) || !SafeEquals(entry.Value, otherNode))
{
return false;
}
}
return true;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
var hashCode = base.GetHashCode();
foreach (var entry in children)
{
hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key));
hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value));
}
return hashCode;
}
/// <summary>
/// Recursively enumerates all the nodes from the document, starting on the current node,
/// and throwing <see cref="MaximumRecursionLevelReachedException"/>
/// if <see cref="RecursionLevel.Maximum"/> is reached.
/// </summary>
internal override IEnumerable<YamlNode> SafeAllNodes(RecursionLevel level)
{
level.Increment();
yield return this;
foreach (var child in children)
{
foreach (var node in child.Key.SafeAllNodes(level))
{
yield return node;
}
foreach (var node in child.Value.SafeAllNodes(level))
{
yield return node;
}
}
level.Decrement();
}
/// <summary>
/// Gets the type of node.
/// </summary>
public override YamlNodeType NodeType
{
get { return YamlNodeType.Mapping; }
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
internal override string ToString(RecursionLevel level)
{
if (!level.TryIncrement())
{
return MaximumRecursionLevelReachedToStringValue;
}
var text = new StringBuilder("{ ");
foreach (var child in children)
{
if (text.Length > 2)
{
text.Append(", ");
}
text.Append("{ ").Append(child.Key.ToString(level)).Append(", ").Append(child.Value.ToString(level)).Append(" }");
}
text.Append(" }");
level.Decrement();
return text.ToString();
}
#region IEnumerable<KeyValuePair<YamlNode,YamlNode>> Members
/// <summary />
public IEnumerator<KeyValuePair<YamlNode, YamlNode>> GetEnumerator()
{
return children.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer)
{
Load(parser, new DocumentLoadingState());
}
void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
{
Emit(emitter, new EmitterState());
}
/// <summary>
/// Creates a <see cref="YamlMappingNode" /> containing a key-value pair for each property of the specified object.
/// </summary>
public static YamlMappingNode FromObject(object mapping)
{
if (mapping == null)
{
throw new ArgumentNullException("mapping");
}
var result = new YamlMappingNode();
foreach (var property in mapping.GetType().GetPublicProperties())
{
if (property.CanRead && property.GetGetMethod().GetParameters().Length == 0)
{
var value = property.GetValue(mapping, null);
var valueNode = (value as YamlNode) ?? (Convert.ToString(value));
result.Add(property.Name, valueNode);
}
}
return result;
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki {
/// <summary>
/// Identifies a title by namespace, topic name, and filename
/// </summary>
[Serializable]
public class Title : IEquatable<Title>, IComparable<Title> {
//--- Class fields ---
public const String INDEX_PHP_TITLE = "index.php?title=";
private static readonly Regex INVALID_TITLE_REGEX = new Regex(@"^\/|^\.\.$|^\.$|^\./|^\.\./|/\./|/\.\./|/\.$|/\..$|\/$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex SEPARATOR_REGEX = new Regex(@"(?<=[^/])/(?=[^/])", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex INDEX_PHP_REGEX = new Regex(@"/?index\.php\?title=", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private static readonly char[] INDEX_PHP_CHARS = new[] { '%', '&', '+' };
private static readonly IDictionary<NS, string> _namespaceNames;
private static readonly IDictionary<string, NS> _namespaceValues;
private static readonly IDictionary<NS, NS> _frontToTalkMap;
private static readonly IDictionary<NS, NS> _talkToFrontMap;
private static readonly char[] TRIM_CHARS = new[] {'/', '_', ' ', '\t', '\r', '\n', '\f', '\v', '\x00A0'};
//--- Class constructor ---
static Title() {
// populate the namespace type to name mapping
_namespaceNames = new Dictionary<NS, string>();
_namespaceNames[NS.MAIN] = String.Empty;
_namespaceNames[NS.MAIN_TALK] = "Talk";
_namespaceNames[NS.USER] = "User";
_namespaceNames[NS.USER_TALK] = "User_talk";
_namespaceNames[NS.PROJECT] = "Project";
_namespaceNames[NS.PROJECT_TALK] = "Project_talk";
_namespaceNames[NS.TEMPLATE] = "Template";
_namespaceNames[NS.TEMPLATE_TALK] = "Template_talk";
_namespaceNames[NS.HELP] = "Help";
_namespaceNames[NS.HELP_TALK] = "Help_talk";
_namespaceNames[NS.ATTACHMENT] = "File";
_namespaceNames[NS.SPECIAL] = "Special";
_namespaceNames[NS.SPECIAL_TALK] = "Special_talk";
_namespaceNames[NS.ADMIN] = "Admin";
// populate the namespace name to type mapping
_namespaceValues = new Dictionary<string, NS>();
foreach(KeyValuePair<NS, string> ns in _namespaceNames) {
_namespaceValues[ns.Value.ToLowerInvariant()] = ns.Key;
}
// populate front to talk mapping
_frontToTalkMap = new Dictionary<NS, NS>();
_frontToTalkMap[NS.MAIN] = NS.MAIN_TALK;
_frontToTalkMap[NS.USER] = NS.USER_TALK;
_frontToTalkMap[NS.PROJECT] = NS.PROJECT_TALK;
_frontToTalkMap[NS.TEMPLATE] = NS.TEMPLATE_TALK;
_frontToTalkMap[NS.HELP] = NS.HELP_TALK;
_frontToTalkMap[NS.SPECIAL] = NS.SPECIAL_TALK;
// populate talk to front mapping
_talkToFrontMap = new Dictionary<NS, NS>();
foreach(KeyValuePair<NS, NS> ns in _frontToTalkMap) {
_talkToFrontMap[ns.Value] = ns.Key;
}
}
//--- Class methods ---
/// <summary>
/// Constructs a title object from a page namespace and database path
/// </summary>
public static Title FromDbPath(NS ns, string dbPath, string displayName) {
return FromDbPath(ns, dbPath, displayName, String.Empty);
}
/// <summary>
/// Constructs a title object from a page namespace, database path, and filename
/// </summary>
public static Title FromDbPath(NS ns, string dbPath, string displayName, string filename) {
return new Title(ns, dbPath, displayName, filename, null, null);
}
/// <summary>
/// Constructs a title object from a page namespace, database path, filename, anchor, and query
/// </summary>
public static Title FromDbPath(NS ns, string dbPath, string displayName, string filename, string anchor, string query) {
return new Title(ns, dbPath, displayName, filename, anchor, query);
}
/// <summary>
/// Contructs a title object from a prefixed database path
/// Ex. User:Admin/MyPage
/// </summary>
public static Title FromPrefixedDbPath(string prefixedDbPath, string displayName) {
NS ns;
string path;
StringToNSAndPath(null, prefixedDbPath, out ns, out path);
return FromDbPath(ns, path, displayName, String.Empty);
}
/// <summary>
/// Constructs a title object from a xdoc
/// </summary>
public static Title FromXDoc(XDoc node, string nsFieldName, string titleFieldName, string displayFieldName) {
return FromDbPath((NS)(node[nsFieldName].AsInt ?? 0), string.IsNullOrEmpty(titleFieldName) ? null : node[titleFieldName].AsText, string.IsNullOrEmpty(displayFieldName) ? null : node[displayFieldName].AsText);
}
/// <summary>
/// Constructs a title from the {pageid} parameter of a given API call. The api param is assumed to be double url encoded.
/// Ex. =User:Admin%252fMyPage
/// </summary>
public static Title FromApiParam(string pageid) {
if(pageid.StartsWith("=")) {
pageid = pageid.Substring(1);
string path = DbEncodePath(XUri.Decode(pageid));
return FromPrefixedDbPath(path, null);
}
if(pageid.EqualsInvariantIgnoreCase("home")) {
return FromDbPath(NS.MAIN, String.Empty, null);
}
return null;
}
public static Title FromUriPath(string path) {
return FromUIUri(null, path, false);
}
public static Title FromUriPath(Title baseTitle, string path) {
return FromUIUri(baseTitle, path, false);
}
public static Title FromUIUri(Title baseTitle, string uiUri) {
return FromUIUri(baseTitle, uiUri, true);
}
/// <summary>
/// Constructs a title from a ui uri segment (ui urls are items inserted by the editor or the user). The ui uri is assumed to be url encoded.
/// Ex. "index.php?title=User:Admin/MyPage", "User:Admin/MyPage", "File:User:Admin/MyPage/MyFile.jpg"
/// </summary>
public static Title FromUIUri(Title baseTitle, string uiUri, bool parseUri) {
NS ns;
string filename = String.Empty;
string query = null;
string anchor = null;
if(parseUri) {
Match indexPhpMatch = INDEX_PHP_REGEX.Match(uiUri);
if(indexPhpMatch.Success) {
uiUri = uiUri.Substring(indexPhpMatch.Length);
int amp = uiUri.IndexOf('&');
if(amp >= 0) {
uiUri = uiUri.Substring(0, amp) + "?" + uiUri.Substring(amp + 1);
}
}
int anchorIndex = uiUri.IndexOf('#');
if(0 <= anchorIndex && (anchorIndex + 1 <= uiUri.Length)) {
anchor = uiUri.Substring(anchorIndex + 1);
uiUri = uiUri.Substring(0, anchorIndex);
if(String.IsNullOrEmpty(uiUri.Trim())) {
uiUri = "./";
}
}
int queryIndex = uiUri.IndexOf('?');
if(0 <= queryIndex && (queryIndex + 1 < uiUri.Length)) {
query = uiUri.Substring(queryIndex + 1);
uiUri = uiUri.Substring(0, queryIndex);
}
}
string path = DbEncodePath(uiUri);
StringToNSAndPath(baseTitle, path, out ns, out path);
// if the url points to a file, extract the filename from it
if(ns == NS.ATTACHMENT) {
int filenameIndex = path.LastIndexOf('/');
if(0 <= filenameIndex) {
filename = path.Substring(filenameIndex, path.Length - filenameIndex);
path = path.Substring(0, filenameIndex);
} else {
filename = path;
path = String.Empty;
}
filename = XUri.Decode(filename.Trim('/'));
StringToNSAndPath(baseTitle, path, out ns, out path);
}
return FromDbPath(ns, path, null, filename, anchor, query);
}
/// <summary>
/// Convert a username to a title representation. I.e., the homepage
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public static Title FromUIUsername(string username) {
//Don't create hierarchies even if the username has /
username = username.Replace("/", "//");
string path = DbEncodePath(username);
if(string.IsNullOrEmpty(path)) {
throw new ArgumentException("username is empty", "username");
}
return FromDbPath(NS.USER, path, null);
}
public static Title FromRelativePath(Title root, string path) {
Title result;
bool isTalk = false;
// Check for relative talk page format
if(path.StartsWith("TALK://")) {
isTalk = true;
path = path.Substring(5);
}
// Check for relative page format
if(path.StartsWith("//")) {
NS ns;
path = '.' + path.Substring(1);
StringToNSAndPath(root, path, out ns, out path);
result = FromDbPath(ns, path, null);
if(isTalk) {
result = result.AsTalk();
}
} else {
result = FromPrefixedDbPath(path, null);
}
return result;
}
/// <summary>
/// Retrieve the string corresponding to the namespace type.
/// </summary>
public static String NSToString(NS ns) {
String nsString;
if(_namespaceNames.TryGetValue(ns, out nsString)) {
return nsString;
}
return String.Empty;
}
/// <summary>
/// Retrieve the type corresponding to the namespace name.
/// </summary>
public static NS StringToNS(String nsString) {
NS ns;
if(_namespaceValues.TryGetValue(nsString.ToLowerInvariant(), out ns)) {
return ns;
}
return NS.UNKNOWN;
}
/// <summary>
/// Retrieves the specified name as an parameter for an API call. The output is double uri encoded.
/// Ex. =my%252fname
/// </summary>
public static string AsApiParam(string name) {
// returns the name in an api consumable form
return "=" + XUri.DoubleEncode(name.Replace(" ", "_"));
}
public static string AnchorEncode(string section) {
return XUri.Encode(section.Trim().Replace(' ', '_')).ReplaceAll(
"%3A", ":",
"%", "."
);
}
/// <summary>
/// Helper to resolve a relative page path
/// </summary>
private static string ResolvePath(Title baseTitle, string prefixedRelativePath) {
bool useBasePath = false;
int basePathSegmentsToRemove = 0;
string savedTitle = prefixedRelativePath;
prefixedRelativePath = prefixedRelativePath.Trim();
// check if the title is a relative path (relative paths are only supported at the beginning of the title)
if(null != baseTitle) {
while(prefixedRelativePath.StartsWith("./") || prefixedRelativePath.StartsWith("../")) {
useBasePath = true;
if(prefixedRelativePath.StartsWith("./")) {
prefixedRelativePath = prefixedRelativePath.Substring(2);
} else {
prefixedRelativePath = prefixedRelativePath.Substring(3);
basePathSegmentsToRemove++;
}
}
if((prefixedRelativePath == ".") || (prefixedRelativePath == "..")) {
useBasePath = true;
if(prefixedRelativePath == "..") {
basePathSegmentsToRemove++;
}
prefixedRelativePath = String.Empty;
}
}
// if the title is a relative path, resolve it
if(useBasePath) {
string basePath = baseTitle.AsPrefixedDbPath();
if(basePathSegmentsToRemove > 0) {
MatchCollection segmentSeparators = SEPARATOR_REGEX.Matches(basePath);
// if the relative path specified more segments than are available, do not resolve the link.
// otherwise, strip the specified number of segments from the base path
if(segmentSeparators.Count + 1 < basePathSegmentsToRemove) {
basePath = String.Empty;
prefixedRelativePath = savedTitle;
} else if(segmentSeparators.Count + 1 == basePathSegmentsToRemove) {
int baseNsPos = basePath.IndexOf(':');
basePath = (baseNsPos < 0 ? String.Empty : basePath.Substring(0, baseNsPos + 1));
} else {
basePath = (basePath.Substring(0, (segmentSeparators[segmentSeparators.Count - basePathSegmentsToRemove].Index)));
}
}
prefixedRelativePath = (basePath + "/" + prefixedRelativePath).Trim('/');
}
return prefixedRelativePath;
}
/// <summary>
/// Helper to retrieve the namespace and path from a relative page path string
/// </summary>
private static void StringToNSAndPath(Title baseTitle, string prefixedRelativePath, out NS ns, out string path) {
ns = NS.MAIN;
path = prefixedRelativePath.Trim(new[] { '/' });
// handle relative paths in the title
path = ResolvePath(baseTitle, path);
// if there is a namespace, retrieve it
int nsPos = path.IndexOf(':');
if(nsPos > 1) {
ns = StringToNS(path.Substring(0, nsPos));
// if the namespace is not found, default to using the main namespace
// if found, extract the namespace from the title text
if(NS.UNKNOWN == ns) {
ns = NS.MAIN;
} else {
path = path.Substring(nsPos + 1);
}
}
// handle relative paths in the title
path = ResolvePath(baseTitle, path);
// if we didn't previously have a namespace, check if we have a namespace after resolving relative paths
if((nsPos < 0) && (null != baseTitle)) {
StringToNSAndPath(null, path, out ns, out path);
}
path = path.Trim(new[] { '/' });
}
/// <summary>
/// Return a title of the form namespace:text, or text if in the main namespace.
/// </summary>
private static String NSAndPathToString(NS ns, string path) {
if(NS.MAIN == ns) {
return path;
}
return NSToString(ns) + ":" + path;
}
/// <summary>
/// Helper method to encode a given path in a database-friendly format
/// </summary>
public static string DbEncodePath(string path) {
// encodes the specified path using the same format as the database
path = XUri.Decode(path);
path = path.ReplaceAll(
"%", "%25",
"[", "%5B",
"]", "%5D",
"{", "%7B",
"}", "%7D",
"|", "%7C",
"+", "%2B",
"<", "%3C",
">", "%3E",
"#", "%23",
"//", "%2F",
" ", "_"
);
path = path.Trim(TRIM_CHARS).Replace("%2F", "//");
return path;
}
public static string DbEncodeDisplayName(string displayName) {
displayName = displayName.ReplaceAll(
"%", "%25",
"[", "%5B",
"]", "%5D",
"{", "%7B",
"}", "%7D",
"|", "%7C",
"+", "%2B",
"<", "%3C",
">", "%3E",
"#", "%23",
" ", "_",
"/", "//"
);
displayName = displayName.Trim(TRIM_CHARS);
return displayName;
}
public static void ValidateDisplayName(string displayName) {
if(displayName == null){
throw new ArgumentException("displayname is null");
}
if(displayName.Trim().Length == 0) {
throw new ArgumentException("displayname is all whitespace or has a length of 0");
}
}
public static bool operator ==(Title o1, Title o2) {
return (Object)o1 == null ? (Object)o2 == null : o1.Equals(o2);
}
public static bool operator !=(Title o1, Title o2) {
return (Object)o1 == null ? (Object)o2 != null : !o1.Equals(o2);
}
//--- Fields ---
private NS _namespace;
private string _path;
private string _displayName;
private string _filename;
private string _anchor;
private string _query;
//--- Constructors ---
public Title(Title title) {
_namespace = title._namespace;
_path = title._path;
_displayName = title._displayName;
_filename = title._filename;
_anchor = title._anchor;
_query = title._query;
}
private Title(NS ns, string path, string displayName, string filename, string anchor, string query) {
_namespace = ns;
_path = path;
_displayName = displayName;
_filename = filename;
_anchor = anchor;
_query = query;
}
//--- Properties ---
public NS Namespace {
get { return _namespace; }
set { _namespace = value; }
}
public string Path {
get { return _path ?? String.Empty; }
set { _path = value; }
}
public string DisplayName {
get { return _displayName; }
set { _displayName = value; }
}
public string Filename {
get { return _filename ?? String.Empty; }
set { _filename = value; }
}
public string Anchor {
get { return _anchor; }
set { _anchor = value; }
}
public string Query {
get { return _query; }
set { _query = value; }
}
public string Extension { get { return System.IO.Path.GetExtension(Filename).TrimStart('.').ToLowerInvariant(); } }
public bool IsHomepage { get { return IsRoot && IsMain; } }
public bool IsRoot { get { return Path == String.Empty; } }
public bool IsMain { get { return NS.MAIN == Namespace; } }
public bool IsTemplate { get { return NS.TEMPLATE == Namespace; } }
public bool IsTemplateTalk { get { return NS.TEMPLATE_TALK == Namespace; } }
public bool IsUser { get { return NS.USER == Namespace; } }
public bool IsUserTalk { get { return NS.USER_TALK == Namespace; } }
public bool IsSpecial { get { return NS.SPECIAL == Namespace; } }
public bool IsSpecialTalk { get { return NS.SPECIAL_TALK == Namespace; } }
public bool IsFile { get { return !String.IsNullOrEmpty(Filename); } }
public bool HasAnchor { get { return null != Anchor; } }
public bool HasQuery { get { return null != Query; } }
public bool ShowHomepageChildren {
get {
switch(Namespace) {
case NS.USER:
case NS.USER_TALK:
case NS.TEMPLATE:
case NS.TEMPLATE_TALK:
case NS.SPECIAL:
case NS.SPECIAL_TALK:
return false;
}
return true;
}
}
public bool IsValid {
get {
if(DisplayName != null) {
try {
ValidateDisplayName(DisplayName);
} catch(ArgumentException) {
return false;
}
}
foreach(string segment in AsUnprefixedDbSegments()) {
if(INVALID_TITLE_REGEX.IsMatch(segment)) {
return false;
}
}
if(AsUnprefixedDbPath().Length > 255) {
return false;
}
return true;
}
}
public bool IsEditable {
get {
switch(Namespace) {
case NS.MAIN:
case NS.MAIN_TALK:
case NS.PROJECT:
case NS.PROJECT_TALK:
case NS.HELP:
case NS.HELP_TALK:
case NS.SPECIAL:
case NS.SPECIAL_TALK:
return true;
case NS.USER:
case NS.USER_TALK:
case NS.TEMPLATE:
case NS.TEMPLATE_TALK:
return !IsRoot;
}
return false;
}
}
public bool IsTalk {
get {
switch(Namespace) {
case NS.MAIN_TALK:
case NS.USER_TALK:
case NS.PROJECT_TALK:
case NS.TEMPLATE_TALK:
case NS.HELP_TALK:
case NS.SPECIAL_TALK:
return true;
default:
return false;
}
}
}
//--- Methods ---
/// <summary>
/// Helper method to include the filename query and anchor with the path
/// </summary>
public string AppendFilenameQueryAnchor(string path, bool containsIndexPhp) {
if(IsFile) {
if(!path.EndsWith("/")) {
path = path + "/";
}
path = "File:" + path + Filename.Replace("?", "%3f").Replace("#", "%23").Replace("&", "%26");
}
if(HasQuery) {
if(path.LastIndexOf('?') >= 0 || containsIndexPhp) {
path += "&" + Query;
} else {
path += "?" + Query;
}
}
if(HasAnchor) {
path += "#" + Anchor;
}
return path;
}
/// <summary>
/// Returns true if this title is a parent of the specified title
/// </summary>
public bool IsParentOf(Title title) {
string parent = AsPrefixedDbPath();
string child = title.AsPrefixedDbPath();
return child.StartsWith(parent + "/", true, null) && ((child.Length < parent.Length + 2) || (child[parent.Length + 2 - 1] != '/'));
}
/// <summary>
/// Retrieves the parent title
/// </summary>
public Title GetParent() {
string[] parents = AsUnprefixedDbSegments();
// parent of the home page is null
if(0 == parents.Length) {
return null;
}
// parent of pages with only one segment is the main page
if(1 == parents.Length) {
// Special:XXX pages should use Special: as their root, instead of the homepage
if(!IsRoot && IsSpecial) {
return FromDbPath(NS.SPECIAL, String.Empty, null);
}
return FromDbPath(NS.MAIN, String.Empty, null);
}
// parent of a page with multiple segments is obtained by combining the segments
if(1 < parents.Length) {
return FromDbPath(_namespace, String.Join("/", parents, 0, parents.Length - 1), null);
}
throw new InvalidOperationException("invalid title state");
}
/// <summary>
/// Retrieves the parent title
/// </summary>
/// <param name="forceNamespace">Force the namespace of the parent Title to be same as the current one</param>
/// <returns>Parent Title instance.</returns>
public Title GetParent(bool forceNamespace) {
if(!forceNamespace) {
return GetParent();
}
var parentTitle = IsFile ? FromDbPath(Namespace, Path, null) : GetParent();
if((null != parentTitle) && (!IsRoot)) {
parentTitle.Namespace = Namespace;
}
return parentTitle;
}
/// <summary>
/// Determine if this Title is the parent of another Title
/// </summary>
/// <param name="forceNamespace">Force the namespace of the child Title to be same as the current one</param>
/// <param name="title">Candidate child Title</param>
/// <returns><see langword="True"/> if the provided Title is a child of the current Title</returns>
public bool IsParentOf(bool forceNamespace, Title title) {
var parent = title;
if(Namespace == title.Namespace) {
while(null != (parent = parent.GetParent(forceNamespace))) {
if(parent == this) {
return true;
}
}
}
return false;
}
public override string ToString() {
return AppendFilenameQueryAnchor(AsPrefixedDbPath(), false);
}
/// <summary>
/// Retrieves the database encoded title
/// </summary>
public string AsUnprefixedDbPath() {
return Path;
}
/// <summary>
/// Retrieves the database encoded title prefixed with the namespace
/// </summary>
public string AsPrefixedDbPath() {
return NSAndPathToString(_namespace, Path);
}
/// <summary>
/// Retrieves the database encoded title as segments
/// </summary>
public string[] AsUnprefixedDbSegments() {
return AsDbSegments(AsUnprefixedDbPath());
}
public string AsSegmentName() {
string[] segments = AsUnprefixedDbSegments();
if(segments.Length > 0) {
return segments[segments.Length - 1];
}
return string.Empty;
}
/// <summary>
/// Retrieves an array of database encoded title segments
/// </summary>
private string[] AsDbSegments(string path) {
// replace '//' with '%2f' ('//' was used as encoding for '/' in titles)
path = path.Replace("//", "%2f");
// split path into segments and encode each segment individually
string[] parts = path.Split('/');
if((parts.Length == 1) && (parts[0].Length == 0) && IsMain) {
// the db-segments for the homepage is an empty array (so that it has length less than its child pages)
return StringUtil.EmptyArray;
}
string[] result = Array.ConvertAll(parts, delegate(string segment) {
// undo addition of capture avoiding symbol
segment = segment.Replace("%2f", "//");
return segment;
});
return result;
}
/// <summary>
/// Retrieves the title as the {pageid} parameter for an API call. The output is double uri encoded.
/// Ex. =User:Admin%252fMyPage
/// </summary>
public string AsApiParam() {
// returns the title in an {pageid} api consumable form
if(IsHomepage) {
return "home";
}
return "=" + NSAndPathToString(_namespace, XUri.DoubleEncode(AsUnprefixedDbPath()));
}
/// <summary>
/// Retrieves the title as a ui uri segment (ui urls can be used to access pages by pre-pending the ui host). The output is db encoded.
/// Ex. "index.php?title=User:Admin/MyPage", "User:Admin/MyPage"
/// </summary>
public string AsUiUriPath() {
return AsUiUriPath(false);
}
/// <summary>
/// Retrieves the title as a ui uri segment (ui urls can be used to access pages by pre-pending the ui host). The output is db encoded.
/// Ex. "index.php?title=User:Admin/MyPage", "User:Admin/MyPage"
/// </summary>
public string AsUiUriPath(bool forceUseIndexPhp) {
string path;
string dbPath = XUri.Decode(AsUnprefixedDbPath());
if(forceUseIndexPhp) {
path = INDEX_PHP_TITLE + AppendFilenameQueryAnchor(NSAndPathToString(Namespace, XUri.EncodeQuery(dbPath).Replace("+", "%2b")), true);
} else {
// returns the title in a wiki ui consumable form
StringBuilder pathBuilder = new StringBuilder();
string[] segments = AsDbSegments(dbPath);
bool useIndexPhp = false;
foreach(string segment in segments) {
if(-1 < segment.IndexOfAny(INDEX_PHP_CHARS)) {
useIndexPhp = true;
break;
}
if(0 < pathBuilder.Length) {
pathBuilder.Append("/");
}
pathBuilder.Append(XUri.EncodeSegment(segment));
}
if(useIndexPhp) {
path = INDEX_PHP_TITLE + AppendFilenameQueryAnchor(NSAndPathToString(Namespace, XUri.EncodeQuery(dbPath).Replace("+", "%2b")), true);
} else {
path = AppendFilenameQueryAnchor(NSAndPathToString(Namespace, pathBuilder.ToString().Replace("?", "%3f")), false);
}
}
// URL encode ?'s so they don't get confused for the query and add the filename, anchor and query
return path;
}
public string AsRelativePath(Title root) {
string dbPath;
Title activeRoot = IsTalk ? root.AsTalk() : root.AsFront();
// Check if the current title is under the root, and if so, make it relative
if((activeRoot.IsParentOf(this) || (activeRoot.Namespace == Namespace && activeRoot.IsRoot) || (activeRoot.AsPrefixedDbPath() == AsPrefixedDbPath()))) {
dbPath = "//" + (AsPrefixedDbPath().Substring(activeRoot.AsPrefixedDbPath().Length).Trim(new[] { '/' }));
if(IsTalk) {
dbPath = "TALK:" + dbPath;
}
} else {
dbPath = AsPrefixedDbPath();
}
return dbPath;
}
/// <summary>
/// Retrieves the talk title associated with this title
/// </summary>
public Title AsTalk() {
Title associatedTalkTitle = FromDbPath(Namespace, Path, DisplayName);
if(!IsTalk) {
NS talkNamespace;
if(_frontToTalkMap.TryGetValue(Namespace, out talkNamespace)) {
associatedTalkTitle.Namespace = talkNamespace;
} else {
associatedTalkTitle = null;
}
}
return associatedTalkTitle;
}
/// <summary>
/// Retrieves the non-talk title associated with this title
/// </summary>
public Title AsFront() {
Title associatedFrontTitle = FromDbPath(Namespace, Path, DisplayName);
if(IsTalk) {
NS frontNamespace;
if(_talkToFrontMap.TryGetValue(Namespace, out frontNamespace)) {
associatedFrontTitle.Namespace = frontNamespace;
} else {
associatedFrontTitle = null;
}
}
return associatedFrontTitle;
}
public Title WithUserFriendlyName(string name) {
name = name.Replace("/", "//");
Title result = this;
// check if current title represents the home page
if(IsHomepage) {
// if appended name is a prefix, change namespaces when appropriate
NS ns;
StringToNSAndPath(null, name, out ns, out name);
result = FromDbPath(ns, Path, null);
}
// construct new path
string path = string.IsNullOrEmpty(result.Path) ? DbEncodePath(name) : result.Path + "/" + DbEncodePath(name);
// initialize new title object
result = new Title(result.Namespace, path, result.DisplayName, result.Filename, result.Anchor, result.Query);
// trim any dangling '/' characters
result.Path = result.Path.TrimEnd(new[] { '/' });
// validate new title object
if(!result.IsValid) {
throw new ArgumentException(string.Format("resulting title object is invalid: {0}", result.AsPrefixedDbPath()), "name");
}
return result;
}
public Title WithUserFriendlyName(string name, string displayName) {
Title result = WithUserFriendlyName(name);
result.DisplayName = displayName;
return result;
}
/// <summary>
/// Change the last segment of a page path and the displayname.
/// * Requires at least a displayname or name to be provided (not empty/null)
/// * displayname provided but null name: name is generated from title
/// * name is provided but null displayname: displayname is unaffected
/// </summary>
/// <param name="name"></param>
/// <param name="displayName"></param>
/// <returns></returns>
public Title Rename(string name, string displayName) {
if(string.IsNullOrEmpty(name) && string.IsNullOrEmpty(displayName)) {
throw new ArgumentNullException("neither 'name' nor 'displayName' were provided");
}
// ensure page is not a root page
if(!IsRoot) {
// check if a name must be generated for the page based on the display name
if(string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(displayName)) {
// name comes from display name
name = displayName; // name gets encoded later by WithUserFriendlyName
}
} else if(!string.IsNullOrEmpty(name)) {
// root pages cannot be renamed
throw new ArgumentException("root pages cannot be renamed");
}
// check if a name was supplied (implies current page is not root)
Title ret;
if(!string.IsNullOrEmpty(name)) {
Title parent = GetParent(true);
// renaming a top level page in a namespace (e.g. special:foo)
if(parent.IsRoot) {
// strip out namespace: prefix if it's same as current namespace
string prefix = _namespaceNames[_namespace] + ":";
if(name.StartsWithInvariantIgnoreCase(prefix)) {
name = name.Substring(prefix.Length);
}
ret = Title.FromDbPath(_namespace, string.Empty, null).WithUserFriendlyName(name);
} else {
ret = parent.WithUserFriendlyName(name);
}
} else {
ret = new Title(this);
}
// "foo" renamed with "template:bar"
if(_namespace != ret._namespace) {
throw new ArgumentException("rename may not change namespaces");
}
// page title modified?
if(!string.IsNullOrEmpty(displayName)) {
ret.DisplayName = displayName;
} else {
ret.DisplayName = _displayName;
}
if(!ret.IsValid) {
throw new ArgumentException("renamed title is invalid");
}
return ret;
}
public override bool Equals(object obj) {
return ((IEquatable<Title>)this).Equals(obj as Title);
}
public override int GetHashCode() {
int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_namespace) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(Path) ^ StringComparer.OrdinalIgnoreCase.GetHashCode(Filename);
if(null != Query) {
result = result ^ StringComparer.OrdinalIgnoreCase.GetHashCode(Query);
}
if(null != Anchor) {
result = result ^ StringComparer.OrdinalIgnoreCase.GetHashCode(Anchor);
}
return result;
}
//--- IEquatable<Title> Members ---
bool IEquatable<Title>.Equals(Title info) {
if(null == info) {
return false;
}
return (Namespace == info.Namespace) && AsUnprefixedDbPath().EqualsInvariantIgnoreCase(info.AsUnprefixedDbPath()) && Filename.EqualsInvariantIgnoreCase(info.Filename) && Query.EqualsInvariantIgnoreCase(info.Query) && Anchor.EqualsInvariantIgnoreCase(info.Anchor);
}
//--- IComparable<Title> Members ---
public int CompareTo(Title other) {
int compare = (int)this.Namespace - (int)other.Namespace;
if(compare != 0) {
return compare;
}
return this.AsUnprefixedDbPath().Replace("//", "\uFFEF").CompareInvariantIgnoreCase(other.AsUnprefixedDbPath().Replace("//", "\uFFEF"));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceBus
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for QueuesOperations.
/// </summary>
public static partial class QueuesOperationsExtensions
{
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
public static IPage<SBQueue> ListByNamespace(this IQueuesOperations operations, string resourceGroupName, string namespaceName)
{
return operations.ListByNamespaceAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SBQueue>> ListByNamespaceAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByNamespaceWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a Service Bus queue. This operation is idempotent.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639395.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a queue resource.
/// </param>
public static SBQueue CreateOrUpdate(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, SBQueue parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, queueName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a Service Bus queue. This operation is idempotent.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639395.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a queue resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SBQueue> CreateOrUpdateAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, SBQueue parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a queue from the specified namespace in a resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639411.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
public static void Delete(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName)
{
operations.DeleteAsync(resourceGroupName, namespaceName, queueName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a queue from the specified namespace in a resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639411.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns a description for the specified queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639380.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
public static SBQueue Get(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName)
{
return operations.GetAsync(resourceGroupName, namespaceName, queueName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a description for the specified queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639380.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SBQueue> GetAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
public static IPage<SBAuthorizationRule> ListAuthorizationRules(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName)
{
return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, queueName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SBAuthorizationRule>> ListAuthorizationRulesAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an authorization rule for a queue.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
public static SBAuthorizationRule CreateOrUpdateAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, SBAuthorizationRule parameters)
{
return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates an authorization rule for a queue.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SBAuthorizationRule> CreateOrUpdateAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, SBAuthorizationRule parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a queue authorization rule.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705609.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
public static void DeleteAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName)
{
operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a queue authorization rule.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705609.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets an authorization rule for a queue by rule name.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705611.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
public static SBAuthorizationRule GetAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName)
{
return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets an authorization rule for a queue by rule name.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705611.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SBAuthorizationRule> GetAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Primary and secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705608.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
public static AccessKeys ListKeys(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName)
{
return operations.ListKeysAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Primary and secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705608.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessKeys> ListKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the primary or secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705606.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the authorization rule.
/// </param>
public static AccessKeys RegenerateKeys(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, RegenerateAccessKeyParameters parameters)
{
return operations.RegenerateKeysAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the primary or secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705606.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<AccessKeys> RegenerateKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SBQueue> ListByNamespaceNext(this IQueuesOperations operations, string nextPageLink)
{
return operations.ListByNamespaceNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SBQueue>> ListByNamespaceNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByNamespaceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SBAuthorizationRule> ListAuthorizationRulesNext(this IQueuesOperations operations, string nextPageLink)
{
return operations.ListAuthorizationRulesNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SBAuthorizationRule>> ListAuthorizationRulesNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using Csla;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="B06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="B07_RegionObjects"/> of type <see cref="B07_RegionColl"/> (1:M relation to <see cref="B08_Region"/>)<br/>
/// This class is an item of <see cref="B05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class B06_Country : BusinessBase<B06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
[NonSerialized]
internal int parent_SubContinent_ID = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Country ID");
/// <summary>
/// Gets the Country ID.
/// </summary>
/// <value>The Country ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Country Name");
/// <summary>
/// Gets or sets the Country Name.
/// </summary>
/// <value>The Country Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<B07_Country_Child> B07_Country_SingleObjectProperty = RegisterProperty<B07_Country_Child>(p => p.B07_Country_SingleObject, "B07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the B07 Country Single Object ("parent load" child property).
/// </summary>
/// <value>The B07 Country Single Object.</value>
public B07_Country_Child B07_Country_SingleObject
{
get { return GetProperty(B07_Country_SingleObjectProperty); }
private set { LoadProperty(B07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<B07_Country_ReChild> B07_Country_ASingleObjectProperty = RegisterProperty<B07_Country_ReChild>(p => p.B07_Country_ASingleObject, "B07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the B07 Country ASingle Object ("parent load" child property).
/// </summary>
/// <value>The B07 Country ASingle Object.</value>
public B07_Country_ReChild B07_Country_ASingleObject
{
get { return GetProperty(B07_Country_ASingleObjectProperty); }
private set { LoadProperty(B07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="B07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<B07_RegionColl> B07_RegionObjectsProperty = RegisterProperty<B07_RegionColl>(p => p.B07_RegionObjects, "B07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the B07 Region Objects ("parent load" child property).
/// </summary>
/// <value>The B07 Region Objects.</value>
public B07_RegionColl B07_RegionObjects
{
get { return GetProperty(B07_RegionObjectsProperty); }
private set { LoadProperty(B07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B06_Country"/> object.</returns>
internal static B06_Country NewB06_Country()
{
return DataPortal.CreateChild<B06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="B06_Country"/> object from the given B06_CountryDto.
/// </summary>
/// <param name="data">The <see cref="B06_CountryDto"/>.</param>
/// <returns>A reference to the fetched <see cref="B06_Country"/> object.</returns>
internal static B06_Country GetB06_Country(B06_CountryDto data)
{
B06_Country obj = new B06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.LoadProperty(B07_RegionObjectsProperty, B07_RegionColl.NewB07_RegionColl());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B06_Country()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(B07_Country_SingleObjectProperty, DataPortal.CreateChild<B07_Country_Child>());
LoadProperty(B07_Country_ASingleObjectProperty, DataPortal.CreateChild<B07_Country_ReChild>());
LoadProperty(B07_RegionObjectsProperty, DataPortal.CreateChild<B07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B06_Country"/> object from the given <see cref="B06_CountryDto"/>.
/// </summary>
/// <param name="data">The B06_CountryDto to use.</param>
private void Fetch(B06_CountryDto data)
{
// Value properties
LoadProperty(Country_IDProperty, data.Country_ID);
LoadProperty(Country_NameProperty, data.Country_Name);
// parent properties
parent_SubContinent_ID = data.Parent_SubContinent_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child <see cref="B07_Country_Child"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(B07_Country_Child child)
{
LoadProperty(B07_Country_SingleObjectProperty, child);
}
/// <summary>
/// Loads child <see cref="B07_Country_ReChild"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(B07_Country_ReChild child)
{
LoadProperty(B07_Country_ASingleObjectProperty, child);
}
/// <summary>
/// Inserts a new <see cref="B06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B04_SubContinent parent)
{
var dto = new B06_CountryDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.Country_Name = Country_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IB06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Country_IDProperty, resultDto.Country_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new B06_CountryDto();
dto.Country_ID = Country_ID;
dto.Country_Name = Country_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IB06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="B06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IB06_CountryDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Country_IDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace System
{
public partial class String
{
[Pure]
public bool Contains(string value)
{
return (IndexOf(value, StringComparison.Ordinal) >= 0);
}
[Pure]
public bool Contains(string value, StringComparison comparisonType)
{
return (IndexOf(value, comparisonType) >= 0);
}
// Returns the index of the first occurrence of a specified character in the current instance.
// The search starts at startIndex and runs thorough the next count characters.
//
[Pure]
public int IndexOf(char value)
{
return IndexOf(value, 0, this.Length);
}
[Pure]
public int IndexOf(char value, int startIndex)
{
return IndexOf(value, startIndex, this.Length - startIndex);
}
[Pure]
public unsafe int IndexOf(char value, int startIndex, int count)
{
if (startIndex < 0 || startIndex > Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || count > Length - startIndex)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count >= 4)
{
if (*pCh == value) goto ReturnIndex;
if (*(pCh + 1) == value) goto ReturnIndex1;
if (*(pCh + 2) == value) goto ReturnIndex2;
if (*(pCh + 3) == value) goto ReturnIndex3;
count -= 4;
pCh += 4;
}
while (count > 0)
{
if (*pCh == value)
goto ReturnIndex;
count--;
pCh++;
}
return -1;
ReturnIndex3: pCh++;
ReturnIndex2: pCh++;
ReturnIndex1: pCh++;
ReturnIndex:
return (int)(pCh - pChars);
}
}
// Returns the index of the first occurrence of any specified character in the current instance.
// The search starts at startIndex and runs to startIndex + count -1.
//
[Pure]
public int IndexOfAny(char[] anyOf)
{
return IndexOfAny(anyOf, 0, this.Length);
}
[Pure]
public int IndexOfAny(char[] anyOf, int startIndex)
{
return IndexOfAny(anyOf, startIndex, this.Length - startIndex);
}
[Pure]
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
if (anyOf == null)
{
throw new ArgumentNullException(nameof(anyOf));
}
if ((uint)startIndex > (uint)Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if ((uint)count > (uint)(Length - startIndex))
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
if (anyOf.Length == 2)
{
// Very common optimization for directory separators (/, \), quotes (", '), brackets, etc
return IndexOfAny(anyOf[0], anyOf[1], startIndex, count);
}
else if (anyOf.Length == 3)
{
return IndexOfAny(anyOf[0], anyOf[1], anyOf[2], startIndex, count);
}
else if (anyOf.Length > 3)
{
return IndexOfCharArray(anyOf, startIndex, count);
}
else if (anyOf.Length == 1)
{
return IndexOf(anyOf[0], startIndex, count);
}
else // anyOf.Length == 0
{
return -1;
}
}
private unsafe int IndexOfAny(char value1, char value2, int startIndex, int count)
{
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count > 0)
{
char c = *pCh;
if (c == value1 || c == value2)
return (int)(pCh - pChars);
// Possibly reads outside of count and can include null terminator
// Handled in the return logic
c = *(pCh + 1);
if (c == value1 || c == value2)
return (count == 1 ? -1 : (int)(pCh - pChars) + 1);
pCh += 2;
count -= 2;
}
return -1;
}
}
private unsafe int IndexOfAny(char value1, char value2, char value3, int startIndex, int count)
{
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count > 0)
{
char c = *pCh;
if (c == value1 || c == value2 || c == value3)
return (int)(pCh - pChars);
pCh++;
count--;
}
return -1;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern int IndexOfCharArray(char[] anyOf, int startIndex, int count);
// Determines the position within this string of the first occurrence of the specified
// string, according to the specified search criteria. The search begins at
// the first character of this string, it is case-sensitive and the current culture
// comparison is used.
//
[Pure]
public int IndexOf(String value)
{
return IndexOf(value, StringComparison.CurrentCulture);
}
// Determines the position within this string of the first occurrence of the specified
// string, according to the specified search criteria. The search begins at
// startIndex, it is case-sensitive and the current culture comparison is used.
//
[Pure]
public int IndexOf(String value, int startIndex)
{
return IndexOf(value, startIndex, StringComparison.CurrentCulture);
}
// Determines the position within this string of the first occurrence of the specified
// string, according to the specified search criteria. The search begins at
// startIndex, ends at endIndex and the current culture comparison is used.
//
[Pure]
public int IndexOf(String value, int startIndex, int count)
{
if (startIndex < 0 || startIndex > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || count > this.Length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
Contract.EndContractBlock();
return IndexOf(value, startIndex, count, StringComparison.CurrentCulture);
}
[Pure]
public int IndexOf(String value, StringComparison comparisonType)
{
return IndexOf(value, 0, this.Length, comparisonType);
}
[Pure]
public int IndexOf(String value, int startIndex, StringComparison comparisonType)
{
return IndexOf(value, startIndex, this.Length - startIndex, comparisonType);
}
[Pure]
public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType)
{
// Validate inputs
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0 || startIndex > this.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > this.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
Contract.EndContractBlock();
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.Ordinal);
case StringComparison.OrdinalIgnoreCase:
if (value.IsAscii() && this.IsAscii())
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
else
return TextInfo.IndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Returns the index of the last occurrence of a specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
[Pure]
public int LastIndexOf(char value)
{
return LastIndexOf(value, this.Length - 1, this.Length);
}
[Pure]
public int LastIndexOf(char value, int startIndex)
{
return LastIndexOf(value, startIndex, startIndex + 1);
}
[Pure]
public unsafe int LastIndexOf(char value, int startIndex, int count)
{
if (Length == 0)
return -1;
if (startIndex < 0 || startIndex >= Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || count - 1 > startIndex)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
//We search [startIndex..EndIndex]
while (count >= 4)
{
if (*pCh == value) goto ReturnIndex;
if (*(pCh - 1) == value) goto ReturnIndex1;
if (*(pCh - 2) == value) goto ReturnIndex2;
if (*(pCh - 3) == value) goto ReturnIndex3;
count -= 4;
pCh -= 4;
}
while (count > 0)
{
if (*pCh == value)
goto ReturnIndex;
count--;
pCh--;
}
return -1;
ReturnIndex3: pCh--;
ReturnIndex2: pCh--;
ReturnIndex1: pCh--;
ReturnIndex:
return (int)(pCh - pChars);
}
}
// Returns the index of the last occurrence of any specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
//ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff"
[Pure]
public int LastIndexOfAny(char[] anyOf)
{
return LastIndexOfAny(anyOf, this.Length - 1, this.Length);
}
[Pure]
public int LastIndexOfAny(char[] anyOf, int startIndex)
{
return LastIndexOfAny(anyOf, startIndex, startIndex + 1);
}
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int LastIndexOfAny(char[] anyOf, int startIndex, int count);
// Returns the index of the last occurrence of any character in value in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
[Pure]
public int LastIndexOf(String value)
{
return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture);
}
[Pure]
public int LastIndexOf(String value, int startIndex)
{
return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture);
}
[Pure]
public int LastIndexOf(String value, int startIndex, int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
Contract.EndContractBlock();
return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture);
}
[Pure]
public int LastIndexOf(String value, StringComparison comparisonType)
{
return LastIndexOf(value, this.Length - 1, this.Length, comparisonType);
}
[Pure]
public int LastIndexOf(String value, int startIndex, StringComparison comparisonType)
{
return LastIndexOf(value, startIndex, startIndex + 1, comparisonType);
}
[Pure]
public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
// Special case for 0 length input strings
if (this.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Now after handling empty strings, make sure we're not out of range
if (startIndex < 0 || startIndex > this.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == this.Length
if (startIndex == this.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.Ordinal);
case StringComparison.OrdinalIgnoreCase:
if (value.IsAscii() && this.IsAscii())
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
else
return TextInfo.LastIndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class ZipTests
{
[Fact]
public void ImplicitTypeParameters()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 5, 9 };
IEnumerable<int> expected = new int[] { 3, 7, 12 };
Assert.Equal(expected, first.Zip(second, (x, y) => x + y));
}
[Fact]
public void ExplicitTypeParameters()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 5, 9 };
IEnumerable<int> expected = new int[] { 3, 7, 12 };
Assert.Equal(expected, first.Zip<int, int, int>(second, (x, y) => x + y));
}
[Fact]
public void FirstIsNull()
{
IEnumerable<int> first = null;
IEnumerable<int> second = new int[] { 2, 5, 9 };
Assert.Throws<ArgumentNullException>(() => first.Zip<int, int, int>(second, (x, y) => x + y));
}
[Fact]
public void SecondIsNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = null;
Assert.Throws<ArgumentNullException>(() => first.Zip<int, int, int>(second, (x, y) => x + y));
}
[Fact]
public void FuncIsNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 4, 6 };
Func<int, int, int> func = null;
Assert.Throws<ArgumentNullException>(() => first.Zip(second, func));
}
private class MyIEnum<T> : IEnumerable<T>
{
public IEnumerable<T> _data;
public MyIEnum(IEnumerable<T> source)
{
_data = source;
}
public IEnumerator<T> GetEnumerator()
{
foreach (var datum in _data)
{
if (datum.Equals(2)) throw new Exception();
yield return datum;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
[Fact]
public void ExceptionThrownFromFirstsEnumerator()
{
MyIEnum<int> first = new MyIEnum<int>(new int[] { 1, 3, 3 });
IEnumerable<int> second = new int[] { 2, 4, 6 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 7, 9 };
Assert.Equal(expected, first.Zip(second, func));
first = new MyIEnum<int>(new int[] { 1, 2, 3 });
var zip = first.Zip(second, func);
Assert.Throws<Exception>(() => zip.ToList());
}
[Fact]
public void ExceptionThrownFromSecondsEnumerator()
{
MyIEnum<int> second = new MyIEnum<int>(new int[] { 1, 3, 3 });
IEnumerable<int> first = new int[] { 2, 4, 6 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 7, 9 };
Assert.Equal(expected, first.Zip(second, func));
second = new MyIEnum<int>(new int[] { 1, 2, 3 });
var zip = first.Zip(second, func);
Assert.Throws<Exception>(() => zip.ToList());
}
[Fact]
public void FirstAndSecondEmpty()
{
IEnumerable<int> first = new int[] { };
IEnumerable<int> second = new int[] { };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstEmptySecondSingle()
{
IEnumerable<int> first = new int[] { };
IEnumerable<int> second = new int[] { 2 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstEmptySecondMany()
{
IEnumerable<int> first = new int[] { };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondEmptyFirstSingle()
{
IEnumerable<int> first = new int[] { 1 };
IEnumerable<int> second = new int[] { };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondEmptyFirstMany()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstAndSecondSingle()
{
IEnumerable<int> first = new int[] { 1 };
IEnumerable<int> second = new int[] { 2 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstAndSecondEqualSize()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 3, 4 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 5, 7 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondOneMoreThanFirst()
{
IEnumerable<int> first = new int[] { 1, 2 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondManyMoreThanFirst()
{
IEnumerable<int> first = new int[] { 1, 2 };
IEnumerable<int> second = new int[] { 2, 4, 8, 16 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstOneMoreThanSecond()
{
IEnumerable<int> first = new int[] { 1, 2, 3 };
IEnumerable<int> second = new int[] { 2, 4 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstManyMoreThanSecond()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void DelegateFuncChanged()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int, int, int> func = (x, y) => x + y;
IEnumerable<int> expected = new int[] { 3, 6, 11 };
Assert.Equal(expected, first.Zip(second, func));
func = (x, y) => x - y;
expected = new int[] { -1, -2, -5 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void LambdaFuncChanged()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
IEnumerable<int> expected = new int[] { 3, 6, 11 };
Assert.Equal(expected, first.Zip(second, (x, y) => x + y));
expected = new int[] { -1, -2, -5 };
Assert.Equal(expected, first.Zip(second, (x, y) => x - y));
}
[Fact]
public void FirstHasFirstElementNull()
{
IEnumerable<int?> first = new[] { (int?)null, 2, 3, 4 };
IEnumerable<int> second = new int[] { 2, 4, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, 6, 11 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstHasLastElementNull()
{
IEnumerable<int?> first = new[] { 1, 2, (int?)null };
IEnumerable<int> second = new int[] { 2, 4, 6, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, 6, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstHasMiddleNullValue()
{
IEnumerable<int?> first = new[] { 1, (int?)null, 3 };
IEnumerable<int> second = new int[] { 2, 4, 6, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, null, 9 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstAllElementsNull()
{
IEnumerable<int?> first = new int?[] { null, null, null };
IEnumerable<int> second = new int[] { 2, 4, 6, 8 };
Func<int?, int, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasFirstElementNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { null, 4, 6 };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, 6, 9 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasLastElementNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { 2, 4, null };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, 6, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasMiddleElementNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { 2, null, 6 };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { 3, null, 9 };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondHasAllElementsNull()
{
IEnumerable<int> first = new int[] { 1, 2, 3, 4 };
IEnumerable<int?> second = new int?[] { null, null, null };
Func<int, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void SecondLargerFirstAllNull()
{
IEnumerable<int?> first = new int?[] { null, null, null, null };
IEnumerable<int?> second = new int?[] { null, null, null };
Func<int?, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstSameSizeSecondAllNull()
{
IEnumerable<int?> first = new int?[] { null, null, null };
IEnumerable<int?> second = new int?[] { null, null, null };
Func<int?, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
[Fact]
public void FirstSmallerSecondAllNull()
{
IEnumerable<int?> first = new int?[] { null, null, null };
IEnumerable<int?> second = new int?[] { null, null, null, null };
Func<int?, int?, int?> func = (x, y) => x + y;
IEnumerable<int?> expected = new int?[] { null, null, null };
Assert.Equal(expected, first.Zip(second, func));
}
}
}
| |
using System;
using Server;
using Server.Mobiles;
namespace Server.Engines.Quests.Collector
{
public class FishPearlsObjective : QuestObjective
{
public override object Message
{
get
{
// Fish up shellfish from Lake Haven and collect rainbow pearls.
return 1055084;
}
}
public override int MaxProgress{ get{ return 6; } }
public FishPearlsObjective()
{
}
public override void RenderProgress( BaseQuestGump gump )
{
if ( !Completed )
{
// Rainbow pearls collected:
gump.AddHtmlObject( 70, 260, 270, 100, 1055085, BaseQuestGump.Blue, false, false );
gump.AddLabel( 70, 280, 0x64, CurProgress.ToString() );
gump.AddLabel( 100, 280, 0x64, "/" );
gump.AddLabel( 130, 280, 0x64, MaxProgress.ToString() );
}
else
{
base.RenderProgress( gump );
}
}
public override void OnComplete()
{
System.AddObjective( new ReturnPearlsObjective() );
}
}
public class ReturnPearlsObjective : QuestObjective
{
public override object Message
{
get
{
/* You've collected enough rainbow pearls. Speak to
* Elwood to give them to him and get your next task.
*/
return 1055088;
}
}
public ReturnPearlsObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new ReturnPearlsConversation() );
}
}
public class FindAlbertaObjective : QuestObjective
{
public override object Message
{
get
{
// Go to Vesper and speak to Alberta Giacco at the Colored Canvas.
return 1055091;
}
}
public FindAlbertaObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new AlbertaPaintingConversation() );
}
}
public class SitOnTheStoolObjective : QuestObjective
{
private static readonly Point3D m_StoolLocation = new Point3D( 2899, 706, 0 );
private static readonly Map m_StoolMap = Map.Trammel;
private DateTime m_Begin;
public override object Message
{
get
{
/* Sit on the stool in front of Alberta's easel so that she can
* paint your portrait. You'll need to sit there for about 30 seconds.
*/
return 1055093;
}
}
public SitOnTheStoolObjective()
{
m_Begin = DateTime.MaxValue;
}
public override void CheckProgress()
{
PlayerMobile pm = System.From;
if ( pm.Map == m_StoolMap && pm.Location == m_StoolLocation )
{
if ( m_Begin == DateTime.MaxValue )
{
m_Begin = DateTime.Now;
}
else if ( DateTime.Now - m_Begin > TimeSpan.FromSeconds( 30.0 ) )
{
Complete();
}
}
else if ( m_Begin != DateTime.MaxValue )
{
m_Begin = DateTime.MaxValue;
pm.SendLocalizedMessage( 1055095, "", 0x26 ); // You must remain seated on the stool until the portrait is complete. Alberta will now have to start again with a fresh canvas.
}
}
public override void OnComplete()
{
System.AddConversation( new AlbertaEndPaintingConversation() );
}
}
public class ReturnPaintingObjective : QuestObjective
{
public override object Message
{
get
{
// Return to Elwood and let him know that the painting is complete.
return 1055099;
}
}
public ReturnPaintingObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new ReturnPaintingConversation() );
}
}
public class FindGabrielObjective : QuestObjective
{
public override object Message
{
get
{
/* Go to Britain and obtain the autograph of renowned
* minstrel, Gabriel Piete. He is often found at the Conservatory of Music.
*/
return 1055101;
}
}
public FindGabrielObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new GabrielAutographConversation() );
}
}
public enum Theater
{
Britain,
Nujelm,
Jhelom
}
public class FindSheetMusicObjective : QuestObjective
{
private Theater m_Theater;
public override object Message
{
get
{
/* Find some sheet music for one of Gabriel's songs.
* Try speaking to an impresario from one of the theaters in the land.
*/
return 1055104;
}
}
public FindSheetMusicObjective( bool init )
{
if ( init )
InitTheater();
}
public FindSheetMusicObjective()
{
}
public void InitTheater()
{
switch ( Utility.Random( 3 ) )
{
case 1: m_Theater = Theater.Britain; break;
case 2: m_Theater = Theater.Nujelm; break;
default: m_Theater = Theater.Jhelom; break;
}
}
public bool IsInRightTheater()
{
PlayerMobile player = System.From;
Region region = Region.Find( player.Location, player.Map );
if ( region == null )
return false;
switch ( m_Theater )
{
case Theater.Britain: return region.IsPartOf( "Britain" );
case Theater.Nujelm: return region.IsPartOf( "Nujel'm" );
case Theater.Jhelom: return region.IsPartOf( "Jhelom" );
default: return false;
}
}
public override void OnComplete()
{
System.AddConversation( new GetSheetMusicConversation() );
}
public override void ChildDeserialize( GenericReader reader )
{
int version = reader.ReadEncodedInt();
m_Theater = (Theater) reader.ReadEncodedInt();
}
public override void ChildSerialize( GenericWriter writer )
{
writer.WriteEncodedInt( (int) 0 ); // version
writer.WriteEncodedInt( (int) m_Theater );
}
}
public class ReturnSheetMusicObjective : QuestObjective
{
public override object Message
{
get
{
// Speak to Gabriel to have him autograph the sheet music.
return 1055110;
}
}
public ReturnSheetMusicObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new GabrielSheetMusicConversation() );
}
}
public class ReturnAutographObjective : QuestObjective
{
public override object Message
{
get
{
// Speak to Elwood to give him the autographed sheet music.
return 1055114;
}
}
public ReturnAutographObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new ReturnAutographConversation() );
}
}
public class FindTomasObjective : QuestObjective
{
public override object Message
{
get
{
// Go to Trinsic and speak to Tomas O'Neerlan, the famous toymaker.
return 1055117;
}
}
public FindTomasObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new TomasToysConversation() );
}
}
public enum CaptureResponse
{
Valid,
AlreadyDone,
Invalid
}
public class CaptureImagesObjective : QuestObjective
{
private ImageType[] m_Images;
private bool[] m_Done;
public override object Message
{
get
{
// Use the enchanted paints to capture the image of all of the creatures listed below.
return 1055120;
}
}
public override bool Completed
{
get
{
for ( int i = 0; i < m_Done.Length; i++ )
{
if ( !m_Done[i] )
return false;
}
return true;
}
}
public CaptureImagesObjective( bool init )
{
if ( init )
{
m_Images = ImageTypeInfo.RandomList( 4 );
m_Done = new bool[4];
}
}
public CaptureImagesObjective()
{
}
public override bool IgnoreYoungProtection( Mobile from )
{
if ( Completed )
return false;
Type fromType = from.GetType();
for ( int i = 0; i < m_Images.Length; i++ )
{
ImageTypeInfo info = ImageTypeInfo.Get( m_Images[i] );
if ( info.Type == fromType )
return true;
}
return false;
}
public CaptureResponse CaptureImage( Type type, out ImageType image )
{
for ( int i = 0; i < m_Images.Length; i++ )
{
ImageTypeInfo info = ImageTypeInfo.Get( m_Images[i] );
if ( info.Type == type )
{
image = m_Images[i];
if ( m_Done[i] )
{
return CaptureResponse.AlreadyDone;
}
else
{
m_Done[i] = true;
CheckCompletionStatus();
return CaptureResponse.Valid;
}
}
}
image = (ImageType)0;
return CaptureResponse.Invalid;
}
public override void RenderProgress( BaseQuestGump gump )
{
if ( !Completed )
{
for ( int i = 0; i < m_Images.Length; i++ )
{
ImageTypeInfo info = ImageTypeInfo.Get( m_Images[i] );
gump.AddHtmlObject( 70, 260 + 20 * i, 200, 100, info.Name, BaseQuestGump.Blue, false, false );
gump.AddLabel( 200, 260 + 20 * i, 0x64, " : " );
gump.AddHtmlObject( 220, 260 + 20 * i, 100, 100, m_Done[i] ? 1055121 : 1055122, BaseQuestGump.Blue, false, false );
}
}
else
{
base.RenderProgress( gump );
}
}
public override void OnComplete()
{
System.AddObjective( new ReturnImagesObjective() );
}
public override void ChildDeserialize( GenericReader reader )
{
int version = reader.ReadEncodedInt();
int count = reader.ReadEncodedInt();
m_Images = new ImageType[count];
m_Done = new bool[count];
for ( int i = 0; i < count; i++ )
{
m_Images[i] = (ImageType) reader.ReadEncodedInt();
m_Done[i] = reader.ReadBool();
}
}
public override void ChildSerialize( GenericWriter writer )
{
writer.WriteEncodedInt( (int) 0 ); // version
writer.WriteEncodedInt( (int) m_Images.Length );
for ( int i = 0; i < m_Images.Length; i++ )
{
writer.WriteEncodedInt( (int) m_Images[i] );
writer.Write( (bool) m_Done[i] );
}
}
}
public class ReturnImagesObjective : QuestObjective
{
public override object Message
{
get
{
/* You now have all of the creature images you need.
* Return to Tomas O'Neerlan so that he can make the toy figurines.
*/
return 1055128;
}
}
public ReturnImagesObjective()
{
}
public override void OnComplete()
{
System.AddConversation( new ReturnImagesConversation() );
}
}
public class ReturnToysObjective : QuestObjective
{
public override object Message
{
get
{
// Return to Elwood with news that the toy figurines will be delivered when ready.
return 1055132;
}
}
public ReturnToysObjective()
{
}
}
public class MakeRoomObjective : QuestObjective
{
public override object Message
{
get
{
// Return to Elwood for your reward when you have some room in your backpack.
return 1055136;
}
}
public MakeRoomObjective()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using SampleMetadata;
using Xunit;
namespace System.Reflection.Tests
{
public static partial class FieldTests
{
[Fact]
public unsafe static void TestFields1()
{
TestField1Worker(typeof(ClassWithFields1<>).Project());
TestField1Worker(typeof(ClassWithFields1<int>).Project());
TestField1Worker(typeof(ClassWithFields1<string>).Project());
}
private static void TestField1Worker(Type t)
{
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
FieldInfo[] fields = t.GetFields(bf);
foreach (FieldInfo f in fields)
{
Assert.Equal(t, f.DeclaringType);
Assert.Equal(t, f.ReflectedType);
Assert.Equal(t.Module, f.Module);
}
Type theT = t.GetGenericArguments()[0];
{
FieldInfo f = fields.Single(f1 => f1.Name == "ConstField1");
Assert.Equal(FieldAttributes.Private | FieldAttributes.Static | FieldAttributes.Literal | FieldAttributes.HasDefault, f.Attributes);
Assert.Equal(typeof(int).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field1");
Assert.Equal(FieldAttributes.Public, f.Attributes);
Assert.Equal(typeof(int).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field2");
Assert.Equal(FieldAttributes.Family, f.Attributes);
Assert.Equal(typeof(GenericClass2<int, string>).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field3");
Assert.Equal(FieldAttributes.Private, f.Attributes);
Assert.Equal(typeof(Interface1).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field4");
Assert.Equal(FieldAttributes.Assembly, f.Attributes);
Assert.Equal(typeof(int[]).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field5");
Assert.Equal(FieldAttributes.FamORAssem, f.Attributes);
Assert.Equal(typeof(int*).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "Field6");
Assert.Equal(FieldAttributes.FamANDAssem, f.Attributes);
Assert.Equal(theT, f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "ReadOnlyField1");
Assert.Equal(FieldAttributes.Private | FieldAttributes.InitOnly, f.Attributes);
Assert.Equal(typeof(IEnumerable<int>).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField1");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Public, f.Attributes);
Assert.Equal(typeof(byte).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField2");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Family, f.Attributes);
Assert.Equal(typeof(GenericClass2<,>).Project().MakeGenericType(typeof(int).Project(), theT), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField3");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Private, f.Attributes);
Assert.Equal(typeof(Interface1).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField4");
Assert.Equal(FieldAttributes.Static | FieldAttributes.Assembly, f.Attributes);
Assert.Equal(typeof(int[,]).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField5");
Assert.Equal(FieldAttributes.Static | FieldAttributes.FamORAssem, f.Attributes);
Assert.Equal(typeof(int*).Project(), f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "SField6");
Assert.Equal(FieldAttributes.Static | FieldAttributes.FamANDAssem, f.Attributes);
Assert.Equal(theT, f.FieldType);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == "VolatileField1");
Assert.Equal(FieldAttributes.Public, f.Attributes);
Assert.Equal(typeof(int).Project(), f.FieldType);
}
}
[Fact]
public unsafe static void TestLiteralFields1()
{
Type t = typeof(ClassWithLiteralFields).Project();
FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly);
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.NotLiteral));
Assert.Throws<InvalidOperationException>(() => f.GetRawConstantValue());
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.NotLiteralJustReadOnly));
Assert.Throws<InvalidOperationException>(() => f.GetRawConstantValue());
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitBool1));
object o = f.GetRawConstantValue();
Assert.True(o is bool);
Assert.Equal(ClassWithLiteralFields.LitBool1, (bool)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitBool2));
object o = f.GetRawConstantValue();
Assert.True(o is bool);
Assert.Equal(ClassWithLiteralFields.LitBool2, (bool)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitChar1));
object o = f.GetRawConstantValue();
Assert.True(o is char);
Assert.Equal(ClassWithLiteralFields.LitChar1, (char)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitChar2));
object o = f.GetRawConstantValue();
Assert.True(o is char);
Assert.Equal(ClassWithLiteralFields.LitChar2, (char)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitChar3));
object o = f.GetRawConstantValue();
Assert.True(o is char);
Assert.Equal(ClassWithLiteralFields.LitChar3, (char)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitByte1));
object o = f.GetRawConstantValue();
Assert.True(o is byte);
Assert.Equal(ClassWithLiteralFields.LitByte1, (byte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitByte2));
object o = f.GetRawConstantValue();
Assert.True(o is byte);
Assert.Equal(ClassWithLiteralFields.LitByte2, (byte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitByte3));
object o = f.GetRawConstantValue();
Assert.True(o is byte);
Assert.Equal(ClassWithLiteralFields.LitByte3, (byte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSByte1));
object o = f.GetRawConstantValue();
Assert.True(o is sbyte);
Assert.Equal(ClassWithLiteralFields.LitSByte1, (sbyte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSByte2));
object o = f.GetRawConstantValue();
Assert.True(o is sbyte);
Assert.Equal(ClassWithLiteralFields.LitSByte2, (sbyte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSByte3));
object o = f.GetRawConstantValue();
Assert.True(o is sbyte);
Assert.Equal(ClassWithLiteralFields.LitSByte3, (sbyte)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitShort1));
object o = f.GetRawConstantValue();
Assert.True(o is short);
Assert.Equal(ClassWithLiteralFields.LitShort1, (short)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitShort2));
object o = f.GetRawConstantValue();
Assert.True(o is short);
Assert.Equal(ClassWithLiteralFields.LitShort2, (short)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitShort3));
object o = f.GetRawConstantValue();
Assert.True(o is short);
Assert.Equal(ClassWithLiteralFields.LitShort3, (short)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUShort1));
object o = f.GetRawConstantValue();
Assert.True(o is ushort);
Assert.Equal(ClassWithLiteralFields.LitUShort1, (ushort)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUShort2));
object o = f.GetRawConstantValue();
Assert.True(o is ushort);
Assert.Equal(ClassWithLiteralFields.LitUShort2, (ushort)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUShort3));
object o = f.GetRawConstantValue();
Assert.True(o is ushort);
Assert.Equal(ClassWithLiteralFields.LitUShort3, (ushort)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitInt1));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal(ClassWithLiteralFields.LitInt1, (int)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitInt2));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal(ClassWithLiteralFields.LitInt2, (int)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitInt3));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal(ClassWithLiteralFields.LitInt3, (int)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUInt1));
object o = f.GetRawConstantValue();
Assert.True(o is uint);
Assert.Equal(ClassWithLiteralFields.LitUInt1, (uint)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUInt2));
object o = f.GetRawConstantValue();
Assert.True(o is uint);
Assert.Equal(ClassWithLiteralFields.LitUInt2, (uint)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitUInt3));
object o = f.GetRawConstantValue();
Assert.True(o is uint);
Assert.Equal(ClassWithLiteralFields.LitUInt3, (uint)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitLong1));
object o = f.GetRawConstantValue();
Assert.True(o is long);
Assert.Equal(ClassWithLiteralFields.LitLong1, (long)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitLong2));
object o = f.GetRawConstantValue();
Assert.True(o is long);
Assert.Equal(ClassWithLiteralFields.LitLong2, (long)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitLong3));
object o = f.GetRawConstantValue();
Assert.True(o is long);
Assert.Equal(ClassWithLiteralFields.LitLong3, (long)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitULong1));
object o = f.GetRawConstantValue();
Assert.True(o is ulong);
Assert.Equal(ClassWithLiteralFields.LitULong1, (ulong)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitULong2));
object o = f.GetRawConstantValue();
Assert.True(o is ulong);
Assert.Equal(ClassWithLiteralFields.LitULong2, (ulong)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitULong3));
object o = f.GetRawConstantValue();
Assert.True(o is ulong);
Assert.Equal(ClassWithLiteralFields.LitULong3, (ulong)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSingle1));
object o = f.GetRawConstantValue();
Assert.True(o is float);
Assert.Equal(ClassWithLiteralFields.LitSingle1, (float)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitSingle2));
object o = f.GetRawConstantValue();
Assert.True(o is float);
Assert.Equal(ClassWithLiteralFields.LitSingle2, (float)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitDouble1));
object o = f.GetRawConstantValue();
Assert.True(o is double);
Assert.Equal(ClassWithLiteralFields.LitDouble1, (double)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitDouble2));
object o = f.GetRawConstantValue();
Assert.True(o is double);
Assert.Equal(ClassWithLiteralFields.LitDouble2, (double)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitString1));
object o = f.GetRawConstantValue();
Assert.True(o is string);
Assert.Equal(ClassWithLiteralFields.LitString1, (string)o);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitString2));
object o = f.GetRawConstantValue();
Assert.True(o == null);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitObject));
object o = f.GetRawConstantValue();
Assert.True(o == null);
}
{
FieldInfo f = fields.Single(f1 => f1.Name == nameof(ClassWithLiteralFields.LitMyColor1));
object o = f.GetRawConstantValue();
Assert.True(o is int);
Assert.Equal((int)(ClassWithLiteralFields.LitMyColor1), (int)o);
}
}
[Fact]
public unsafe static void TestCustomModifiers1()
{
using (MetadataLoadContext lc = new MetadataLoadContext(
new FuncMetadataAssemblyResolver(
delegate (MetadataLoadContext context, AssemblyName name)
{
if (name.Name == "mscorlib")
return context.LoadFromStream(TestUtils.CreateStreamForCoreAssembly());
return null;
}),
"mscorlib"))
{
Assembly a = lc.LoadFromByteArray(TestData.s_CustomModifiersImage);
Type t = a.GetType("N", throwOnError: true);
Type reqA = a.GetType("ReqA", throwOnError: true);
Type reqB = a.GetType("ReqB", throwOnError: true);
Type reqC = a.GetType("ReqC", throwOnError: true);
Type optA = a.GetType("OptA", throwOnError: true);
Type optB = a.GetType("OptB", throwOnError: true);
Type optC = a.GetType("OptC", throwOnError: true);
FieldInfo f = t.GetField("MyField");
Type[] req = f.GetRequiredCustomModifiers();
Type[] opt = f.GetOptionalCustomModifiers();
Assert.Equal<Type>(new Type[] { reqA, reqB, reqC }, req);
Assert.Equal<Type>(new Type[] { optA, optB, optC }, opt);
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetRequiredCustomModifiers());
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetOptionalCustomModifiers());
}
}
[Fact]
public unsafe static void TestCustomModifiers2()
{
using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib"))
{
Assembly a = lc.LoadFromByteArray(TestData.s_CustomModifiersImage);
Type t = a.GetType("N", throwOnError: true);
Type reqA = a.GetType("ReqA", throwOnError: true);
Type reqB = a.GetType("ReqB", throwOnError: true);
Type reqC = a.GetType("ReqC", throwOnError: true);
Type optA = a.GetType("OptA", throwOnError: true);
Type optB = a.GetType("OptB", throwOnError: true);
Type optC = a.GetType("OptC", throwOnError: true);
FieldInfo f = t.GetField("MyArrayField");
Type[] req = f.GetRequiredCustomModifiers();
Type[] opt = f.GetOptionalCustomModifiers();
Assert.Equal<Type>(new Type[] { reqB }, req);
Assert.Equal<Type>(new Type[] { }, opt);
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetRequiredCustomModifiers());
TestUtils.AssertNewObjectReturnedEachTime(() => f.GetOptionalCustomModifiers());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
/*
* A simple class to output a JSON file.
*/
class JSON {
TextWriter w;
Stack<bool> state;
bool firstElement;
internal JSON(TextWriter w)
{
this.w = w;
state = new Stack<bool>();
firstElement = true;
}
void CheckInObject()
{
if (state.Count == 0 || state.Peek()) {
throw new ArgumentException("Not in an object");
}
}
void CheckInArray()
{
if (state.Count == 0 || !state.Peek()) {
throw new ArgumentException("Not in an array");
}
}
void NewLine()
{
if (!firstElement) {
w.Write(",");
}
firstElement = false;
w.WriteLine();
for (int n = state.Count; n > 0; n --) {
w.Write(" ");
}
}
internal void AddPair(string name, bool val)
{
CheckInObject();
NewLine();
w.Write("{0} : {1}", Encode(name), Encode(val));
}
internal void AddPair(string name, long val)
{
CheckInObject();
NewLine();
w.Write("{0} : {1}", Encode(name), Encode(val));
}
internal void AddPair(string name, string val)
{
CheckInObject();
NewLine();
w.Write("{0} : {1}", Encode(name), Encode(val));
}
internal void OpenPairObject(string name)
{
CheckInObject();
NewLine();
w.Write("{0} : {{", Encode(name));
state.Push(false);
firstElement = true;
}
internal void OpenPairArray(string name)
{
CheckInObject();
NewLine();
w.Write("{0} : [", Encode(name));
state.Push(true);
firstElement = true;
}
internal void AddElement(bool val)
{
CheckInArray();
NewLine();
w.Write("{0}", Encode(val));
}
internal void AddElement(long val)
{
CheckInArray();
NewLine();
w.Write("{0}", Encode(val));
}
internal void AddElement(string val)
{
CheckInArray();
NewLine();
w.Write("{0}", Encode(val));
}
internal void OpenElementObject()
{
CheckInArray();
NewLine();
w.Write("{");
state.Push(false);
firstElement = true;
}
internal void OpenElementArray()
{
CheckInArray();
NewLine();
w.Write("[");
state.Push(true);
firstElement = true;
}
internal void OpenInit(bool array)
{
if (state.Count != 0) {
throw new ArgumentException("Not in starting state");
}
w.Write("{0}", array ? "[" : "{");
state.Push(array);
firstElement = true;
}
internal void Close()
{
if (state.Count == 0) {
throw new ArgumentException("No open object/array");
}
bool ns = state.Pop();
w.WriteLine();
for (int i = state.Count; i > 0; i --) {
w.Write(" ");
}
if (ns) {
w.Write("]");
} else {
w.Write("}");
}
firstElement = false;
/*
* If closing the top element, add a newline.
*/
if (state.Count == 0) {
w.WriteLine();
}
}
static string Encode(bool val)
{
return val ? "true" : "false";
}
static string Encode(long val)
{
return val.ToString();
}
static string Encode(string val)
{
if (val == null) {
return "null";
}
StringBuilder sb = new StringBuilder();
sb.Append("\"");
foreach (char c in val) {
switch (c) {
case '\t':
sb.Append("\\t");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
default:
if (c >= 32 && c <= 126) {
sb.Append(c);
} else {
sb.AppendFormat("\\u{0:X4}", (int)c);
}
break;
}
}
sb.Append("\"");
return sb.ToString();
}
}
| |
//
// CalendarMonthView.cs
//
// Converted to MonoTouch on 1/22/09 - Eduardo Scoz || http://UICatalog.com
// Originally reated by Devin Ross on 7/28/09 - tapku.com || http://github.com/devinross/tapkulibrary
//
/*
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 MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using MonoTouch.CoreAnimation;
using System.Linq;
using ClanceysLib;
namespace MonoTouch.Dialog
{
public delegate void DateSelected (DateTime date);
public delegate void MonthChanged (DateTime monthSelected);
public delegate bool IsDayMarked (DateTime date);
public class CalendarMonthView : UIView
{
public DateSelected OnDateSelected;
public DateSelected OnFinishedDateSelection;
public DateSelected MonthChanged;
public IsDayMarked IsDayMarkedDelegate;
public ICollection<DateTime> MarkedDay;
public UIColor ToolbarColor {
get{return toolbar.TintColor;}
set{toolbar.TintColor = value;}
}
public DateTime CurrentMonthYear;
public DateTime CurrentDate { get; internal set; }
public bool ShowToolBar;
private UIScrollView _scrollView;
private UIImageView _shadow;
private bool calendarIsLoaded;
private UIToolbar toolbar;
private UIBarButtonItem todayButton;
private UIBarButtonItem tomorrowBtn;
private UIBarButtonItem nextWeekBtn;
private UIBarButtonItem noneBtn;
private MonthGridView _monthGridView;
private UIButton _leftButton, _rightButton;
public Action SizeChanged;
public SizeF Size {
get { return new SizeF (_scrollView.Frame.Size.Width, _scrollView.Frame.Size.Height + _scrollView.Frame.Y + (ShowToolBar ? toolbar.Frame.Height : 0)); }
}
public CalendarMonthView () : this(DateTime.Today)
{
}
public CalendarMonthView (DateTime currentDate, bool showToolBar) : base(new RectangleF (0, 0, 320, 260))
{
ShowToolBar = showToolBar;
if (currentDate.Year < 2010)
CurrentDate = DateTime.Today;
else
CurrentDate = currentDate;
CurrentMonthYear = new DateTime (CurrentDate.Year, CurrentDate.Month, 1);
LayoutSubviews ();
}
public CalendarMonthView (DateTime currentDate) : base(new RectangleF (0, 0, 320, 260))
{
if (currentDate.Year < 2010)
CurrentDate = DateTime.Today;
else
CurrentDate = currentDate;
CurrentMonthYear = new DateTime (CurrentDate.Year, CurrentDate.Month, 1);
LayoutSubviews ();
}
public CalendarMonthView (DateTime currentDate, DateTime[] markedDays) : base(new RectangleF (0, 0, 320, 260))
{
Console.WriteLine ("Date Received");
MarkedDay = markedDays;
if (currentDate.Year < 2010)
CurrentDate = DateTime.Today;
else
CurrentDate = currentDate;
CurrentMonthYear = new DateTime (CurrentDate.Year, CurrentDate.Month, 1);
LayoutSubviews ();
}
public override void LayoutSubviews ()
{
if (calendarIsLoaded)
return;
_scrollView = new UIScrollView (new RectangleF (0, 44, 320, 460 - 44)) { ContentSize = new SizeF (320, 260), ScrollEnabled = false, Frame = new RectangleF (0, 44, 320, 460 - 44), BackgroundColor = UIColor.FromRGBA (222 / 255f, 222 / 255f, 225 / 255f, 1f) };
_shadow = new UIImageView (Util.FromResource (null, "shadow.png"));
if (ShowToolBar) {
toolbar = new UIToolbar (new RectangleF (0, 0, 320, 44));
todayButton = new UIBarButtonItem ("Today", UIBarButtonItemStyle.Bordered, delegate {
if (OnDateSelected != null)
OnDateSelected (DateTime.Today);
else
MoveCalendarMonths (DateTime.Today, true);
});
tomorrowBtn = new UIBarButtonItem ("Tomorrow", UIBarButtonItemStyle.Bordered, delegate {
if (OnDateSelected != null)
OnDateSelected (DateTime.Today.AddDays (1));
else
MoveCalendarMonths (DateTime.Today.AddDays (1), true);
});
nextWeekBtn = new UIBarButtonItem ("Next Week", UIBarButtonItemStyle.Bordered, delegate {
if (OnDateSelected != null)
OnDateSelected (DateTime.Today.AddDays (7));
else
MoveCalendarMonths (DateTime.Today.AddDays (7), true);
});
noneBtn = new UIBarButtonItem ("None", UIBarButtonItemStyle.Bordered, delegate {
if (OnDateSelected != null)
OnDateSelected (DateTime.MinValue);
});
toolbar.SetItems (new UIBarButtonItem[3] { todayButton, tomorrowBtn, nextWeekBtn }, true);
}
LoadButtons ();
LoadInitialGrids ();
BackgroundColor = UIColor.Clear;
AddSubview (_scrollView);
AddSubview (_shadow);
if (ShowToolBar)
AddSubview (toolbar);
_scrollView.AddSubview (_monthGridView);
calendarIsLoaded = true;
}
private void LoadButtons ()
{
_leftButton = UIButton.FromType (UIButtonType.Custom);
_leftButton.TouchUpInside += HandlePreviousMonthTouch;
_leftButton.SetImage (Util.FromResource (null, "leftarrow.png"), UIControlState.Normal);
AddSubview (_leftButton);
_leftButton.Frame = new RectangleF (10, 0, 44, 42);
_rightButton = UIButton.FromType (UIButtonType.Custom);
_rightButton.TouchUpInside += HandleNextMonthTouch;
_rightButton.SetImage (Util.FromResource (null, "rightarrow.png"), UIControlState.Normal);
AddSubview (_rightButton);
_rightButton.Frame = new RectangleF (320 - 56, 0, 44, 42);
}
private void HandlePreviousMonthTouch (object sender, EventArgs e)
{
MoveCalendarMonths (false, true);
}
private void HandleNextMonthTouch (object sender, EventArgs e)
{
MoveCalendarMonths (true, true);
}
public void MoveCalendarMonths (bool upwards, bool animated)
{
CurrentMonthYear = CurrentMonthYear.AddMonths (upwards ? 1 : -1);
if (MonthChanged != null)
MonthChanged (CurrentMonthYear);
UserInteractionEnabled = false;
var gridToMove = CreateNewGrid (CurrentMonthYear);
var pointsToMove = (upwards ? 0 + _monthGridView.Lines : 0 - _monthGridView.Lines) * 44;
if (upwards && gridToMove.weekdayOfFirst == 0)
pointsToMove += 44;
if (!upwards && _monthGridView.weekdayOfFirst == 0)
pointsToMove -= 44;
gridToMove.Frame = new RectangleF (new PointF (0, pointsToMove), gridToMove.Frame.Size);
_scrollView.AddSubview (gridToMove);
if (animated) {
UIView.BeginAnimations ("changeMonth");
UIView.SetAnimationDuration (0.4);
UIView.SetAnimationDelay (0.1);
UIView.SetAnimationCurve (UIViewAnimationCurve.EaseInOut);
}
_monthGridView.Center = new PointF (_monthGridView.Center.X, _monthGridView.Center.Y - pointsToMove);
gridToMove.Center = new PointF (gridToMove.Center.X, gridToMove.Center.Y - pointsToMove);
_monthGridView.Alpha = 0;
_shadow.Frame = new RectangleF (new PointF (0, gridToMove.Lines * 44 - 88), _shadow.Frame.Size);
var oldFrame = _scrollView.Frame;
_scrollView.Frame = new RectangleF (_scrollView.Frame.Location, new SizeF (_scrollView.Frame.Width, (gridToMove.Lines + 1) * 44));
_scrollView.ContentSize = _scrollView.Frame.Size;
if (ShowToolBar) {
var toolRect = toolbar.Frame;
toolRect.Y = _scrollView.Frame.Y + _scrollView.Frame.Height;
toolbar.Frame = toolRect;
}
SetNeedsDisplay ();
if (animated)
UIView.CommitAnimations ();
_monthGridView = gridToMove;
UserInteractionEnabled = true;
if (oldFrame != _scrollView.Frame && SizeChanged != null)
{
this.Frame = new RectangleF(this.Frame.Location,Size);
SizeChanged ();
}
}
public void MoveCalendarMonths (DateTime date, bool animated)
{
bool upwards = false;
if (date.Month == CurrentMonthYear.Month && date.Year == CurrentMonthYear.Year)
animated = false; else if (date > CurrentMonthYear)
upwards = true;
CurrentMonthYear = new DateTime (date.Year, date.Month, 1);
if (MonthChanged != null)
MonthChanged (CurrentMonthYear);
UserInteractionEnabled = false;
var gridToMove = CreateNewGrid (CurrentMonthYear);
var pointsToMove = (upwards ? 0 + _monthGridView.Lines : 0 - _monthGridView.Lines) * 44;
if (upwards && gridToMove.weekdayOfFirst == 0)
pointsToMove += 44;
if (!upwards && _monthGridView.weekdayOfFirst == 0)
pointsToMove -= 44;
gridToMove.Frame = new RectangleF (new PointF (0, pointsToMove), gridToMove.Frame.Size);
_scrollView.AddSubview (gridToMove);
if (animated) {
UIView.BeginAnimations ("changeMonth");
UIView.SetAnimationDuration (0.4);
UIView.SetAnimationDelay (0.1);
UIView.SetAnimationCurve (UIViewAnimationCurve.EaseInOut);
}
_monthGridView.Center = new PointF (_monthGridView.Center.X, _monthGridView.Center.Y - pointsToMove);
gridToMove.Center = new PointF (gridToMove.Center.X, gridToMove.Center.Y - pointsToMove);
_monthGridView.Alpha = 0;
_shadow.Frame = new RectangleF (new PointF (0, gridToMove.Lines * 44 - 88), _shadow.Frame.Size);
var oldFrame = _scrollView.Frame;
_scrollView.Frame = new RectangleF (_scrollView.Frame.Location, new SizeF (_scrollView.Frame.Width, (gridToMove.Lines + 1) * 44));
_scrollView.ContentSize = _scrollView.Frame.Size;
if (ShowToolBar) {
var toolRect = toolbar.Frame;
toolRect.Y = _scrollView.Frame.Y + _scrollView.Frame.Height;
toolbar.Frame = toolRect;
}
SetNeedsDisplay ();
if (animated)
UIView.CommitAnimations ();
_monthGridView = gridToMove;
UserInteractionEnabled = true;
if (oldFrame != _scrollView.Frame && SizeChanged != null)
{
this.Frame = new RectangleF(this.Frame.Location,Size);
SizeChanged ();
}
}
private MonthGridView CreateNewGrid (DateTime date)
{
var grid = new MonthGridView (this, date, CurrentDate);
grid.BuildGrid ();
grid.Frame = new RectangleF (0, 0, 320, 400);
return grid;
}
private void LoadInitialGrids ()
{
_monthGridView = CreateNewGrid (CurrentMonthYear);
var rect = _scrollView.Frame;
rect.Size = new SizeF { Height = (_monthGridView.Lines + 1) * 44, Width = rect.Size.Width };
_scrollView.Frame = rect;
Frame = new RectangleF (Frame.X, Frame.Y, _scrollView.Frame.Size.Width, _scrollView.Frame.Size.Height + 44);
var imgRect = _shadow.Frame;
imgRect.Y = rect.Size.Height - 132;
_shadow.Frame = imgRect;
if (ShowToolBar) {
var toolRect = toolbar.Frame;
toolRect.Y = rect.Size.Height + rect.Y;
toolbar.Frame = toolRect;
}
}
public override void Draw (RectangleF rect)
{
Util.FromResource (null, "topbar.png").Draw (new PointF (0, 0));
DrawDayLabels (rect);
DrawMonthLabel (rect);
}
private void DrawMonthLabel (RectangleF rect)
{
var r = new RectangleF (new PointF (0, 5), new SizeF { Width = 320, Height = 42 });
UIColor.DarkGray.SetColor ();
DrawString (CurrentMonthYear.ToString ("MMMM yyyy"), r, UIFont.BoldSystemFontOfSize (20), UILineBreakMode.WordWrap, UITextAlignment.Center);
}
private void DrawDayLabels (RectangleF rect)
{
var font = UIFont.BoldSystemFontOfSize (10);
UIColor.DarkGray.SetColor ();
var context = UIGraphics.GetCurrentContext ();
context.SaveState ();
context.SetShadowWithColor (new SizeF (0, -1), 0.5f, UIColor.White.CGColor);
var i = 0;
foreach (var d in Enum.GetNames (typeof(DayOfWeek))) {
DrawString (d.Substring (0, 3), new RectangleF (i * 46, 44 - 12, 45, 10), font, UILineBreakMode.WordWrap, UITextAlignment.Center);
i++;
}
context.RestoreState ();
}
internal bool isDayMarker (DateTime date)
{
if (IsDayMarkedDelegate != null) {
return IsDayMarkedDelegate (date);
}
if (MarkedDay != null) {
var isMarked = MarkedDay.Contains (date.Date);
return isMarked;
}
return false;
}
}
internal class MonthGridView : UIView
{
private CalendarMonthView _calendarMonthView;
private readonly DateTime _currentDay;
public DateTime SelectedDate;
private DateTime _currentMonth;
protected readonly IList<CalendarDayView> _dayTiles = new List<CalendarDayView> ();
public int Lines { get; set; }
protected CalendarDayView SelectedDayView { get; set; }
public int weekdayOfFirst;
public IList<DateTime> Marks { get; set; }
public MonthGridView (CalendarMonthView calendarMonthView, DateTime month, DateTime day)
{
SelectedDate = day;
_calendarMonthView = calendarMonthView;
_currentDay = DateTime.Today;
_currentMonth = month.Date;
}
public void BuildGrid ()
{
DateTime previousMonth;
try {
previousMonth = _currentMonth.AddMonths (-1);
} catch {
previousMonth = _currentMonth;
}
var daysInPreviousMonth = DateTime.DaysInMonth (previousMonth.Year, previousMonth.Month);
var daysInMonth = DateTime.DaysInMonth (_currentMonth.Year, _currentMonth.Month);
weekdayOfFirst = (int)_currentMonth.DayOfWeek;
var lead = daysInPreviousMonth - (weekdayOfFirst - 1);
// build last month's days
for (int i = 1; i <= weekdayOfFirst; i++) {
var viewDay = new DateTime (_currentMonth.Year, _currentMonth.Month, i);
var dayView = new CalendarDayView { Frame = new RectangleF ((i - 1) * 46 - 1, 0, 47, 45), Text = lead.ToString (), Marked = _calendarMonthView.isDayMarker (viewDay) };
AddSubview (dayView);
_dayTiles.Add (dayView);
lead++;
}
var position = weekdayOfFirst + 1;
var line = 0;
// current month
for (int i = 1; i <= daysInMonth; i++) {
var viewDay = new DateTime (_currentMonth.Year, _currentMonth.Month, i);
var dayView = new CalendarDayView { Frame = new RectangleF ((position - 1) * 46 - 1, line * 44, 47, 45), Today = (_currentDay.Date == viewDay.Date), Text = i.ToString (), Active = true, Tag = i, Marked = _calendarMonthView.isDayMarker (viewDay), Selected = (SelectedDate.Day == i) };
if (dayView.Selected)
SelectedDayView = dayView;
AddSubview (dayView);
_dayTiles.Add (dayView);
position++;
if (position > 7) {
position = 1;
line++;
}
}
//next month
if (position != 1) {
int dayCounter = 1;
for (int i = position; i < 8; i++) {
var viewDay = new DateTime (_currentMonth.Year, _currentMonth.Month, i);
var dayView = new CalendarDayView { Frame = new RectangleF ((i - 1) * 46 - 1, line * 44, 47, 45), Text = dayCounter.ToString (), Marked = _calendarMonthView.isDayMarker (viewDay) };
AddSubview (dayView);
_dayTiles.Add (dayView);
dayCounter++;
}
}
Frame = new RectangleF (Frame.Location, new SizeF (Frame.Width, (line + 1) * 44));
Lines = (position == 1 ? line - 1 : line);
if (SelectedDayView != null)
this.BringSubviewToFront (SelectedDayView);
}
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
base.TouchesBegan (touches, evt);
if (SelectDayView ((UITouch)touches.AnyObject)) {
SelectedDate = new DateTime (_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag);
if (_calendarMonthView.OnDateSelected != null)
_calendarMonthView.OnDateSelected (new DateTime (_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag));
}
}
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
base.TouchesMoved (touches, evt);
if (SelectDayView ((UITouch)touches.AnyObject)) {
SelectedDate = new DateTime (_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag);
if (_calendarMonthView.OnDateSelected != null)
_calendarMonthView.OnDateSelected (new DateTime (_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag));
}
}
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
base.TouchesEnded (touches, evt);
if (_calendarMonthView.OnFinishedDateSelection == null)
return;
SelectedDate = new DateTime (_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag);
_calendarMonthView.OnFinishedDateSelection (new DateTime (_currentMonth.Year, _currentMonth.Month, SelectedDayView.Tag));
}
private bool SelectDayView (UITouch touch)
{
var p = touch.LocationInView (this);
int index = ((int)p.Y / 44) * 7 + ((int)p.X / 46);
if (index < 0 || index >= _dayTiles.Count)
return false;
var newSelectedDayView = _dayTiles[index];
if (newSelectedDayView == SelectedDayView)
return false;
if (!newSelectedDayView.Active && touch.Phase != UITouchPhase.Moved) {
var day = int.Parse (newSelectedDayView.Text);
if (day > 15)
_calendarMonthView.MoveCalendarMonths (false, true);
else
_calendarMonthView.MoveCalendarMonths (true, true);
return false;
} else if (!newSelectedDayView.Active) {
return false;
}
SelectedDayView.Selected = false;
this.BringSubviewToFront (newSelectedDayView);
newSelectedDayView.Selected = true;
SelectedDayView = newSelectedDayView;
SetNeedsDisplay ();
return true;
}
}
internal class CalendarDayView : UIView
{
string _text;
bool _active, _today, _selected, _marked;
public string Text {
get { return _text; }
set {
_text = value;
SetNeedsDisplay ();
}
}
public bool Active {
get { return _active; }
set {
_active = value;
SetNeedsDisplay ();
}
}
public bool Today {
get { return _today; }
set {
_today = value;
SetNeedsDisplay ();
}
}
public bool Selected {
get { return _selected; }
set {
_selected = value;
SetNeedsDisplay ();
}
}
public bool Marked {
get { return _marked; }
set {
_marked = value;
SetNeedsDisplay ();
}
}
public override void Draw (RectangleF rect)
{
UIImage img;
UIColor color;
if (!Active) {
color = UIColor.FromRGBA (0.576f, 0.608f, 0.647f, 1f);
img = Util.FromResource (null, "datecell.png");
} else if (Today && Selected) {
color = UIColor.White;
img = Util.FromResource (null, "todayselected.png");
} else if (Today) {
color = UIColor.White;
img = Util.FromResource (null, "today.png");
} else if (Selected) {
color = UIColor.White;
img = Util.FromResource (null, "datecellselected.png");
} else {
//color = UIColor.DarkTextColor;
color = UIColor.FromRGBA (0.275f, 0.341f, 0.412f, 1f);
img = Util.FromResource (null, "datecell.png");
}
img.Draw (new PointF (0, 0));
color.SetColor ();
DrawString (Text, RectangleF.Inflate (Bounds, 4, -8), UIFont.BoldSystemFontOfSize (22), UILineBreakMode.WordWrap, UITextAlignment.Center);
if (Marked) {
var context = UIGraphics.GetCurrentContext ();
if (Selected || Today)
context.SetRGBFillColor (1, 1, 1, 1); else if (!Active)
UIColor.LightGray.SetColor ();
else
context.SetRGBFillColor (75 / 255f, 92 / 255f, 111 / 255f, 1);
context.SetLineWidth (0);
context.AddEllipseInRect (new RectangleF (Frame.Size.Width / 2 - 2, 45 - 10, 4, 4));
context.FillPath ();
}
}
}
}
| |
//#define LOG
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.GZip;
namespace ICSimulator {
public class InstructionWindow {
#if LOG
StreamWriter sw;
#endif
//private CPU m_cpu;
public static readonly ulong NULL_ADDRESS = ulong.MaxValue;
public int windowFree { get { return addresses.Length - load; } }
private int load;
private ulong[] addresses;
private bool[] writes;
private bool[] ready;
private Request[] requests;
private int next, oldest;
private ulong[] issueT, headT;
public ulong instrNr;
public ulong totalInstructionsRetired;
public ulong stallStart;
public int outstandingReqs;
public BinaryReader m_readlog;
public BinaryWriter m_writelog;
public string m_readfile, m_writefile;
public bool readLog, writeLog;
public int readlog_delta;
public ulong oldestT; // kept in sync with retire point in corresponding annotate-log
public ulong oldestT_base; // when wrapping to beginning, keep
// the virtual retire time stream going
ulong m_match_mask;
public InstructionWindow(CPU cpu) {
//m_cpu = cpu;
next = oldest = 0;
addresses = new ulong[Config.proc.instWindowSize];
writes = new bool[Config.proc.instWindowSize];
ready = new bool[Config.proc.instWindowSize];
requests = new Request[Config.proc.instWindowSize];
issueT = new ulong[Config.proc.instWindowSize];
headT = new ulong[Config.proc.instWindowSize];
m_match_mask = ~ ( ((ulong)1 << Config.cache_block) - 1 );
for (int i = 0; i < Config.proc.instWindowSize; i++) {
addresses[i] = NULL_ADDRESS;
writes[i] = false;
ready[i] = false;
requests[i] = null;
}
outstandingReqs = 0;
readLog = writeLog = false;
if (Config.writelog != "" && Config.writelog_node == cpu.node.coord.ID)
SetWrite(Config.writelog);
if (Config.readlog != "")
{
if (Config.readlog.StartsWith("auto"))
{
string prefix = Config.readlog.StartsWith("auto_") ?
Config.readlog.Substring(5) :
Config.router.algorithm.ToString();
SetRead(Simulator.network.workload.getLogFile(cpu.node.coord.ID, prefix));
}
else
SetRead(Config.readlog.Split(' ')[cpu.node.coord.ID]);
}
#if LOG
if (Simulator.sources.soloMode && Simulator.sources.solo.ID == procID)
{
sw = new StreamWriter ("insn.log");
sw.WriteLine("# cycle instrNr req_seq bank netlat injlat");
}
else
sw = null;
#endif
}
public void SetRead(string filename)
{
if (!File.Exists(filename))
filename = Config.logpath + "/" + filename;
if (!File.Exists(filename))
{
Console.Error.WriteLine("WARNING: could not find annotation log {0}", filename);
return;
}
m_readfile = filename;
readLog = true;
openReadStream();
}
public void openReadStream()
{
if (m_readlog != null) m_readlog.Close();
m_readlog = new BinaryReader(new GZipInputStream(File.OpenRead(m_readfile)));
readlog_delta = (int) m_readlog.ReadUInt64();
}
public void SetWrite(string filename)
{
m_writefile = filename;
writeLog = true;
//m_writelog = new BinaryWriter(new GZipOutputStream(File.Open(filename, FileMode.Create)));
m_writelog = new BinaryWriter(File.Open(filename, FileMode.Create));
m_writelog.Write((ulong)Config.writelog_delta);
}
public void SeekLog(ulong insns)
{
if (!readLog) return;
long count = (long)insns;
while (count > 0)
{
advanceReadLog();
count -= readlog_delta;
}
}
public bool isFull() {
return (load == Config.proc.instWindowSize);
}
public bool isEmpty() {
return (load == 0);
}
public void fetch(Request r, ulong address, bool isWrite, bool isReady) {
//Console.WriteLine("pr{0}: fetch addr {1:X}, write {2}, isReady {3}, next {4}",
// m_cpu.ID, address, isWrite, isReady, next);
if (load < Config.proc.instWindowSize) {
load++;
addresses[next] = address;
writes[next] = isWrite;
ready[next] = isReady;
requests[next] = r;
issueT[next] = Simulator.CurrentRound;
headT[next] = Simulator.CurrentRound;
if (isReady && r != null) r.service();
//Console.WriteLine("pr{0}: new req in slot {1}: addr {2}, write {3} ready {4}", m_cpu.ID, next, address, isWrite, isReady);
next++;
if (!isReady) outstandingReqs++;
//Console.WriteLine("pr{0}: outstanding reqs now at {1}", m_cpu.ID, outstandingReqs);
if (next == Config.proc.instWindowSize) next = 0;
}
else throw new Exception("Instruction Window is full!");
}
public int retire(int n) {
int i = 0;
while (i < n && load > 0 && ready[oldest])
{
if (requests[oldest] != null)
requests[oldest].retire();
ulong deadline = headT[oldest] - issueT[oldest];
Simulator.stats.deadline.Add(deadline);
oldest++;
if (oldest == Config.proc.instWindowSize) oldest = 0;
headT[oldest] = Simulator.CurrentRound;
i++;
load--;
instrNr++;
totalInstructionsRetired++;
if (writeLog)
{
if (instrNr % (ulong)Config.writelog_delta == 0)
{
m_writelog.Write((ulong)Simulator.CurrentRound);
m_writelog.Flush();
}
}
if (readLog)
{
if (instrNr % (ulong)readlog_delta == 0)
advanceReadLog();
}
}
if (load > 0 && i < n)
requests[oldest].backStallsCaused += (1.0 * n - i) / n;
return i;
}
void advanceReadLog()
{
ulong old_oldestT = oldestT;
try
{
oldestT = oldestT_base + m_readlog.ReadUInt64();
}
catch (EndOfStreamException)
{
openReadStream();
oldestT_base = old_oldestT;
oldestT = oldestT_base + m_readlog.ReadUInt64();
}
catch (SharpZipBaseException)
{
openReadStream();
oldestT_base = old_oldestT;
oldestT = oldestT_base + m_readlog.ReadUInt64();
}
}
public bool contains(ulong address, bool write) {
int i = oldest;
while (i != next) {
if ((addresses[i] >> Config.cache_block) == (address >> Config.cache_block)) {
// this new request will be satisfied by outstanding request i if:
// 1. this new request is not a write (i.e., will be satisfied by R or W completion), OR
// 2. there is an outstanding write (i.e., a write completion will satisfy any pending req)
if (!write || writes[i])
return true;
}
i++;
if (i == Config.proc.instWindowSize) i = 0;
}
return false;
}
public void setReady(ulong address, bool write) {
//Console.WriteLine("pr{0}: ready {1:X} (block {2:X}) write {3}", m_cpu.ID, address,
// address >> Config.cache_block, write);
if (isEmpty()) throw new Exception("Instruction Window is empty!");
for (int i = 0; i < Config.proc.instWindowSize; i++) {
if ((addresses[i] & m_match_mask) == (address & m_match_mask) && !ready[i]) {
// this completion does not satisfy outstanding req i if and only if
// 1. the outstanding req is a write, AND
// 2. the completion is a read completion.
if (writes[i] && !write) continue;
requests[i].service();
ready[i] = true;
addresses[i] = NULL_ADDRESS;
outstandingReqs--;
//Console.WriteLine("pr{0}: set slot {1} ready, now {2} outstanding", m_cpu.ID, i, outstandingReqs);
}
}
}
public bool isOldestAddrAndStalled(ulong address, out ulong stallCount)
{
if (!ready[oldest] && addresses[oldest] == address)
{
stallCount = Simulator.CurrentRound - stallStart;
return true;
}
else
{
stallCount = 0;
return false;
}
}
/**
* Returns true if the oldest instruction in the window is a non-ready memory request
*/
public bool isOldestReady() {
return ready[oldest];
}
public ulong stallingAddr()
{
return addresses[oldest];
}
public void close()
{
if (m_writelog != null)
{
m_writelog.Flush();
m_writelog.Close();
}
}
public void dumpOutstanding()
{
Console.Write("Pending blocks: ");
for (int i = 0; i < Config.proc.instWindowSize; i++)
{
if (addresses[i] != NULL_ADDRESS && !ready[i])
Console.Write("{0:X} ", addresses[i] >> Config.cache_block);
}
Console.WriteLine();
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities.Runtime
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.Runtime.Serialization;
[DataContract]
class ExecutionPropertyManager
{
ActivityInstance owningInstance;
Dictionary<string, ExecutionProperty> properties;
// Since the ExecutionProperty objects in this list
// could exist in several places we need to make sure
// that we clean up any booleans before more work items run
List<ExecutionProperty> threadProperties;
bool ownsThreadPropertiesList;
string lastPropertyName;
object lastProperty;
IdSpace lastPropertyVisibility;
// used by the root activity instance to chain parents correctly
ExecutionPropertyManager rootPropertyManager;
int exclusiveHandleCount;
public ExecutionPropertyManager(ActivityInstance owningInstance)
{
Fx.Assert(owningInstance != null, "null instance should be using the internal host-based ctor");
this.owningInstance = owningInstance;
// This object is only constructed if we know we have properties to add to it
this.properties = new Dictionary<string, ExecutionProperty>();
if (owningInstance.HasChildren)
{
ActivityInstance previousOwner = owningInstance.PropertyManager != null ? owningInstance.PropertyManager.owningInstance : null;
// we're setting a handle property. Walk the children and associate the new property manager
// then walk our instance list, fixup parent references, and perform basic validation
ActivityUtilities.ProcessActivityInstanceTree(owningInstance, null, (instance, executor) => AttachPropertyManager(instance, previousOwner));
}
else
{
owningInstance.PropertyManager = this;
}
}
public ExecutionPropertyManager(ActivityInstance owningInstance, ExecutionPropertyManager parentPropertyManager)
: this(owningInstance)
{
Fx.Assert(parentPropertyManager != null, "caller must verify");
this.threadProperties = parentPropertyManager.threadProperties;
// if our parent is null, capture any root properties
if (owningInstance.Parent == null)
{
this.rootPropertyManager = parentPropertyManager.rootPropertyManager;
}
}
internal ExecutionPropertyManager(ActivityInstance owningInstance, Dictionary<string, ExecutionProperty> properties)
{
Fx.Assert(properties != null, "properties should never be null");
this.owningInstance = owningInstance;
this.properties = properties;
// owningInstance can be null (for host-provided root properties)
if (owningInstance == null)
{
this.rootPropertyManager = this;
}
}
[DataMember(EmitDefaultValue = false, Name = "properties")]
internal Dictionary<string, ExecutionProperty> SerializedProperties
{
get { return this.properties; }
set { this.properties = value; }
}
[DataMember(EmitDefaultValue = false, Name = "exclusiveHandleCount")]
internal int SerializedExclusiveHandleCount
{
get { return this.exclusiveHandleCount; }
set { this.exclusiveHandleCount = value; }
}
internal Dictionary<string, ExecutionProperty> Properties
{
get
{
return this.properties;
}
}
internal bool HasExclusiveHandlesInScope
{
get
{
return this.exclusiveHandleCount > 0;
}
}
bool AttachPropertyManager(ActivityInstance instance, ActivityInstance previousOwner)
{
if (instance.PropertyManager == null || instance.PropertyManager.owningInstance == previousOwner)
{
instance.PropertyManager = this;
return true;
}
else
{
return false;
}
}
public object GetProperty(string name, IdSpace currentIdSpace)
{
Fx.Assert(!string.IsNullOrEmpty(name), "The name should be validated by the caller.");
if (lastPropertyName == name && (this.lastPropertyVisibility == null || this.lastPropertyVisibility == currentIdSpace))
{
return lastProperty;
}
ExecutionPropertyManager currentManager = this;
while (currentManager != null)
{
ExecutionProperty property;
if (currentManager.properties.TryGetValue(name, out property))
{
if (!property.IsRemoved && (!property.HasRestrictedVisibility || property.Visibility == currentIdSpace))
{
this.lastPropertyName = name;
this.lastProperty = property.Property;
this.lastPropertyVisibility = property.Visibility;
return this.lastProperty;
}
}
currentManager = GetParent(currentManager);
}
return null;
}
void AddProperties(IDictionary<string, ExecutionProperty> properties, IDictionary<string, object> flattenedProperties, IdSpace currentIdSpace)
{
foreach (KeyValuePair<string, ExecutionProperty> item in properties)
{
if (!item.Value.IsRemoved && !flattenedProperties.ContainsKey(item.Key) && (!item.Value.HasRestrictedVisibility || item.Value.Visibility == currentIdSpace))
{
flattenedProperties.Add(item.Key, item.Value.Property);
}
}
}
public IEnumerable<KeyValuePair<string, object>> GetFlattenedProperties(IdSpace currentIdSpace)
{
ExecutionPropertyManager currentManager = this;
Dictionary<string, object> flattenedProperties = new Dictionary<string, object>();
while (currentManager != null)
{
AddProperties(currentManager.Properties, flattenedProperties, currentIdSpace);
currentManager = GetParent(currentManager);
}
return flattenedProperties;
}
//Currently this is only used for the exclusive scope processing
internal List<T> FindAll<T>() where T : class
{
ExecutionPropertyManager currentManager = this;
List<T> list = null;
while (currentManager != null)
{
foreach (ExecutionProperty property in currentManager.Properties.Values)
{
if (property.Property is T)
{
if (list == null)
{
list = new List<T>();
}
list.Add((T)property.Property);
}
}
currentManager = GetParent(currentManager);
}
return list;
}
static ExecutionPropertyManager GetParent(ExecutionPropertyManager currentManager)
{
if (currentManager.owningInstance != null)
{
if (currentManager.owningInstance.Parent != null)
{
return currentManager.owningInstance.Parent.PropertyManager;
}
else
{
return currentManager.rootPropertyManager;
}
}
else
{
return null;
}
}
public void Add(string name, object property, IdSpace visibility)
{
Fx.Assert(!string.IsNullOrEmpty(name), "The name should be validated before calling this collection.");
Fx.Assert(property != null, "The property should be validated before caling this collection.");
ExecutionProperty executionProperty = new ExecutionProperty(name, property, visibility);
this.properties.Add(name, executionProperty);
if (this.lastPropertyName == name)
{
this.lastProperty = property;
}
if (property is ExclusiveHandle)
{
this.exclusiveHandleCount++;
UpdateChildExclusiveHandleCounts(1);
}
if (property is IExecutionProperty)
{
AddIExecutionProperty(executionProperty, false);
}
}
void UpdateChildExclusiveHandleCounts(int amountToUpdate)
{
Queue<HybridCollection<ActivityInstance>> toProcess = null;
HybridCollection<ActivityInstance> children = this.owningInstance.GetRawChildren();
if (children != null && children.Count > 0)
{
ProcessChildrenForExclusiveHandles(children, amountToUpdate, ref toProcess);
if (toProcess != null)
{
while (toProcess.Count > 0)
{
children = toProcess.Dequeue();
ProcessChildrenForExclusiveHandles(children, amountToUpdate, ref toProcess);
}
}
}
}
void ProcessChildrenForExclusiveHandles(HybridCollection<ActivityInstance> children, int amountToUpdate, ref Queue<HybridCollection<ActivityInstance>> toProcess)
{
for (int i = 0; i < children.Count; i++)
{
ActivityInstance child = children[i];
ExecutionPropertyManager childManager = child.PropertyManager;
if (childManager.IsOwner(child))
{
childManager.exclusiveHandleCount += amountToUpdate;
}
HybridCollection<ActivityInstance> tempChildren = child.GetRawChildren();
if (tempChildren != null && tempChildren.Count > 0)
{
if (toProcess == null)
{
toProcess = new Queue<HybridCollection<ActivityInstance>>();
}
toProcess.Enqueue(tempChildren);
}
}
}
void AddIExecutionProperty(ExecutionProperty property, bool isDeserializationFixup)
{
bool willCleanupBeCalled = !isDeserializationFixup;
if (this.threadProperties == null)
{
this.threadProperties = new List<ExecutionProperty>(1);
this.ownsThreadPropertiesList = true;
}
else if (!this.ownsThreadPropertiesList)
{
List<ExecutionProperty> updatedProperties = new List<ExecutionProperty>(this.threadProperties.Count);
// We need to copy all properties to our new list and we
// need to mark hidden properties as "to be removed" (or just
// not copy them on the deserialization path)
for (int i = 0; i < this.threadProperties.Count; i++)
{
ExecutionProperty currentProperty = this.threadProperties[i];
if (currentProperty.Name == property.Name)
{
if (willCleanupBeCalled)
{
currentProperty.ShouldBeRemovedAfterCleanup = true;
updatedProperties.Add(currentProperty);
}
// If cleanup won't be called then we are on the
// deserialization path and shouldn't copy this
// property over to our new list
}
else
{
updatedProperties.Add(currentProperty);
}
}
this.threadProperties = updatedProperties;
this.ownsThreadPropertiesList = true;
}
else
{
for (int i = this.threadProperties.Count - 1; i >= 0; i--)
{
ExecutionProperty currentProperty = this.threadProperties[i];
if (currentProperty.Name == property.Name)
{
if (willCleanupBeCalled)
{
currentProperty.ShouldBeRemovedAfterCleanup = true;
}
else
{
this.threadProperties.RemoveAt(i);
}
// There will only be at most one property in this list that
// matches the name
break;
}
}
}
property.ShouldSkipNextCleanup = willCleanupBeCalled;
this.threadProperties.Add(property);
}
public void Remove(string name)
{
Fx.Assert(!string.IsNullOrEmpty(name), "This should have been validated by the caller.");
ExecutionProperty executionProperty = this.properties[name];
Fx.Assert(executionProperty != null, "This should only be called if we know the property exists");
if (executionProperty.Property is IExecutionProperty)
{
Fx.Assert(this.ownsThreadPropertiesList && this.threadProperties != null, "We should definitely be the list owner if we have an IExecutionProperty");
if (!this.threadProperties.Remove(executionProperty))
{
Fx.Assert("We should have had this property in the list.");
}
}
this.properties.Remove(name);
if (executionProperty.Property is ExclusiveHandle)
{
this.exclusiveHandleCount--;
UpdateChildExclusiveHandleCounts(-1);
}
if (this.lastPropertyName == name)
{
this.lastPropertyName = null;
this.lastProperty = null;
}
}
public object GetPropertyAtCurrentScope(string name)
{
Fx.Assert(!string.IsNullOrEmpty(name), "This should be validated elsewhere");
ExecutionProperty property;
if (this.properties.TryGetValue(name, out property))
{
return property.Property;
}
return null;
}
public bool IsOwner(ActivityInstance instance)
{
return this.owningInstance == instance;
}
[SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode, Justification = "Called from Serialization")]
internal bool ShouldSerialize(ActivityInstance instance)
{
return IsOwner(instance) && this.properties.Count > 0;
}
public void SetupWorkflowThread()
{
if (this.threadProperties != null)
{
for (int i = 0; i < this.threadProperties.Count; i++)
{
ExecutionProperty executionProperty = this.threadProperties[i];
executionProperty.ShouldSkipNextCleanup = false;
IExecutionProperty property = (IExecutionProperty)executionProperty.Property;
property.SetupWorkflowThread();
}
}
}
// This method only throws fatal exceptions
public void CleanupWorkflowThread(ref Exception abortException)
{
if (this.threadProperties != null)
{
for (int i = this.threadProperties.Count - 1; i >= 0; i--)
{
ExecutionProperty current = this.threadProperties[i];
if (current.ShouldSkipNextCleanup)
{
current.ShouldSkipNextCleanup = false;
}
else
{
IExecutionProperty property = (IExecutionProperty)current.Property;
try
{
property.CleanupWorkflowThread();
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
abortException = e;
}
}
if (current.ShouldBeRemovedAfterCleanup)
{
this.threadProperties.RemoveAt(i);
current.ShouldBeRemovedAfterCleanup = false;
}
}
}
}
public void UnregisterProperties(ActivityInstance completedInstance, IdSpace currentIdSpace)
{
UnregisterProperties(completedInstance, currentIdSpace, false);
}
public void UnregisterProperties(ActivityInstance completedInstance, IdSpace currentIdSpace, bool ignoreExceptions)
{
if (IsOwner(completedInstance))
{
RegistrationContext registrationContext = new RegistrationContext(this, currentIdSpace);
foreach (ExecutionProperty property in this.properties.Values)
{
// We do a soft removal because we're about to throw away this dictionary
// and we don't want to mess up our enumerator
property.IsRemoved = true;
IPropertyRegistrationCallback registrationCallback = property.Property as IPropertyRegistrationCallback;
if (registrationCallback != null)
{
try
{
registrationCallback.Unregister(registrationContext);
}
catch (Exception e)
{
if (Fx.IsFatal(e) || !ignoreExceptions)
{
throw;
}
}
}
}
Fx.Assert(completedInstance == null || completedInstance.GetRawChildren() == null || completedInstance.GetRawChildren().Count == 0, "There must not be any children at this point otherwise our exclusive handle count would be incorrect.");
// We still need to clear this list in case any non-serializable
// properties were being used in a no persist zone
this.properties.Clear();
}
}
public void ThrowIfAlreadyDefined(string name, ActivityInstance executingInstance)
{
if (executingInstance == this.owningInstance)
{
if (this.properties.ContainsKey(name))
{
throw FxTrace.Exception.Argument("name", SR.ExecutionPropertyAlreadyDefined(name));
}
}
}
public void OnDeserialized(ActivityInstance owner, ActivityInstance parent, IdSpace visibility, ActivityExecutor executor)
{
this.owningInstance = owner;
if (parent != null)
{
if (parent.PropertyManager != null)
{
this.threadProperties = parent.PropertyManager.threadProperties;
}
}
else
{
this.rootPropertyManager = executor.RootPropertyManager;
}
foreach (ExecutionProperty property in this.properties.Values)
{
if (property.Property is IExecutionProperty)
{
AddIExecutionProperty(property, true);
}
if (property.HasRestrictedVisibility)
{
property.Visibility = visibility;
}
}
}
[DataContract]
internal class ExecutionProperty
{
string name;
object property;
bool hasRestrictedVisibility;
public ExecutionProperty(string name, object property, IdSpace visibility)
{
this.Name = name;
this.Property = property;
if (visibility != null)
{
this.Visibility = visibility;
this.HasRestrictedVisibility = true;
}
}
public string Name
{
get
{
return this.name;
}
private set
{
this.name = value;
}
}
public object Property
{
get
{
return this.property;
}
private set
{
this.property = value;
}
}
public bool HasRestrictedVisibility
{
get
{
return this.hasRestrictedVisibility;
}
private set
{
this.hasRestrictedVisibility = value;
}
}
// This property is fixed up at deserialization time
public IdSpace Visibility
{
get;
set;
}
// This is always false at persistence because
// a removed property belongs to an activity which
// has completed and is therefore not part of the
// instance map anymore
public bool IsRemoved { get; set; }
// These don't need to be serialized because they are only
// ever false at persistence time. We potentially set
// them to true when a property is added but we always
// reset them to false after cleaning up the thread
public bool ShouldBeRemovedAfterCleanup { get; set; }
public bool ShouldSkipNextCleanup { get; set; }
[DataMember(Name = "Name")]
internal string SerializedName
{
get { return this.Name; }
set { this.Name = value; }
}
[DataMember(Name = "Property")]
internal object SerializedProperty
{
get { return this.Property; }
set { this.Property = value; }
}
[DataMember(EmitDefaultValue = false, Name = "HasRestrictedVisibility")]
internal bool SerializedHasRestrictedVisibility
{
get { return this.HasRestrictedVisibility; }
set { this.HasRestrictedVisibility = value; }
}
}
}
}
| |
// Contestants do not need to worry about anything in this file. This is just
// helper code that does the boring stuff for you, so you can focus on the
// interesting stuff. That being said, you're welcome to change anything in
// this file if you know what you're doing.
using System;
using System.IO;
using System.Collections.Generic;
public class PlanetWars {
// Constructs a PlanetWars object instance, given a string containing a
// description of a game state.
public PlanetWars(string gameStatestring) {
planets = new List<Planet>();
fleets = new List<Fleet>();
ParseGameState(gameStatestring);
}
// Returns the number of planets. Planets are numbered starting with 0.
public int NumPlanets() {
return planets.Count;
}
// Returns the planet with the given planet_id. There are NumPlanets()
// planets. They are numbered starting at 0.
public Planet GetPlanet(int planetID) {
return planets[planetID];
}
// Returns the number of fleets.
public int NumFleets() {
return fleets.Count;
}
// Returns the fleet with the given fleet_id. Fleets are numbered starting
// with 0. There are NumFleets() fleets. fleet_id's are not consistent from
// one turn to the next.
public Fleet GetFleet(int fleetID) {
return fleets[fleetID];
}
// Returns a list of all the planets.
public List<Planet> Planets() {
return planets;
}
// Return a list of all the planets owned by the current player. By
// convention, the current player is always player number 1.
public List<Planet> MyPlanets() {
List<Planet> r = new List<Planet>();
foreach (Planet p in planets) {
if (p.Owner() == 1) {
r.Add(p);
}
}
return r;
}
// Return a list of all neutral planets.
public List<Planet> NeutralPlanets() {
List<Planet> r = new List<Planet>();
foreach (Planet p in planets) {
if (p.Owner() == 0) {
r.Add(p);
}
}
return r;
}
// Return a list of all the planets owned by rival players. This excludes
// planets owned by the current player, as well as neutral planets.
public List<Planet> EnemyPlanets() {
List<Planet> r = new List<Planet>();
foreach (Planet p in planets) {
if (p.Owner() >= 2) {
r.Add(p);
}
}
return r;
}
// Return a list of all the planets that are not owned by the current
// player. This includes all enemy planets and neutral planets.
public List<Planet> NotMyPlanets() {
List<Planet> r = new List<Planet>();
foreach (Planet p in planets) {
if (p.Owner() != 1) {
r.Add(p);
}
}
return r;
}
// Return a list of all the fleets.
public List<Fleet> Fleets() {
List<Fleet> r = new List<Fleet>();
foreach (Fleet f in fleets) {
r.Add(f);
}
return r;
}
// Return a list of all the fleets owned by the current player.
public List<Fleet> MyFleets() {
List<Fleet> r = new List<Fleet>();
foreach (Fleet f in fleets) {
if (f.Owner() == 1) {
r.Add(f);
}
}
return r;
}
// Return a list of all the fleets owned by enemy players.
public List<Fleet> EnemyFleets() {
List<Fleet> r = new List<Fleet>();
foreach (Fleet f in fleets) {
if (f.Owner() != 1) {
r.Add(f);
}
}
return r;
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int Distance(int sourcePlanet, int destinationPlanet) {
Planet source = planets[sourcePlanet];
Planet destination = planets[destinationPlanet];
double dx = source.X() - destination.X();
double dy = source.Y() - destination.Y();
return (int)Math.Ceiling(Math.Sqrt(dx * dx + dy * dy));
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void IssueOrder(int sourcePlanet,
int destinationPlanet,
int numShips) {
Console.WriteLine("" + sourcePlanet + " " + destinationPlanet + " " +
numShips);
Console.Out.Flush();
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void IssueOrder(Planet source, Planet dest, int numShips) {
Console.WriteLine("" + source.PlanetID() + " " + dest.PlanetID() +
" " + numShips);
Console.Out.Flush();
}
// Sends the game engine a message to let it know that we're done sending
// orders. This signifies the end of our turn.
public void FinishTurn() {
Console.WriteLine("go");
Console.Out.Flush();
}
// Returns true if the named player owns at least one planet or fleet.
// Otherwise, the player is deemed to be dead and false is returned.
public bool IsAlive(int playerID) {
foreach (Planet p in planets) {
if (p.Owner() == playerID) {
return true;
}
}
foreach (Fleet f in fleets) {
if (f.Owner() == playerID) {
return true;
}
}
return false;
}
// If the game is not yet over (ie: at least two players have planets or
// fleets remaining), returns -1. If the game is over (ie: only one player
// is left) then that player's number is returned. If there are no
// remaining players, then the game is a draw and 0 is returned.
public int Winner() {
List<int> remainingPlayers = new List<int>();
foreach (Planet p in planets) {
if (!remainingPlayers.Contains(p.Owner())) {
remainingPlayers.Add(p.Owner());
}
}
foreach (Fleet f in fleets) {
if (!remainingPlayers.Contains(f.Owner())) {
remainingPlayers.Add(f.Owner());
}
}
switch (remainingPlayers.Count) {
case 0:
return 0;
case 1:
return remainingPlayers[0];
default:
return -1;
}
}
// Returns the number of ships that the current player has, either located
// on planets or in flight.
public int NumShips(int playerID) {
int numShips = 0;
foreach (Planet p in planets) {
if (p.Owner() == playerID) {
numShips += p.NumShips();
}
}
foreach (Fleet f in fleets) {
if (f.Owner() == playerID) {
numShips += f.NumShips();
}
}
return numShips;
}
// Parses a game state from a string. On success, returns 1. On failure,
// returns 0.
private int ParseGameState(string s) {
planets.Clear();
fleets.Clear();
int planetID = 0;
string[] lines = s.Split('\n');
for (int i = 0; i < lines.Length; ++i) {
string line = lines[i];
int commentBegin = line.IndexOf('#');
if (commentBegin >= 0) {
line = line.Substring(0, commentBegin);
}
if (line.Trim().Length == 0) {
continue;
}
string[] tokens = line.Split(' ');
if (tokens.Length == 0) {
continue;
}
if (tokens[0].Equals("P")) {
if (tokens.Length != 6) {
return 0;
}
double x = double.Parse(tokens[1]);
double y = double.Parse(tokens[2]);
int owner = int.Parse(tokens[3]);
int numShips = int.Parse(tokens[4]);
int growthRate = int.Parse(tokens[5]);
Planet p = new Planet(planetID++,
owner,
numShips,
growthRate,
x, y);
planets.Add(p);
} else if (tokens[0].Equals("F")) {
if (tokens.Length != 7) {
return 0;
}
int owner = int.Parse(tokens[1]);
int numShips = int.Parse(tokens[2]);
int source = int.Parse(tokens[3]);
int destination = int.Parse(tokens[4]);
int totalTripLength = int.Parse(tokens[5]);
int turnsRemaining = int.Parse(tokens[6]);
Fleet f = new Fleet(owner,
numShips,
source,
destination,
totalTripLength,
turnsRemaining);
fleets.Add(f);
} else {
return 0;
}
}
return 1;
}
// Store all the planets and fleets. OMG we wouldn't wanna lose all the
// planets and fleets, would we!?
private List<Planet> planets;
private List<Fleet> fleets;
}
| |
/*
* ******************************************************************************
* Copyright 2014-2016 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetTapeDrivesSpectraS3Request : Ds3Request
{
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _partitionId;
public string PartitionId
{
get { return _partitionId; }
set { WithPartitionId(value); }
}
private string _serialNumber;
public string SerialNumber
{
get { return _serialNumber; }
set { WithSerialNumber(value); }
}
private TapeDriveState? _state;
public TapeDriveState? State
{
get { return _state; }
set { WithState(value); }
}
private TapeDriveType? _type;
public TapeDriveType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetTapeDrivesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPartitionId(Guid? partitionId)
{
this._partitionId = partitionId.ToString();
if (partitionId != null)
{
this.QueryParams.Add("partition_id", partitionId.ToString());
}
else
{
this.QueryParams.Remove("partition_id");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithPartitionId(string partitionId)
{
this._partitionId = partitionId;
if (partitionId != null)
{
this.QueryParams.Add("partition_id", partitionId);
}
else
{
this.QueryParams.Remove("partition_id");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithSerialNumber(string serialNumber)
{
this._serialNumber = serialNumber;
if (serialNumber != null)
{
this.QueryParams.Add("serial_number", serialNumber);
}
else
{
this.QueryParams.Remove("serial_number");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithState(TapeDriveState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetTapeDrivesSpectraS3Request WithType(TapeDriveType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetTapeDrivesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/tape_drive";
}
}
}
}
| |
/*
* Copyright 2013 Stanislav Muhametsin. 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using CollectionsWithRoles.API;
using CommonUtils;
using CILAssemblyManipulator.Physical;
namespace CILAssemblyManipulator.Logical.Implementation
{
internal abstract class CILTypeOrParameterImpl : CILCustomAttributeContainerImpl, CILTypeOrTypeParameter, CILTypeOrGenericParamInternal
{
private static readonly IDictionary<String, CILTypeCode> TC_MAPPING = new Dictionary<String, CILTypeCode>()
{
{typeof(void).FullName, CILTypeCode.Void},
{typeof(ValueType).FullName, CILTypeCode.Value},
{typeof(Enum).FullName, CILTypeCode.Enum},
{typeof(IntPtr).FullName, CILTypeCode.IntPtr},
{typeof(UIntPtr).FullName, CILTypeCode.UIntPtr},
{typeof(Object).FullName, CILTypeCode.SystemObject},
{typeof(Type).FullName, CILTypeCode.Type},
{"System.TypedReference", CILTypeCode.TypedByRef}
};
protected internal readonly TypeKind typeKind;
protected internal readonly WriteableLazy<CILTypeCode> typeCode;
protected internal readonly SettableValueForClasses<String> name;
protected internal readonly SettableValueForClasses<String> @namespace;
protected internal readonly Lazy<CILModule> module;
protected internal readonly Lazy<CILType> declaringType;
protected CILTypeOrParameterImpl( CILReflectionContextImpl ctx, Int32 anID, Type type )
: base( ctx, anID, CILElementKind.Type, cb => cb.GetCustomAttributesDataForOrThrow( type ) )
{
ArgumentValidator.ValidateNotNull( "Reflection context", ctx );
InitFields(
ctx,
ref this.typeKind,
ref this.typeCode,
ref this.name,
ref this.@namespace,
ref this.module,
ref this.declaringType,
type.IsGenericParameter ? TypeKind.TypeParameter : TypeKind.Type,
() =>
{
var tc =
#if WINDOWS_PHONE_APP
type.GetTypeCode()
#else
(CILTypeCode) Type.GetTypeCode( type )
#endif
;
if ( tc == (CILTypeCode) 2 )
{
// DBNull
tc = CILTypeCode.Object;
}
else if ( tc == CILTypeCode.Object && LogicalUtils.NATIVE_MSCORLIB.Equals( type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.Assembly ) && type.FullName != null )
{
// Check for void, typedbyref, valuetype, enum, etc
if ( !TC_MAPPING.TryGetValue( type.FullName, out tc ) )
{
tc = CILTypeCode.Object;
}
}
return tc;
},
new SettableValueForClasses<String>( type.Name ),
new SettableValueForClasses<String>( type.DeclaringType == null ? type.Namespace : null ),
() => ctx.NewWrapper( ctx.WrapperCallbacks.GetModuleOfType( type ) ),
() => ctx.NewWrapperAsType( type.DeclaringType ),
true
);
}
protected CILTypeOrParameterImpl(
CILReflectionContextImpl ctx,
Int32 anID,
Lazy<ListProxy<CILCustomAttribute>> cAttrDataFunc,
TypeKind aTypeKind,
Func<CILTypeCode> typeCode,
SettableValueForClasses<String> aName,
SettableValueForClasses<String> aNamespace,
Func<CILModule> moduleFunc,
Func<CILType> declaringTypeFunc,
Boolean baseTypeSettable
)
: base( ctx, CILElementKind.Type, anID, cAttrDataFunc )
{
InitFields(
ctx,
ref this.typeKind,
ref this.typeCode,
ref this.name,
ref this.@namespace,
ref this.module,
ref this.declaringType,
aTypeKind,
typeCode,
aName,
aNamespace,
moduleFunc,
declaringTypeFunc,
baseTypeSettable
);
}
private static void InitFields(
CILReflectionContextImpl ctx,
ref TypeKind typeKind,
ref WriteableLazy<CILTypeCode> typeCode,
ref SettableValueForClasses<String> name,
ref SettableValueForClasses<String> @namespace,
ref Lazy<CILModule> module,
ref Lazy<CILType> declaringType,
TypeKind aTypeKind,
Func<CILTypeCode> aTypeCode,
SettableValueForClasses<String> aName,
SettableValueForClasses<String> aNamespace,
Func<CILModule> moduleFunc,
Func<CILType> declaringTypeFunc,
Boolean baseTypeSettable
)
{
typeKind = aTypeKind;
typeCode = LazyFactory.NewWriteableLazy( aTypeCode, ctx.LazyThreadSafetyMode );
name = aName;
@namespace = aNamespace;
module = new Lazy<CILModule>( moduleFunc, ctx.LazyThreadSafetyMode );
declaringType = new Lazy<CILType>( declaringTypeFunc, ctx.LazyThreadSafetyMode );
}
#region CILTypeBase Members
public CILModule Module
{
get
{
return this.module.Value;
}
}
public String Namespace
{
set
{
this.@namespace.Value = value;
}
get
{
return this.@namespace.Value;
}
}
public TypeKind TypeKind
{
get
{
return this.typeKind;
}
}
public CILTypeCode TypeCode
{
get
{
return this.typeCode.Value;
}
//set
//{
// this.typeCode.Value = value;
//}
}
public CILType MakeElementType( ElementKind kind, GeneralArrayInfo arrayInfo )
{
return this.context.Cache.MakeElementType( this, kind, arrayInfo );
}
#endregion
#region CILElementWithSimpleName Members
public virtual String Name
{
set
{
this.name.Value = value;
}
get
{
return this.name.Value;
}
}
#endregion
#region CILElementOwnedByType Members
public CILType DeclaringType
{
get
{
return this.declaringType.Value;
}
}
#endregion
#region CILTypeBaseInternal Members
SettableValueForClasses<String> CILTypeBaseInternal.NamespaceInternal
{
get
{
return this.@namespace;
}
}
#endregion
#region CILElementWithSimpleNameInternal Members
SettableValueForClasses<String> CILElementWithSimpleNameInternal.NameInternal
{
get
{
return this.name;
}
}
#endregion
#region CILElementInstantiable Members
public Boolean IsTrueDefinition
{
get
{
return this.IsCapableOfChanging() == null;
}
}
#endregion
internal virtual String GetNameString()
{
return this.name.Value;
}
public CILElementWithinILCode ElementTypeKind
{
get
{
return CILElementWithinILCode.Type;
}
}
}
internal class CILTypeImpl : CILTypeOrParameterImpl, CILType, CILTypeInternal
{
// TODO move this to API
internal const Int32 NO_ARRAY_RANK = -1;
internal const String NESTED_TYPENAME_SEPARATOR = "+";
//internal const String NAMESPACE_SEPARATOR = ".";
internal const String G_ARGS_START = "[";
internal const String G_ARGS_END = "]";
internal static readonly CILTypeParameter[] EMPTY_TYPE_PARAMS = new CILTypeParameter[0];
private readonly SettableValueForEnums<TypeAttributes> typeAttributes;
private readonly ElementKind? elementKind;
private readonly GeneralArrayInfo arrayInfo;
private readonly Lazy<ListProxy<CILTypeBase>> gArgs;
private readonly Lazy<ListProxy<CILType>> nestedTypes;
private readonly ReadOnlyResettableLazy<ListProxy<CILField>> fields;
private readonly WriteableLazy<CILType> genericDefinition;
private readonly Lazy<CILTypeBase> elementType;
private readonly ReadOnlyResettableLazy<ListProxy<CILMethod>> methods;
private readonly ReadOnlyResettableLazy<ListProxy<CILConstructor>> ctors;
private readonly ReadOnlyResettableLazy<ListProxy<CILProperty>> properties;
private readonly ReadOnlyResettableLazy<ListProxy<CILEvent>> events;
private readonly WriteableLazy<LogicalClassLayout?> layout;
private readonly IResettableLazy<CILType> baseType;
private readonly ReadOnlyResettableLazy<ListProxy<CILType>> declaredInterfaces;
private readonly Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> securityInfo;
private readonly ReadOnlyResettableLazy<DictionaryWithRoles<CILMethod, ListProxy<CILMethod>, ListProxyQuery<CILMethod>, ListQuery<CILMethod>>> explicitMethodImplementationMap;
internal CILTypeImpl( CILReflectionContextImpl ctx, Int32 anID, Type type )
: base( ctx, anID, type )
{
if ( TypeKind.Type != this.typeKind )
{
throw new ArgumentException( "Trying to create type for type parameter " + type );
}
var isGDef = type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.IsGenericTypeDefinition;
if ( type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.IsGenericType && !isGDef )
{
throw new ArgumentException( "This constructor may only be used for non-generic types or generic type defintions." );
}
if ( type.GetElementKind().HasValue )
{
throw new ArgumentException( "This constructor may only be used for non-array, non-pointer, and non-byref types." );
}
var nGDef = isGDef ? type : null;
var tAttrs = (TypeAttributes) type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.Attributes;
var bType = type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.BaseType;
InitFields(
ctx,
ref this.typeAttributes,
ref this.elementKind,
ref this.arrayInfo,
ref this.gArgs,
ref this.genericDefinition,
ref this.nestedTypes,
ref this.fields,
ref this.elementType,
ref this.methods,
ref this.ctors,
ref this.properties,
ref this.events,
ref this.layout,
ref this.baseType,
ref this.declaredInterfaces,
ref this.securityInfo,
ref this.explicitMethodImplementationMap,
new SettableValueForEnums<TypeAttributes>( tAttrs ),
null,
null,
() => ctx.CollectionsFactory.NewListProxy<CILTypeBase>(
type.GetGenericArguments()
.Select( gArg => ctx.Cache.GetOrAdd( gArg ) )
.ToList() ),
() => (CILType) ctx.Cache.GetOrAdd( nGDef ),
new Lazy<ListProxy<CILType>>( () => ctx.CollectionsFactory.NewListProxy<CILType>(
type.GetNestedTypes(
#if !WINDOWS_PHONE_APP
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic
#endif
)
.Select( nested => (CILType) ctx.Cache.GetOrAdd( nested ) )
.ToList() ), ctx.LazyThreadSafetyMode ),
() => ctx.CollectionsFactory.NewListProxy<CILField>(
type.GetFields(
#if !WINDOWS_PHONE_APP
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly
#endif
)
.Select( field => ctx.Cache.GetOrAdd( field ) )
.ToList() ),
() => ctx.Cache.GetOrAdd( type.GetElementType() ),
() => ctx.CollectionsFactory.NewListProxy<CILMethod>(
type.GetMethods(
#if !WINDOWS_PHONE_APP
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly
#endif
)
.Select( method => ctx.Cache.GetOrAdd( method ) )
.ToList()
),
() => ctx.CollectionsFactory.NewListProxy<CILConstructor>(
type.GetConstructors(
#if !WINDOWS_PHONE_APP
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly
#endif
)
.Select( ctor => ctx.Cache.GetOrAdd( ctor ) )
.ToList()
),
() => ctx.CollectionsFactory.NewListProxy<CILProperty>(
type.GetProperties(
#if !WINDOWS_PHONE_APP
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly
#endif
)
.Select( property => ctx.Cache.GetOrAdd( property ) )
.ToList()
),
() => ctx.CollectionsFactory.NewListProxy<CILEvent>(
type.GetEvents(
#if !WINDOWS_PHONE_APP
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.DeclaredOnly
#endif
)
.Select( evt => ctx.Cache.GetOrAdd( evt ) )
.ToList()
),
LazyFactory.NewWriteableLazy<LogicalClassLayout?>( () =>
{
if ( tAttrs.IsExplicitLayout() || tAttrs.IsSequentialLayout() )
{
var layout = ctx.WrapperCallbacks.GetStructLayoutAttributeOrThrow( type );
return new LogicalClassLayout( layout.Size
#if !CAM_LOGICAL_IS_SL
// For some reason, SL version of this attribute does not have Pack property...
, layout.Pack
#endif
);
}
else
{
return null;
}
}, ctx.LazyThreadSafetyMode ),
() => (CILType) ctx.Cache.GetOrAdd( bType ),
() =>
{
var iFaces = type.GetInterfaces().GetBottomTypes();
if ( bType != null )
{
var iFacesSet = new HashSet<Type>( iFaces );
var bIFaces = bType.GetInterfaces();
foreach ( var iFace in iFaces )
{
if ( bIFaces.Any( bIFace => Object.Equals( bIFace.GetGenericDefinitionIfContainsGenericParameters(), iFace.GetGenericDefinitionIfContainsGenericParameters() ) ) )
{
iFacesSet.Remove( iFace );
}
}
iFaces = iFacesSet.ToArray();
}
return ctx.CollectionsFactory.NewListProxy<CILType>(
iFaces
.Select( iFace => (CILType) ctx.Cache.GetOrAdd( iFace ) )
.ToList() );
},
new Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>>( this.SecurityInfoFromAttributes, ctx.LazyThreadSafetyMode ),
() => ctx.CollectionsFactory.NewDictionary<CILMethod, ListProxy<CILMethod>, ListProxyQuery<CILMethod>, ListQuery<CILMethod>>(
type.IsInterface ? null : ( ctx.WrapperCallbacks.GetExplicitlyImplementedMethodsOrThrow( type )
.ToDictionary(
kvp => ctx.NewWrapper( kvp.Key ),
kvp => ctx.CollectionsFactory.NewListProxy( kvp.Value.Select( m => ctx.NewWrapper( m ) ).ToList() ) ) ) ),
true
);
}
internal CILTypeImpl( CILReflectionContextImpl ctx, Int32 anID, CILTypeCode typeCode, CILModule owningModule, String name, CILType declaringType, TypeAttributes attrs )
: this(
ctx,
anID,
new Lazy<ListProxy<CILCustomAttribute>>( () => ctx.CollectionsFactory.NewListProxy<CILCustomAttribute>(), ctx.LazyThreadSafetyMode ),
() => typeCode,
new SettableValueForClasses<String>( name ),
new SettableValueForClasses<String>( null ),
() => owningModule,
() => declaringType,
() =>
{
return attrs.IsInterface() ? null : owningModule.AssociatedMSCorLibModule.GetTypeByName( Consts.OBJECT );
},
() => ctx.CollectionsFactory.NewListProxy<CILType>(),
new SettableValueForEnums<TypeAttributes>( attrs ),
null,
null,
() => ctx.CollectionsFactory.NewListProxy<CILTypeBase>(),
() => null,
new Lazy<ListProxy<CILType>>( () => ctx.CollectionsFactory.NewListProxy<CILType>(), ctx.LazyThreadSafetyMode ),
() => ctx.CollectionsFactory.NewListProxy<CILField>(),
() => null,
() => ctx.CollectionsFactory.NewListProxy<CILMethod>(),
() => ctx.CollectionsFactory.NewListProxy<CILConstructor>(),
() => ctx.CollectionsFactory.NewListProxy<CILProperty>(),
() => ctx.CollectionsFactory.NewListProxy<CILEvent>(),
LazyFactory.NewWriteableLazy<LogicalClassLayout?>( () => null, ctx.LazyThreadSafetyMode ),
null,
null,
true
)
{
}
internal CILTypeImpl(
CILReflectionContextImpl ctx,
Int32 anID,
Lazy<ListProxy<CILCustomAttribute>> cAttrDataFunc,
Func<CILTypeCode> typeCode,
SettableValueForClasses<String> aName,
SettableValueForClasses<String> aNamespace,
Func<CILModule> moduleFunc,
Func<CILType> declaringTypeFunc,
Func<CILType> baseTypeFunc,
Func<ListProxy<CILType>> declaredInterfacesFunc,
SettableValueForEnums<TypeAttributes> typeAttrs,
ElementKind? anElementKind,
GeneralArrayInfo arrayInfo,
Func<ListProxy<CILTypeBase>> gArgsFunc,
Func<CILType> gDefFunc,
Lazy<ListProxy<CILType>> nestedTypesFunc,
Func<ListProxy<CILField>> fieldsFunc,
Func<CILTypeBase> elementTypeFunc,
Func<ListProxy<CILMethod>> methodsFunc,
Func<ListProxy<CILConstructor>> ctorsFunc,
Func<ListProxy<CILProperty>> propertiesFunc,
Func<ListProxy<CILEvent>> eventsFunc,
WriteableLazy<LogicalClassLayout?> aLayout,
Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> aSecurityInfo,
Func<DictionaryWithRoles<CILMethod, ListProxy<CILMethod>, ListProxyQuery<CILMethod>, ListQuery<CILMethod>>> anExplicitMethodImplementationMap,
Boolean resettablesAreSettable = false
)
: base( ctx, anID, cAttrDataFunc, TypeKind.Type, typeCode, aName, aNamespace, moduleFunc, declaringTypeFunc, resettablesAreSettable )
{
InitFields(
ctx,
ref this.typeAttributes,
ref this.elementKind,
ref this.arrayInfo,
ref this.gArgs,
ref this.genericDefinition,
ref this.nestedTypes,
ref this.fields,
ref this.elementType,
ref this.methods,
ref this.ctors,
ref this.properties,
ref this.events,
ref this.layout,
ref this.baseType,
ref this.declaredInterfaces,
ref this.securityInfo,
ref this.explicitMethodImplementationMap,
typeAttrs,
anElementKind,
arrayInfo,
gArgsFunc,
gDefFunc,
nestedTypesFunc,
fieldsFunc,
elementTypeFunc,
methodsFunc,
ctorsFunc,
propertiesFunc,
eventsFunc,
aLayout,
baseTypeFunc,
declaredInterfacesFunc,
aSecurityInfo ?? new Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>>( () => ctx.CollectionsFactory.NewDictionary<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>(), ctx.LazyThreadSafetyMode ),
anExplicitMethodImplementationMap ?? ( () => ctx.CollectionsFactory.NewDictionary<CILMethod, ListProxy<CILMethod>, ListProxyQuery<CILMethod>, ListQuery<CILMethod>>() ),
resettablesAreSettable
);
}
private static void InitFields(
CILReflectionContextImpl ctx,
ref SettableValueForEnums<TypeAttributes> typeAttrs,
ref ElementKind? elementKind,
ref GeneralArrayInfo arrayInfo,
ref Lazy<ListProxy<CILTypeBase>> gArgs,
ref WriteableLazy<CILType> genericDefinition,
ref Lazy<ListProxy<CILType>> nested,
ref ReadOnlyResettableLazy<ListProxy<CILField>> fields,
ref Lazy<CILTypeBase> elementType,
ref ReadOnlyResettableLazy<ListProxy<CILMethod>> methods,
ref ReadOnlyResettableLazy<ListProxy<CILConstructor>> ctors,
ref ReadOnlyResettableLazy<ListProxy<CILProperty>> properties,
ref ReadOnlyResettableLazy<ListProxy<CILEvent>> events,
ref WriteableLazy<LogicalClassLayout?> layout,
ref IResettableLazy<CILType> baseType,
ref ReadOnlyResettableLazy<ListProxy<CILType>> declaredInterfaces,
ref Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> securityInfo,
ref ReadOnlyResettableLazy<DictionaryWithRoles<CILMethod, ListProxy<CILMethod>, ListProxyQuery<CILMethod>, ListQuery<CILMethod>>> explicitMethodImplementationMap,
SettableValueForEnums<TypeAttributes> typeAttrsVal,
ElementKind? anElementKind,
GeneralArrayInfo anArrayInfo,
Func<ListProxy<CILTypeBase>> gArgsFunc,
Func<CILType> genericDefinitionFunc,
Lazy<ListProxy<CILType>> nestedTypesFunc,
Func<ListProxy<CILField>> fieldsFunc,
Func<CILTypeBase> elementTypeFunc,
Func<ListProxy<CILMethod>> methodsFunc,
Func<ListProxy<CILConstructor>> ctorsFunc,
Func<ListProxy<CILProperty>> propertiesFunc,
Func<ListProxy<CILEvent>> eventsFunc,
WriteableLazy<LogicalClassLayout?> aLayout,
Func<CILType> baseTypeFunc,
Func<ListProxy<CILType>> declaredInterfacesFunc,
Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> aSecurityInfo,
Func<DictionaryWithRoles<CILMethod, ListProxy<CILMethod>, ListProxyQuery<CILMethod>, ListQuery<CILMethod>>> anExplicitMethodImplementationMap,
Boolean resettablesAreSettable
)
{
var lazyThreadSafety = ctx.LazyThreadSafetyMode;
typeAttrs = typeAttrsVal;
elementKind = anElementKind;
arrayInfo = anArrayInfo;
gArgs = new Lazy<ListProxy<CILTypeBase>>( gArgsFunc, lazyThreadSafety );
genericDefinition = LazyFactory.NewWriteableLazy( genericDefinitionFunc, lazyThreadSafety );
nested = nestedTypesFunc;
fields = LazyFactory.NewReadOnlyResettableLazy( fieldsFunc, lazyThreadSafety );
elementType = new Lazy<CILTypeBase>( elementTypeFunc, lazyThreadSafety );
methods = LazyFactory.NewReadOnlyResettableLazy( methodsFunc, lazyThreadSafety );
ctors = LazyFactory.NewReadOnlyResettableLazy( ctorsFunc, lazyThreadSafety );
properties = LazyFactory.NewReadOnlyResettableLazy( propertiesFunc, lazyThreadSafety );
events = LazyFactory.NewReadOnlyResettableLazy( eventsFunc, lazyThreadSafety );
baseType = LazyFactory.NewResettableLazy( resettablesAreSettable, baseTypeFunc, lazyThreadSafety );
declaredInterfaces = LazyFactory.NewReadOnlyResettableLazy( declaredInterfacesFunc, lazyThreadSafety );
layout = aLayout;
securityInfo = aSecurityInfo;
explicitMethodImplementationMap = LazyFactory.NewReadOnlyResettableLazy( anExplicitMethodImplementationMap, lazyThreadSafety );
}
public override String ToString()
{
return LogicalUtils.CreateTypeString( this, true );
}
internal override String GetNameString()
{
// TODO move this to Utils.
var eKind = this.elementKind;
return eKind.HasValue ? ( ( (CILTypeOrParameterImpl) this.elementType.Value ).GetNameString() + LogicalUtils.CreateElementKindString( eKind.Value, this.arrayInfo ) ) : base.GetNameString();
}
#region CILType Members
public TypeAttributes Attributes
{
set
{
if ( value.IsInterface() )
{
this.GetTypeCapableOfChanging().BaseType = null;
}
this.typeAttributes.Value = value;
}
get
{
return this.typeAttributes.Value;
}
}
public CILType BaseType
{
set
{
var lazy = this.ThrowIfNotCapableOfChanging( this.baseType );
lazy.Value = value;
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetBaseType() );
}
get
{
return this.baseType.Value;
}
}
public CILTypeBase ElementType
{
get
{
return this.elementType.Value;
}
}
public LogicalClassLayout? Layout
{
set
{
//if ( value.HasValue && this.typeAttributes.Value.IsInterface() )
//{
// throw new InvalidOperationException( "Setting class layout is not possible for interfaces." );
//}
this.layout.Value = value;
}
get
{
return this.layout.Value;
}
}
public CILField AddField( String name, CILTypeBase fieldType, FieldAttributes attr )
{
this.ThrowIfNotCapableOfChanging();
var result = this.fields.AddToResettableLazyList( this.context.Cache.NewBlankField( this, name, attr, fieldType ) );
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredFields() );
return result;
}
public Boolean RemoveField( CILField field )
{
this.ThrowIfNotCapableOfChanging();
var result = this.fields.Value.Remove( field );
if ( result )
{
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredFields() );
}
return result;
}
public CILConstructor AddConstructor( MethodAttributes attrs, CallingConventions callingConventions )
{
this.ThrowIfNotCapableOfChanging();
var result = this.ctors.AddToResettableLazyList( this.context.Cache.NewBlankConstructor( this, attrs ) );
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetConstructors() );
return result;
}
public Boolean RemoveConstructor( CILConstructor ctor )
{
this.ThrowIfNotCapableOfChanging();
var result = this.ctors.Value.Remove( ctor );
if ( result )
{
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetConstructors() );
}
return result;
}
public CILMethod AddMethod( String name, MethodAttributes attrs, CallingConventions callingConventions )
{
this.ThrowIfNotCapableOfChanging();
var result = this.methods.AddToResettableLazyList( this.context.Cache.NewBlankMethod( this, name, attrs, callingConventions ) );
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredMethods() );
return result;
}
public Boolean RemoveMethod( CILMethod method )
{
this.ThrowIfNotCapableOfChanging();
var result = this.methods.Value.Remove( method );
if ( result )
{
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredMethods() );
}
return result;
}
public CILProperty AddProperty( String name, PropertyAttributes attrs )
{
this.ThrowIfNotCapableOfChanging();
var result = this.properties.AddToResettableLazyList( this.context.Cache.NewBlankProperty( this, name, attrs ) );
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredProperties() );
return result;
}
public Boolean RemoveProperty( CILProperty property )
{
this.ThrowIfNotCapableOfChanging();
var result = this.properties.Value.Remove( property );
if ( result )
{
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredProperties() );
}
return result;
}
public CILEvent AddEvent( String name, EventAttributes attrs, CILTypeBase eventType )
{
this.ThrowIfNotCapableOfChanging();
var result = this.events.AddToResettableLazyList( this.context.Cache.NewBlankEvent( this, name, attrs, eventType ) );
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredEvents() );
return result;
}
public Boolean RemoveEvent( CILEvent evt )
{
this.ThrowIfNotCapableOfChanging();
var result = this.events.Value.Remove( evt );
if ( result )
{
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredEvents() );
}
return result;
}
public void ChangeTypeCode( CILTypeCode newTypeCode )
{
this.ThrowIfNotCapableOfChanging();
// TODO maybe throw if generic parameters are present?
this.typeCode.Value = newTypeCode;
}
//public CILType ForwardedType
//{
// get
// {
// return this.forwardedType.Value;
// }
// set
// {
// this.ThrowIfNotCapableOfChanging();
// this.forwardedType.Value = value;
// }
//}
#endregion
#region CILElementWithGenericArguments<CILType> Members
public CILType GenericDefinition
{
get
{
return this.genericDefinition.Value;
}
}
#endregion
#region CILTypeInternal Members
SettableValueForEnums<TypeAttributes> CILTypeInternal.TypeAttributesInternal
{
get
{
return this.typeAttributes;
}
}
Lazy<ListProxy<CILType>> CILTypeInternal.NestedTypesInternal
{
get
{
return this.nestedTypes;
}
}
WriteableLazy<LogicalClassLayout?> CILTypeInternal.ClassLayoutInternal
{
get
{
return this.layout;
}
}
//SettableLazy<CILType> CILTypeInternal.ForwardedTypeInternal
//{
// get
// {
// return this.forwardedType;
// }
//}
void CILTypeInternal.ResetDeclaredInterfaces()
{
this.declaredInterfaces.Reset();
}
void CILTypeInternal.ResetDeclaredMethods()
{
this.methods.Reset();
}
void CILTypeInternal.ResetDeclaredFields()
{
this.fields.Reset();
}
void CILTypeInternal.ResetConstructors()
{
this.ctors.Reset();
}
void CILTypeInternal.ResetDeclaredProperties()
{
this.properties.Reset();
}
void CILTypeInternal.ResetDeclaredEvents()
{
this.events.Reset();
}
void CILTypeInternal.ResetBaseType()
{
this.baseType.Reset();
}
void CILTypeInternal.ResetExplicitMethods()
{
this.explicitMethodImplementationMap.Reset();
}
#endregion
public override String Name
{
set
{
if ( this.elementKind.HasValue )
{
throw new InvalidOperationException( "Can not set name on " + this.elementKind + " type." );
}
else
{
( (CILModuleImpl) this.module.Value ).TypeNameChanged( base.name.Value );
base.Name = value;
}
}
get
{
return this.GetNameString();
}
}
public void AddDeclaredInterfaces( params CILType[] iFaces )
{
this.ThrowIfNotCapableOfChanging();
if ( iFaces.Any( iFace => TypeKind.Type != iFace.TypeKind ) )
{
throw new ArgumentException( "Given types must be actual types (not type parameters or method signatures)." );
}
// Since declared interfaces are mutable, no point checking this...
//iFaces.SelectMany( iFace => iFace.AsDepthFirstEnumerable( i => i.DeclaredInterfaces ) ).CheckCyclity( this );
this.declaredInterfaces.Value.AddRange( iFaces.OnlyBottomTypes().Except( this.declaredInterfaces.Value.MQ ) );
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredInterfaces() );
}
public Boolean RemoveDeclaredInterface( CILType iFace )
{
this.ThrowIfNotCapableOfChanging();
Boolean result;
result = this.declaredInterfaces.Value.Remove( iFace );
if ( result )
{
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetDeclaredInterfaces() );
}
return result;
}
internal override String IsCapableOfChanging()
{
if ( this.IsGenericType() && !this.IsGenericTypeDefinition() )
{
return "Type is generic type instance.";
}
//else if ( this.elementKind.HasValue ) // If this limitation will be removed, the CILReflectionContextCache.EMPTY_* fields must be changed from ListProxy<...> to ...[] arrays.
//{
// return "Type is array, pointer or by-ref type.";
//}
else
{
return null;
}
}
private CILType GetTypeCapableOfChanging()
{
return this.IsCapableOfChanging() == null ? this : this.genericDefinition.Value;
}
#region CILElementCapableOfDefiningType Members
public CILType AddType( String name, TypeAttributes attrs, CILTypeCode tc = CILTypeCode.Object )
{
this.ThrowIfNotCapableOfChanging();
var result = this.context.Cache.NewBlankType( this.module.Value, this, name, attrs, tc );
this.nestedTypes.Value.Add( result );
return result;
}
public Boolean RemoveType( CILType type )
{
this.ThrowIfNotCapableOfChanging();
//( (CILTypeInternal) type ).RemoveDeclaringType(); // TODO
return this.nestedTypes.Value.Remove( type );
}
#endregion
#region CILElementWithGenericArguments<CILType> Members
public CILTypeParameter[] DefineGenericParameters( String[] names )
{
CILTypeParameter[] result;
LogicalUtils.CheckWhenDefiningGArgs( this.gArgs.Value, names );
if ( names != null && names.Length > 0 )
{
result = Enumerable.Range( 0, names.Length ).Select( idx => this.context.Cache.NewBlankTypeParameter( this, null, names[idx], idx ) ).ToArray();
this.gArgs.Value.AddRange( result );
this.genericDefinition.Value = this;
}
else
{
result = EMPTY_TYPE_PARAMS;
}
return result;
}
#endregion
#region CILType Members
public ElementKind? ElementKind
{
get
{
return this.elementKind;
}
}
public GeneralArrayInfo ArrayInformation
{
get
{
return this.arrayInfo;
}
}
public ListQuery<CILField> DeclaredFields
{
get
{
return this.fields.Value.CQ;
}
}
public ListQuery<CILConstructor> Constructors
{
get
{
return this.ctors.Value.CQ;
}
}
public ListQuery<CILType> DeclaredNestedTypes
{
get
{
return this.nestedTypes.Value.CQ;
}
}
public ListQuery<CILProperty> DeclaredProperties
{
get
{
return this.properties.Value.CQ;
}
}
public ListQuery<CILEvent> DeclaredEvents
{
get
{
return this.events.Value.CQ;
}
}
public ListQuery<CILType> DeclaredInterfaces
{
get
{
return this.declaredInterfaces.Value.CQ;
}
}
public CILType MakeGenericType( params CILTypeBase[] args )
{
return this.context.Cache.MakeGenericType( this, this.GenericDefinition, args );
}
public void AddExplicitMethodImplementation( CILMethod methodBody, params CILMethod[] methodDeclarations )
{
this.ThrowIfNotTrueDefinition();
var map = this.explicitMethodImplementationMap.Value;
ListProxy<CILMethod> list;
if ( !map.MQ.TryGetValue( methodBody, out list ) )
{
list = this.context.CollectionsFactory.NewListProxy<CILMethod>();
map.Add( methodBody, list );
}
list.AddRange( methodDeclarations );
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetExplicitMethods() );
}
public Boolean RemoveExplicitMethodImplementation( CILMethod methodBody, params CILMethod[] methodDeclarations )
{
this.ThrowIfNotTrueDefinition();
var map = this.explicitMethodImplementationMap.Value;
ListProxy<CILMethod> list;
var retVal = false;
if ( map.MQ.TryGetValue( methodBody, out list ) )
{
foreach ( var method in methodDeclarations )
{
retVal = list.Remove( method ) || retVal;
}
if ( list.MQ.Count <= 0 )
{
map.Remove( methodBody );
}
if ( retVal )
{
this.context.Cache.ForAllGenericInstancesOf( this, type => type.ResetExplicitMethods() );
}
}
return retVal;
}
public DictionaryQuery<CILMethod, ListQuery<CILMethod>> ExplicitMethodImplementations
{
get
{
return this.explicitMethodImplementationMap.Value.CQ.IQ;
}
}
#endregion
#region CILElementWithGenericArguments<CILType> Members
public ListQuery<CILTypeBase> GenericArguments
{
get
{
return this.gArgs.Value.CQ;
}
}
#endregion
#region CapableOfDefiningMethod Members
public ListQuery<CILMethod> DeclaredMethods
{
get
{
return this.methods.Value.CQ;
}
}
#endregion
public DictionaryQuery<SecurityAction, ListQuery<LogicalSecurityInformation>> DeclarativeSecurity
{
get
{
return this.securityInfo.Value.CQ.IQ;
}
}
public LogicalSecurityInformation AddDeclarativeSecurity( SecurityAction action, CILType securityAttributeType )
{
lock ( this.securityInfo.Value )
{
ListProxy<LogicalSecurityInformation> list;
if ( !this.securityInfo.Value.CQ.TryGetValue( action, out list ) )
{
list = this.context.CollectionsFactory.NewListProxy<LogicalSecurityInformation>();
this.securityInfo.Value.Add( action, list );
}
var result = new LogicalSecurityInformation( action, securityAttributeType );
list.Add( result );
return result;
}
}
public Boolean RemoveDeclarativeSecurity( LogicalSecurityInformation information )
{
lock ( this.securityInfo.Value )
{
var result = information != null;
if ( !result )
{
ListProxy<LogicalSecurityInformation> list;
if ( this.securityInfo.Value.CQ.TryGetValue( information.SecurityAction, out list ) )
{
result = list.Remove( information );
}
}
return result;
}
}
internal Lazy<DictionaryWithRoles<SecurityAction, ListProxy<LogicalSecurityInformation>, ListProxyQuery<LogicalSecurityInformation>, ListQuery<LogicalSecurityInformation>>> DeclarativeSecurityInternal
{
get
{
return this.securityInfo;
}
}
}
internal class CILTypeParameterImpl : CILTypeOrParameterImpl, CILTypeParameter
{
private GenericParameterAttributes paramAttributes;
private readonly Int32 position;
private readonly Lazy<CILMethod> declaringMethod;
private readonly Lazy<ListProxy<CILTypeBase>> genericParameterConstraints;
internal CILTypeParameterImpl( CILReflectionContextImpl ctx, Int32 anID, Type type )
: base( ctx, anID, type )
{
if ( TypeKind.TypeParameter != this.typeKind )
{
throw new ArgumentException( "Trying to create type parameter for type " + type );
}
InitFields(
ctx,
ref this.paramAttributes,
ref this.position,
ref this.declaringMethod,
ref this.genericParameterConstraints,
(GenericParameterAttributes) type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.GenericParameterAttributes,
type.GenericParameterPosition,
() => ctx.Cache.GetOrAdd( (System.Reflection.MethodInfo) type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.DeclaringMethod ),
() => ctx.CollectionsFactory.NewListProxy<CILTypeBase>( type
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.GetGenericParameterConstraints().Select( constraint => ctx.Cache.GetOrAdd( constraint ) ).ToList() )
);
}
internal CILTypeParameterImpl(
CILReflectionContextImpl ctx,
Int32 anID,
Lazy<ListProxy<CILCustomAttribute>> cAttrs,
GenericParameterAttributes gpAttrs,
CILType declaringType,
CILMethod declaringMethod,
String aName,
Int32 aPosition,
Func<ListProxy<CILTypeBase>> constraintsFunc
)
: base(
ctx,
anID,
cAttrs,
TypeKind.TypeParameter,
() => CILTypeCode.Object,
new SettableValueForClasses<String>( aName ),
new SettableValueForClasses<String>( null ),
() => declaringType.Module,
() => declaringType,
true
)
{
InitFields(
ctx,
ref this.paramAttributes,
ref this.position,
ref this.declaringMethod,
ref this.genericParameterConstraints,
gpAttrs,
aPosition,
() => declaringMethod,
constraintsFunc
);
}
private static void InitFields(
CILReflectionContextImpl ctx,
ref GenericParameterAttributes paramAttributes,
ref Int32 position,
ref Lazy<CILMethod> declaringMethod,
ref Lazy<ListProxy<CILTypeBase>> genericParameterConstraints,
GenericParameterAttributes aParamAttributes,
Int32 aPosition,
Func<CILMethod> declaringMethodFunc,
Func<ListProxy<CILTypeBase>> genericParameterConstraintsFunc
)
{
var lazyThreadSafety = ctx.LazyThreadSafetyMode;
paramAttributes = aParamAttributes;
position = aPosition;
declaringMethod = new Lazy<CILMethod>( declaringMethodFunc, lazyThreadSafety );
genericParameterConstraints = new Lazy<ListProxy<CILTypeBase>>( genericParameterConstraintsFunc, lazyThreadSafety );
}
public override String ToString()
{
return this.name.Value;
}
#region CILTypeParameter Members
public GenericParameterAttributes Attributes
{
set
{
this.paramAttributes = value;
}
get
{
return this.paramAttributes;
}
}
public CILMethod DeclaringMethod
{
get
{
return this.declaringMethod.Value;
}
}
public void AddGenericParameterConstraints( params CILTypeBase[] constraints )
{
this.genericParameterConstraints.Value.AddRange( constraints.Except( this.genericParameterConstraints.Value.CQ ) );
}
public Boolean RemoveGenericParameterConstraint( CILTypeBase constraint )
{
return this.genericParameterConstraints.Value.Remove( constraint );
}
public Int32 GenericParameterPosition
{
get
{
return this.position;
}
}
public ListQuery<CILTypeBase> GenericParameterConstraints
{
get
{
return this.genericParameterConstraints.Value.CQ;
}
}
#endregion
internal override String IsCapableOfChanging()
{
// Always capable of changing
return null;
}
}
// Reason for method sig immutability:
// use it in other module -> copy is created
// modify original -> copy is not modified! (modify copy -> original is not modified)
// -> behavious is very tricky from user point of view
internal class CILMethodSignatureImpl : AbstractSignatureElement, CILMethodSignature, CILTypeBaseInternal
{
private readonly UnmanagedCallingConventions _callConv;
private readonly CILModule _module;
private readonly ListQuery<CILParameterSignature> _params;
private readonly CILParameterSignature _returnParam;
private readonly SettableValueForClasses<String> _nsDummy;
private readonly Lazy<SettableValueForClasses<String>> _nameDummy;
private readonly CILMethodBase _originatingMethod;
internal CILMethodSignatureImpl( CILReflectionContextImpl ctx, CILModule module, UnmanagedCallingConventions callConv, ListProxy<CILCustomModifier> rpCMods, CILTypeBase rpType, IList<Tuple<ListProxy<CILCustomModifier>, CILTypeBase>> paramsInfo, CILMethodBase originatingMethod )
: base( ctx )
{
ArgumentValidator.ValidateNotNull( "Module", module );
ArgumentValidator.ValidateNotNull( "Return parameter type", rpType );
if ( paramsInfo != null )
{
foreach ( var p in paramsInfo )
{
ArgumentValidator.ValidateNotNull( "Parameter type", p.Item2 );
}
}
this._module = module;
this._callConv = callConv;
this._returnParam = new CILParameterSignatureImpl( ctx, this, E_CILLogical.RETURN_PARAMETER_POSITION, rpType, rpCMods );
var parameters = this._ctx.CollectionsFactory.NewListProxy<CILParameterSignature>();
if ( paramsInfo != null )
{
parameters.AddRange( paramsInfo.Select( ( tuple, idx ) => new CILParameterSignatureImpl( ctx, this, idx, paramsInfo[idx].Item2, paramsInfo[idx].Item1 ) ) );
}
this._params = parameters.CQ;
this._nsDummy = new SettableValueForClasses<string>( null );
this._nameDummy = new Lazy<SettableValueForClasses<string>>( () => new SettableValueForClasses<string>( this.ToString() ), ctx.LazyThreadSafetyMode );
this._originatingMethod = originatingMethod;
}
private CILMethodSignatureImpl( CILMethodSignatureImpl other, CILModule newModule )
: base( other._ctx )
{
this._module = newModule;
this._callConv = other._callConv;
this._returnParam = other._returnParam;
this._params = other._params;
this._nsDummy = other._nsDummy;
this._nameDummy = other._nameDummy;
this._originatingMethod = other._originatingMethod;
}
#region CILMethodSignature Members
public CILMethodSignature CopyToOtherModule( CILModule newModule )
{
return new CILMethodSignatureImpl( this, newModule );
}
public CILMethodBase OriginatingMethod
{
get
{
return this._originatingMethod;
}
}
#endregion
#region CILTypeBase Members
public TypeKind TypeKind
{
get
{
return TypeKind.MethodSignature;
}
}
public CILModule Module
{
get
{
return this._module;
}
}
public CILType MakeElementType( ElementKind kind, GeneralArrayInfo arrayInfo )
{
return this._ctx.Cache.MakeElementType( this, kind, arrayInfo );
}
#endregion
#region CILMethodOrSignature<CILParameterSignature> Members
public UnmanagedCallingConventions CallingConvention
{
get
{
return this._callConv;
}
}
public ListQuery<CILParameterSignature> Parameters
{
get
{
return this._params;
}
}
#endregion
#region CILMethodWithReturnParameter<CILParameterSignature> Members
public CILParameterSignature ReturnParameter
{
get
{
return this._returnParam;
}
}
#endregion
public override Boolean Equals( Object obj )
{
return this.Equals( obj as CILMethodSignature );
}
public override Int32 GetHashCode()
{
return ( ( (Int32) this._callConv ) << 24 ) | this._params.Count;
}
public override String ToString()
{
// TODO: method <type> <mods> *(<type> <mods>)
return "method " + this._returnParam + " *(" + String.Join( ", ", this._params.Select( p => p.ToString() ).Concat( Enumerable.Repeat( "...", this._callConv.IsVarArg() ? 1 : 0 ) ) ) + ")";
}
internal Boolean Equals( CILMethodSignature other )
{
// Don't check module when checking equality.
return Object.ReferenceEquals( this, other )
|| ( other != null
&& this.CallingConvention == other.CallingConvention
&& ( (CILParameterSignatureImpl) this._returnParam ).Equals( other.ReturnParameter, false )
&& this._params.Count == other.Parameters.Count
&& this._params.Where( ( p, idx ) => ( (CILParameterSignatureImpl) p ).Equals( other.Parameters[idx], false ) ).Count() == this._params.Count
);
}
#region CILTypeBaseInternal Members
SettableValueForClasses<string> CILTypeBaseInternal.NamespaceInternal
{
get
{
return this._nsDummy;
}
}
#endregion
#region CILElementWithSimpleNameInternal Members
SettableValueForClasses<string> CILElementWithSimpleNameInternal.NameInternal
{
get
{
return this._nameDummy.Value;
}
}
#endregion
public CILElementWithinILCode ElementTypeKind
{
get
{
return CILElementWithinILCode.Type;
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel;
namespace Lumix
{
public class Component
{
private static byte[] s_imgui_text_buffer = new byte[4096];
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern static int create(IntPtr universe, int entity, string cmp_type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern static IntPtr getScene(IntPtr universe, string cmp_type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern static int entityInput(IntPtr editor, IntPtr universe, string label, int entity);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern static int getEntityIDFromGUID(IntPtr manager, ulong guid);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern static ulong getEntityGUIDFromID(IntPtr manager, int id);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern static IntPtr resourceInput(IntPtr editor, string label, string type, IntPtr resource);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern static void pushUndoCommand(IntPtr editor, IntPtr universe, int entity, Component cmp, string property, string old_value, string value);
public string Serialize(IntPtr manager)
{
var type = this.GetType();
var string_builder = new System.Text.StringBuilder();
string_builder.Append("0|"); // header (version)
foreach (var f in type.GetFields())
{
if (!f.IsPublic) continue;
if(f.Name == "entity_") continue;
if(f.Name == "componentId_") continue;
if(f.Name == "scene_") continue;
var val = f.GetValue(this);
Type val_type = f.FieldType;
string_builder.Append(val_type.Name);
string_builder.Append("|");
string_builder.Append(f.Name);
string_builder.Append("|");
if(f.FieldType == typeof(Entity))
{
if (manager != IntPtr.Zero)
{
ulong guid = getEntityGUIDFromID(manager, ((Entity)val).entity_Id_);
string_builder.Append(guid.ToString());
}
else
{
string_builder.Append(((Entity)val).entity_Id_);
}
}
else if(f.FieldType.BaseType == typeof(Resource))
{
IntPtr native_res = val == null ? IntPtr.Zero : ((Resource)val).__Instance;
string path = Resource.getPath(native_res);
string_builder.Append(path);
}
else
{
string_builder.Append(val);
}
string_builder.Append("|");
}
return string_builder.ToString();
}
public static string ConvertGUIDToID(string data, IntPtr manager)
{
var string_builder = new System.Text.StringBuilder();
string[] values = data.Split('|');
int version = int.Parse(values[0]);
if (version > 0) return "";
string_builder.Append(values[0]);
string_builder.Append("|");
for (int i = 1; i < values.Length - 1; i += 3)
{
string type = values[i];
string name = values[i + 1];
string value = values[i + 2];
string_builder.Append(type);
string_builder.Append("|");
string_builder.Append(name);
string_builder.Append("|");
if (type == typeof(Entity).Name)
{
value = getEntityIDFromGUID(manager, ulong.Parse(value)).ToString();
}
string_builder.Append(value);
string_builder.Append("|");
}
return string_builder.ToString();
}
public void Deserialize(string data)
{
var this_type = this.GetType();
string[] values = data.Split('|');
int version = int.Parse(values[0]);
if (version > 0) return;
for (int i = 1; i < values.Length - 1; i += 3)
{
string type = values[i];
string name = values[i+1];
string value = values[i+2];
var field = this_type.GetField(name);
Type field_type = field.FieldType;
if (field_type.Name != type) continue;
if (field_type == typeof(Entity))
{
int entity_id = int.Parse(value);
Entity e = Universe.GetEntity(entity_id);
field.SetValue(this, e);
}
else if(field_type.BaseType == typeof(Resource))
{
var resource = Activator.CreateInstance(field_type, new object[] { value });
field.SetValue(this, resource);
}
else
{
var converter = TypeDescriptor.GetConverter(field_type);
field.SetValue(this, converter.ConvertFrom(value));
}
}
}
public void OnUndo(IntPtr editor, string property, string value)
{
var field = this.GetType().GetField(property);
if (field == null) return;
Type field_type = field.FieldType;
if(field_type == typeof(int))
{
field.SetValue(this, int.Parse(value));
}
else if(field_type == typeof(float))
{
field.SetValue(this, float.Parse(value));
}
else if(field_type == typeof(bool))
{
field.SetValue(this, bool.Parse(value));
}
else if(field_type == typeof(string))
{
field.SetValue(this, value);
}
else if(field_type == typeof(Lumix.Entity))
{
int entity_id = int.Parse(value);
Entity e = Universe.GetEntity(entity_id);
field.SetValue(this, e);
}
else if(field_type.BaseType == typeof(Lumix.Resource))
{
var resource = Activator.CreateInstance(field_type, new object[] { value });
field.SetValue(this, resource);
}
else
{
string msg = "Unsupported type " + field_type.FullName + " = " + value;
Engine.logError(msg);
throw new Exception(msg);
}
}
public IntPtr scene_;
protected Entity entity_;
public Entity entity
{
get { return entity_; }
set
{
if(entity_ != null) throw new Exception("Component's entity can not be reset");
entity_ = value;
entity_.components_.Add(this);
}
}
public Universe Universe
{
get { return entity.Universe; }
}
public Component()
{
}
public Component(Entity _entity, IntPtr _scene)
{
entity_ = _entity;
scene_ = _scene;
}
public T GetComponent<T>() where T : Component
{
return entity.GetComponent<T>();
}
public T CreateComponent<T>() where T : Component
{
return entity.CreateComponent<T>();
}
public virtual void OnInspector(IntPtr editor)
{
var type = this.GetType();
foreach (var f in type.GetFields())
{
if (!f.IsPublic) continue;
if(f.Name == "entity_") continue;
if(f.Name == "componentId_") continue;
if(f.Name == "scene_") continue;
var val = f.GetValue(this);
Type val_type = f.FieldType;
if (val_type == typeof(float))
{
float old_value = (float)val;
float new_value = old_value;
if(ImGui.DragFloat(f.Name, ref new_value, 0.1f, float.MaxValue, float.MaxValue, "%f", 1))
{
pushUndoCommand(editor, entity.instance_, entity.entity_Id_, this, f.Name, old_value.ToString(), new_value.ToString());
}
}
else if (val_type == typeof(bool))
{
bool old_value = (bool)val;
bool new_value = old_value;
if(ImGui.Checkbox(f.Name, ref new_value))
{
pushUndoCommand(editor, entity.instance_, entity.entity_Id_, this, f.Name, old_value.ToString(), new_value.ToString());
}
}
else if (val_type == typeof(int))
{
int old_value = (int)val;
int new_value = old_value;
if(ImGui.InputInt(f.Name, ref new_value, 1, 10, 0))
{
pushUndoCommand(editor, entity.instance_, entity.entity_Id_, this, f.Name, old_value.ToString(), new_value.ToString());
}
}
else if (val_type == typeof(string))
{
string old_value = (string)val;
byte[] str_bytes = System.Text.Encoding.ASCII.GetBytes(old_value);
str_bytes.CopyTo(s_imgui_text_buffer, 0);
s_imgui_text_buffer[str_bytes.Length] = 0;
if (ImGui.InputText(f.Name, s_imgui_text_buffer, 0, IntPtr.Zero, IntPtr.Zero))
{
string new_value = System.Text.Encoding.ASCII.GetString(s_imgui_text_buffer);
pushUndoCommand(editor, entity.instance_, entity.entity_Id_, this, f.Name, old_value, new_value);
}
}
else if(f.FieldType == typeof(Entity))
{
int old_entity_id = val == null ? -1 : ((Entity)val).entity_Id_;
int new_entity_id = entityInput(editor, entity.instance_, f.Name, old_entity_id);
if(new_entity_id != old_entity_id)
{
pushUndoCommand(editor, entity.instance_, entity.entity_Id_, this, f.Name, old_entity_id.ToString(), new_entity_id.ToString());
}
}
else if(f.FieldType.BaseType == typeof(Resource))
{
IntPtr old_res = val == null ? IntPtr.Zero : ((Resource)val).__Instance;
IntPtr new_res = resourceInput(editor, f.Name, "prefab", old_res);
if (new_res != old_res)
{
string old_path = old_res == IntPtr.Zero ? "" : Resource.getPath(old_res);
if (new_res == IntPtr.Zero)
{
pushUndoCommand(editor, entity.instance_, entity.entity_Id_, this, f.Name, old_path, "");
}
else
{
pushUndoCommand(editor, entity.instance_, entity.entity_Id_, this, f.Name, old_path, Resource.getPath(new_res));
}
}
}
else
{
if (val == null)
ImGui.Text(f.Name + " = null");
else
ImGui.Text(f.Name + " = " + val.ToString());
}
}
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nager.Date.Contract;
using Nager.Date.Model;
using System;
using System.Linq;
namespace Nager.Date.UnitTest.Common
{
[TestClass]
public class LogicTest
{
[TestMethod]
[Ignore("debuging")]
public void CheckNoCorruptPublicHolidays()
{
var startYear = DateTime.Today.Year - 100;
var endYear = DateTime.Today.Year + 100;
foreach (CountryCode countryCode in Enum.GetValues(typeof(CountryCode)))
{
for (var calculationYear = startYear; calculationYear < endYear; calculationYear++)
{
var items = DateSystem.GetPublicHolidays(calculationYear, countryCode);
var corruptPublicHolidaysAvailable = items.Any(o => !o.Date.Year.Equals(calculationYear));
Assert.IsFalse(corruptPublicHolidaysAvailable, $"Check country {countryCode} {calculationYear}");
//Trace.WriteLineIf(corruptPublicHolidaysAvailable, $"Check country {countryCode} {calculationYear}");
}
}
}
[TestMethod]
[DataRow(1900, 4, 15)]
[DataRow(2014, 4, 20)]
[DataRow(2015, 4, 5)]
[DataRow(2016, 3, 27)]
[DataRow(2017, 4, 16)]
[DataRow(2018, 4, 1)]
[DataRow(2019, 4, 21)]
[DataRow(2020, 4, 12)]
[DataRow(2200, 4, 6)]
public void CheckEasterSunday(int year, int month, int day)
{
var catholicProvider = new MockPublicHolidayProvider(new CatholicProvider());
var easterSunday = catholicProvider.EasterSunday(year);
Assert.AreEqual(new DateTime(year, month, day), easterSunday);
}
[TestMethod]
public void CheckIsPublicHoliday()
{
var isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2016, 5, 1), CountryCode.AT);
Assert.AreEqual(true, isPublicHoliday);
isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2016, 1, 6), CountryCode.AT);
Assert.AreEqual(true, isPublicHoliday);
isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2016, 1, 6), "AT");
Assert.AreEqual(true, isPublicHoliday);
isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2016, 1, 6), "AT");
Assert.AreEqual(true, isPublicHoliday);
}
[TestMethod]
public void CheckIsWeekend()
{
var isPublicHoliday = DateSystem.IsWeekend(new DateTime(2021, 10, 20), CountryCode.AT);
Assert.IsFalse(isPublicHoliday);
isPublicHoliday = DateSystem.IsWeekend(new DateTime(2021, 10, 20), "AT");
Assert.IsFalse(isPublicHoliday);
isPublicHoliday = DateSystem.IsWeekend(new DateTime(2021, 10, 24), CountryCode.AT);
Assert.IsTrue(isPublicHoliday);
isPublicHoliday = DateSystem.IsWeekend(new DateTime(2021, 10, 24), "AT");
Assert.IsTrue(isPublicHoliday);
}
[TestMethod]
public void CheckFindDay()
{
var result = DateSystem.FindDay(2017, 1, 1, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 6), result);
result = DateSystem.FindDay(2017, 1, 2, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 6), result);
result = DateSystem.FindDay(2017, 1, 3, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 6), result);
result = DateSystem.FindDay(2017, 1, 4, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 6), result);
result = DateSystem.FindDay(2017, 1, 5, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 6), result);
result = DateSystem.FindDay(2017, 1, 6, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 6), result);
result = DateSystem.FindDay(2017, 1, 7, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 13), result);
result = DateSystem.FindDay(2017, 1, 8, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 13), result);
result = DateSystem.FindDay(2017, 1, 9, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 13), result);
result = DateSystem.FindDay(2017, 1, 10, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 13), result);
result = DateSystem.FindDay(2017, 1, 11, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 13), result);
result = DateSystem.FindDay(2017, 1, 12, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 13), result);
result = DateSystem.FindDay(2017, 1, 13, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2017, 1, 13), result);
result = DateSystem.FindDay(2017, 1, 14, DayOfWeek.Wednesday);
Assert.AreEqual(new DateTime(2017, 1, 18), result);
result = DateSystem.FindDay(2022, 1, 1, DayOfWeek.Monday);
Assert.AreEqual(new DateTime(2022, 1, 3), result);
result = DateSystem.FindDay(2022, 1, 1, DayOfWeek.Tuesday);
Assert.AreEqual(new DateTime(2022, 1, 4), result);
}
[TestMethod]
public void CheckFindDayBefore()
{
var result = DateSystem.FindDayBefore(2018, 5, 25, DayOfWeek.Monday);
Assert.AreEqual(new DateTime(2018, 5, 21), result);
result = DateSystem.FindDayBefore(2018, 1, 9, DayOfWeek.Monday);
Assert.AreEqual(new DateTime(2018, 1, 8), result);
result = DateSystem.FindDayBefore(2018, 1, 8, DayOfWeek.Monday);
Assert.AreEqual(new DateTime(2018, 1, 1), result);
result = DateSystem.FindDayBefore(2018, 1, 12, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2018, 1, 5), result);
}
[TestMethod]
public void CheckFindDayBetween()
{
var result = DateSystem.FindDayBetween(2019, 7, 1, 2019, 7, 7, DayOfWeek.Tuesday);
Assert.AreEqual(new DateTime(2019, 7, 2), result);
result = DateSystem.FindDayBetween(2019, 7, 1, 2019, 7, 7, DayOfWeek.Wednesday);
Assert.AreEqual(new DateTime(2019, 7, 3), result);
result = DateSystem.FindDayBetween(2019, 7, 1, 2019, 7, 7, DayOfWeek.Friday);
Assert.AreEqual(new DateTime(2019, 7, 5), result);
result = DateSystem.FindDayBetween(2019, 7, 1, 2019, 7, 7, DayOfWeek.Saturday);
Assert.AreEqual(new DateTime(2019, 7, 6), result);
}
[TestMethod]
public void CheckPublicHolidayWithDateFilter1()
{
this.CheckPublicHolidayWithDateFilter1(new DateTime(2016, 5, 1), new DateTime(2018, 5, 31));
this.CheckPublicHolidayWithDateFilter1(new DateTime(2016, 5, 1, 0, 0, 1), new DateTime(2018, 5, 31, 23, 59, 59));
this.CheckPublicHolidayWithDateFilter1(new DateTime(2016, 5, 1, 12, 30, 0), new DateTime(2018, 5, 31, 0, 0, 0));
this.CheckPublicHolidayWithDateFilter1(new DateTime(2016, 5, 1, 23, 59, 59), new DateTime(2018, 5, 31, 23, 59, 59));
}
private void CheckPublicHolidayWithDateFilter1(DateTime startDate, DateTime endDate)
{
var items = DateSystem.GetPublicHolidays(startDate, endDate, CountryCode.DE);
Assert.AreEqual(43, items.Count());
Assert.IsTrue(items.First().Date > new DateTime(2016, 4, 28));
Assert.IsTrue(items.Last().Date < new DateTime(2018, 6, 1));
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "endDate is before startDate")]
public void CheckPublicHolidayWithDateFilter2()
{
DateSystem.GetPublicHolidays(new DateTime(2016, 1, 2), new DateTime(2016, 1, 1), CountryCode.DE).First();
}
[TestMethod]
public void CheckIsOfficialPublicHolidayByCounty1()
{
var isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2019, 8, 5), CountryCode.AU);
Assert.IsFalse(isPublicHoliday);
isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2019, 8, 5), CountryCode.AU, "AUS-NT");
Assert.IsTrue(isPublicHoliday);
isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2019, 8, 5), CountryCode.AU, "AUS-WA");
Assert.IsFalse(isPublicHoliday);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException), "Invalid countyCode AU-NT")]
public void CheckIsOfficialPublicHolidayByCounty2()
{
var isPublicHoliday = DateSystem.IsPublicHoliday(new DateTime(2019, 8, 5), CountryCode.AU, "AU-NT");
Assert.IsTrue(isPublicHoliday);
}
[TestMethod]
public void CheckGlobalSwtichWork()
{
var publicHoliday = new PublicHoliday(2020, 01, 30, "Test", "Test", CountryCode.AT, null, null, PublicHolidayType.Public);
Assert.IsTrue(publicHoliday.Global);
publicHoliday = new PublicHoliday(2020, 01, 30, "Test", "Test", CountryCode.AT, null, new[] { "AT-1" }, PublicHolidayType.Public);
Assert.IsFalse(publicHoliday.Global);
}
}
}
| |
using System;
namespace Avalonia.Utilities
{
/// <summary>
/// Provides math utilities not provided in System.Math.
/// </summary>
#if !BUILDTASK
public
#endif
static class MathUtilities
{
// smallest such that 1.0+DoubleEpsilon != 1.0
internal static readonly double DoubleEpsilon = 2.2204460492503131e-016;
private const float FloatEpsilon = 1.192092896e-07F;
/// <summary>
/// AreClose - Returns whether or not two doubles are "close". That is, whether or
/// not they are within epsilon of each other.
/// </summary>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
public static bool AreClose(double value1, double value2)
{
//in case they are Infinities (then epsilon check does not work)
if (value1 == value2) return true;
double eps = (Math.Abs(value1) + Math.Abs(value2) + 10.0) * DoubleEpsilon;
double delta = value1 - value2;
return (-eps < delta) && (eps > delta);
}
/// <summary>
/// AreClose - Returns whether or not two doubles are "close". That is, whether or
/// not they are within epsilon of each other.
/// </summary>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
/// <param name="eps"> The fixed epsilon value used to compare.</param>
public static bool AreClose(double value1, double value2, double eps)
{
//in case they are Infinities (then epsilon check does not work)
if (value1 == value2) return true;
double delta = value1 - value2;
return (-eps < delta) && (eps > delta);
}
/// <summary>
/// AreClose - Returns whether or not two floats are "close". That is, whether or
/// not they are within epsilon of each other.
/// </summary>
/// <param name="value1"> The first float to compare. </param>
/// <param name="value2"> The second float to compare. </param>
public static bool AreClose(float value1, float value2)
{
//in case they are Infinities (then epsilon check does not work)
if (value1 == value2) return true;
float eps = (Math.Abs(value1) + Math.Abs(value2) + 10.0f) * FloatEpsilon;
float delta = value1 - value2;
return (-eps < delta) && (eps > delta);
}
/// <summary>
/// LessThan - Returns whether or not the first double is less than the second double.
/// That is, whether or not the first is strictly less than *and* not within epsilon of
/// the other number.
/// </summary>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
public static bool LessThan(double value1, double value2)
{
return (value1 < value2) && !AreClose(value1, value2);
}
/// <summary>
/// LessThan - Returns whether or not the first float is less than the second float.
/// That is, whether or not the first is strictly less than *and* not within epsilon of
/// the other number.
/// </summary>
/// <param name="value1"> The first single float to compare. </param>
/// <param name="value2"> The second single float to compare. </param>
public static bool LessThan(float value1, float value2)
{
return (value1 < value2) && !AreClose(value1, value2);
}
/// <summary>
/// GreaterThan - Returns whether or not the first double is greater than the second double.
/// That is, whether or not the first is strictly greater than *and* not within epsilon of
/// the other number.
/// </summary>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
public static bool GreaterThan(double value1, double value2)
{
return (value1 > value2) && !AreClose(value1, value2);
}
/// <summary>
/// GreaterThan - Returns whether or not the first float is greater than the second float.
/// That is, whether or not the first is strictly greater than *and* not within epsilon of
/// the other number.
/// </summary>
/// <param name="value1"> The first float to compare. </param>
/// <param name="value2"> The second float to compare. </param>
public static bool GreaterThan(float value1, float value2)
{
return (value1 > value2) && !AreClose(value1, value2);
}
/// <summary>
/// LessThanOrClose - Returns whether or not the first double is less than or close to
/// the second double. That is, whether or not the first is strictly less than or within
/// epsilon of the other number.
/// </summary>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
public static bool LessThanOrClose(double value1, double value2)
{
return (value1 < value2) || AreClose(value1, value2);
}
/// <summary>
/// LessThanOrClose - Returns whether or not the first float is less than or close to
/// the second float. That is, whether or not the first is strictly less than or within
/// epsilon of the other number.
/// </summary>
/// <param name="value1"> The first float to compare. </param>
/// <param name="value2"> The second float to compare. </param>
public static bool LessThanOrClose(float value1, float value2)
{
return (value1 < value2) || AreClose(value1, value2);
}
/// <summary>
/// GreaterThanOrClose - Returns whether or not the first double is greater than or close to
/// the second double. That is, whether or not the first is strictly greater than or within
/// epsilon of the other number.
/// </summary>
/// <param name="value1"> The first double to compare. </param>
/// <param name="value2"> The second double to compare. </param>
public static bool GreaterThanOrClose(double value1, double value2)
{
return (value1 > value2) || AreClose(value1, value2);
}
/// <summary>
/// GreaterThanOrClose - Returns whether or not the first float is greater than or close to
/// the second float. That is, whether or not the first is strictly greater than or within
/// epsilon of the other number.
/// </summary>
/// <param name="value1"> The first float to compare. </param>
/// <param name="value2"> The second float to compare. </param>
public static bool GreaterThanOrClose(float value1, float value2)
{
return (value1 > value2) || AreClose(value1, value2);
}
/// <summary>
/// IsOne - Returns whether or not the double is "close" to 1. Same as AreClose(double, 1),
/// but this is faster.
/// </summary>
/// <param name="value"> The double to compare to 1. </param>
public static bool IsOne(double value)
{
return Math.Abs(value - 1.0) < 10.0 * DoubleEpsilon;
}
/// <summary>
/// IsOne - Returns whether or not the float is "close" to 1. Same as AreClose(float, 1),
/// but this is faster.
/// </summary>
/// <param name="value"> The float to compare to 1. </param>
public static bool IsOne(float value)
{
return Math.Abs(value - 1.0f) < 10.0f * FloatEpsilon;
}
/// <summary>
/// IsZero - Returns whether or not the double is "close" to 0. Same as AreClose(double, 0),
/// but this is faster.
/// </summary>
/// <param name="value"> The double to compare to 0. </param>
public static bool IsZero(double value)
{
return Math.Abs(value) < 10.0 * DoubleEpsilon;
}
/// <summary>
/// IsZero - Returns whether or not the float is "close" to 0. Same as AreClose(float, 0),
/// but this is faster.
/// </summary>
/// <param name="value"> The float to compare to 0. </param>
public static bool IsZero(float value)
{
return Math.Abs(value) < 10.0f * FloatEpsilon;
}
/// <summary>
/// Clamps a value between a minimum and maximum value.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns>
public static double Clamp(double val, double min, double max)
{
if (min > max)
{
ThrowCannotBeGreaterThanException(min, max);
}
if (val < min)
{
return min;
}
else if (val > max)
{
return max;
}
else
{
return val;
}
}
/// <summary>
/// Clamps a value between a minimum and maximum value.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns>
public static decimal Clamp(decimal val, decimal min, decimal max)
{
if (min > max)
{
ThrowCannotBeGreaterThanException(min, max);
}
if (val < min)
{
return min;
}
else if (val > max)
{
return max;
}
else
{
return val;
}
}
/// <summary>
/// Clamps a value between a minimum and maximum value.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The clamped value.</returns>
public static int Clamp(int val, int min, int max)
{
if (min > max)
{
ThrowCannotBeGreaterThanException(min, max);
}
if (val < min)
{
return min;
}
else if (val > max)
{
return max;
}
else
{
return val;
}
}
/// <summary>
/// Converts an angle in degrees to radians.
/// </summary>
/// <param name="angle">The angle in degrees.</param>
/// <returns>The angle in radians.</returns>
public static double Deg2Rad(double angle)
{
return angle * (Math.PI / 180d);
}
/// <summary>
/// Converts an angle in gradians to radians.
/// </summary>
/// <param name="angle">The angle in gradians.</param>
/// <returns>The angle in radians.</returns>
public static double Grad2Rad(double angle)
{
return angle * (Math.PI / 200d);
}
/// <summary>
/// Converts an angle in turns to radians.
/// </summary>
/// <param name="angle">The angle in turns.</param>
/// <returns>The angle in radians.</returns>
public static double Turn2Rad(double angle)
{
return angle * 2 * Math.PI;
}
private static void ThrowCannotBeGreaterThanException<T>(T min, T max)
{
throw new ArgumentException($"{min} cannot be greater than {max}.");
}
}
}
| |
/**
* @file
* SessionListener is an abstract base class (interface) implemented by users of the
* AllJoyn API in order to receive sessions related event information.
*/
/******************************************************************************
* Copyright (c) 2012, AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
using System;
using System.Runtime.InteropServices;
namespace AllJoynUnity
{
public partial class AllJoyn
{
/**
* Abstract base class implemented by AllJoyn users and called by AllJoyn to inform
* users of session related events.
*/
public class SessionListener : IDisposable
{
/** Reason for the session being lost */
public enum SessionLostReason{
ALLJOYN_SESSIONLOST_INVALID = 0x00, /**< Invalid */
ALLJOYN_SESSIONLOST_REMOTE_END_LEFT_SESSION = 0x01, /**< Remote end called LeaveSession */
ALLJOYN_SESSIONLOST_REMOTE_END_CLOSED_ABRUPTLY = 0x02, /**< Remote end closed abruptly */
ALLJOYN_SESSIONLOST_REMOVED_BY_BINDER = 0x03, /**< Session binder removed this endpoint by calling RemoveSessionMember */
ALLJOYN_SESSIONLOST_LINK_TIMEOUT = 0x04, /**< Link was timed-out */
ALLJOYN_SESSIONLOST_REASON_OTHER = 0x05 /**< Unspecified reason for session loss */
};
/**
* Constructor for a SessionListener.
*/
public SessionListener()
{
_sessionLost = new InternalSessionLost(this._SessionLost);
_sessionMemberAdded = new InternalSessionMemberAdded(this._SessionMemberAdded);
_sessionMemberRemoved = new InternalSessionMemberRemoved(this._SessionMemberRemoved);
callbacks.sessionLost = Marshal.GetFunctionPointerForDelegate(_sessionLost);
callbacks.sessionMemberAdded = Marshal.GetFunctionPointerForDelegate(_sessionMemberAdded);
callbacks.sessionMemberRemoved = Marshal.GetFunctionPointerForDelegate(_sessionMemberRemoved);
main = GCHandle.Alloc(callbacks, GCHandleType.Pinned);
_sessionListener = alljoyn_sessionlistener_create(main.AddrOfPinnedObject(), IntPtr.Zero);
}
/**
* Request the raw pointer of the AllJoyn C SessionListener
*
* @return the raw pointer of the AllJoyn C SessionListener
*/
public IntPtr getAddr()
{
return _sessionListener;
}
#region Virtual Methods
/**
* Called by the bus when an existing session becomes disconnected.(Deprecated)
*
* @see SessionLost(uint sessionId, SessionLostReason reason)
*
* @param sessionId Id of session that was lost.
*/
[System.Obsolete("SessionLost callback that only returns sessionId has been depricated in favor of the SessionLost that returns the SessionLostReason.")]
protected virtual void SessionLost(uint sessionId)
{
}
/**
* Called by the bus when an existing session becomes disconnected.
*
* @param sessionId Id of session that was lost.
* @param reason The reason for the session being lost
*/
protected virtual void SessionLost(uint sessionId, SessionLostReason reason)
{
}
/**
* Called by the bus when a member of a multipoint session is added.
*
* @param sessionId Id of session whose member(s) changed.
* @param uniqueName Unique name of member who was added.
*/
protected virtual void SessionMemberAdded(uint sessionId, string uniqueName)
{
}
/**
* Called by the bus when a member of a multipoint session is removed.
*
* @param sessionId Id of session whose member(s) changed.
* @param uniqueName Unique name of member who was removed.
*/
protected virtual void SessionMemberRemoved(uint sessionId, string uniqueName)
{
}
#endregion
#region Callbacks
private void _SessionLost(IntPtr context, uint sessionId, SessionLostReason reason)
{
uint _sessionId = sessionId;
SessionLostReason _reason = reason;
System.Threading.Thread callIt = new System.Threading.Thread((object o) =>
{
/* SessionLost must be called here for the obsolite callback function to
* continue to work
*/
#pragma warning disable 618
SessionLost(_sessionId);
#pragma warning restore 618
SessionLost(_sessionId, _reason);
});
callIt.Start();
}
private void _SessionMemberAdded(IntPtr context, uint sessionId, IntPtr uniqueName)
{
uint _sessionId = sessionId;
String _uniqueName = Marshal.PtrToStringAnsi(uniqueName);
System.Threading.Thread callIt = new System.Threading.Thread((object o) =>
{
SessionMemberAdded(_sessionId, _uniqueName);
});
callIt.Start();
}
private void _SessionMemberRemoved(IntPtr context, uint sessionId, IntPtr uniqueName)
{
uint _sessionId = sessionId;
String _uniqueName = Marshal.PtrToStringAnsi(uniqueName);
System.Threading.Thread callIt = new System.Threading.Thread((object o) =>
{
SessionMemberRemoved(_sessionId, _uniqueName);
});
callIt.Start();
}
#endregion
#region Delegates
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalSessionLost(IntPtr context, uint sessionId, SessionLostReason reason);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalSessionMemberAdded(IntPtr context, uint sessionId, IntPtr uniqueName);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void InternalSessionMemberRemoved(IntPtr context, uint sessionId, IntPtr uniqueName);
#endregion
#region DLL Imports
[DllImport(DLL_IMPORT_TARGET)]
private extern static IntPtr alljoyn_sessionlistener_create(
IntPtr callbacks,
IntPtr context);
[DllImport(DLL_IMPORT_TARGET)]
private extern static void alljoyn_sessionlistener_destroy(IntPtr listener);
#endregion
#region IDisposable
~SessionListener()
{
Dispose(false);
}
/**
* Dispose the SessionListener
* @param disposing describes if its activly being disposed
*/
protected virtual void Dispose(bool disposing)
{
if(!_isDisposed)
{
alljoyn_sessionlistener_destroy(_sessionListener);
_sessionListener = IntPtr.Zero;
main.Free();
}
_isDisposed = true;
}
/**
* Dispose the SessionListener
*/
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Structs
private struct SessionListenerCallbacks
{
public IntPtr sessionLost;
public IntPtr sessionMemberAdded;
public IntPtr sessionMemberRemoved;
}
#endregion
#region Internal Properties
internal IntPtr UnmanagedPtr
{
get
{
return _sessionListener;
}
}
#endregion
#region Data
IntPtr _sessionListener;
bool _isDisposed = false;
GCHandle main;
InternalSessionLost _sessionLost;
InternalSessionMemberAdded _sessionMemberAdded;
InternalSessionMemberRemoved _sessionMemberRemoved;
SessionListenerCallbacks callbacks;
#endregion
}
}
}
| |
// TarHeader.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
/* The tar format and its POSIX successor PAX have a long history which makes for compatability
issues when creating and reading files...
This is further complicated by a large number of programs with variations on formats
One common issue is the handling of names longer than 100 characters.
GNU style long names are currently supported.
This is the ustar (Posix 1003.1) header.
struct header
{
char t_name[100]; // 0 Filename
char t_mode[8]; // 100 Permissions
char t_uid[8]; // 108 Numerical User ID
char t_gid[8]; // 116 Numerical Group ID
char t_size[12]; // 124 Filesize
char t_mtime[12]; // 136 st_mtime
char t_chksum[8]; // 148 Checksum
char t_typeflag; // 156 Type of File
char t_linkname[100]; // 157 Target of Links
char t_magic[6]; // 257 "ustar" or other...
char t_version[2]; // 263 Version fixed to 00
char t_uname[32]; // 265 User Name
char t_gname[32]; // 297 Group Name
char t_devmajor[8]; // 329 Major for devices
char t_devminor[8]; // 337 Minor for devices
char t_prefix[155]; // 345 Prefix for t_name
char t_mfill[12]; // 500 Filler up to 512
};
*/
using System;
using System.Text;
namespace ICSharpCode.SharpZipLib.Tar
{
/// <summary>
/// This class encapsulates the Tar Entry Header used in Tar Archives.
/// The class also holds a number of tar constants, used mostly in headers.
/// </summary>
public class TarHeader : ICloneable
{
/// <summary>
/// The length of the name field in a header buffer.
/// </summary>
public readonly static int NAMELEN = 100;
/// <summary>
/// The length of the mode field in a header buffer.
/// </summary>
public readonly static int MODELEN = 8;
/// <summary>
/// The length of the user id field in a header buffer.
/// </summary>
public readonly static int UIDLEN = 8;
/// <summary>
/// The length of the group id field in a header buffer.
/// </summary>
public readonly static int GIDLEN = 8;
/// <summary>
/// The length of the checksum field in a header buffer.
/// </summary>
public readonly static int CHKSUMLEN = 8;
/// <summary>
/// The length of the size field in a header buffer.
/// </summary>
public readonly static int SIZELEN = 12;
/// <summary>
/// The length of the magic field in a header buffer.
/// </summary>
public readonly static int MAGICLEN = 6;
/// <summary>
/// The length of the version field in a header buffer.
/// </summary>
public readonly static int VERSIONLEN = 2;
/// <summary>
/// The length of the modification time field in a header buffer.
/// </summary>
public readonly static int MODTIMELEN = 12;
/// <summary>
/// The length of the user name field in a header buffer.
/// </summary>
public readonly static int UNAMELEN = 32;
/// <summary>
/// The length of the group name field in a header buffer.
/// </summary>
public readonly static int GNAMELEN = 32;
/// <summary>
/// The length of the devices field in a header buffer.
/// </summary>
public readonly static int DEVLEN = 8;
//
// LF_ constants represent the "type" of an entry
//
/// <summary>
/// The "old way" of indicating a normal file.
/// </summary>
public const byte LF_OLDNORM = 0;
/// <summary>
/// Normal file type.
/// </summary>
public const byte LF_NORMAL = (byte) '0';
/// <summary>
/// Link file type.
/// </summary>
public const byte LF_LINK = (byte) '1';
/// <summary>
/// Symbolic link file type.
/// </summary>
public const byte LF_SYMLINK = (byte) '2';
/// <summary>
/// Character device file type.
/// </summary>
public const byte LF_CHR = (byte) '3';
/// <summary>
/// Block device file type.
/// </summary>
public const byte LF_BLK = (byte) '4';
/// <summary>
/// Directory file type.
/// </summary>
public const byte LF_DIR = (byte) '5';
/// <summary>
/// FIFO (pipe) file type.
/// </summary>
public const byte LF_FIFO = (byte) '6';
/// <summary>
/// Contiguous file type.
/// </summary>
public const byte LF_CONTIG = (byte) '7';
/// <summary>
/// Posix.1 2001 global extended header
/// </summary>
public const byte LF_GHDR = (byte) 'g';
/// <summary>
/// Posix.1 2001 extended header
/// </summary>
public readonly static byte LF_XHDR = (byte) 'x';
// POSIX allows for upper case ascii type as extensions
/// <summary>
/// Solaris access control list file type
/// </summary>
public const byte LF_ACL = (byte) 'A';
/// <summary>
/// GNU dir dump file type
/// This is a dir entry that contains the names of files that were in the
/// dir at the time the dump was made
/// </summary>
public const byte LF_GNU_DUMPDIR = (byte) 'D';
/// <summary>
/// Solaris Extended Attribute File
/// </summary>
public const byte LF_EXTATTR = (byte) 'E' ;
/// <summary>
/// Inode (metadata only) no file content
/// </summary>
public const byte LF_META = (byte) 'I';
/// <summary>
/// Identifies the next file on the tape as having a long link name
/// </summary>
public const byte LF_GNU_LONGLINK = (byte) 'K';
/// <summary>
/// Identifies the next file on the tape as having a long name
/// </summary>
public const byte LF_GNU_LONGNAME = (byte) 'L';
/// <summary>
/// Continuation of a file that began on another volume
/// </summary>
public const byte LF_GNU_MULTIVOL = (byte) 'M';
/// <summary>
/// For storing filenames that dont fit in the main header (old GNU)
/// </summary>
public const byte LF_GNU_NAMES = (byte) 'N';
/// <summary>
/// GNU Sparse file
/// </summary>
public const byte LF_GNU_SPARSE = (byte) 'S';
/// <summary>
/// GNU Tape/volume header ignore on extraction
/// </summary>
public const byte LF_GNU_VOLHDR = (byte) 'V';
/// <summary>
/// The magic tag representing a POSIX tar archive. (includes trailing NULL)
/// </summary>
public readonly static string TMAGIC = "ustar ";
/// <summary>
/// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it
/// </summary>
public readonly static string GNU_TMAGIC = "ustar ";
/// <summary>
/// The entry's name.
/// </summary>
public StringBuilder name;
/// <summary>
/// The entry's Unix style permission mode.
/// </summary>
public int mode;
/// <summary>
/// The entry's user id.
/// </summary>
public int userId;
/// <summary>
/// The entry's group id.
/// </summary>
public int groupId;
/// <summary>
/// The entry's size.
/// </summary>
public long size;
/// <summary>
/// The entry's modification time.
/// </summary>
public DateTime modTime;
/// <summary>
/// The entry's checksum.
/// </summary>
public int checkSum;
/// <summary>
/// The entry's type flag.
/// </summary>
public byte typeFlag;
/// <summary>
/// The entry's link name.
/// </summary>
public StringBuilder linkName;
/// <summary>
/// The entry's magic tag.
/// </summary>
public StringBuilder magic;
/// <summary>
/// The entry's version.
/// </summary>
public StringBuilder version;
/// <summary>
/// The entry's user name.
/// </summary>
public StringBuilder userName;
/// <summary>
/// The entry's group name.
/// </summary>
public StringBuilder groupName;
/// <summary>
/// The entry's major device number.
/// </summary>
public int devMajor;
/// <summary>
/// The entry's minor device number.
/// </summary>
public int devMinor;
/// <summary>
/// Construct default TarHeader instance
/// </summary>
public TarHeader()
{
this.magic = new StringBuilder(TarHeader.TMAGIC);
this.version = new StringBuilder(" ");
this.name = new StringBuilder();
this.linkName = new StringBuilder();
#if COMPACT_FRAMEWORK
string user = "PocketPC";
#else
string user = Environment.UserName;
#endif
if (user.Length > 31) {
user = user.Substring(0, 31);
}
this.userId = 0;
this.groupId = 0;
this.userName = new StringBuilder(user);
this.groupName = new StringBuilder("None");
this.size = 0;
}
/// <summary>
/// TarHeaders can be cloned.
/// </summary>
public object Clone()
{
TarHeader hdr = new TarHeader();
hdr.name = (this.name == null) ? null : new StringBuilder(this.name.ToString());
hdr.mode = this.mode;
hdr.userId = this.userId;
hdr.groupId = this.groupId;
hdr.size = this.size;
hdr.modTime = this.modTime;
hdr.checkSum = this.checkSum;
hdr.typeFlag = this.typeFlag;
hdr.linkName = (this.linkName == null) ? null : new StringBuilder(this.linkName.ToString());
hdr.magic = (this.magic == null) ? null : new StringBuilder(this.magic.ToString());
hdr.version = (this.version == null) ? null : new StringBuilder(this.version.ToString());
hdr.userName = (this.userName == null) ? null : new StringBuilder(this.userName.ToString());
hdr.groupName = (this.groupName == null) ? null : new StringBuilder(this.groupName.ToString());
hdr.devMajor = this.devMajor;
hdr.devMinor = this.devMinor;
return hdr;
}
/// <summary>
/// Get the name of this entry.
/// </summary>
/// <returns>
/// The entry's name.
/// </returns>
public string GetName()
{
return this.name.ToString();
}
/// <summary>
/// Parse an octal string from a header buffer. This is used for the
/// file permission mode value.
/// </summary>
/// <param name = "header">
/// The header buffer from which to parse.
/// </param>
/// <param name = "offset">
/// The offset into the buffer from which to parse.
/// </param>
/// <param name = "length">
/// The number of header bytes to parse.
/// </param>
/// <returns>
/// The long value of the octal string.
/// </returns>
public static long ParseOctal(byte[] header, int offset, int length)
{
long result = 0;
bool stillPadding = true;
int end = offset + length;
for (int i = offset; i < end ; ++i) {
if (header[i] == 0) {
break;
}
if (header[i] == (byte)' ' || header[i] == '0') {
if (stillPadding) {
continue;
}
if (header[i] == (byte)' ') {
break;
}
}
stillPadding = false;
result = (result << 3) + (header[i] - '0');
}
return result;
}
/// <summary>
/// Parse an entry name from a header buffer.
/// </summary>
/// <param name="header">
/// The header buffer from which to parse.
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to parse.
/// </param>
/// <param name="length">
/// The number of header bytes to parse.
/// </param>
/// <returns>
/// The header's entry name.
/// </returns>
public static StringBuilder ParseName(byte[] header, int offset, int length)
{
StringBuilder result = new StringBuilder(length);
for (int i = offset; i < offset + length; ++i) {
if (header[i] == 0) {
break;
}
result.Append((char)header[i]);
}
return result;
}
/// <summary>
/// Add <paramref name="name">name</paramref> to the buffer as a collection of bytes
/// </summary>
/// <param name="name">the name to add</param>
/// <param name="nameOffset">the offset of the first character</param>
/// <param name="buf">the buffer to add to</param>
/// <param name="bufferOffset">the index of the first byte to add</param>
/// <param name="length">the number of characters/bytes to add</param>
/// <returns>the next free index in the <paramref name="buf">buffer</paramref></returns>
public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buf, int bufferOffset, int length)
{
int i;
for (i = 0 ; i < length && nameOffset + i < name.Length; ++i) {
buf[bufferOffset + i] = (byte)name[nameOffset + i];
}
for (; i < length ; ++i) {
buf[bufferOffset + i] = 0;
}
return bufferOffset + length;
}
/// <summary>
/// Add an entry name to the buffer
/// </summary>
/// <param name="name">
/// The name to add
/// </param>
/// <param name="buf">
/// The buffer to add to
/// </param>
/// <param name="offset">
/// The offset into the buffer from which to start adding
/// </param>
/// <param name="length">
/// The number of header bytes to add
/// </param>
/// <returns>
/// The index of the next free byte in the buffer
/// </returns>
public static int GetNameBytes(StringBuilder name, byte[] buf, int offset, int length)
{
return GetNameBytes(name, 0, buf, offset, length);
}
/// <summary>
/// Put an octal representation of a value into a buffer
/// </summary>
/// <param name = "val">
/// the value to be converted to octal
/// </param>
/// <param name = "buf">
/// buffer to store the octal string
/// </param>
/// <param name = "offset">
/// The offset into the buffer where the value starts
/// </param>
/// <param name = "length">
/// The length of the octal string to create
/// </param>
/// <returns>
/// The offset of the character next byte after the octal string
/// </returns>
public static int GetOctalBytes(long val, byte[] buf, int offset, int length)
{
int idx = length - 1;
// Either a space or null is valid here. We use NULL as per GNUTar
buf[offset + idx] = 0;
--idx;
if (val > 0) {
for (long v = val; idx >= 0 && v > 0; --idx) {
buf[offset + idx] = (byte)((byte)'0' + (byte)(v & 7));
v >>= 3;
}
}
for (; idx >= 0; --idx) {
buf[offset + idx] = (byte)'0';
}
return offset + length;
}
/// <summary>
/// Put an octal representation of a value into a buffer
/// </summary>
/// <param name = "val">
/// Value to be convert to octal
/// </param>
/// <param name = "buf">
/// The buffer to update
/// </param>
/// <param name = "offset">
/// The offset into the buffer to store the value
/// </param>
/// <param name = "length">
/// The length of the octal string
/// </param>
/// <returns>
/// Index of next byte
/// </returns>
public static int GetLongOctalBytes(long val, byte[] buf, int offset, int length)
{
return GetOctalBytes(val, buf, offset, length);
}
/// <summary>
/// Add the checksum octal integer to header buffer.
/// </summary>
/// <param name = "val">
/// </param>
/// <param name = "buf">
/// The header buffer to set the checksum for
/// </param>
/// <param name = "offset">
/// The offset into the buffer for the checksum
/// </param>
/// <param name = "length">
/// The number of header bytes to update.
/// It's formatted differently from the other fields: it has 6 digits, a
/// null, then a space -- rather than digits, a space, then a null.
/// The final space is already there, from checksumming
/// </param>
/// <returns>
/// The modified buffer offset
/// </returns>
private static int GetCheckSumOctalBytes(long val, byte[] buf, int offset, int length)
{
TarHeader.GetOctalBytes(val, buf, offset, length - 1);
// buf[offset + length - 1] = (byte)' '; -jr- 23-Jan-2004 this causes failure!!!
// buf[offset + length - 2] = 0;
return offset + length;
}
/// <summary>
/// Compute the checksum for a tar entry header.
/// The checksum field must be all spaces prior to this happening
/// </summary>
/// <param name = "buf">
/// The tar entry's header buffer.
/// </param>
/// <returns>
/// The computed checksum.
/// </returns>
private static long ComputeCheckSum(byte[] buf)
{
long sum = 0;
for (int i = 0; i < buf.Length; ++i) {
sum += buf[i];
}
return sum;
}
readonly static long timeConversionFactor = 10000000L; // -jr- 1 tick == 100 nanoseconds
readonly static DateTime datetTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
// readonly static DateTime datetTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToUniversalTime(); // -jr- Should be UTC? doesnt match Gnutar if this is so though, why?
static int GetCTime(System.DateTime dateTime)
{
return (int)((dateTime.Ticks - datetTime1970.Ticks) / timeConversionFactor);
}
static DateTime GetDateTimeFromCTime(long ticks)
{
return new DateTime(datetTime1970.Ticks + ticks * timeConversionFactor);
}
/// <summary>
/// Parse TarHeader information from a header buffer.
/// </summary>
/// <param name = "header">
/// The tar entry header buffer to get information from.
/// </param>
public void ParseBuffer(byte[] header)
{
int offset = 0;
name = TarHeader.ParseName(header, offset, TarHeader.NAMELEN);
offset += TarHeader.NAMELEN;
mode = (int)TarHeader.ParseOctal(header, offset, TarHeader.MODELEN);
offset += TarHeader.MODELEN;
userId = (int)TarHeader.ParseOctal(header, offset, TarHeader.UIDLEN);
offset += TarHeader.UIDLEN;
groupId = (int)TarHeader.ParseOctal(header, offset, TarHeader.GIDLEN);
offset += TarHeader.GIDLEN;
size = TarHeader.ParseOctal(header, offset, TarHeader.SIZELEN);
offset += TarHeader.SIZELEN;
modTime = GetDateTimeFromCTime(TarHeader.ParseOctal(header, offset, TarHeader.MODTIMELEN));
offset += TarHeader.MODTIMELEN;
checkSum = (int)TarHeader.ParseOctal(header, offset, TarHeader.CHKSUMLEN);
offset += TarHeader.CHKSUMLEN;
typeFlag = header[ offset++ ];
linkName = TarHeader.ParseName(header, offset, TarHeader.NAMELEN);
offset += TarHeader.NAMELEN;
magic = TarHeader.ParseName(header, offset, TarHeader.MAGICLEN);
offset += TarHeader.MAGICLEN;
version = TarHeader.ParseName(header, offset, TarHeader.VERSIONLEN);
offset += TarHeader.VERSIONLEN;
userName = TarHeader.ParseName(header, offset, TarHeader.UNAMELEN);
offset += TarHeader.UNAMELEN;
groupName = TarHeader.ParseName(header, offset, TarHeader.GNAMELEN);
offset += TarHeader.GNAMELEN;
devMajor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN);
offset += TarHeader.DEVLEN;
devMinor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN);
// Fields past this point not currently parsed or used...
}
/// <summary>
/// 'Write' header information to buffer provided
/// </summary>
/// <param name="outbuf">output buffer for header information</param>
public void WriteHeader(byte[] outbuf)
{
int offset = 0;
offset = GetNameBytes(this.name, outbuf, offset, TarHeader.NAMELEN);
offset = GetOctalBytes(this.mode, outbuf, offset, TarHeader.MODELEN);
offset = GetOctalBytes(this.userId, outbuf, offset, TarHeader.UIDLEN);
offset = GetOctalBytes(this.groupId, outbuf, offset, TarHeader.GIDLEN);
long size = this.size;
offset = GetLongOctalBytes(size, outbuf, offset, TarHeader.SIZELEN);
offset = GetLongOctalBytes(GetCTime(this.modTime), outbuf, offset, TarHeader.MODTIMELEN);
int csOffset = offset;
for (int c = 0; c < TarHeader.CHKSUMLEN; ++c) {
outbuf[offset++] = (byte)' ';
}
outbuf[offset++] = this.typeFlag;
offset = GetNameBytes(this.linkName, outbuf, offset, NAMELEN);
offset = GetNameBytes(this.magic, outbuf, offset, MAGICLEN);
offset = GetNameBytes(this.version, outbuf, offset, VERSIONLEN);
offset = GetNameBytes(this.userName, outbuf, offset, UNAMELEN);
offset = GetNameBytes(this.groupName, outbuf, offset, GNAMELEN);
if (this.typeFlag == LF_CHR || this.typeFlag == LF_BLK) {
offset = GetOctalBytes(this.devMajor, outbuf, offset, DEVLEN);
offset = GetOctalBytes(this.devMinor, outbuf, offset, DEVLEN);
}
for ( ; offset < outbuf.Length; ) {
outbuf[offset++] = 0;
}
long checkSum = ComputeCheckSum(outbuf);
GetCheckSumOctalBytes(checkSum, outbuf, csOffset, CHKSUMLEN);
}
}
}
/* The original Java file had this header:
*
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Syndication
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Schema;
using System.Collections;
using DiagnosticUtility = System.ServiceModel.DiagnosticUtility;
using System.ServiceModel.Channels;
using System.Runtime.CompilerServices;
[XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)]
public class Atom10FeedFormatter : SyndicationFeedFormatter, IXmlSerializable
{
internal static readonly TimeSpan zeroOffset = new TimeSpan(0, 0, 0);
internal const string XmlNs = "http://www.w3.org/XML/1998/namespace";
internal const string XmlNsNs = "http://www.w3.org/2000/xmlns/";
private static readonly XmlQualifiedName s_atom10Href = new XmlQualifiedName(Atom10Constants.HrefTag, string.Empty);
private static readonly XmlQualifiedName s_atom10Label = new XmlQualifiedName(Atom10Constants.LabelTag, string.Empty);
private static readonly XmlQualifiedName s_atom10Length = new XmlQualifiedName(Atom10Constants.LengthTag, string.Empty);
private static readonly XmlQualifiedName s_atom10Relative = new XmlQualifiedName(Atom10Constants.RelativeTag, string.Empty);
private static readonly XmlQualifiedName s_atom10Scheme = new XmlQualifiedName(Atom10Constants.SchemeTag, string.Empty);
private static readonly XmlQualifiedName s_atom10Term = new XmlQualifiedName(Atom10Constants.TermTag, string.Empty);
private static readonly XmlQualifiedName s_atom10Title = new XmlQualifiedName(Atom10Constants.TitleTag, string.Empty);
private static readonly XmlQualifiedName s_atom10Type = new XmlQualifiedName(Atom10Constants.TypeTag, string.Empty);
private static readonly UriGenerator s_idGenerator = new UriGenerator();
private const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz";
private const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
private Type _feedType;
private int _maxExtensionSize;
private bool _preserveAttributeExtensions;
private bool _preserveElementExtensions;
public Atom10FeedFormatter()
: this(typeof(SyndicationFeed))
{
}
public Atom10FeedFormatter(Type feedTypeToCreate)
: base()
{
if (feedTypeToCreate == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feedTypeToCreate");
}
if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("feedTypeToCreate",
SR.Format(SR.InvalidObjectTypePassed, "feedTypeToCreate", "SyndicationFeed"));
}
_maxExtensionSize = int.MaxValue;
_preserveAttributeExtensions = _preserveElementExtensions = true;
_feedType = feedTypeToCreate;
}
public Atom10FeedFormatter(SyndicationFeed feedToWrite)
: base(feedToWrite)
{
// No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
_maxExtensionSize = int.MaxValue;
_preserveAttributeExtensions = _preserveElementExtensions = true;
_feedType = feedToWrite.GetType();
}
public bool PreserveAttributeExtensions
{
get { return _preserveAttributeExtensions; }
set { _preserveAttributeExtensions = value; }
}
public bool PreserveElementExtensions
{
get { return _preserveElementExtensions; }
set { _preserveElementExtensions = value; }
}
public override string Version
{
get { return SyndicationVersions.Atom10; }
}
protected Type FeedType
{
get
{
return _feedType;
}
}
public override bool CanRead(XmlReader reader)
{
if (reader == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
}
return reader.IsStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace);
}
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")]
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")]
void IXmlSerializable.ReadXml(XmlReader reader)
{
if (reader == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
}
TraceFeedReadBegin();
ReadFeed(reader);
TraceFeedReadEnd();
}
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")]
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
TraceFeedWriteBegin();
WriteFeed(writer);
TraceFeedWriteEnd();
}
public override void ReadFrom(XmlReader reader)
{
TraceFeedReadBegin();
if (!CanRead(reader))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI)));
}
ReadFeed(reader);
TraceFeedReadEnd();
}
public override void WriteTo(XmlWriter writer)
{
if (writer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
}
TraceFeedWriteBegin();
writer.WriteStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace);
WriteFeed(writer);
writer.WriteEndElement();
TraceFeedWriteEnd();
}
internal static void ReadCategory(XmlReader reader, SyndicationCategory category, string version, bool preserveAttributeExtensions, bool preserveElementExtensions, int maxExtensionSize)
{
MoveToStartElement(reader);
bool isEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == Atom10Constants.TermTag && reader.NamespaceURI == string.Empty)
{
category.Name = reader.Value;
}
else if (reader.LocalName == Atom10Constants.SchemeTag && reader.NamespaceURI == string.Empty)
{
category.Scheme = reader.Value;
}
else if (reader.LocalName == Atom10Constants.LabelTag && reader.NamespaceURI == string.Empty)
{
category.Label = reader.Value;
}
else
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (FeedUtils.IsXmlns(name, ns))
{
continue;
}
string val = reader.Value;
if (!TryParseAttribute(name, ns, val, category, version))
{
if (preserveAttributeExtensions)
{
category.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
}
}
}
}
}
if (!isEmpty)
{
reader.ReadStartElement();
XmlBuffer buffer = null;
XmlDictionaryWriter extWriter = null;
try
{
while (reader.IsStartElement())
{
if (TryParseElement(reader, category, version))
{
continue;
}
else if (!preserveElementExtensions)
{
TraceSyndicationElementIgnoredOnRead(reader);
reader.Skip();
}
else
{
CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, maxExtensionSize);
}
}
LoadElementExtensions(buffer, extWriter, category);
}
finally
{
if (extWriter != null)
{
((IDisposable)extWriter).Dispose();
}
}
reader.ReadEndElement();
}
else
{
reader.ReadStartElement();
}
}
internal static TextSyndicationContent ReadTextContentFrom(XmlReader reader, string context, bool preserveAttributeExtensions)
{
string type = reader.GetAttribute(Atom10Constants.TypeTag);
return ReadTextContentFromHelper(reader, type, context, preserveAttributeExtensions);
}
internal static void WriteCategory(XmlWriter writer, SyndicationCategory category, string version)
{
writer.WriteStartElement(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace);
WriteAttributeExtensions(writer, category, version);
string categoryName = category.Name ?? string.Empty;
if (!category.AttributeExtensions.ContainsKey(s_atom10Term))
{
writer.WriteAttributeString(Atom10Constants.TermTag, categoryName);
}
if (!string.IsNullOrEmpty(category.Label) && !category.AttributeExtensions.ContainsKey(s_atom10Label))
{
writer.WriteAttributeString(Atom10Constants.LabelTag, category.Label);
}
if (!string.IsNullOrEmpty(category.Scheme) && !category.AttributeExtensions.ContainsKey(s_atom10Scheme))
{
writer.WriteAttributeString(Atom10Constants.SchemeTag, category.Scheme);
}
WriteElementExtensions(writer, category, version);
writer.WriteEndElement();
}
internal void ReadItemFrom(XmlReader reader, SyndicationItem result)
{
ReadItemFrom(reader, result, null);
}
internal bool TryParseFeedElementFrom(XmlReader reader, SyndicationFeed result)
{
if (reader.IsStartElement(Atom10Constants.AuthorTag, Atom10Constants.Atom10Namespace))
{
result.Authors.Add(ReadPersonFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace))
{
result.Categories.Add(ReadCategoryFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.ContributorTag, Atom10Constants.Atom10Namespace))
{
result.Contributors.Add(ReadPersonFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.GeneratorTag, Atom10Constants.Atom10Namespace))
{
result.Generator = reader.ReadElementString();
}
else if (reader.IsStartElement(Atom10Constants.IdTag, Atom10Constants.Atom10Namespace))
{
result.Id = reader.ReadElementString();
}
else if (reader.IsStartElement(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace))
{
result.Links.Add(ReadLinkFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.LogoTag, Atom10Constants.Atom10Namespace))
{
result.ImageUrl = new Uri(reader.ReadElementString(), UriKind.RelativeOrAbsolute);
}
else if (reader.IsStartElement(Atom10Constants.RightsTag, Atom10Constants.Atom10Namespace))
{
result.Copyright = ReadTextContentFrom(reader, "//atom:feed/atom:rights[@type]");
}
else if (reader.IsStartElement(Atom10Constants.SubtitleTag, Atom10Constants.Atom10Namespace))
{
result.Description = ReadTextContentFrom(reader, "//atom:feed/atom:subtitle[@type]");
}
else if (reader.IsStartElement(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace))
{
result.Title = ReadTextContentFrom(reader, "//atom:feed/atom:title[@type]");
}
else if (reader.IsStartElement(Atom10Constants.UpdatedTag, Atom10Constants.Atom10Namespace))
{
reader.ReadStartElement();
result.LastUpdatedTime = DateFromString(reader.ReadString(), reader);
reader.ReadEndElement();
}
else
{
return false;
}
return true;
}
internal bool TryParseItemElementFrom(XmlReader reader, SyndicationItem result)
{
if (reader.IsStartElement(Atom10Constants.AuthorTag, Atom10Constants.Atom10Namespace))
{
result.Authors.Add(ReadPersonFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace))
{
result.Categories.Add(ReadCategoryFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.ContentTag, Atom10Constants.Atom10Namespace))
{
result.Content = ReadContentFrom(reader, result);
}
else if (reader.IsStartElement(Atom10Constants.ContributorTag, Atom10Constants.Atom10Namespace))
{
result.Contributors.Add(ReadPersonFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.IdTag, Atom10Constants.Atom10Namespace))
{
result.Id = reader.ReadElementString();
}
else if (reader.IsStartElement(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace))
{
result.Links.Add(ReadLinkFrom(reader, result));
}
else if (reader.IsStartElement(Atom10Constants.PublishedTag, Atom10Constants.Atom10Namespace))
{
reader.ReadStartElement();
result.PublishDate = DateFromString(reader.ReadString(), reader);
reader.ReadEndElement();
}
else if (reader.IsStartElement(Atom10Constants.RightsTag, Atom10Constants.Atom10Namespace))
{
result.Copyright = ReadTextContentFrom(reader, "//atom:feed/atom:entry/atom:rights[@type]");
}
else if (reader.IsStartElement(Atom10Constants.SourceFeedTag, Atom10Constants.Atom10Namespace))
{
reader.ReadStartElement();
result.SourceFeed = ReadFeedFrom(reader, new SyndicationFeed(), true); // isSourceFeed
reader.ReadEndElement();
}
else if (reader.IsStartElement(Atom10Constants.SummaryTag, Atom10Constants.Atom10Namespace))
{
result.Summary = ReadTextContentFrom(reader, "//atom:feed/atom:entry/atom:summary[@type]");
}
else if (reader.IsStartElement(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace))
{
result.Title = ReadTextContentFrom(reader, "//atom:feed/atom:entry/atom:title[@type]");
}
else if (reader.IsStartElement(Atom10Constants.UpdatedTag, Atom10Constants.Atom10Namespace))
{
reader.ReadStartElement();
result.LastUpdatedTime = DateFromString(reader.ReadString(), reader);
reader.ReadEndElement();
}
else
{
return false;
}
return true;
}
internal void WriteContentTo(XmlWriter writer, string elementName, SyndicationContent content)
{
if (content != null)
{
content.WriteTo(writer, elementName, Atom10Constants.Atom10Namespace);
}
}
internal void WriteElement(XmlWriter writer, string elementName, string value)
{
if (value != null)
{
writer.WriteElementString(elementName, Atom10Constants.Atom10Namespace, value);
}
}
internal void WriteFeedAuthorsTo(XmlWriter writer, Collection<SyndicationPerson> authors)
{
for (int i = 0; i < authors.Count; ++i)
{
SyndicationPerson p = authors[i];
WritePersonTo(writer, p, Atom10Constants.AuthorTag);
}
}
internal void WriteFeedContributorsTo(XmlWriter writer, Collection<SyndicationPerson> contributors)
{
for (int i = 0; i < contributors.Count; ++i)
{
SyndicationPerson p = contributors[i];
WritePersonTo(writer, p, Atom10Constants.ContributorTag);
}
}
internal void WriteFeedLastUpdatedTimeTo(XmlWriter writer, DateTimeOffset lastUpdatedTime, bool isRequired)
{
if (lastUpdatedTime == DateTimeOffset.MinValue && isRequired)
{
lastUpdatedTime = DateTimeOffset.UtcNow;
}
if (lastUpdatedTime != DateTimeOffset.MinValue)
{
WriteElement(writer, Atom10Constants.UpdatedTag, AsString(lastUpdatedTime));
}
}
internal void WriteItemAuthorsTo(XmlWriter writer, Collection<SyndicationPerson> authors)
{
for (int i = 0; i < authors.Count; ++i)
{
SyndicationPerson p = authors[i];
WritePersonTo(writer, p, Atom10Constants.AuthorTag);
}
}
internal void WriteItemContents(XmlWriter dictWriter, SyndicationItem item)
{
WriteItemContents(dictWriter, item, null);
}
internal void WriteItemContributorsTo(XmlWriter writer, Collection<SyndicationPerson> contributors)
{
for (int i = 0; i < contributors.Count; ++i)
{
SyndicationPerson p = contributors[i];
WritePersonTo(writer, p, Atom10Constants.ContributorTag);
}
}
internal void WriteItemLastUpdatedTimeTo(XmlWriter writer, DateTimeOffset lastUpdatedTime)
{
if (lastUpdatedTime == DateTimeOffset.MinValue)
{
lastUpdatedTime = DateTimeOffset.UtcNow;
}
writer.WriteElementString(Atom10Constants.UpdatedTag,
Atom10Constants.Atom10Namespace,
AsString(lastUpdatedTime));
}
internal void WriteLink(XmlWriter writer, SyndicationLink link, Uri baseUri)
{
writer.WriteStartElement(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace);
Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri);
if (baseUriToWrite != null)
{
writer.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite));
}
link.WriteAttributeExtensions(writer, SyndicationVersions.Atom10);
if (!string.IsNullOrEmpty(link.RelationshipType) && !link.AttributeExtensions.ContainsKey(s_atom10Relative))
{
writer.WriteAttributeString(Atom10Constants.RelativeTag, link.RelationshipType);
}
if (!string.IsNullOrEmpty(link.MediaType) && !link.AttributeExtensions.ContainsKey(s_atom10Type))
{
writer.WriteAttributeString(Atom10Constants.TypeTag, link.MediaType);
}
if (!string.IsNullOrEmpty(link.Title) && !link.AttributeExtensions.ContainsKey(s_atom10Title))
{
writer.WriteAttributeString(Atom10Constants.TitleTag, link.Title);
}
if (link.Length != 0 && !link.AttributeExtensions.ContainsKey(s_atom10Length))
{
writer.WriteAttributeString(Atom10Constants.LengthTag, Convert.ToString(link.Length, CultureInfo.InvariantCulture));
}
if (!link.AttributeExtensions.ContainsKey(s_atom10Href))
{
writer.WriteAttributeString(Atom10Constants.HrefTag, FeedUtils.GetUriString(link.Uri));
}
link.WriteElementExtensions(writer, SyndicationVersions.Atom10);
writer.WriteEndElement();
}
protected override SyndicationFeed CreateFeedInstance()
{
return SyndicationFeedFormatter.CreateFeedInstance(_feedType);
}
protected virtual SyndicationItem ReadItem(XmlReader reader, SyndicationFeed feed)
{
if (feed == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed");
}
if (reader == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
}
SyndicationItem item = CreateItem(feed);
TraceItemReadBegin();
ReadItemFrom(reader, item, feed.BaseUri);
TraceItemReadEnd();
return item;
}
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "The out parameter is needed to enable implementations that read in items from the stream on demand")]
protected virtual IEnumerable<SyndicationItem> ReadItems(XmlReader reader, SyndicationFeed feed, out bool areAllItemsRead)
{
if (feed == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed");
}
if (reader == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
}
NullNotAllowedCollection<SyndicationItem> items = new NullNotAllowedCollection<SyndicationItem>();
while (reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace))
{
items.Add(ReadItem(reader, feed));
}
areAllItemsRead = true;
return items;
}
protected virtual void WriteItem(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
{
TraceItemWriteBegin();
writer.WriteStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace);
WriteItemContents(writer, item, feedBaseUri);
writer.WriteEndElement();
TraceItemWriteEnd();
}
protected virtual void WriteItems(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri)
{
if (items == null)
{
return;
}
foreach (SyndicationItem item in items)
{
this.WriteItem(writer, item, feedBaseUri);
}
}
private static TextSyndicationContent ReadTextContentFromHelper(XmlReader reader, string type, string context, bool preserveAttributeExtensions)
{
if (string.IsNullOrEmpty(type))
{
type = Atom10Constants.PlaintextType;
}
TextSyndicationContentKind kind;
switch (type)
{
case Atom10Constants.PlaintextType:
kind = TextSyndicationContentKind.Plaintext;
break;
case Atom10Constants.HtmlType:
kind = TextSyndicationContentKind.Html;
break;
case Atom10Constants.XHtmlType:
kind = TextSyndicationContentKind.XHtml;
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(FeedUtils.AddLineInfo(reader, SR.Format(SR.Atom10SpecRequiresTextConstruct, context, type))));
}
Dictionary<XmlQualifiedName, string> attrs = null;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty)
{
continue;
}
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (FeedUtils.IsXmlns(name, ns))
{
continue;
}
if (preserveAttributeExtensions)
{
string value = reader.Value;
if (attrs == null)
{
attrs = new Dictionary<XmlQualifiedName, string>();
}
attrs.Add(new XmlQualifiedName(name, ns), value);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
}
}
}
reader.MoveToElement();
string val = (kind == TextSyndicationContentKind.XHtml) ? reader.ReadInnerXml() : reader.ReadElementString();
TextSyndicationContent result = new TextSyndicationContent(val, kind);
if (attrs != null)
{
foreach (XmlQualifiedName attr in attrs.Keys)
{
if (!FeedUtils.IsXmlns(attr.Name, attr.Namespace))
{
result.AttributeExtensions.Add(attr, attrs[attr]);
}
}
}
return result;
}
private string AsString(DateTimeOffset dateTime)
{
if (dateTime.Offset == zeroOffset)
{
return dateTime.ToUniversalTime().ToString(Rfc3339UTCDateTimeFormat, CultureInfo.InvariantCulture);
}
else
{
return dateTime.ToString(Rfc3339LocalDateTimeFormat, CultureInfo.InvariantCulture);
}
}
private DateTimeOffset DateFromString(string dateTimeString, XmlReader reader)
{
dateTimeString = dateTimeString.Trim();
if (dateTimeString.Length < 20)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new XmlException(FeedUtils.AddLineInfo(reader,
SR.ErrorParsingDateTime)));
}
if (dateTimeString[19] == '.')
{
// remove any fractional seconds, we choose to ignore them
int i = 20;
while (dateTimeString.Length > i && char.IsDigit(dateTimeString[i]))
{
++i;
}
dateTimeString = dateTimeString.Substring(0, 19) + dateTimeString.Substring(i);
}
DateTimeOffset localTime;
if (DateTimeOffset.TryParseExact(dateTimeString, Rfc3339LocalDateTimeFormat,
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.None, out localTime))
{
return localTime;
}
DateTimeOffset utcTime;
if (DateTimeOffset.TryParseExact(dateTimeString, Rfc3339UTCDateTimeFormat,
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out utcTime))
{
return utcTime;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new XmlException(FeedUtils.AddLineInfo(reader,
SR.ErrorParsingDateTime)));
}
private void ReadCategory(XmlReader reader, SyndicationCategory category)
{
ReadCategory(reader, category, this.Version, this.PreserveAttributeExtensions, this.PreserveElementExtensions, _maxExtensionSize);
}
private SyndicationCategory ReadCategoryFrom(XmlReader reader, SyndicationFeed feed)
{
SyndicationCategory result = CreateCategory(feed);
ReadCategory(reader, result);
return result;
}
private SyndicationCategory ReadCategoryFrom(XmlReader reader, SyndicationItem item)
{
SyndicationCategory result = CreateCategory(item);
ReadCategory(reader, result);
return result;
}
private SyndicationContent ReadContentFrom(XmlReader reader, SyndicationItem item)
{
MoveToStartElement(reader);
string type = reader.GetAttribute(Atom10Constants.TypeTag, string.Empty);
SyndicationContent result;
if (TryParseContent(reader, item, type, this.Version, out result))
{
return result;
}
if (string.IsNullOrEmpty(type))
{
type = Atom10Constants.PlaintextType;
}
string src = reader.GetAttribute(Atom10Constants.SourceTag, string.Empty);
if (string.IsNullOrEmpty(src) && type != Atom10Constants.PlaintextType && type != Atom10Constants.HtmlType && type != Atom10Constants.XHtmlType)
{
return new XmlSyndicationContent(reader);
}
if (!string.IsNullOrEmpty(src))
{
result = new UrlSyndicationContent(new Uri(src, UriKind.RelativeOrAbsolute), type);
bool isEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty)
{
continue;
}
else if (reader.LocalName == Atom10Constants.SourceTag && reader.NamespaceURI == string.Empty)
{
continue;
}
else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI))
{
if (_preserveAttributeExtensions)
{
result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
}
}
}
}
reader.ReadStartElement();
if (!isEmpty)
{
reader.ReadEndElement();
}
return result;
}
else
{
return ReadTextContentFromHelper(reader, type, "//atom:feed/atom:entry/atom:content[@type]", _preserveAttributeExtensions);
}
}
private void ReadFeed(XmlReader reader)
{
SetFeed(CreateFeedInstance());
ReadFeedFrom(reader, this.Feed, false);
}
private SyndicationFeed ReadFeedFrom(XmlReader reader, SyndicationFeed result, bool isSourceFeed)
{
reader.MoveToContent();
try
{
bool elementIsEmpty = false;
if (!isSourceFeed)
{
MoveToStartElement(reader);
elementIsEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == "lang" && reader.NamespaceURI == XmlNs)
{
result.Language = reader.Value;
}
else if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs)
{
result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, reader.Value);
}
else
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
{
continue;
}
string val = reader.Value;
if (!TryParseAttribute(name, ns, val, result, this.Version))
{
if (_preserveAttributeExtensions)
{
result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
}
}
}
}
}
reader.ReadStartElement();
}
XmlBuffer buffer = null;
XmlDictionaryWriter extWriter = null;
bool areAllItemsRead = true;
bool readItemsAtLeastOnce = false;
if (!elementIsEmpty)
{
try
{
while (reader.IsStartElement())
{
if (TryParseFeedElementFrom(reader, result))
{
// nothing, we parsed something, great
}
else if (reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace) && !isSourceFeed)
{
if (readItemsAtLeastOnce)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR.Format(SR.FeedHasNonContiguousItems, this.GetType().ToString())));
}
result.Items = ReadItems(reader, result, out areAllItemsRead);
readItemsAtLeastOnce = true;
// if the derived class is reading the items lazily, then stop reading from the stream
if (!areAllItemsRead)
{
break;
}
}
else
{
if (!TryParseElement(reader, result, this.Version))
{
if (_preserveElementExtensions)
{
CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
reader.Skip();
}
}
}
}
LoadElementExtensions(buffer, extWriter, result);
}
finally
{
if (extWriter != null)
{
((IDisposable)extWriter).Dispose();
}
}
}
if (!isSourceFeed && areAllItemsRead)
{
reader.ReadEndElement(); // feed
}
}
catch (FormatException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e));
}
catch (ArgumentException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e));
}
return result;
}
private void ReadItemFrom(XmlReader reader, SyndicationItem result, Uri feedBaseUri)
{
try
{
result.BaseUri = feedBaseUri;
MoveToStartElement(reader);
bool isEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (name == "base" && ns == XmlNs)
{
result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, reader.Value);
continue;
}
if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
{
continue;
}
string val = reader.Value;
if (!TryParseAttribute(name, ns, val, result, this.Version))
{
if (_preserveAttributeExtensions)
{
result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
}
}
}
}
reader.ReadStartElement();
if (!isEmpty)
{
XmlBuffer buffer = null;
XmlDictionaryWriter extWriter = null;
try
{
while (reader.IsStartElement())
{
if (TryParseItemElementFrom(reader, result))
{
// nothing, we parsed something, great
}
else
{
if (!TryParseElement(reader, result, this.Version))
{
if (_preserveElementExtensions)
{
CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
reader.Skip();
}
}
}
}
LoadElementExtensions(buffer, extWriter, result);
}
finally
{
if (extWriter != null)
{
((IDisposable)extWriter).Dispose();
}
}
reader.ReadEndElement(); // item
}
}
catch (FormatException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e));
}
catch (ArgumentException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e));
}
}
private void ReadLink(XmlReader reader, SyndicationLink link, Uri baseUri)
{
bool isEmpty = reader.IsEmptyElement;
string mediaType = null;
string relationship = null;
string title = null;
string lengthStr = null;
string val = null;
link.BaseUri = baseUri;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs)
{
link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, reader.Value);
}
else if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty)
{
mediaType = reader.Value;
}
else if (reader.LocalName == Atom10Constants.RelativeTag && reader.NamespaceURI == string.Empty)
{
relationship = reader.Value;
}
else if (reader.LocalName == Atom10Constants.TitleTag && reader.NamespaceURI == string.Empty)
{
title = reader.Value;
}
else if (reader.LocalName == Atom10Constants.LengthTag && reader.NamespaceURI == string.Empty)
{
lengthStr = reader.Value;
}
else if (reader.LocalName == Atom10Constants.HrefTag && reader.NamespaceURI == string.Empty)
{
val = reader.Value;
}
else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI))
{
if (_preserveAttributeExtensions)
{
link.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
}
}
}
}
long length = 0;
if (!string.IsNullOrEmpty(lengthStr))
{
length = Convert.ToInt64(lengthStr, CultureInfo.InvariantCulture.NumberFormat);
}
reader.ReadStartElement();
if (!isEmpty)
{
XmlBuffer buffer = null;
XmlDictionaryWriter extWriter = null;
try
{
while (reader.IsStartElement())
{
if (TryParseElement(reader, link, this.Version))
{
continue;
}
else if (!_preserveElementExtensions)
{
SyndicationFeedFormatter.TraceSyndicationElementIgnoredOnRead(reader);
reader.Skip();
}
else
{
CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize);
}
}
LoadElementExtensions(buffer, extWriter, link);
}
finally
{
if (extWriter != null)
{
((IDisposable)extWriter).Dispose();
}
}
reader.ReadEndElement();
}
link.Length = length;
link.MediaType = mediaType;
link.RelationshipType = relationship;
link.Title = title;
link.Uri = (val != null) ? new Uri(val, UriKind.RelativeOrAbsolute) : null;
}
private SyndicationLink ReadLinkFrom(XmlReader reader, SyndicationFeed feed)
{
SyndicationLink result = CreateLink(feed);
ReadLink(reader, result, feed.BaseUri);
return result;
}
private SyndicationLink ReadLinkFrom(XmlReader reader, SyndicationItem item)
{
SyndicationLink result = CreateLink(item);
ReadLink(reader, result, item.BaseUri);
return result;
}
private SyndicationPerson ReadPersonFrom(XmlReader reader, SyndicationFeed feed)
{
SyndicationPerson result = CreatePerson(feed);
ReadPersonFrom(reader, result);
return result;
}
private SyndicationPerson ReadPersonFrom(XmlReader reader, SyndicationItem item)
{
SyndicationPerson result = CreatePerson(item);
ReadPersonFrom(reader, result);
return result;
}
private void ReadPersonFrom(XmlReader reader, SyndicationPerson result)
{
bool isEmpty = reader.IsEmptyElement;
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
string ns = reader.NamespaceURI;
string name = reader.LocalName;
if (FeedUtils.IsXmlns(name, ns))
{
continue;
}
string val = reader.Value;
if (!TryParseAttribute(name, ns, val, result, this.Version))
{
if (_preserveAttributeExtensions)
{
result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
}
}
}
}
reader.ReadStartElement();
if (!isEmpty)
{
XmlBuffer buffer = null;
XmlDictionaryWriter extWriter = null;
try
{
while (reader.IsStartElement())
{
if (reader.IsStartElement(Atom10Constants.NameTag, Atom10Constants.Atom10Namespace))
{
result.Name = reader.ReadElementString();
}
else if (reader.IsStartElement(Atom10Constants.UriTag, Atom10Constants.Atom10Namespace))
{
result.Uri = reader.ReadElementString();
}
else if (reader.IsStartElement(Atom10Constants.EmailTag, Atom10Constants.Atom10Namespace))
{
result.Email = reader.ReadElementString();
}
else
{
if (!TryParseElement(reader, result, this.Version))
{
if (_preserveElementExtensions)
{
CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize);
}
else
{
TraceSyndicationElementIgnoredOnRead(reader);
reader.Skip();
}
}
}
}
LoadElementExtensions(buffer, extWriter, result);
}
finally
{
if (extWriter != null)
{
((IDisposable)extWriter).Dispose();
}
}
reader.ReadEndElement();
}
}
private TextSyndicationContent ReadTextContentFrom(XmlReader reader, string context)
{
return ReadTextContentFrom(reader, context, this.PreserveAttributeExtensions);
}
private void WriteCategoriesTo(XmlWriter writer, Collection<SyndicationCategory> categories)
{
for (int i = 0; i < categories.Count; ++i)
{
WriteCategory(writer, categories[i], this.Version);
}
}
private void WriteFeed(XmlWriter writer)
{
if (this.Feed == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.FeedFormatterDoesNotHaveFeed)));
}
WriteFeedTo(writer, this.Feed, false); // isSourceFeed
}
private void WriteFeedTo(XmlWriter writer, SyndicationFeed feed, bool isSourceFeed)
{
if (!isSourceFeed)
{
if (!string.IsNullOrEmpty(feed.Language))
{
writer.WriteAttributeString("xml", "lang", XmlNs, feed.Language);
}
if (feed.BaseUri != null)
{
writer.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(feed.BaseUri));
}
WriteAttributeExtensions(writer, feed, this.Version);
}
bool isElementRequired = !isSourceFeed;
TextSyndicationContent title = feed.Title;
if (isElementRequired)
{
title = title ?? new TextSyndicationContent(string.Empty);
}
WriteContentTo(writer, Atom10Constants.TitleTag, title);
WriteContentTo(writer, Atom10Constants.SubtitleTag, feed.Description);
string id = feed.Id;
if (isElementRequired)
{
id = id ?? s_idGenerator.Next();
}
WriteElement(writer, Atom10Constants.IdTag, id);
WriteContentTo(writer, Atom10Constants.RightsTag, feed.Copyright);
WriteFeedLastUpdatedTimeTo(writer, feed.LastUpdatedTime, isElementRequired);
WriteCategoriesTo(writer, feed.Categories);
if (feed.ImageUrl != null)
{
WriteElement(writer, Atom10Constants.LogoTag, feed.ImageUrl.ToString());
}
WriteFeedAuthorsTo(writer, feed.Authors);
WriteFeedContributorsTo(writer, feed.Contributors);
WriteElement(writer, Atom10Constants.GeneratorTag, feed.Generator);
for (int i = 0; i < feed.Links.Count; ++i)
{
WriteLink(writer, feed.Links[i], feed.BaseUri);
}
WriteElementExtensions(writer, feed, this.Version);
if (!isSourceFeed)
{
WriteItems(writer, feed.Items, feed.BaseUri);
}
}
private void WriteItemContents(XmlWriter dictWriter, SyndicationItem item, Uri feedBaseUri)
{
Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri);
if (baseUriToWrite != null)
{
dictWriter.WriteAttributeString("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite));
}
WriteAttributeExtensions(dictWriter, item, this.Version);
string id = item.Id ?? s_idGenerator.Next();
WriteElement(dictWriter, Atom10Constants.IdTag, id);
TextSyndicationContent title = item.Title ?? new TextSyndicationContent(string.Empty);
WriteContentTo(dictWriter, Atom10Constants.TitleTag, title);
WriteContentTo(dictWriter, Atom10Constants.SummaryTag, item.Summary);
if (item.PublishDate != DateTimeOffset.MinValue)
{
dictWriter.WriteElementString(Atom10Constants.PublishedTag,
Atom10Constants.Atom10Namespace,
AsString(item.PublishDate));
}
WriteItemLastUpdatedTimeTo(dictWriter, item.LastUpdatedTime);
WriteItemAuthorsTo(dictWriter, item.Authors);
WriteItemContributorsTo(dictWriter, item.Contributors);
for (int i = 0; i < item.Links.Count; ++i)
{
WriteLink(dictWriter, item.Links[i], item.BaseUri);
}
WriteCategoriesTo(dictWriter, item.Categories);
WriteContentTo(dictWriter, Atom10Constants.ContentTag, item.Content);
WriteContentTo(dictWriter, Atom10Constants.RightsTag, item.Copyright);
if (item.SourceFeed != null)
{
dictWriter.WriteStartElement(Atom10Constants.SourceFeedTag, Atom10Constants.Atom10Namespace);
WriteFeedTo(dictWriter, item.SourceFeed, true); // isSourceFeed
dictWriter.WriteEndElement();
}
WriteElementExtensions(dictWriter, item, this.Version);
}
private void WritePersonTo(XmlWriter writer, SyndicationPerson p, string elementName)
{
writer.WriteStartElement(elementName, Atom10Constants.Atom10Namespace);
WriteAttributeExtensions(writer, p, this.Version);
WriteElement(writer, Atom10Constants.NameTag, p.Name);
if (!string.IsNullOrEmpty(p.Uri))
{
writer.WriteElementString(Atom10Constants.UriTag, Atom10Constants.Atom10Namespace, p.Uri);
}
if (!string.IsNullOrEmpty(p.Email))
{
writer.WriteElementString(Atom10Constants.EmailTag, Atom10Constants.Atom10Namespace, p.Email);
}
WriteElementExtensions(writer, p, this.Version);
writer.WriteEndElement();
}
}
[XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)]
public class Atom10FeedFormatter<TSyndicationFeed> : Atom10FeedFormatter
where TSyndicationFeed : SyndicationFeed, new()
{
// constructors
public Atom10FeedFormatter()
: base(typeof(TSyndicationFeed))
{
}
public Atom10FeedFormatter(TSyndicationFeed feedToWrite)
: base(feedToWrite)
{
}
protected override SyndicationFeed CreateFeedInstance()
{
return new TSyndicationFeed();
}
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class UserAccountServicesConnector : BaseServiceConnector, IUserAccountService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
public UserAccountServicesConnector()
{
}
public UserAccountServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public UserAccountServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig assetConfig = source.Configs["UserAccountService"];
if (assetConfig == null)
{
m_log.Error("[ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini");
throw new Exception("User account connector init error");
}
string serviceURI = assetConfig.GetString("UserAccountServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[ACCOUNT CONNECTOR]: No Server URI named in section UserAccountService");
throw new Exception("User account connector init error");
}
m_ServerURI = serviceURI;
base.Initialise(source, "UserAccountService");
}
public virtual UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["FirstName"] = firstName.ToString();
sendData["LastName"] = lastName.ToString();
return SendAndGetReply(sendData);
}
public virtual UserAccount GetUserAccount(UUID scopeID, string email)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["Email"] = email;
return SendAndGetReply(sendData);
}
public virtual UserAccount GetUserAccount(UUID scopeID, UUID userID)
{
//m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccount {0}", userID);
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccount";
sendData["ScopeID"] = scopeID;
sendData["UserID"] = userID.ToString();
return SendAndGetReply(sendData);
}
public List<UserAccount> GetUserAccounts(UUID scopeID, string query)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "getaccounts";
sendData["ScopeID"] = scopeID.ToString();
sendData["query"] = query;
string reply = string.Empty;
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/accounts";
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString,
m_Auth);
if (reply == null || (reply != null && reply == string.Empty))
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received null or empty reply");
return null;
}
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
}
List<UserAccount> accounts = new List<UserAccount>();
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
if (replyData.ContainsKey("result") && replyData["result"].ToString() == "null")
{
return accounts;
}
Dictionary<string, object>.ValueCollection accountList = replyData.Values;
//m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count);
foreach (object acc in accountList)
{
if (acc is Dictionary<string, object>)
{
UserAccount pinfo = new UserAccount((Dictionary<string, object>)acc);
accounts.Add(pinfo);
}
else
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received invalid response type {0}",
acc.GetType());
}
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccounts received null response");
return accounts;
}
public void InvalidateCache(UUID userID)
{
}
public virtual bool StoreUserAccount(UserAccount data)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
//sendData["SCOPEID"] = scopeID.ToString();
sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString();
sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString();
sendData["METHOD"] = "setaccount";
Dictionary<string, object> structData = data.ToKeyValuePairs();
foreach (KeyValuePair<string, object> kvp in structData)
{
if (kvp.Value == null)
{
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Null value for {0}", kvp.Key);
continue;
}
sendData[kvp.Key] = kvp.Value.ToString();
}
return SendAndGetBoolReply(sendData);
}
private UserAccount SendAndGetReply(Dictionary<string, object> sendData)
{
string reply = string.Empty;
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/accounts";
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString,
m_Auth);
if (reply == null || (reply != null && reply == string.Empty))
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccount received null or empty reply");
return null;
}
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
UserAccount account = null;
if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
{
account = new UserAccount((Dictionary<string, object>)replyData["result"]);
}
}
return account;
}
private bool SendAndGetBoolReply(Dictionary<string, object> sendData)
{
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/accounts";
// m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString,
m_Auth);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("result"))
{
if (replyData["result"].ToString().ToLower() == "success")
return true;
else
return false;
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount reply data does not contain result field");
}
else
m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount received empty reply");
}
catch (Exception e)
{
m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message);
}
return 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;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Diagnostics;
using Internal.Runtime.Augments;
namespace System
{
public class Exception : ISerializable
{
private void Init()
{
_message = null;
HResult = __HResults.COR_E_EXCEPTION;
}
public Exception()
{
Init();
}
public Exception(String message)
{
Init();
_message = message;
}
// Creates a new Exception. All derived classes should
// provide this constructor.
// Note: the stack trace is not started until the exception
// is thrown
//
public Exception(String message, Exception innerException)
{
Init();
_message = message;
_innerException = innerException;
}
protected Exception(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
public virtual String Message
{
get
{
if (_message == null)
{
String className = GetClassName();
return SR.Format(SR.Exception_WasThrown, className);
}
else
{
return _message;
}
}
}
public virtual IDictionary Data
{
get
{
if (_data == null)
_data = new LowLevelListDictionary();
return _data;
}
}
#region Interop Helpers
internal class __RestrictedErrorObject
{
private object _realErrorObject;
internal __RestrictedErrorObject(object errorObject)
{
_realErrorObject = errorObject;
}
public object RealErrorObject
{
get
{
return _realErrorObject;
}
}
}
internal void AddExceptionDataForRestrictedErrorInfo(
string restrictedError,
string restrictedErrorReference,
string restrictedCapabilitySid,
object restrictedErrorObject)
{
IDictionary dict = Data;
if (dict != null)
{
dict.Add("RestrictedDescription", restrictedError);
dict.Add("RestrictedErrorReference", restrictedErrorReference);
dict.Add("RestrictedCapabilitySid", restrictedCapabilitySid);
// Keep the error object alive so that user could retrieve error information
// using Data["RestrictedErrorReference"]
dict.Add("__RestrictedErrorObject", (restrictedErrorObject == null ? null : new __RestrictedErrorObject(restrictedErrorObject)));
}
}
internal bool TryGetRestrictedErrorObject(out object restrictedErrorObject)
{
restrictedErrorObject = null;
if (Data != null && Data.Contains("__RestrictedErrorObject"))
{
__RestrictedErrorObject restrictedObject = Data["__RestrictedErrorObject"] as __RestrictedErrorObject;
if (restrictedObject != null)
{
restrictedErrorObject = restrictedObject.RealErrorObject;
return true;
}
}
return false;
}
internal bool TryGetRestrictedErrorDetails(out string restrictedError, out string restrictedErrorReference, out string restrictedCapabilitySid)
{
if (Data != null && Data.Contains("__RestrictedErrorObject"))
{
// We might not need to store this value any more.
restrictedError = (string)Data["RestrictedDescription"];
restrictedErrorReference = (string)Data[nameof(restrictedErrorReference)];
restrictedCapabilitySid = (string)Data["RestrictedCapabilitySid"];
return true;
}
else
{
restrictedError = null;
restrictedErrorReference = null;
restrictedCapabilitySid = null;
return false;
}
}
/// <summary>
/// Allow System.Private.Interop to set HRESULT of an exception
/// </summary>
internal void SetErrorCode(int hr)
{
HResult = hr;
}
/// <summary>
/// Allow System.Private.Interop to set message of an exception
/// </summary>
internal void SetMessage(string msg)
{
_message = msg;
}
#endregion
private string GetClassName()
{
return GetType().ToString();
}
// Retrieves the lowest exception (inner most) for the given Exception.
// This will traverse exceptions using the innerException property.
//
public virtual Exception GetBaseException()
{
Exception inner = InnerException;
Exception back = this;
while (inner != null)
{
back = inner;
inner = inner.InnerException;
}
return back;
}
// Returns the inner exception contained in this exception
//
public Exception InnerException
{
get { return _innerException; }
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
private string GetStackTrace(bool needFileInfo)
{
return this.StackTrace;
}
public virtual String HelpLink
{
get
{
return _helpURL;
}
set
{
_helpURL = value;
}
}
public virtual String Source
{
get
{
if (_source == null && HasBeenThrown)
{
_source = "<unknown>";
}
return _source;
}
set
{
_source = value;
}
}
public override String ToString()
{
return ToString(true, true);
}
private String ToString(bool needFileLineInfo, bool needMessage)
{
String message = (needMessage ? Message : null);
String s;
if (message == null || message.Length <= 0)
{
s = GetClassName();
}
else
{
s = GetClassName() + ": " + message;
}
if (_innerException != null)
{
s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine +
" " + SR.Exception_EndOfInnerExceptionStack;
}
string stackTrace = GetStackTrace(needFileLineInfo);
if (stackTrace != null)
{
s += Environment.NewLine + stackTrace;
}
return s;
}
// WARNING: We allow diagnostic tools to directly inspect these three members (_message, _innerException and _HResult)
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
internal String _message;
private IDictionary _data;
private Exception _innerException;
private String _helpURL;
private String _source; // Mainly used by VB.
private int _HResult; // HResult
public int HResult
{
get { return _HResult; }
protected set { _HResult = value; }
}
// Returns the stack trace as a string. If no stack trace is
// available, null is returned.
public virtual String StackTrace
{
get
{
if (!HasBeenThrown)
return null;
return StackTraceHelper.FormatStackTrace(GetStackIPs(), true);
}
}
internal IntPtr[] GetStackIPs()
{
IntPtr[] ips = new IntPtr[_idxFirstFreeStackTraceEntry];
if (_corDbgStackTrace != null)
{
Array.Copy(_corDbgStackTrace, ips, ips.Length);
}
return ips;
}
// WARNING: We allow diagnostic tools to directly inspect these two members (_corDbgStackTrace and _idxFirstFreeStackTraceEntry)
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
// _corDbgStackTrace: Do not rename: This is for the use of the CorDbg interface. Contains the stack trace as an array of EIP's (ordered from
// most nested call to least.) May also include a few "special" IP's from the SpecialIP class:
private IntPtr[] _corDbgStackTrace;
private int _idxFirstFreeStackTraceEntry;
private void AppendStackIP(IntPtr IP, bool isFirstRethrowFrame)
{
Debug.Assert(!(this is OutOfMemoryException), "Avoid allocations if out of memory");
if (_idxFirstFreeStackTraceEntry == 0)
{
_corDbgStackTrace = new IntPtr[16];
}
else if (isFirstRethrowFrame)
{
// For the first frame after rethrow, we replace the last entry in the stack trace with the IP
// of the rethrow. This is overwriting the IP of where control left the corresponding try
// region for the catch that is rethrowing.
_corDbgStackTrace[_idxFirstFreeStackTraceEntry - 1] = IP;
return;
}
if (_idxFirstFreeStackTraceEntry >= _corDbgStackTrace.Length)
GrowStackTrace();
_corDbgStackTrace[_idxFirstFreeStackTraceEntry++] = IP;
}
private void GrowStackTrace()
{
IntPtr[] newArray = new IntPtr[_corDbgStackTrace.Length * 2];
for (int i = 0; i < _corDbgStackTrace.Length; i++)
{
newArray[i] = _corDbgStackTrace[i];
}
_corDbgStackTrace = newArray;
}
private bool HasBeenThrown
{
get
{
return _idxFirstFreeStackTraceEntry != 0;
}
}
private enum RhEHFrameType
{
RH_EH_FIRST_FRAME = 1,
RH_EH_FIRST_RETHROW_FRAME = 2,
}
[RuntimeExport("AppendExceptionStackFrame")]
private static void AppendExceptionStackFrame(object exceptionObj, IntPtr IP, int flags)
{
// This method is called by the runtime's EH dispatch code and is not allowed to leak exceptions
// back into the dispatcher.
try
{
Exception ex = exceptionObj as Exception;
if (ex == null)
Environment.FailFast("Exceptions must derive from the System.Exception class");
if (!RuntimeExceptionHelpers.SafeToPerformRichExceptionSupport)
return;
bool isFirstFrame = (flags & (int)RhEHFrameType.RH_EH_FIRST_FRAME) != 0;
bool isFirstRethrowFrame = (flags & (int)RhEHFrameType.RH_EH_FIRST_RETHROW_FRAME) != 0;
// If out of memory, avoid any calls that may allocate. Otherwise, they may fail
// with another OutOfMemoryException, which may lead to infinite recursion.
bool outOfMemory = ex is OutOfMemoryException;
if (!outOfMemory)
ex.AppendStackIP(IP, isFirstRethrowFrame);
// CORERT-TODO: RhpEtwExceptionThrown
// https://github.com/dotnet/corert/issues/2457
#if !CORERT
if (isFirstFrame)
{
string typeName = !outOfMemory ? ex.GetType().ToString() : "System.OutOfMemoryException";
string message = !outOfMemory ? ex.Message :
"Insufficient memory to continue the execution of the program.";
unsafe
{
fixed (char* exceptionTypeName = typeName, exceptionMessage = message)
RuntimeImports.RhpEtwExceptionThrown(exceptionTypeName, exceptionMessage, IP, ex.HResult);
}
}
#endif
}
catch
{
// We may end up with a confusing stack trace or a confusing ETW trace log, but at least we
// can continue to dispatch this exception.
}
}
//==================================================================================================================
// Support for ExceptionDispatchInfo class - imports and exports the stack trace.
//==================================================================================================================
internal EdiCaptureState CaptureEdiState()
{
IntPtr[] stackTrace = _corDbgStackTrace;
if (stackTrace != null)
{
IntPtr[] newStackTrace = new IntPtr[stackTrace.Length];
Array.Copy(stackTrace, 0, newStackTrace, 0, stackTrace.Length);
stackTrace = newStackTrace;
}
return new EdiCaptureState() { StackTrace = stackTrace };
}
internal void RestoreEdiState(EdiCaptureState ediCaptureState)
{
IntPtr[] stackTrace = ediCaptureState.StackTrace;
int idxFirstFreeStackTraceEntry = 0;
if (stackTrace != null)
{
IntPtr[] newStackTrace = new IntPtr[stackTrace.Length + 1];
Array.Copy(stackTrace, 0, newStackTrace, 0, stackTrace.Length);
stackTrace = newStackTrace;
while (stackTrace[idxFirstFreeStackTraceEntry] != (IntPtr)0)
idxFirstFreeStackTraceEntry++;
stackTrace[idxFirstFreeStackTraceEntry++] = StackTraceHelper.SpecialIP.EdiSeparator;
}
// Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance,
// they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock.
lock (s_EDILock)
{
_corDbgStackTrace = stackTrace;
_idxFirstFreeStackTraceEntry = idxFirstFreeStackTraceEntry;
}
}
internal struct EdiCaptureState
{
public IntPtr[] StackTrace;
}
// This is the object against which a lock will be taken
// when attempt to restore the EDI. Since its static, its possible
// that unrelated exception object restorations could get blocked
// for a small duration but that sounds reasonable considering
// such scenarios are going to be extremely rare, where timing
// matches precisely.
private static Object s_EDILock = new Object();
/// <summary>
/// This is the binary format for serialized exceptions that get saved into a special buffer that is
/// known to WER (by way of a runtime API) and will be saved into triage dumps. This format is known
/// to SOS, so any changes must update CurrentSerializationVersion and have corresponding updates to
/// SOS.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct SERIALIZED_EXCEPTION_HEADER
{
internal IntPtr ExceptionEEType;
internal Int32 HResult;
internal Int32 StackTraceElementCount;
// IntPtr * N : StackTrace elements
}
internal const int CurrentSerializationSignature = 0x31305845; // 'EX01'
/// <summary>
/// This method performs the serialization of one Exception object into the returned byte[].
/// </summary>
internal unsafe byte[] SerializeForDump()
{
checked
{
int nStackTraceElements = _idxFirstFreeStackTraceEntry;
int cbBuffer = sizeof(SERIALIZED_EXCEPTION_HEADER) + (nStackTraceElements * IntPtr.Size);
byte[] buffer = new byte[cbBuffer];
fixed (byte* pBuffer = &buffer[0])
{
SERIALIZED_EXCEPTION_HEADER* pHeader = (SERIALIZED_EXCEPTION_HEADER*)pBuffer;
pHeader->HResult = _HResult;
pHeader->ExceptionEEType = m_pEEType;
pHeader->StackTraceElementCount = nStackTraceElements;
IntPtr* pStackTraceElements = (IntPtr*)(pBuffer + sizeof(SERIALIZED_EXCEPTION_HEADER));
for (int i = 0; i < nStackTraceElements; i++)
{
pStackTraceElements[i] = _corDbgStackTrace[i];
}
}
return buffer;
}
}
}
}
| |
/*
* 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.Reflection;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using System.Timers;
using OpenMetaverse;
using OpenMetaverse.Packets;
using log4net;
using OpenSim.Framework;
using Timer=System.Timers.Timer;
namespace OpenSim.Region.ClientStack.LindenUDP
{
public class LLPacketHandler : ILLPacketHandler
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
//private int m_resentCount;
// Packet queues
//
LLPacketQueue m_PacketQueue;
public LLPacketQueue PacketQueue
{
get { return m_PacketQueue; }
}
// Timer to run stats and acks on
//
private Timer m_AckTimer = new Timer(250);
// A list of the packets we haven't acked yet
//
private List<uint> m_PendingAcks = new List<uint>();
private Dictionary<uint, uint> m_PendingAcksMap = new Dictionary<uint, uint>();
private Dictionary<uint, LLQueItem> m_NeedAck =
new Dictionary<uint, LLQueItem>();
/// <summary>
/// The number of milliseconds that can pass before a packet that needs an ack is resent.
/// </param>
private uint m_ResendTimeout = 4000;
public uint ResendTimeout
{
get { return m_ResendTimeout; }
set { m_ResendTimeout = value; }
}
private int m_MaxReliableResends = 3;
public int MaxReliableResends
{
get { return m_MaxReliableResends; }
set { m_MaxReliableResends = value; }
}
// Track duplicated packets. This uses a Dictionary. Both insertion
// and lookup are common operations and need to take advantage of
// the hashing. Expiration is less common and can be allowed the
// time for a linear scan.
//
private List<uint> m_alreadySeenList = new List<uint>();
private Dictionary<uint, int>m_alreadySeenTracker = new Dictionary<uint, int>();
private int m_alreadySeenWindow = 30000;
private int m_lastAlreadySeenCheck = Environment.TickCount & Int32.MaxValue;
// private Dictionary<uint, int> m_DupeTracker =
// new Dictionary<uint, int>();
// private uint m_DupeTrackerWindow = 30;
// private int m_DupeTrackerLastCheck = Environment.TickCount;
// Values for the SimStatsReporter
//
private int m_PacketsReceived = 0;
private int m_PacketsReceivedReported = 0;
private int m_PacketsSent = 0;
private int m_PacketsSentReported = 0;
private int m_UnackedBytes = 0;
private int m_LastResend = 0;
public int PacketsReceived
{
get { return m_PacketsReceived; }
}
public int PacketsReceivedReported
{
get { return m_PacketsReceivedReported; }
}
// The client we are working for
//
private IClientAPI m_Client;
// Some events
//
public event PacketStats OnPacketStats;
public event PacketDrop OnPacketDrop;
//private SynchronizeClientHandler m_SynchronizeClient = null;
public SynchronizeClientHandler SynchronizeClient
{
set { /* m_SynchronizeClient = value; */ }
}
// Packet sequencing
//
private uint m_Sequence = 0;
private object m_SequenceLock = new object();
private const int MAX_SEQUENCE = 0xFFFFFF;
// Packet dropping
//
List<PacketType> m_ImportantPackets = new List<PacketType>();
private bool m_ReliableIsImportant = false;
public bool ReliableIsImportant
{
get { return m_ReliableIsImportant; }
set { m_ReliableIsImportant = value; }
}
private int m_DropSafeTimeout;
LLPacketServer m_PacketServer;
private byte[] m_ZeroOutBuffer = new byte[4096];
////////////////////////////////////////////////////////////////////
// Constructors
//
public LLPacketHandler(IClientAPI client, LLPacketServer server, ClientStackUserSettings userSettings)
{
m_Client = client;
m_PacketServer = server;
m_DropSafeTimeout = Environment.TickCount + 15000;
m_PacketQueue = new LLPacketQueue(client.AgentId, userSettings);
m_AckTimer.Elapsed += AckTimerElapsed;
m_AckTimer.Start();
}
public void Stop()
{
m_AckTimer.Stop();
m_PacketQueue.Enqueue(null);
m_PacketQueue.Close();
m_Client = null;
}
// Send one packet. This actually doesn't send anything, it queues
// it. Designed to be fire-and-forget, but there is an optional
// notifier.
//
public void OutPacket(
Packet packet, ThrottleOutPacketType throttlePacketType)
{
OutPacket(packet, throttlePacketType, null);
}
public void OutPacket(
Packet packet, ThrottleOutPacketType throttlePacketType,
Object id)
{
// Call the load balancer's hook. If this is not active here
// we defer to the sim server this client is actually connected
// to. Packet drop notifies will not be triggered in this
// configuration!
//
packet.Header.Sequence = 0;
lock (m_NeedAck)
{
DropResend(id);
AddAcks(ref packet);
QueuePacket(packet, throttlePacketType, id);
}
}
private void AddAcks(ref Packet packet)
{
// These packet types have shown to have issues with
// acks being appended to the payload, just don't send
// any with them until libsl is fixed.
//
if (packet is ViewerEffectPacket)
return;
if (packet is SimStatsPacket)
return;
// Add acks to outgoing packets
//
if (m_PendingAcks.Count > 0)
{
int count = m_PendingAcks.Count;
if (count > 10)
count = 10;
packet.Header.AckList = new uint[count];
packet.Header.AppendedAcks = true;
for (int i = 0; i < count; i++)
{
packet.Header.AckList[i] = m_PendingAcks[i];
m_PendingAcksMap.Remove(m_PendingAcks[i]);
}
m_PendingAcks.RemoveRange(0, count);
}
}
private void QueuePacket(
Packet packet, ThrottleOutPacketType throttlePacketType,
Object id)
{
LLQueItem item = new LLQueItem();
item.Packet = packet;
item.Incoming = false;
item.throttleType = throttlePacketType;
item.TickCount = Environment.TickCount;
item.Identifier = id;
item.Resends = 0;
item.Length = packet.Length;
item.Sequence = packet.Header.Sequence;
m_PacketQueue.Enqueue(item);
m_PacketsSent++;
}
private void ResendUnacked()
{
int now = Environment.TickCount;
int intervalMs = 250;
if (m_LastResend != 0)
intervalMs = now - m_LastResend;
lock (m_NeedAck)
{
if (m_DropSafeTimeout > now ||
intervalMs > 500) // We were frozen!
{
foreach (LLQueItem data in m_NeedAck.Values)
{
if (m_DropSafeTimeout > now)
{
m_NeedAck[data.Packet.Header.Sequence].TickCount = now;
}
else
{
m_NeedAck[data.Packet.Header.Sequence].TickCount += intervalMs;
}
}
}
m_LastResend = now;
// Unless we have received at least one ack, don't bother resending
// anything. There may not be a client there, don't clog up the
// pipes.
// Nothing to do
//
if (m_NeedAck.Count == 0)
return;
int resent = 0;
long dueDate = now - m_ResendTimeout;
List<LLQueItem> dropped = new List<LLQueItem>();
foreach (LLQueItem data in m_NeedAck.Values)
{
Packet packet = data.Packet;
// Packets this old get resent
//
if (data.TickCount < dueDate && data.Sequence != 0 && !m_PacketQueue.Contains(data.Sequence))
{
if (resent < 20) // Was 20 (= Max 117kbit/sec resends)
{
m_NeedAck[packet.Header.Sequence].Resends++;
// The client needs to be told that a packet is being resent, otherwise it appears to believe
// that it should reset its sequence to that packet number.
packet.Header.Resent = true;
if ((m_NeedAck[packet.Header.Sequence].Resends >= m_MaxReliableResends) &&
(!m_ReliableIsImportant))
{
dropped.Add(data);
continue;
}
m_NeedAck[packet.Header.Sequence].TickCount = Environment.TickCount;
QueuePacket(packet, ThrottleOutPacketType.Resend, data.Identifier);
resent++;
}
else
{
m_NeedAck[packet.Header.Sequence].TickCount += intervalMs;
}
}
}
foreach (LLQueItem data in dropped)
{
m_NeedAck.Remove(data.Packet.Header.Sequence);
TriggerOnPacketDrop(data.Packet, data.Identifier);
m_PacketQueue.Cancel(data.Packet.Header.Sequence);
PacketPool.Instance.ReturnPacket(data.Packet);
}
}
}
// Send the pending packet acks to the client
// Will send blocks of acks for up to 250 packets
//
private void SendAcks()
{
lock (m_NeedAck)
{
if (m_PendingAcks.Count == 0)
return;
PacketAckPacket acks = (PacketAckPacket)PacketPool.Instance.GetPacket(PacketType.PacketAck);
// The case of equality is more common than one might think,
// because this function will be called unconditionally when
// the counter reaches 250. So there is a good chance another
// packet with 250 blocks exists.
//
if (acks.Packets == null ||
acks.Packets.Length != m_PendingAcks.Count)
acks.Packets = new PacketAckPacket.PacketsBlock[m_PendingAcks.Count];
for (int i = 0; i < m_PendingAcks.Count; i++)
{
acks.Packets[i] = new PacketAckPacket.PacketsBlock();
acks.Packets[i].ID = m_PendingAcks[i];
}
m_PendingAcks.Clear();
m_PendingAcksMap.Clear();
acks.Header.Reliable = false;
OutPacket(acks, ThrottleOutPacketType.Unknown);
}
}
// Queue a packet ack. It will be sent either after 250 acks are
// queued, or when the timer fires.
//
private void AckPacket(Packet packet)
{
lock (m_NeedAck)
{
if (m_PendingAcks.Count < 250)
{
if (!m_PendingAcksMap.ContainsKey(packet.Header.Sequence))
{
m_PendingAcks.Add(packet.Header.Sequence);
m_PendingAcksMap.Add(packet.Header.Sequence,
packet.Header.Sequence);
}
return;
}
}
SendAcks();
lock (m_NeedAck)
{
// If this is still full we have a truly exceptional
// condition (means, can't happen)
//
if (m_PendingAcks.Count < 250)
{
if (!m_PendingAcksMap.ContainsKey(packet.Header.Sequence))
{
m_PendingAcks.Add(packet.Header.Sequence);
m_PendingAcksMap.Add(packet.Header.Sequence,
packet.Header.Sequence);
}
return;
}
}
}
// When the timer elapses, send the pending acks, trigger resends
// and report all the stats.
//
private void AckTimerElapsed(object sender, ElapsedEventArgs ea)
{
SendAcks();
ResendUnacked();
SendPacketStats();
}
// Push out pachet counts for the sim status reporter
//
private void SendPacketStats()
{
PacketStats handlerPacketStats = OnPacketStats;
if (handlerPacketStats != null)
{
handlerPacketStats(
m_PacketsReceived - m_PacketsReceivedReported,
m_PacketsSent - m_PacketsSentReported,
m_UnackedBytes);
m_PacketsReceivedReported = m_PacketsReceived;
m_PacketsSentReported = m_PacketsSent;
}
}
// We can't keep an unlimited record of dupes. This will prune the
// dictionary by age.
//
// NOTE: this needs to be called from within lock
// (m_alreadySeenTracker) context!
private void ExpireSeenPackets()
{
if (m_alreadySeenList.Count < 1024)
return;
int ticks = 0;
int tc = Environment.TickCount & Int32.MaxValue;
if (tc >= m_lastAlreadySeenCheck)
ticks = tc - m_lastAlreadySeenCheck;
else
ticks = Int32.MaxValue - m_lastAlreadySeenCheck + tc;
if (ticks < 2000) return;
m_lastAlreadySeenCheck = tc;
// we calculate the drop dead tick count here instead of
// in the loop: any packet with a timestamp before
// dropDeadTC can be expired
int dropDeadTC = tc - m_alreadySeenWindow;
int i = 0;
while (i < m_alreadySeenList.Count && m_alreadySeenTracker[m_alreadySeenList[i]] < dropDeadTC)
{
m_alreadySeenTracker.Remove(m_alreadySeenList[i]);
i++;
}
// if we dropped packet from m_alreadySeenTracker we need
// to drop them from m_alreadySeenList as well, let's do
// that in one go: the list is ordered after all.
if (i > 0)
{
m_alreadySeenList.RemoveRange(0, i);
// m_log.DebugFormat("[CLIENT]: expired {0} packets, {1}:{2} left", i, m_alreadySeenList.Count, m_alreadySeenTracker.Count);
}
}
public void InPacket(Packet packet)
{
if (packet == null)
return;
// When too many acks are needed to be sent, the client sends
// a packet consisting of acks only
//
if (packet.Type == PacketType.PacketAck)
{
PacketAckPacket ackPacket = (PacketAckPacket)packet;
foreach (PacketAckPacket.PacketsBlock block in ackPacket.Packets)
{
ProcessAck(block.ID);
}
PacketPool.Instance.ReturnPacket(packet);
return;
}
// Any packet can have some packet acks in the header.
// Process them here
//
if (packet.Header.AppendedAcks)
{
foreach (uint id in packet.Header.AckList)
{
ProcessAck(id);
}
}
// If this client is on another partial instance, no need
// to handle packets
//
if (!m_Client.IsActive && packet.Type != PacketType.LogoutRequest)
{
PacketPool.Instance.ReturnPacket(packet);
return;
}
if (packet.Type == PacketType.StartPingCheck)
{
StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
CompletePingCheckPacket endPing
= (CompletePingCheckPacket)PacketPool.Instance.GetPacket(PacketType.CompletePingCheck);
endPing.PingID.PingID = startPing.PingID.PingID;
OutPacket(endPing, ThrottleOutPacketType.Task);
}
else
{
LLQueItem item = new LLQueItem();
item.Packet = packet;
item.Incoming = true;
m_PacketQueue.Enqueue(item);
}
}
public void ProcessInPacket(LLQueItem item)
{
Packet packet = item.Packet;
// Always ack the packet!
//
if (packet.Header.Reliable)
AckPacket(packet);
if (packet.Type != PacketType.AgentUpdate)
m_PacketsReceived++;
// Check for duplicate packets.. packets that the client is
// resending because it didn't receive our ack
//
lock (m_alreadySeenTracker)
{
ExpireSeenPackets();
if (m_alreadySeenTracker.ContainsKey(packet.Header.Sequence))
return;
m_alreadySeenTracker.Add(packet.Header.Sequence, Environment.TickCount & Int32.MaxValue);
m_alreadySeenList.Add(packet.Header.Sequence);
}
m_Client.ProcessInPacket(packet);
}
public void Flush()
{
m_PacketQueue.Flush();
m_UnackedBytes = (-1 * m_UnackedBytes);
SendPacketStats();
}
public void Clear()
{
m_UnackedBytes = (-1 * m_UnackedBytes);
SendPacketStats();
lock (m_NeedAck)
{
m_NeedAck.Clear();
m_PendingAcks.Clear();
m_PendingAcksMap.Clear();
}
m_Sequence += 1000000;
}
private void ProcessAck(uint id)
{
LLQueItem data;
lock (m_NeedAck)
{
//m_log.DebugFormat("[CLIENT]: In {0} received ack for packet {1}", m_Client.Scene.RegionInfo.ExternalEndPoint.Port, id);
if (!m_NeedAck.TryGetValue(id, out data))
return;
m_NeedAck.Remove(id);
m_PacketQueue.Cancel(data.Sequence);
PacketPool.Instance.ReturnPacket(data.Packet);
m_UnackedBytes -= data.Length;
}
}
// Allocate packet sequence numbers in a threadsave manner
//
protected uint NextPacketSequenceNumber()
{
// Set the sequence number
uint seq = 1;
lock (m_SequenceLock)
{
if (m_Sequence >= MAX_SEQUENCE)
{
m_Sequence = 1;
}
else
{
m_Sequence++;
}
seq = m_Sequence;
}
return seq;
}
public ClientInfo GetClientInfo()
{
ClientInfo info = new ClientInfo();
info.pendingAcks = m_PendingAcksMap;
info.needAck = new Dictionary<uint, byte[]>();
lock (m_NeedAck)
{
foreach (uint key in m_NeedAck.Keys)
info.needAck.Add(key, m_NeedAck[key].Packet.ToBytes());
}
LLQueItem[] queitems = m_PacketQueue.GetQueueArray();
for (int i = 0; i < queitems.Length; i++)
{
if (queitems[i].Incoming == false)
info.out_packets.Add(queitems[i].Packet.ToBytes());
}
info.sequence = m_Sequence;
float multiplier = m_PacketQueue.ThrottleMultiplier;
info.resendThrottle = (int) (m_PacketQueue.ResendThrottle.Throttle / multiplier);
info.landThrottle = (int) (m_PacketQueue.LandThrottle.Throttle / multiplier);
info.windThrottle = (int) (m_PacketQueue.WindThrottle.Throttle / multiplier);
info.cloudThrottle = (int) (m_PacketQueue.CloudThrottle.Throttle / multiplier);
info.taskThrottle = (int) (m_PacketQueue.TaskThrottle.Throttle / multiplier);
info.assetThrottle = (int) (m_PacketQueue.AssetThrottle.Throttle / multiplier);
info.textureThrottle = (int) (m_PacketQueue.TextureThrottle.Throttle / multiplier);
info.totalThrottle = (int) (m_PacketQueue.TotalThrottle.Throttle / multiplier);
return info;
}
public void SetClientInfo(ClientInfo info)
{
m_PendingAcksMap = info.pendingAcks;
m_PendingAcks = new List<uint>(m_PendingAcksMap.Keys);
m_NeedAck = new Dictionary<uint, LLQueItem>();
Packet packet = null;
int packetEnd = 0;
byte[] zero = new byte[3000];
foreach (uint key in info.needAck.Keys)
{
byte[] buff = info.needAck[key];
packetEnd = buff.Length - 1;
try
{
packet = PacketPool.Instance.GetPacket(buff, ref packetEnd, zero);
}
catch (Exception)
{
}
LLQueItem item = new LLQueItem();
item.Packet = packet;
item.Incoming = false;
item.throttleType = 0;
item.TickCount = Environment.TickCount;
item.Identifier = 0;
item.Resends = 0;
item.Length = packet.Length;
item.Sequence = packet.Header.Sequence;
m_NeedAck.Add(key, item);
}
m_Sequence = info.sequence;
m_PacketQueue.ResendThrottle.Throttle = info.resendThrottle;
m_PacketQueue.LandThrottle.Throttle = info.landThrottle;
m_PacketQueue.WindThrottle.Throttle = info.windThrottle;
m_PacketQueue.CloudThrottle.Throttle = info.cloudThrottle;
m_PacketQueue.TaskThrottle.Throttle = info.taskThrottle;
m_PacketQueue.AssetThrottle.Throttle = info.assetThrottle;
m_PacketQueue.TextureThrottle.Throttle = info.textureThrottle;
m_PacketQueue.TotalThrottle.Throttle = info.totalThrottle;
}
public void AddImportantPacket(PacketType type)
{
if (m_ImportantPackets.Contains(type))
return;
m_ImportantPackets.Add(type);
}
public void RemoveImportantPacket(PacketType type)
{
if (!m_ImportantPackets.Contains(type))
return;
m_ImportantPackets.Remove(type);
}
private void DropResend(Object id)
{
LLQueItem d = null;
foreach (LLQueItem data in m_NeedAck.Values)
{
if (data.Identifier != null && data.Identifier == id)
{
d = data;
break;
}
}
if (null == d) return;
m_NeedAck.Remove(d.Packet.Header.Sequence);
m_PacketQueue.Cancel(d.Sequence);
PacketPool.Instance.ReturnPacket(d.Packet);
}
private void TriggerOnPacketDrop(Packet packet, Object id)
{
PacketDrop handlerPacketDrop = OnPacketDrop;
if (handlerPacketDrop == null)
return;
handlerPacketDrop(packet, id);
}
// Convert the packet to bytes and stuff it onto the send queue
//
public void ProcessOutPacket(LLQueItem item)
{
Packet packet = item.Packet;
// Assign sequence number here to prevent out of order packets
if (packet.Header.Sequence == 0)
{
lock (m_NeedAck)
{
packet.Header.Sequence = NextPacketSequenceNumber();
item.Sequence = packet.Header.Sequence;
item.TickCount = Environment.TickCount;
// We want to see that packet arrive if it's reliable
if (packet.Header.Reliable)
{
m_UnackedBytes += item.Length;
// Keep track of when this packet was sent out
item.TickCount = Environment.TickCount;
m_NeedAck[packet.Header.Sequence] = item;
}
}
}
// If we sent a killpacket
if (packet is KillPacket)
Abort();
try
{
// If this packet has been reused/returned, the ToBytes
// will blow up in our face.
// Fail gracefully.
//
// Actually make the byte array and send it
byte[] sendbuffer = item.Packet.ToBytes();
if (packet.Header.Zerocoded)
{
int packetsize = Helpers.ZeroEncode(sendbuffer,
sendbuffer.Length, m_ZeroOutBuffer);
m_PacketServer.SendPacketTo(m_ZeroOutBuffer, packetsize,
SocketFlags.None, m_Client.CircuitCode);
}
else
{
// Need some extra space in case we need to add proxy
// information to the message later
Buffer.BlockCopy(sendbuffer, 0, m_ZeroOutBuffer, 0,
sendbuffer.Length);
m_PacketServer.SendPacketTo(m_ZeroOutBuffer,
sendbuffer.Length, SocketFlags.None, m_Client.CircuitCode);
}
}
catch (NullReferenceException)
{
m_log.Error("[PACKET]: Detected reuse of a returned packet");
m_PacketQueue.Cancel(item.Sequence);
return;
}
// If this is a reliable packet, we are still holding a ref
// Dont't return in that case
//
if (!packet.Header.Reliable)
{
m_PacketQueue.Cancel(item.Sequence);
PacketPool.Instance.ReturnPacket(packet);
}
}
private void Abort()
{
m_PacketQueue.Close();
Thread.CurrentThread.Abort();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Text;
using OLEDB.Test.ModuleCore;
namespace System.Xml.XmlDiff
{
public enum NodePosition
{
Before = 0,
After = 1,
Unknown = 2,
Same = 3
}
public enum XmlDiffNodeType
{
Element = 0,
Attribute = 1,
ER = 2,
Text = 3,
CData = 4,
Comment = 5,
PI = 6,
WS = 7,
Document = 8
}
internal class PositionInfo : IXmlLineInfo
{
public virtual bool HasLineInfo() { return false; }
public virtual int LineNumber { get { return 0; } }
public virtual int LinePosition { get { return 0; } }
public static PositionInfo GetPositionInfo(Object o)
{
IXmlLineInfo lineInfo = o as IXmlLineInfo;
if (lineInfo != null && lineInfo.HasLineInfo())
{
return new ReaderPositionInfo(lineInfo);
}
else
{
return new PositionInfo();
}
}
}
internal class ReaderPositionInfo : PositionInfo
{
private IXmlLineInfo _mlineInfo;
public ReaderPositionInfo(IXmlLineInfo lineInfo)
{
_mlineInfo = lineInfo;
}
public override bool HasLineInfo() { return true; }
public override int LineNumber { get { return _mlineInfo.LineNumber; } }
public override int LinePosition
{
get { return _mlineInfo.LinePosition; }
}
}
public class XmlDiffDocument : XmlDiffNode
{
private bool _bLoaded;
private bool _bIgnoreAttributeOrder;
private bool _bIgnoreChildOrder;
private bool _bIgnoreComments;
private bool _bIgnoreWhitespace;
private bool _bIgnoreDTD;
private bool _bIgnoreNS;
private bool _bIgnorePrefix;
private bool _bCDataAsText;
private bool _bNormalizeNewline;
public XmlNameTable nameTable;
public XmlDiffDocument()
: base()
{
_bLoaded = false;
_bIgnoreAttributeOrder = false;
_bIgnoreChildOrder = false;
_bIgnoreComments = false;
_bIgnoreWhitespace = false;
_bIgnoreDTD = false;
_bCDataAsText = false;
}
public XmlDiffOption Option
{
set
{
this.IgnoreAttributeOrder = (((int)value & (int)(XmlDiffOption.IgnoreAttributeOrder)) > 0);
this.IgnoreChildOrder = (((int)value & (int)(XmlDiffOption.IgnoreChildOrder)) > 0);
this.IgnoreComments = (((int)value & (int)(XmlDiffOption.IgnoreComments)) > 0);
this.IgnoreWhitespace = (((int)value & (int)(XmlDiffOption.IgnoreWhitespace)) > 0);
this.IgnoreDTD = (((int)value & (int)(XmlDiffOption.IgnoreDTD)) > 0);
this.IgnoreNS = (((int)value & (int)(XmlDiffOption.IgnoreNS)) > 0);
this.IgnorePrefix = (((int)value & (int)(XmlDiffOption.IgnorePrefix)) > 0);
this.CDataAsText = (((int)value & (int)(XmlDiffOption.CDataAsText)) > 0);
this.NormalizeNewline = (((int)value & (int)(XmlDiffOption.NormalizeNewline)) > 0);
}
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Document; } }
public bool IgnoreAttributeOrder
{
get { return this._bIgnoreAttributeOrder; }
set { this._bIgnoreAttributeOrder = value; }
}
public bool IgnoreChildOrder
{
get { return this._bIgnoreChildOrder; }
set { this._bIgnoreChildOrder = value; }
}
public bool IgnoreComments
{
get { return this._bIgnoreComments; }
set { this._bIgnoreComments = value; }
}
public bool IgnoreWhitespace
{
get { return this._bIgnoreWhitespace; }
set { this._bIgnoreWhitespace = value; }
}
public bool IgnoreDTD
{
get { return this._bIgnoreDTD; }
set { this._bIgnoreDTD = value; }
}
public bool IgnoreNS
{
get { return this._bIgnoreNS; }
set { this._bIgnoreNS = value; }
}
public bool IgnorePrefix
{
get { return this._bIgnorePrefix; }
set { this._bIgnorePrefix = value; }
}
public bool CDataAsText
{
get { return this._bCDataAsText; }
set { this._bCDataAsText = value; }
}
public bool NormalizeNewline
{
get { return this._bNormalizeNewline; }
set { this._bNormalizeNewline = value; }
}
//NodePosition.Before is returned if node2 should be before node1;
//NodePosition.After is returned if node2 should be after node1;
//In any case, NodePosition.Unknown should never be returned.
internal NodePosition ComparePosition(XmlDiffNode node1, XmlDiffNode node2)
{
int nt1 = (int)(node1.NodeType);
int nt2 = (int)(node2.NodeType);
if (nt2 > nt1)
return NodePosition.After;
if (nt2 < nt1)
return NodePosition.Before;
//now nt1 == nt2
if (nt1 == (int)XmlDiffNodeType.Element)
{
return CompareElements(node1 as XmlDiffElement, node2 as XmlDiffElement);
}
else if (nt1 == (int)XmlDiffNodeType.Attribute)
{
return CompareAttributes(node1 as XmlDiffAttribute, node2 as XmlDiffAttribute);
}
else if (nt1 == (int)XmlDiffNodeType.ER)
{
return CompareERs(node1 as XmlDiffEntityReference, node2 as XmlDiffEntityReference);
}
else if (nt1 == (int)XmlDiffNodeType.PI)
{
return ComparePIs(node1 as XmlDiffProcessingInstruction, node2 as XmlDiffProcessingInstruction);
}
else if (node1 is XmlDiffCharacterData)
{
return CompareTextLikeNodes(node1 as XmlDiffCharacterData, node2 as XmlDiffCharacterData);
}
else
{
//something really wrong here, what should we do???
Debug.Assert(false, "ComparePosition meets an undecision situation.");
return NodePosition.Unknown;
}
}
private NodePosition CompareElements(XmlDiffElement elem1, XmlDiffElement elem2)
{
Debug.Assert(elem1 != null);
Debug.Assert(elem2 != null);
int nCompare = 0;
if ((nCompare = CompareText(elem2.LocalName, elem1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(elem2.NamespaceURI, elem1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(elem2.Prefix, elem1.Prefix)) == 0)
{
if ((nCompare = CompareText(elem2.Value, elem1.Value)) == 0)
{
if ((nCompare = CompareAttributes(elem2, elem1)) == 0)
{
return NodePosition.After;
}
}
}
}
}
if (nCompare > 0)
//elem2 > elem1
return NodePosition.After;
else
//elem2 < elem1
return NodePosition.Before;
}
private int CompareAttributes(XmlDiffElement elem1, XmlDiffElement elem2)
{
int count1 = elem1.AttributeCount;
int count2 = elem2.AttributeCount;
if (count1 > count2)
return 1;
else if (count1 < count2)
return -1;
else
{
XmlDiffAttribute current1 = elem1.FirstAttribute;
XmlDiffAttribute current2 = elem2.FirstAttribute;
// NodePosition result = 0;
int nCompare = 0;
while (current1 != null && current2 != null && nCompare == 0)
{
if ((nCompare = CompareText(current2.LocalName, current1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(current2.NamespaceURI, current1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(current2.Prefix, current1.Prefix)) == 0)
{
if ((nCompare = CompareText(current2.Value, current1.Value)) == 0)
{
//do nothing!
}
}
}
}
current1 = (XmlDiffAttribute)current1._next;
current2 = (XmlDiffAttribute)current2._next;
}
if (nCompare > 0)
//elem1 > attr2
return 1;
else
//elem1 < elem2
return -1;
}
}
private NodePosition CompareAttributes(XmlDiffAttribute attr1, XmlDiffAttribute attr2)
{
Debug.Assert(attr1 != null);
Debug.Assert(attr2 != null);
int nCompare = 0;
if ((nCompare = CompareText(attr2.LocalName, attr1.LocalName)) == 0)
{
if (IgnoreNS || (nCompare = CompareText(attr2.NamespaceURI, attr1.NamespaceURI)) == 0)
{
if (IgnorePrefix || (nCompare = CompareText(attr2.Prefix, attr1.Prefix)) == 0)
{
if ((nCompare = CompareText(attr2.Value, attr1.Value)) == 0)
{
return NodePosition.After;
}
}
}
}
if (nCompare > 0)
//attr2 > attr1
return NodePosition.After;
else
//attr2 < attr1
return NodePosition.Before;
}
private NodePosition CompareERs(XmlDiffEntityReference er1, XmlDiffEntityReference er2)
{
Debug.Assert(er1 != null);
Debug.Assert(er2 != null);
int nCompare = CompareText(er2.Name, er1.Name);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
private NodePosition ComparePIs(XmlDiffProcessingInstruction pi1, XmlDiffProcessingInstruction pi2)
{
Debug.Assert(pi1 != null);
Debug.Assert(pi2 != null);
int nCompare = 0;
if ((nCompare = CompareText(pi2.Name, pi1.Name)) == 0)
{
if ((nCompare = CompareText(pi2.Value, pi1.Value)) == 0)
{
return NodePosition.After;
}
}
if (nCompare > 0)
//pi2 > pi1
return NodePosition.After;
else
//pi2 < pi1
return NodePosition.Before;
}
private NodePosition CompareTextLikeNodes(XmlDiffCharacterData t1, XmlDiffCharacterData t2)
{
Debug.Assert(t1 != null);
Debug.Assert(t2 != null);
int nCompare = CompareText(t2.Value, t1.Value);
if (nCompare >= 0)
return NodePosition.After;
else
return NodePosition.Before;
}
//returns 0 if the same string; 1 if s1 > s1 and -1 if s1 < s2
private int CompareText(string s1, string s2)
{
int len = s1.Length;
//len becomes the smaller of the two
if (len > s2.Length)
len = s2.Length;
int nInd = 0;
char c1 = (char)0x0;
char c2 = (char)0x0;
while (nInd < len)
{
c1 = s1[nInd];
c2 = s2[nInd];
if (c1 < c2)
return -1; //s1 < s2
else if (c1 > c2)
return 1; //s1 > s2
nInd++;
}
if (s2.Length > s1.Length)
return -1; //s1 < s2
else if (s2.Length < s1.Length)
return 1; //s1 > s2
else return 0;
}
public virtual void Load(XmlReader reader)
{
if (_bLoaded)
throw new InvalidOperationException("The document already contains data and should not be used again.");
if (reader.ReadState == ReadState.Initial)
{
if (!reader.Read())
return;
}
PositionInfo pInfo = PositionInfo.GetPositionInfo(reader);
ReadChildNodes(this, reader, pInfo);
this._bLoaded = true;
this.nameTable = reader.NameTable;
}
internal void ReadChildNodes(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
bool lookAhead = false;
do
{
lookAhead = false;
switch (reader.NodeType)
{
case XmlNodeType.Element:
LoadElement(parent, reader, pInfo);
break;
case XmlNodeType.Comment:
if (!IgnoreComments)
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Comment);
break;
case XmlNodeType.ProcessingInstruction:
LoadPI(parent, reader, pInfo);
break;
case XmlNodeType.SignificantWhitespace:
if (reader.XmlSpace == XmlSpace.Preserve)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.WS);
}
break;
case XmlNodeType.CDATA:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.CData);
}
else //merge with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
LoadTextNode(parent, text.ToString(), pInfo, XmlDiffNodeType.Text);
}
break;
case XmlNodeType.Text:
if (!CDataAsText)
{
LoadTextNode(parent, reader, pInfo, XmlDiffNodeType.Text);
}
else //megre with adjacent text/CDATA nodes
{
StringBuilder text = new StringBuilder();
text.Append(reader.Value);
while ((lookAhead = reader.Read()) && (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA))
{
text.Append(reader.Value);
}
LoadTextNode(parent, text.ToString(), pInfo, XmlDiffNodeType.Text);
}
break;
case XmlNodeType.EntityReference:
LoadEntityReference(parent, reader, pInfo);
break;
case XmlNodeType.EndElement:
SetElementEndPosition(parent as XmlDiffElement, pInfo);
return;
case XmlNodeType.Attribute: //attribute at top level
string attrVal = reader.Name + "=\"" + reader.Value + "\"";
LoadTopLevelAttribute(parent, attrVal, pInfo, XmlDiffNodeType.Text);
break;
default:
break;
}
} while (lookAhead || reader.Read());
}
private void LoadElement(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffElement elem = null;
bool bEmptyElement = reader.IsEmptyElement;
if (bEmptyElement)
elem = new XmlDiffEmptyElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
else
elem = new XmlDiffElement(reader.LocalName, reader.Prefix, reader.NamespaceURI);
elem.LineNumber = pInfo.LineNumber;
elem.LinePosition = pInfo.LinePosition;
ReadAttributes(elem, reader, pInfo);
if (!bEmptyElement)
{
reader.Read(); //move to child
ReadChildNodes(elem, reader, pInfo);
}
InsertChild(parent, elem);
}
private void ReadAttributes(XmlDiffElement parent, XmlReader reader, PositionInfo pInfo)
{
if (reader.MoveToFirstAttribute())
{
XmlDiffAttribute attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value);
attr.LineNumber = pInfo.LineNumber;
attr.LinePosition = pInfo.LinePosition;
InsertAttribute(parent, attr);
while (reader.MoveToNextAttribute())
{
attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, reader.Value);
attr.LineNumber = pInfo.LineNumber;
attr.LinePosition = pInfo.LinePosition;
InsertAttribute(parent, attr);
}
}
}
private void LoadTextNode(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(reader.Value, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertChild(parent, textNode);
}
private void LoadTextNode(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertChild(parent, textNode);
}
private void LoadTopLevelAttribute(XmlDiffNode parent, string text, PositionInfo pInfo, XmlDiffNodeType nt)
{
XmlDiffCharacterData textNode = new XmlDiffCharacterData(text, nt, this.NormalizeNewline);
textNode.LineNumber = pInfo.LineNumber;
textNode.LinePosition = pInfo.LinePosition;
InsertTopLevelAttributeAsText(parent, textNode);
}
private void LoadPI(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffProcessingInstruction pi = new XmlDiffProcessingInstruction(reader.Name, reader.Value);
pi.LineNumber = pInfo.LineNumber;
pi.LinePosition = pInfo.LinePosition;
InsertChild(parent, pi);
}
private void LoadEntityReference(XmlDiffNode parent, XmlReader reader, PositionInfo pInfo)
{
XmlDiffEntityReference er = new XmlDiffEntityReference(reader.Name);
er.LineNumber = pInfo.LineNumber;
er.LinePosition = pInfo.LinePosition;
InsertChild(parent, er);
}
private void SetElementEndPosition(XmlDiffElement elem, PositionInfo pInfo)
{
Debug.Assert(elem != null);
elem.EndLineNumber = pInfo.LineNumber;
elem.EndLinePosition = pInfo.LinePosition;
}
private void InsertChild(XmlDiffNode parent, XmlDiffNode newChild)
{
if (IgnoreChildOrder)
{
XmlDiffNode child = parent.FirstChild;
XmlDiffNode prevChild = null;
while (child != null && (ComparePosition(child, newChild) == NodePosition.After))
{
prevChild = child;
child = child.NextSibling;
}
parent.InsertChildAfter(prevChild, newChild);
}
else
parent.InsertChildAfter(parent.LastChild, newChild);
}
private void InsertTopLevelAttributeAsText(XmlDiffNode parent, XmlDiffCharacterData newChild)
{
if (parent.LastChild != null && (parent.LastChild.NodeType == XmlDiffNodeType.Text || parent.LastChild.NodeType == XmlDiffNodeType.WS))
{
((XmlDiffCharacterData)parent.LastChild).Value = ((XmlDiffCharacterData)parent.LastChild).Value + " " + newChild.Value;
}
else
{
parent.InsertChildAfter(parent.LastChild, newChild);
}
}
private void InsertAttribute(XmlDiffElement parent, XmlDiffAttribute newAttr)
{
Debug.Assert(parent != null);
Debug.Assert(newAttr != null);
newAttr._parent = parent;
if (IgnoreAttributeOrder)
{
XmlDiffAttribute attr = parent.FirstAttribute;
XmlDiffAttribute prevAttr = null;
while (attr != null && (CompareAttributes(attr, newAttr) == NodePosition.After))
{
prevAttr = attr;
attr = (XmlDiffAttribute)(attr.NextSibling);
}
parent.InsertAttributeAfter(prevAttr, newAttr);
}
else
parent.InsertAttributeAfter(parent.LastAttribute, newAttr);
}
public override void WriteTo(XmlWriter w)
{
WriteContentTo(w);
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
public XmlDiffNavigator CreateNavigator()
{
return new XmlDiffNavigator(this);
}
public void SortChildren()
{
if (this.FirstChild != null)
{
XmlDiffNode _first = this.FirstChild;
XmlDiffNode _current = this.FirstChild;
XmlDiffNode _last = this.LastChild;
this._firstChild = null;
this._lastChild = null;
//set flag to ignore child order
bool temp = IgnoreChildOrder;
IgnoreChildOrder = true;
XmlDiffNode _next = null;
do
{
if (_current is XmlDiffElement)
_next = _current._next;
_current._next = null;
InsertChild(this, _current);
if (_current == _last)
break;
_current = _next;
}
while (true);
//restore flag for ignoring child order
IgnoreChildOrder = temp;
}
}
void SortChildren(XmlDiffElement elem)
{
if (elem.FirstChild != null)
{
XmlDiffNode _first = elem.FirstChild;
XmlDiffNode _current = elem.FirstChild;
XmlDiffNode _last = elem.LastChild;
elem._firstChild = null;
elem._lastChild = null;
//set flag to ignore child order
bool temp = IgnoreChildOrder;
IgnoreChildOrder = true;
XmlDiffNode _next = null;
do
{
if (_current is XmlDiffElement)
_next = _current._next;
_current._next = null;
InsertChild(elem, _current);
if (_current == _last)
break;
_current = _next;
}
while (true);
//restore flag for ignoring child order
IgnoreChildOrder = temp;
}
}
}
//navgator over the xmldiffdocument
public class XmlDiffNavigator
{
private XmlDiffDocument _document;
private XmlDiffNode _currentNode;
public XmlDiffNavigator(XmlDiffDocument doc)
{
_document = doc;
_currentNode = _document;
}
public XmlDiffNavigator Clone()
{
XmlDiffNavigator _clone = new XmlDiffNavigator(_document);
if (!_clone.MoveTo(this))
throw new Exception("Cannot clone");
return _clone;
}
public NodePosition ComparePosition(XmlDiffNavigator nav)
{
XmlDiffNode targetNode = ((XmlDiffNavigator)nav).CurrentNode;
if (!(nav is XmlDiffNavigator))
{
return NodePosition.Unknown;
}
if (targetNode == this.CurrentNode)
{
return NodePosition.Same;
}
else
{
if (this.CurrentNode.ParentNode == null) //this is root
{
return NodePosition.After;
}
else if (targetNode.ParentNode == null) //this is root
{
return NodePosition.Before;
}
else //look in the following nodes
{
if (targetNode.LineNumber != 0 && this.CurrentNode.LineNumber != 0)
{
if (targetNode.LineNumber > this.CurrentNode.LineNumber)
{
return NodePosition.Before;
}
else if (targetNode.LineNumber == this.CurrentNode.LineNumber && targetNode.LinePosition > this.CurrentNode.LinePosition)
{
return NodePosition.Before;
}
else
return NodePosition.After;
}
return NodePosition.Before;
}
}
}
public String GetAttribute(String localName, String namespaceURI)
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).GetAttributeValue(localName, namespaceURI);
}
return "";
}
public String GetNamespace(String name)
{
Debug.Assert(false, "GetNamespace is NYI");
return "";
}
public bool IsSamePosition(XmlDiffNavigator other)
{
if (other is XmlDiffNavigator)
{
if (_currentNode == ((XmlDiffNavigator)other).CurrentNode)
return true;
}
return false;
}
public bool MoveTo(XmlDiffNavigator other)
{
if (other is XmlDiffNavigator)
{
_currentNode = ((XmlDiffNavigator)other).CurrentNode;
return true;
}
return false;
}
public bool MoveToAttribute(String localName, String namespaceURI)
{
if (_currentNode is XmlDiffElement)
{
XmlDiffAttribute _attr = ((XmlDiffElement)_currentNode).GetAttribute(localName, namespaceURI);
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
return false;
}
public bool MoveToFirst()
{
if (!(_currentNode is XmlDiffAttribute))
{
if (_currentNode.ParentNode.FirstChild == _currentNode)
{
if (_currentNode.ParentNode.FirstChild._next != null)
{
_currentNode = _currentNode.ParentNode.FirstChild._next;
return true;
}
}
else
{
_currentNode = _currentNode.ParentNode.FirstChild;
return true;
}
}
return false;
}
public bool MoveToFirstAttribute()
{
if (_currentNode is XmlDiffElement)
{
if (((XmlDiffElement)_currentNode).FirstAttribute != null)
{
XmlDiffAttribute _attr = ((XmlDiffElement)_currentNode).FirstAttribute;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
}
return false;
}
public bool MoveToFirstChild()
{
if ((_currentNode is XmlDiffDocument || _currentNode is XmlDiffElement) && _currentNode.FirstChild != null)
{
_currentNode = _currentNode.FirstChild;
return true;
}
return false;
}
public bool MoveToId(String id)
{
Debug.Assert(false, "MoveToId is NYI");
return false;
}
public bool MoveToNamespace(String name)
{
Debug.Assert(false, "MoveToNamespace is NYI");
return false;
}
public bool MoveToNext()
{
if (!(_currentNode is XmlDiffAttribute) && _currentNode._next != null)
{
_currentNode = _currentNode._next;
return true;
}
return false;
}
public bool MoveToNextAttribute()
{
if (_currentNode is XmlDiffAttribute)
{
XmlDiffAttribute _attr = (XmlDiffAttribute)_currentNode._next;
while (_attr != null && IsNamespaceNode(_attr))
{
_attr = (XmlDiffAttribute)_attr._next;
}
if (_attr != null)
{
_currentNode = _attr;
return true;
}
}
return false;
}
private bool IsNamespaceNode(XmlDiffAttribute attr)
{
return attr.LocalName.ToLower() == "xmlns" ||
attr.Prefix.ToLower() == "xmlns";
}
public bool MoveToParent()
{
if (!(_currentNode is XmlDiffDocument))
{
_currentNode = _currentNode.ParentNode;
return true;
}
return false;
}
public bool MoveToPrevious()
{
if (_currentNode != _currentNode.ParentNode.FirstChild)
{
XmlDiffNode _current = _currentNode.ParentNode.FirstChild;
XmlDiffNode _prev = _currentNode.ParentNode.FirstChild;
while (_current != _currentNode)
{
_prev = _current;
_current = _current._next;
}
_currentNode = _prev;
return true;
}
return false;
}
public void MoveToRoot()
{
_currentNode = _document;
}
public string LocalName
{
get
{
if (_currentNode.NodeType == XmlDiffNodeType.Element)
{
return ((XmlDiffElement)_currentNode).LocalName;
}
else if (_currentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)_currentNode).LocalName;
}
else if (_currentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)_currentNode).Name;
}
return "";
}
}
public string Name
{
get
{
if (_currentNode.NodeType == XmlDiffNodeType.Element)
{
return _document.nameTable.Get(((XmlDiffElement)_currentNode).Name);
}
else if (_currentNode.NodeType == XmlDiffNodeType.Attribute)
{
return ((XmlDiffAttribute)_currentNode).Name;
}
else if (_currentNode.NodeType == XmlDiffNodeType.PI)
{
return ((XmlDiffProcessingInstruction)_currentNode).Name;
}
return "";
}
}
public string NamespaceURI
{
get
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).NamespaceURI;
}
else if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).NamespaceURI;
}
return "";
}
}
public string Value
{
get
{
if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).Value;
}
else if (_currentNode is XmlDiffCharacterData)
{
return ((XmlDiffCharacterData)_currentNode).Value;
}
else if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).Value;
}
return "";
}
}
public string Prefix
{
get
{
if (_currentNode is XmlDiffElement)
{
return ((XmlDiffElement)_currentNode).Prefix;
}
else if (_currentNode is XmlDiffAttribute)
{
return ((XmlDiffAttribute)_currentNode).Prefix;
}
return "";
}
}
public string BaseURI
{
get
{
Debug.Assert(false, "BaseURI is NYI");
return "";
}
}
public string XmlLang
{
get
{
Debug.Assert(false, "XmlLang not supported");
return "";
}
}
public bool HasAttributes
{
get
{
return (_currentNode is XmlDiffElement && ((XmlDiffElement)_currentNode).FirstAttribute != null) ? true : false;
}
}
public bool HasChildren
{
get
{
return _currentNode._next != null ? true : false;
}
}
public bool IsEmptyElement
{
get
{
return _currentNode is XmlDiffEmptyElement ? true : false;
}
}
public XmlNameTable NameTable
{
get
{
return _document.nameTable;
}
}
public XmlDiffNode CurrentNode
{
get
{
return _currentNode;
}
}
public bool IsOnRoot()
{
return _currentNode == null ? true : false;
}
}
public class PropertyCollection : MyDict<string, object> { }
public abstract class XmlDiffNode
{
internal XmlDiffNode _next;
internal XmlDiffNode _firstChild;
internal XmlDiffNode _lastChild;
internal XmlDiffNode _parent;
internal int _lineNumber, _linePosition;
internal bool _bIgnoreValue;
private PropertyCollection _extendedProperties;
public XmlDiffNode()
{
this._next = null;
this._firstChild = null;
this._lastChild = null;
this._parent = null;
_lineNumber = 0;
_linePosition = 0;
}
public XmlDiffNode FirstChild
{
get
{
return this._firstChild;
}
}
public XmlDiffNode LastChild
{
get
{
return this._lastChild;
}
}
public XmlDiffNode NextSibling
{
get
{
return this._next;
}
}
public XmlDiffNode ParentNode
{
get
{
return this._parent;
}
}
public virtual bool IgnoreValue
{
get
{
return _bIgnoreValue;
}
set
{
_bIgnoreValue = value;
XmlDiffNode current = this._firstChild;
while (current != null)
{
current.IgnoreValue = value;
current = current._next;
}
}
}
public abstract XmlDiffNodeType NodeType { get; }
public virtual string OuterXml
{
get
{
StringWriter sw = new StringWriter();
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.CheckCharacters = false;
XmlWriter xw = XmlWriter.Create(sw, xws);
WriteTo(xw);
xw.Dispose();
return sw.ToString();
}
}
public virtual string InnerXml
{
get
{
StringWriter sw = new StringWriter();
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.CheckCharacters = false;
XmlWriter xw = XmlWriter.Create(sw, xws);
WriteTo(xw);
xw.Dispose();
return sw.ToString();
}
}
public abstract void WriteTo(XmlWriter w);
public abstract void WriteContentTo(XmlWriter w);
public PropertyCollection ExtendedProperties
{
get
{
if (_extendedProperties == null)
_extendedProperties = new PropertyCollection();
return _extendedProperties;
}
}
public virtual void InsertChildAfter(XmlDiffNode child, XmlDiffNode newChild)
{
Debug.Assert(newChild != null);
newChild._parent = this;
if (child == null)
{
newChild._next = this._firstChild;
this._firstChild = newChild;
}
else
{
Debug.Assert(child._parent == this);
newChild._next = child._next;
child._next = newChild;
}
if (newChild._next == null)
this._lastChild = newChild;
}
public virtual void DeleteChild(XmlDiffNode child)
{
if (child == this.FirstChild)//delete head
{
_firstChild = this.FirstChild.NextSibling;
}
else
{
XmlDiffNode current = this.FirstChild;
XmlDiffNode previous = null;
while (current != child)
{
previous = current;
current = current.NextSibling;
}
Debug.Assert(current != null);
if (current == this.LastChild) //tail being deleted
{
this._lastChild = current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int LineNumber
{
get { return this._lineNumber; }
set { this._lineNumber = value; }
}
public int LinePosition
{
get { return this._linePosition; }
set { this._linePosition = value; }
}
}
public class XmlDiffElement : XmlDiffNode
{
private string _lName;
private string _prefix;
private string _ns;
private XmlDiffAttribute _firstAttribute;
private XmlDiffAttribute _lastAttribute;
private int _attrC;
private int _endLineNumber, _endLinePosition;
public XmlDiffElement(string localName, string prefix, string ns)
: base()
{
this._lName = localName;
this._prefix = prefix;
this._ns = ns;
this._firstAttribute = null;
this._lastAttribute = null;
this._attrC = -1;
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Element; } }
public string LocalName { get { return this._lName; } }
public string NamespaceURI { get { return this._ns; } }
public string Prefix { get { return this._prefix; } }
public string Name
{
get
{
if (this._prefix.Length > 0)
return Prefix + ":" + LocalName;
else
return LocalName;
}
}
public XmlDiffAttribute FirstAttribute
{
get
{
return this._firstAttribute;
}
}
public XmlDiffAttribute LastAttribute
{
get
{
return this._lastAttribute;
}
}
public string GetAttributeValue(string LocalName, string NamespaceUri)
{
if (_firstAttribute != null)
{
XmlDiffAttribute _current = _firstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current.Value;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != _lastAttribute);
}
return "";
}
public XmlDiffAttribute GetAttribute(string LocalName, string NamespaceUri)
{
if (_firstAttribute != null)
{
XmlDiffAttribute _current = _firstAttribute;
do
{
if (_current.LocalName == LocalName && _current.NamespaceURI == NamespaceURI)
{
return _current;
}
_current = (XmlDiffAttribute)_current._next;
}
while (_current != _lastAttribute);
}
return null;
}
internal void InsertAttributeAfter(XmlDiffAttribute attr, XmlDiffAttribute newAttr)
{
Debug.Assert(newAttr != null);
newAttr._ownerElement = this;
if (attr == null)
{
newAttr._next = this._firstAttribute;
this._firstAttribute = newAttr;
}
else
{
Debug.Assert(attr._ownerElement == this);
newAttr._next = attr._next;
attr._next = newAttr;
}
if (newAttr._next == null)
this._lastAttribute = newAttr;
}
internal void DeleteAttribute(XmlDiffAttribute attr)
{
if (attr == this.FirstAttribute)//delete head
{
if (attr == this.LastAttribute) //tail being deleted
{
this._lastAttribute = (XmlDiffAttribute)attr.NextSibling;
}
_firstAttribute = (XmlDiffAttribute)this.FirstAttribute.NextSibling;
}
else
{
XmlDiffAttribute current = this.FirstAttribute;
XmlDiffAttribute previous = null;
while (current != attr)
{
previous = current;
current = (XmlDiffAttribute)current.NextSibling;
}
Debug.Assert(current != null);
if (current == this.LastAttribute) //tail being deleted
{
this._lastAttribute = (XmlDiffAttribute)current.NextSibling;
}
previous._next = current.NextSibling;
}
}
public int AttributeCount
{
get
{
if (this._attrC != -1)
return this._attrC;
XmlDiffAttribute attr = this._firstAttribute;
this._attrC = 0;
while (attr != null)
{
this._attrC++;
attr = (XmlDiffAttribute)attr.NextSibling;
}
return this._attrC;
}
}
public override bool IgnoreValue
{
set
{
base.IgnoreValue = value;
XmlDiffAttribute current = this._firstAttribute;
while (current != null)
{
current.IgnoreValue = value;
current = (XmlDiffAttribute)current._next;
}
}
}
public int EndLineNumber
{
get { return this._endLineNumber; }
set { this._endLineNumber = value; }
}
public int EndLinePosition
{
get { return this._endLinePosition; }
set { this._endLinePosition = value; }
}
public override void WriteTo(XmlWriter w)
{
w.WriteStartElement(Prefix, LocalName, NamespaceURI);
XmlDiffAttribute attr = this._firstAttribute;
while (attr != null)
{
attr.WriteTo(w);
attr = (XmlDiffAttribute)(attr.NextSibling);
}
WriteContentTo(w);
w.WriteFullEndElement();
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
if (_firstChild != null)
{
StringBuilder _bldr = new StringBuilder();
XmlDiffNode _current = _firstChild;
do
{
if (_current is XmlDiffCharacterData && _current.NodeType != XmlDiffNodeType.Comment && _current.NodeType != XmlDiffNodeType.PI)
{
_bldr.Append(((XmlDiffCharacterData)_current).Value);
}
else if (_current is XmlDiffElement)
{
_bldr.Append(((XmlDiffElement)_current).Value);
}
_current = _current._next;
}
while (_current != null);
return _bldr.ToString();
}
return "";
}
}
}
public class XmlDiffEmptyElement : XmlDiffElement
{
public XmlDiffEmptyElement(string localName, string prefix, string ns) : base(localName, prefix, ns) { }
}
public class XmlDiffAttribute : XmlDiffNode
{
internal XmlDiffElement _ownerElement;
private string _lName;
private string _prefix;
private string _ns;
private string _value;
public XmlDiffAttribute(string localName, string prefix, string ns, string value)
: base()
{
this._lName = localName;
this._prefix = prefix;
this._ns = ns;
this._value = value;
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
return this._value;
}
}
public string LocalName { get { return this._lName; } }
public string NamespaceURI { get { return this._ns; } }
public string Prefix { get { return this._prefix; } }
public string Name
{
get
{
if (this._prefix.Length > 0)
return this._prefix + ":" + this._lName;
else
return this._lName;
}
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Attribute; } }
public override void WriteTo(XmlWriter w)
{
w.WriteStartAttribute(Prefix, LocalName, NamespaceURI);
WriteContentTo(w);
w.WriteEndAttribute();
}
public override void WriteContentTo(XmlWriter w)
{
w.WriteString(Value);
}
}
public class XmlDiffEntityReference : XmlDiffNode
{
private string _name;
public XmlDiffEntityReference(string name)
: base()
{
this._name = name;
}
public override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.ER; } }
public string Name { get { return this._name; } }
public override void WriteTo(XmlWriter w)
{
w.WriteEntityRef(this._name);
}
public override void WriteContentTo(XmlWriter w)
{
XmlDiffNode child = this.FirstChild;
while (child != null)
{
child.WriteTo(w);
child = child.NextSibling;
}
}
}
public class XmlDiffCharacterData : XmlDiffNode
{
private string _value;
private XmlDiffNodeType _nodetype;
public XmlDiffCharacterData(string value, XmlDiffNodeType nt, bool NormalizeNewline)
: base()
{
this._value = value;
if (NormalizeNewline)
{
this._value = this._value.Replace("\n", "");
this._value = this._value.Replace("\r", "");
}
this._nodetype = nt;
}
public string Value
{
get
{
if (this.IgnoreValue)
{
return "";
}
return this._value;
}
set
{
_value = value;
}
}
public override XmlDiffNodeType NodeType { get { return _nodetype; } }
public override void WriteTo(XmlWriter w)
{
switch (this._nodetype)
{
case XmlDiffNodeType.Comment:
w.WriteComment(Value);
break;
case XmlDiffNodeType.CData:
w.WriteCData(Value);
break;
case XmlDiffNodeType.WS:
case XmlDiffNodeType.Text:
w.WriteString(Value);
break;
default:
Debug.Assert(false, "Wrong type for text-like node : " + this._nodetype.ToString());
break;
}
}
public override void WriteContentTo(XmlWriter w) { }
}
public class XmlDiffProcessingInstruction : XmlDiffCharacterData
{
private string _name;
public XmlDiffProcessingInstruction(string name, string value)
: base(value, XmlDiffNodeType.PI, false)
{
this._name = name;
}
public string Name { get { return this._name; } }
public override void WriteTo(XmlWriter w)
{
w.WriteProcessingInstruction(this._name, Value);
}
public override void WriteContentTo(XmlWriter w) { }
}
}
| |
namespace sapHowmuch.Api.Repositories
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("OJDT")]
public partial class OJDT
{
public int? BatchNum { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int TransId { get; set; }
[StringLength(1)]
public string BtfStatus { get; set; }
[StringLength(20)]
public string TransType { get; set; }
[StringLength(11)]
public string BaseRef { get; set; }
public DateTime? RefDate { get; set; }
[StringLength(50)]
public string Memo { get; set; }
[StringLength(100)]
public string Ref1 { get; set; }
[StringLength(100)]
public string Ref2 { get; set; }
public int? CreatedBy { get; set; }
[Column(TypeName = "numeric")]
public decimal? LocTotal { get; set; }
[Column(TypeName = "numeric")]
public decimal? FcTotal { get; set; }
[Column(TypeName = "numeric")]
public decimal? SysTotal { get; set; }
[StringLength(4)]
public string TransCode { get; set; }
[StringLength(3)]
public string OrignCurr { get; set; }
[Column(TypeName = "numeric")]
public decimal? TransRate { get; set; }
public int? BtfLine { get; set; }
[StringLength(3)]
public string TransCurr { get; set; }
[StringLength(20)]
public string Project { get; set; }
public DateTime? DueDate { get; set; }
public DateTime? TaxDate { get; set; }
[StringLength(1)]
public string PCAddition { get; set; }
public int? FinncPriod { get; set; }
[StringLength(1)]
public string DataSource { get; set; }
public DateTime? UpdateDate { get; set; }
public DateTime? CreateDate { get; set; }
public short? UserSign { get; set; }
public short? UserSign2 { get; set; }
[StringLength(1)]
public string RefndRprt { get; set; }
public int? LogInstanc { get; set; }
[StringLength(20)]
public string ObjType { get; set; }
[StringLength(2)]
public string Indicator { get; set; }
[StringLength(1)]
public string AdjTran { get; set; }
[StringLength(1)]
public string RevSource { get; set; }
public DateTime? StornoDate { get; set; }
public int? StornoToTr { get; set; }
[StringLength(1)]
public string AutoStorno { get; set; }
[StringLength(1)]
public string Corisptivi { get; set; }
public DateTime? VatDate { get; set; }
[StringLength(1)]
public string StampTax { get; set; }
public short Series { get; set; }
public int Number { get; set; }
[StringLength(1)]
public string AutoVAT { get; set; }
public short? DocSeries { get; set; }
[StringLength(4)]
public string FolioPref { get; set; }
public int? FolioNum { get; set; }
public short? CreateTime { get; set; }
[StringLength(1)]
public string BlockDunn { get; set; }
[StringLength(1)]
public string ReportEU { get; set; }
[StringLength(1)]
public string Report347 { get; set; }
[StringLength(1)]
public string Printed { get; set; }
[StringLength(60)]
public string DocType { get; set; }
public int? AttNum { get; set; }
[StringLength(1)]
public string GenRegNo { get; set; }
public int? RG23APart2 { get; set; }
public int? RG23CPart2 { get; set; }
public int? MatType { get; set; }
[StringLength(155)]
public string Creator { get; set; }
[StringLength(155)]
public string Approver { get; set; }
public int? Location { get; set; }
public short? SeqCode { get; set; }
public int? Serial { get; set; }
[StringLength(3)]
public string SeriesStr { get; set; }
[StringLength(3)]
public string SubStr { get; set; }
[StringLength(1)]
public string AutoWT { get; set; }
[Column(TypeName = "numeric")]
public decimal? WTSum { get; set; }
[Column(TypeName = "numeric")]
public decimal? WTSumSC { get; set; }
[Column(TypeName = "numeric")]
public decimal? WTSumFC { get; set; }
[Column(TypeName = "numeric")]
public decimal? WTApplied { get; set; }
[Column(TypeName = "numeric")]
public decimal? WTAppliedS { get; set; }
[Column(TypeName = "numeric")]
public decimal? WTAppliedF { get; set; }
[Column(TypeName = "numeric")]
public decimal? BaseAmnt { get; set; }
[Column(TypeName = "numeric")]
public decimal? BaseAmntSC { get; set; }
[Column(TypeName = "numeric")]
public decimal? BaseAmntFC { get; set; }
[Column(TypeName = "numeric")]
public decimal? BaseVtAt { get; set; }
[Column(TypeName = "numeric")]
public decimal? BaseVtAtSC { get; set; }
[Column(TypeName = "numeric")]
public decimal? BaseVtAtFC { get; set; }
[StringLength(11)]
public string VersionNum { get; set; }
public int? BaseTrans { get; set; }
[StringLength(1)]
public string ResidenNum { get; set; }
[StringLength(1)]
public string OperatCode { get; set; }
[StringLength(27)]
public string Ref3 { get; set; }
[StringLength(1)]
public string SSIExmpt { get; set; }
[Column(TypeName = "ntext")]
public string SignMsg { get; set; }
[Column(TypeName = "ntext")]
public string SignDigest { get; set; }
[StringLength(50)]
public string CertifNum { get; set; }
public int? KeyVersion { get; set; }
public int? CUP { get; set; }
public int? CIG { get; set; }
[StringLength(254)]
public string SupplCode { get; set; }
public int? SPSrcType { get; set; }
public int? SPSrcID { get; set; }
public int? SPSrcDLN { get; set; }
[StringLength(1)]
public string DeferedTax { get; set; }
public int? AgrNo { get; set; }
public int? SeqNum { get; set; }
[StringLength(1)]
public string ECDPosTyp { get; set; }
[StringLength(5)]
public string RptPeriod { get; set; }
public DateTime? RptMonth { get; set; }
public int? ExTransId { get; set; }
[StringLength(1)]
public string PrlLinked { get; set; }
[StringLength(5)]
public string PTICode { get; set; }
[StringLength(1)]
public string Letter { get; set; }
public int? FolNumFrom { get; set; }
public int? FolNumTo { get; set; }
[StringLength(3)]
public string RepSection { get; set; }
[StringLength(1)]
public string ExclTaxRep { get; set; }
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using XenAdmin.Alerts;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAdminTests.UnitTests.UnitTestHelper;
using XenAPI;
namespace XenAdminTests.UnitTests.AlertTests
{
[TestFixture, Category(TestCategories.Unit), Category(TestCategories.SmokeTest)]
public class XenServerPatchAlertTests
{
private Mock<IXenConnection> connA;
private Mock<IXenConnection> connB;
private Mock<Host> hostA;
private Mock<Host> hostB;
protected Cache cacheA;
protected Cache cacheB;
[Test]
public void TestAlertWithConnectionAndHosts()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
alert.IncludeHosts(new List<Host> { hostA.Object, hostB.Object });
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName, ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Priority2"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithHostsAndNoConnection()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "1", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
alert.IncludeHosts(new List<Host>() { hostA.Object, hostB.Object });
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Priority1"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithConnectionAndNoHosts()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "0", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Unknown"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Never);
}
[Test]
public void TestAlertWithNoConnectionAndNoHosts()
{
XenServerPatch p = new XenServerPatch("uuid", "name", "My description", "guidance", string.Empty, "6.0.1", "http://url", "http://patchUrl", new DateTime(2011, 4, 1).ToString(), "5", "");
XenServerPatchAlert alert = new XenServerPatchAlert(p);
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = string.Empty,
FixLinkText = "Go to Web Page",
HelpID = "XenServerPatchAlert",
Description = "My description",
HelpLinkText = "Help",
Title = "New Update Available - name",
Priority = "Priority5"
});
Assert.IsTrue(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Never);
}
[Test, ExpectedException(typeof(NullReferenceException))]
public void TestAlertWithNullPatch()
{
XenServerPatchAlert alert = new XenServerPatchAlert(null);
}
private void VerifyConnExpectations(Func<Times> times)
{
connA.VerifyGet(n => n.Name, times());
connB.VerifyGet(n => n.Name, times());
}
private void VerifyHostsExpectations(Func<Times> times)
{
hostA.VerifyGet(n => n.Name, times());
hostB.VerifyGet(n => n.Name, times());
}
[SetUp]
public void TestSetUp()
{
connA = new Mock<IXenConnection>(MockBehavior.Strict);
connA.Setup(n => n.Name).Returns("ConnAName");
cacheA = new Cache();
connA.Setup(x => x.Cache).Returns(cacheA);
connB = new Mock<IXenConnection>(MockBehavior.Strict);
connB.Setup(n => n.Name).Returns("ConnBName");
cacheB = new Cache();
connB.Setup(x => x.Cache).Returns(cacheB);
hostA = new Mock<Host>(MockBehavior.Strict);
hostA.Setup(n => n.Name).Returns("HostAName");
hostA.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostA.Object));
hostB = new Mock<Host>(MockBehavior.Strict);
hostB.Setup(n => n.Name).Returns("HostBName");
hostB.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostB.Object));
}
[TearDown]
public void TestTearDown()
{
cacheA = null;
cacheB = null;
connA = null;
connB = null;
hostA = null;
hostB = null;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc. All rights reserved.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM 'AS IS' AND WITH ALL ITS FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
namespace Revit.SDK.Samples.ObjectViewer.CS
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using Autodesk.Revit.Structural;
using Autodesk.Revit.Geometry;
/// <summary>
/// interface as the datasource of view, include nececessary members
/// </summary>
public interface IGraphicsData
{
/// <summary>
/// 2D lines
/// </summary>
/// <returns></returns>
List<PointF[]> PointCurves();
/// <summary>
/// view data update
/// </summary>
event UpdateViewDelegate UpdateViewEvent;
/// <summary>
/// region of 3D view data
/// </summary>
RectangleF Region
{
get;
}
}
/// <summary>
/// abstrace class include general members
/// </summary>
public abstract class GraphicsDataBase : IGraphicsData
{
protected XYZ m_transferedMax; //3D max point after transfered
protected XYZ m_transferedMin; //3D min point after transfered
protected XYZ m_originMax = new XYZ(double.MinValue, double.MinValue, double.MinValue); //3D max point
protected XYZ m_originMin = new XYZ(double.MaxValue, double.MaxValue, double.MaxValue); //3d min point
protected double[,] m_origin = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } }; //tranform matrix between origin matrix and view matrix
public const float MINEDGElENGTH = 1.0f; //minimum value of the region box's edge
public const double ROTATEANGLE = System.Math.PI / 90; //default angle when rotate around X,Y,Z axis
public virtual event UpdateViewDelegate UpdateViewEvent;
/// <summary>
/// constructor
/// </summary>
public GraphicsDataBase()
{
Initialize();
}
public double[,] Origin
{
get
{
return m_origin;
}
set
{
m_origin = value;
}
}
/// <summary>
/// initialize some member data
/// </summary>
protected virtual void Initialize()
{
m_transferedMax = new XYZ(double.MinValue, double.MinValue, double.MinValue);
m_transferedMin = new XYZ(double.MaxValue, double.MaxValue, double.MaxValue);
}
/// <summary>
/// trig updata view event
/// </summary>
public virtual void UpdataData()
{
UpdateViewEvent();
}
public abstract List<PointF[]> PointCurves();
/// <summary>
/// rectangular region of 3D view data
/// </summary>
public RectangleF Region
{
get
{
float width = (float)Math.Abs(m_transferedMax.X - m_transferedMin.X);
float height = (float)Math.Abs(m_transferedMax.Y - m_transferedMin.Y);
if (width < 1f)
{
width = 1f;
}
if (height < 1f)
{
height = 1f;
}
float maxX = (width / 2);
float maxY = (height / 2);
float minX = -(width / 2);
float minY = -(height / 2);
RectangleF rec = new RectangleF(minX, minY, width, height);
return rec;
}
}
/// <summary>
/// rotate around Z axis with default angle
/// </summary>
/// <param name="direction">minus or positive angle</param>
public void RotateZ(bool direction)
{
double angle = ROTATEANGLE;
if (!direction)
{
angle = -ROTATEANGLE;
}
RotateZ(ref m_origin, angle);
UpdataData();
}
/// <summary>
/// rotate 3*3 matrix around Z axis
/// </summary>
/// <param name="origin">matrix to rotate</param>
/// <param name="angle"></param>
private void RotateZ(ref double[,] origin, double angle)
{
double sin = Math.Sin(angle);
double cos = Math.Cos(angle);
double[,] rotate = { { cos, sin, 0.0 }, { -sin, cos, 0.0 }, { 0.0, 0.0, 1.0 } };
origin = MathUtil.MultiCross(m_origin, rotate);
}
/// <summary>
/// rotate around Y axis with default angle
/// </summary>
/// <param name="direction">minus or positive angle</param>
public void RotateY(bool direction)
{
double angle = ROTATEANGLE;
if (!direction)
{
angle = -ROTATEANGLE;
}
RotateY(ref m_origin, angle);
UpdataData();
}
/// <summary>
/// rotate 3*3 matrix around Y axis
/// </summary>
/// <param name="origin">matrix to rotate</param>
/// <param name="angle"></param>
private void RotateY(ref double[,] origin, double angle)
{
double sin = Math.Sin(angle);
double cos = Math.Cos(angle);
double[,] rotate = { { cos, 0.0, -sin }, { 0.0, 1.0, 0.0 }, { sin, 0.0, cos } };
origin = MathUtil.MultiCross(m_origin, rotate);
}
/// <summary>
/// rotate around X axis with default angle
/// </summary>
/// <param name="direction">minus or positive angle</param>
public void RotateX(bool direction)
{
double angle = ROTATEANGLE;
if (!direction)
{
angle = -ROTATEANGLE;
}
RotateX(ref m_origin, angle);
UpdataData();
}
/// <summary>
/// rotate 3*3 matrix around X axis
/// </summary>
/// <param name="origin">matrix to rotate</param>
/// <param name="angle"></param>
private void RotateX(ref double[,] origin, double angle)
{
double sin = Math.Sin(angle);
double cos = Math.Cos(angle);
double[,] rotate = { { 1.0, 0.0, 0.0 }, { 0.0, cos, sin }, { 0.0, -sin, cos } };
origin = MathUtil.MultiCross(m_origin, rotate);
}
}
/// <summary>
/// datasource that can bind to PictureBox3D
/// </summary>
public class GraphicsData : GraphicsDataBase
{
List<XYZArray> m_originCurves;
List<XYZArray> m_transferedCurves;
List<PointF[]> m_curves2D;
public override event UpdateViewDelegate UpdateViewEvent;
/// <summary>
/// constructor to initialize member data
/// </summary>
public GraphicsData()
: base()
{
m_originCurves = new List<XYZArray>();
m_transferedCurves = new List<XYZArray>();
m_curves2D = new List<PointF[]>();
}
/// <summary>
/// curves array
/// </summary>
/// <returns></returns>
public override List<PointF[]> PointCurves()
{
return m_curves2D;
}
/// <summary>
/// insert curves array into datasource
/// </summary>
/// <param name="points">points compose the curve</param>
public void InsertCurve(XYZArray points)
{
m_originCurves.Add(points);
foreach (XYZ point in points)
{
XYZ temp = TransferRotate(point);
UpdateRange(point, ref m_originMin, ref m_originMax);
UpdateRange(temp, ref m_transferedMin, ref m_transferedMax);
}
}
/// <summary>
/// update 3D view data
/// </summary>
public override void UpdataData()
{
m_transferedCurves.Clear();
m_curves2D.Clear();
foreach (XYZArray points in m_originCurves)
{
SynChroData(points);
}
if (null != UpdateViewEvent)
{
UpdateViewEvent();
}
}
/// <summary>
/// update 3D view curve data with origin data and transfer matrix
/// </summary>
/// <param name="points"></param>
private void SynChroData(XYZArray points)
{
int size = points.Size;
PointF[] points2D = new PointF[size];
XYZArray transferedPoints = new XYZArray();
for (int i = 0; i < size; i++)
{
XYZ point = points.get_Item(i);
XYZ temp = TransferMove(point);
XYZ transferedPoint = TransferRotate(temp);
points2D[i] = new PointF((float)transferedPoint.X, (float)transferedPoint.Y);
transferedPoints.Append(ref transferedPoint);
}
m_transferedCurves.Add(transferedPoints);
m_curves2D.Add(points2D);
}
/// <summary>
/// compare to get the max and min value
/// </summary>
/// <param name="point">point to be compared</param>
/// <param name="min"></param>
/// <param name="max"></param>
private void UpdateRange(XYZ point, ref XYZ min, ref XYZ max)
{
if (point.X > max.X)
{
max.X = point.X;
}
if (point.Y > max.Y)
{
max.Y = point.Y;
}
if (point.Z > max.Z)
{
max.Z = point.Z;
}
if (point.X < min.X)
{
min.X = point.X;
}
if (point.Y < min.Y)
{
min.Y = point.Y;
}
if (point.Z < min.Z)
{
min.Z = point.Z;
}
}
/// <summary>
/// rotate points with origion matrix
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
private XYZ TransferRotate(XYZ point)
{
XYZ newPoint = new XYZ();
double x = point.X;
double y = point.Y;
double z = point.Z;
//transform the origin of the old coordinate system in the new coordinate system
newPoint.X = x * m_origin[0, 0] + y * m_origin[0, 1] + z * m_origin[0, 2];
newPoint.Y = x * m_origin[1, 0] + y * m_origin[1, 1] + z * m_origin[1, 2];
newPoint.Z = x * m_origin[2, 0] + y * m_origin[2, 1] + z * m_origin[2, 2];
return newPoint;
}
/// <summary>
/// move the point so that the center of the curves in 3D view is origin
/// </summary>
/// <param name="point">points to be moved</param>
/// <returns>moved result</returns>
private XYZ TransferMove(XYZ point)
{
XYZ newPoint = new XYZ();
//transform the origin of the old coordinate system in the new coordinate system
newPoint.X = point.X - (m_transferedMax.X + m_transferedMin.X) / 2;
newPoint.Y = point.Y - (m_transferedMax.Y + m_transferedMin.Y) / 2;
newPoint.Z = point.Z - (m_transferedMax.Z + m_transferedMin.Z) / 2;
return newPoint;
}
}
}
| |
using System;
using System.Collections.Generic;
using OggVorbisEncoder.Lookups;
using OggVorbisEncoder.Setup;
namespace OggVorbisEncoder
{
/// <summary>
/// Buffers the current vorbis audio analysis/synthesis state.
/// The DSP state belongs to a specific logical bitstream
/// </summary>
public class ProcessingState
{
// .345 is a hack; the original ToDecibel estimation used on IEEE 754
// compliant machines had an error that returned dB values about a third
// of a decibel too high. The error was harmless because tunings
// implicitly took that into account. However, fixing the error
// in the estimator requires changing all the tunings as well.
// For now, it's easier to sync things back up here, and
// recalibrate the tunings in the next major model upgrade.
private const float DecibelOffset = .345f;
private readonly LookupCollection _lookups;
private readonly float[][] _pcm;
private readonly VorbisInfo _vorbisInfo;
private readonly int[] _window;
private int _centerWindow;
private int _currentWindow;
private int _eofFlag;
private int _granulePosition;
private int _lastWindow;
private int _nextWindow;
private int _pcmCurrent;
private bool _preExtrapolated;
private int _sequence = 3; // compressed audio packets start after the headers with sequence number 3
private ProcessingState(
VorbisInfo vorbisInfo,
LookupCollection lookups,
float[][] pcm,
int[] window,
int centerWindow)
{
_vorbisInfo = vorbisInfo;
_lookups = lookups;
_pcm = pcm;
_window = window;
_centerWindow = centerWindow;
}
/// <summary>
/// Writes the provided data to the pcm buffer
/// </summary>
/// <param name="data">The data to write in an array of dimensions: channels * length</param>
/// <param name="length">The number of elements to write</param>
public void WriteData(float[][] data, int length, int read_offset = 0)
{
if (length <= 0)
return;
EnsureBufferSize(length);
for (var i = 0; i < data.Length; ++i)
Array.Copy(data[i], read_offset, _pcm[i], _pcmCurrent, length);
var vi = _vorbisInfo;
var ci = vi.CodecSetup;
_pcmCurrent += length;
// we may want to reverse extrapolate the beginning of a stream too... in case we're beginning on a cliff!
// clumsy, but simple. It only runs once, so simple is good.
if (!_preExtrapolated && (_pcmCurrent - _centerWindow > ci.BlockSizes[1]))
PreExtrapolate();
}
public void WriteEndOfStream()
{
var ci = _vorbisInfo.CodecSetup;
const int order = 32;
var lpc = new float[order];
// if it wasn't done earlier (very short sample)
if (!_preExtrapolated)
PreExtrapolate();
// We're encoding the end of the stream. Just make sure we have [at least] a few full blocks of zeroes at the end.
// actually, we don't want zeroes; that could drop a large amplitude off a cliff, creating spread spectrum noise that will
// suck to encode. Extrapolate for the sake of cleanliness.
EnsureBufferSize(ci.BlockSizes[1]*3);
_eofFlag = _pcmCurrent;
_pcmCurrent += ci.BlockSizes[1]*3;
for (var channel = 0; channel < _pcm.Length; channel++)
if (_eofFlag > order*2)
{
// extrapolate with LPC to fill in
// make and run a predictor filter
var n = _eofFlag;
if (n > ci.BlockSizes[1])
n = ci.BlockSizes[1];
PopulateLpcFromPcm(lpc, _pcm[channel], _eofFlag - n, n, order);
UpdatePcmFromLpcPredict(lpc, _pcm[channel], _eofFlag, order, _pcmCurrent - _eofFlag);
}
else
{
// not enough data to extrapolate (unlikely to happen due to guarding the overlap,
// but bulletproof in case that assumption goes away). zeroes will do.
Array.Clear(_pcm[channel], _eofFlag, _pcmCurrent - _eofFlag);
}
}
private static void UpdatePcmFromLpcPredict(
float[] lpcCoeff,
IList<float> data,
int offset,
int m,
int n)
{
var work = new float[m + n];
for (var i = 0; i < m; i++)
work[i] = data[offset - m + i];
for (var i = 0; i < n; i++)
{
int o = i, p = m;
float y = 0;
for (var j = 0; j < m; j++)
y = y - work[o++]*lpcCoeff[--p];
data[offset + i] = work[o] = y;
}
}
private static void PopulateLpcFromPcm(IList<float> lpci, IList<float> data, int offset, int n, int m)
{
var aut = new double[m + 1];
var lpc = new double[m];
// autocorrelation, p+1 lag coefficients
var j = m + 1;
while (j-- > 0)
{
double d = 0; // double needed for accumulator depth
for (var i = j; i < n; i++)
d += (double) data[offset + i]
*data[offset + i - j];
aut[j] = d;
}
// Generate lpc coefficients from autocorr values
// set our noise floor to about -100dB
var error = aut[0]*(1.0 + 1e-10);
var epsilon = 1e-9*aut[0] + 1e-10;
for (var i = 0; i < m; i++)
{
var r = -aut[i + 1];
if (error < epsilon)
{
Array.Clear(lpc, i, m - i);
break;
}
// Sum up ampPtr iteration's reflection coefficient; note that in
// Vorbis we don't save it. If anyone wants to recycle ampPtr code
// and needs reflection coefficients, save the results of 'r' from
// each iteration.
for (j = 0; j < i; j++)
r -= lpc[j]*aut[i - j];
r /= error;
// Update LPC coefficients and total error
lpc[i] = r;
for (j = 0; j < i/2; j++)
{
var tmp = lpc[j];
lpc[j] += r*lpc[i - 1 - j];
lpc[i - 1 - j] += r*tmp;
}
if ((i & 1) != 0)
lpc[j] += lpc[j]*r;
error *= 1.0 - r*r;
}
// slightly damp the filter
{
var g = .99;
var damp = g;
for (j = 0; j < m; j++)
{
lpc[j] *= damp;
damp *= g;
}
}
for (j = 0; j < m; j++)
lpci[j] = (float) lpc[j];
}
private void PreExtrapolate()
{
const int order = 16;
_preExtrapolated = true;
if (_pcmCurrent - _centerWindow <= order*2)
return;
var lpc = new float[order];
var work = new float[_pcmCurrent];
for (var channel = 0; channel < _pcm.Length; channel++)
{
// need to run the extrapolation in reverse!
for (var j = 0; j < _pcmCurrent; j++)
work[j] = _pcm[channel][_pcmCurrent - j - 1];
// prime as above
PopulateLpcFromPcm(lpc, work, 0, _pcmCurrent - _centerWindow, order);
// run the predictor filter
UpdatePcmFromLpcPredict(lpc, work, _pcmCurrent - _centerWindow, order, _centerWindow);
for (var j = 0; j < _pcmCurrent; j++)
_pcm[channel][_pcmCurrent - j - 1] = work[j];
}
}
public void EnsureBufferSize(int needed)
{
var pcmStorage = _pcm[0].Length;
if (_pcmCurrent + needed < pcmStorage)
return;
pcmStorage = _pcmCurrent + needed*2;
for (var i = 0; i < _pcm.Length; i++)
{
var buffer = _pcm[i];
Array.Resize(ref buffer, pcmStorage);
_pcm[i] = buffer;
}
}
public bool PacketOut(out OggPacket packet)
{
packet = null;
// Have we started?
if (!_preExtrapolated)
return false;
// Are we done?
if (_eofFlag == -1)
return false;
var codecSetup = _vorbisInfo.CodecSetup;
// By our invariant, we have lW, W and centerW set. Search for
// the next boundary so we can determine nW (the next window size)
// which lets us compute the shape of the current block's window
// we do an envelope search even on a single blocksize; we may still
// be throwing more bits at impulses, and envelope search handles
// marking impulses too.
var testWindow =
_centerWindow +
codecSetup.BlockSizes[_currentWindow]/4 +
codecSetup.BlockSizes[1]/2 +
codecSetup.BlockSizes[0]/4;
var bp = _lookups.EnvelopeLookup.Search(_pcm, _pcmCurrent, _centerWindow, testWindow);
if (bp == -1)
{
if (_eofFlag == 0)
return false; // not enough data currently to search for a full int block
_nextWindow = 0;
}
else
{
_nextWindow = codecSetup.BlockSizes[0] == codecSetup.BlockSizes[1] ? 0 : bp;
}
var centerNext = _centerWindow
+ codecSetup.BlockSizes[_currentWindow]/4
+ codecSetup.BlockSizes[_nextWindow]/4;
// center of next block + next block maximum right side.
var blockbound = centerNext + codecSetup.BlockSizes[_nextWindow]/2;
// Not enough data yet
if (_pcmCurrent < blockbound)
return false;
// copy the vectors; ampPtr uses the local storage in vb
// ampPtr tracks 'strongest peak' for later psychoacoustics
var n = codecSetup.BlockSizes[_currentWindow]/2;
_lookups.PsyGlobalLookup.DecayAmpMax(n, _vorbisInfo.SampleRate);
var pcmEnd = codecSetup.BlockSizes[_currentWindow];
var pcm = new float[_pcm.Length][];
var beginWindow = _centerWindow - codecSetup.BlockSizes[_currentWindow]/2;
for (var channel = 0; channel < _pcm.Length; channel++)
{
pcm[channel] = new float[pcmEnd];
Array.Copy(_pcm[channel], beginWindow, pcm[channel], 0, pcm[channel].Length);
}
// handle eof detection: eof==0 means that we've not yet received EOF eof>0
// marks the last 'real' sample in pcm[] eof<0 'no more to do'; doesn't get here
var eofFlag = false;
if (_eofFlag != 0)
if (_centerWindow >= _eofFlag)
{
_eofFlag = -1;
eofFlag = true;
}
var data = PerformAnalysis(pcm, pcmEnd);
packet = new OggPacket(data, eofFlag, _granulePosition, _sequence++);
if (!eofFlag)
AdvanceStorageVectors(centerNext);
return true;
}
private void AdvanceStorageVectors(int centerNext)
{
// advance storage vectors and clean up
var newCenterNext = _vorbisInfo.CodecSetup.BlockSizes[1]/2;
var movementW = centerNext - newCenterNext;
if (movementW <= 0)
return;
_lookups.EnvelopeLookup.Shift(movementW);
_pcmCurrent -= movementW;
for (var channel = 0; channel < _pcm.Length; channel++)
Array.Copy(_pcm[channel], movementW, _pcm[channel], 0, _pcmCurrent);
_lastWindow = _currentWindow;
_currentWindow = _nextWindow;
_centerWindow = newCenterNext;
if (_eofFlag != 0)
{
_eofFlag -= movementW;
if (_eofFlag <= 0)
_eofFlag = -1;
// do not add padding to end of stream!
if (_centerWindow >= _eofFlag)
_granulePosition += movementW - (_centerWindow - _eofFlag);
else
_granulePosition += movementW;
}
else
{
_granulePosition += movementW;
}
}
private bool MarkEnvelope()
{
var ve = _lookups.EnvelopeLookup;
var ci = _vorbisInfo.CodecSetup;
var beginW = _centerWindow - ci.BlockSizes[_currentWindow]/4;
var endW = _centerWindow + ci.BlockSizes[_currentWindow]/4;
if (_currentWindow != 0)
{
beginW -= ci.BlockSizes[_lastWindow]/4;
endW += ci.BlockSizes[_nextWindow]/4;
}
else
{
beginW -= ci.BlockSizes[0]/4;
endW += ci.BlockSizes[0]/4;
}
return ve.Mark(beginW, endW);
}
public static ProcessingState Create(VorbisInfo info)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
var codecSetup = info.CodecSetup;
// initialize the storage vectors. blocksize[1] is small for encode, but the correct size for decode
var pcmStorage = codecSetup.BlockSizes[1];
var pcm = new float[info.Channels][];
for (var i = 0; i < pcm.Length; i++)
pcm[i] = new float[pcmStorage];
// Vorbis I uses only window type 0
var window = new int[2];
window[0] = Encoding.Log(codecSetup.BlockSizes[0]) - 7;
window[1] = Encoding.Log(codecSetup.BlockSizes[1]) - 7;
var centerWindow = codecSetup.BlockSizes[1]/2;
var lookups = LookupCollection.Create(info);
return new ProcessingState(
info,
lookups,
pcm,
window,
centerWindow);
}
private byte[] PerformAnalysis(
float[][] pcm,
int pcmEnd)
{
var channels = pcm.Length;
var gmdct = new float[channels][];
var work = new int[channels][];
var floorPosts = new int[channels][][];
var localAmpMax = new float[channels];
var blockType = 0;
if (_currentWindow != 0)
{
if ((_lastWindow != 0) && (_nextWindow != 0))
blockType = 1;
}
else
{
if (!MarkEnvelope())
blockType = 1;
}
var mapping = _vorbisInfo.CodecSetup.MapParams[_currentWindow];
var psyLookup = _lookups.PsyLookup[blockType + (_currentWindow != 0 ? 2 : 0)];
var buffer = new EncodeBuffer();
TransformPcm(pcm, pcmEnd, work, gmdct, localAmpMax);
ApplyMasks(pcm, pcmEnd, mapping, floorPosts, gmdct, psyLookup, localAmpMax);
Encode(pcm, pcmEnd, buffer, mapping, work, floorPosts, psyLookup, gmdct);
return buffer.GetBytes();
}
private void Encode(
float[][] pcm,
int pcmEnd,
EncodeBuffer buffer,
Mapping mapping,
int[][] work,
int[][][] floorPosts,
PsyLookup psyLookup,
float[][] gmdct)
{
var codecSetup = _vorbisInfo.CodecSetup;
var channels = pcm.Length;
var nonzero = new bool[channels];
//the next phases are performed once for vbr-only and PACKETBLOB
//times for bitrate managed modes.
//1) encode actual mode being used
//2) encode the floor for each channel, compute coded mask curve/res
//3) normalize and couple.
//4) encode residue
//5) save packet bytes to the packetblob vector
// iterate over the many masking curve fits we've created
var coupleBundle = new int[channels][];
var zerobundle = new bool[channels];
const int k = PsyGlobal.PacketBlobs/2;
// start out our new packet blob with packet type and mode
// Encode the packet type
buffer.Write(0, 1);
// Encode the modenumber
// Encode frame mode, pre,post windowsize, then dispatch
var modeBits = Encoding.Log(codecSetup.ModeParams.Count - 1);
buffer.Write((uint) _currentWindow, modeBits);
if (_currentWindow != 0)
{
buffer.Write((uint) _lastWindow, 1);
buffer.Write((uint) _nextWindow, 1);
}
// encode floor, compute masking curve, sep out residue
for (var i = 0; i < channels; i++)
{
var submap = mapping.ChannelMuxList[i];
nonzero[i] = _lookups.FloorLookup[mapping.FloorSubMap[submap]].Encode(
buffer,
codecSetup.BookParams,
codecSetup.FullBooks,
floorPosts[i][k],
work[i],
pcmEnd,
codecSetup.BlockSizes[_currentWindow]/2);
}
// our iteration is now based on masking curve, not prequant and
// coupling. Only one prequant/coupling step quantize/couple
// incomplete implementation that assumes the tree is all depth
// one, or no tree at all
psyLookup.CoupleQuantizeNormalize(
k,
codecSetup.PsyGlobalParam,
mapping,
gmdct,
work,
nonzero,
codecSetup.PsyGlobalParam.SlidingLowPass[_currentWindow][k],
channels);
// classify and encode by submap
for (var i = 0; i < mapping.SubMaps; i++)
{
var channelsInBundle = 0;
var resNumber = mapping.ResidueSubMap[i];
for (var j = 0; j < channels; j++)
if (mapping.ChannelMuxList[j] == i)
{
zerobundle[channelsInBundle] = nonzero[j];
coupleBundle[channelsInBundle++] = work[j];
}
var residue = _lookups.ResidueLookup[resNumber];
var classifications = residue.Class(
coupleBundle,
zerobundle,
channelsInBundle);
channelsInBundle = 0;
for (var j = 0; j < channels; j++)
if (mapping.ChannelMuxList[j] == i)
coupleBundle[channelsInBundle++] = work[j];
residue.Forward(
buffer,
pcmEnd,
coupleBundle,
zerobundle,
channelsInBundle,
classifications);
}
}
private void TransformPcm(
float[][] inputPcm,
int pcmEnd,
IList<int[]> work,
IList<float[]> gmdct,
IList<float> localAmpMax)
{
for (var channel = 0; channel < inputPcm.Length; channel++)
{
work[channel] = new int[pcmEnd/2];
gmdct[channel] = new float[pcmEnd/2];
var scale = 4f/pcmEnd;
var scaleDecibel = scale.ToDecibel() + DecibelOffset;
var pcm = inputPcm[channel];
// window the PCM data
ApplyWindow(
pcm,
_lastWindow,
_currentWindow,
_nextWindow);
// transform the PCM data - only MDCT right now..
var transform = _lookups.TransformLookup[_currentWindow];
transform.Forward(pcm, gmdct[channel]);
// FFT yields more accurate tonal estimation (not phase sensitive)
var ffft = _lookups.FftLookup[_currentWindow];
ffft.Forward(pcm);
pcm[0] = scaleDecibel
+ pcm[0].ToDecibel()
+ DecibelOffset;
localAmpMax[channel] = inputPcm[channel][0];
for (var j = 1; j < pcmEnd - 1; j += 2)
{
var temp = pcm[j]*pcm[j]
+ pcm[j + 1]*pcm[j + 1];
var index = (j + 1) >> 1;
temp = pcm[index] = scaleDecibel + .5f
*temp.ToDecibel()
+ DecibelOffset;
if (temp > localAmpMax[channel])
localAmpMax[channel] = temp;
}
if (localAmpMax[channel] > 0f)
localAmpMax[channel] = 0f;
}
}
private void ApplyWindow(
IList<float> pcm,
int lastWindow,
int window,
int nextWindow)
{
lastWindow = window != 0 ? lastWindow : 0;
nextWindow = window != 0 ? nextWindow : 0;
var windowLastWindow = Block.Windows[_window[lastWindow]];
var windowNextWindow = Block.Windows[_window[nextWindow]];
var blockSizes = _vorbisInfo.CodecSetup.BlockSizes;
var n = blockSizes[window];
var ln = blockSizes[lastWindow];
var rn = blockSizes[nextWindow];
var leftbegin = n/4 - ln/4;
var leftend = leftbegin + ln/2;
var rightbegin = n/2 + n/4 - rn/4;
var rightend = rightbegin + rn/2;
int i, p;
for (i = 0; i < leftbegin; i++)
pcm[i] = 0f;
for (p = 0; i < leftend; i++, p++)
pcm[i] *= windowLastWindow[p];
for (i = rightbegin, p = rn/2 - 1; i < rightend; i++, p--)
pcm[i] *= windowNextWindow[p];
for (; i < n; i++)
pcm[i] = 0f;
}
private void ApplyMasks(
float[][] inputPcm,
int pcmEnd,
Mapping mapping,
IList<int[][]> floorPosts,
float[][] gmdct,
PsyLookup psyLookup,
float[] localAmpMax)
{
var noise = new float[pcmEnd/2];
var tone = new float[pcmEnd/2];
for (var channel = 0; channel < inputPcm.Length; channel++)
{
// the encoder setup assumes that all the modes used by any
// specific bitrate tweaking use the same floor
var submap = mapping.ChannelMuxList[channel];
var pcm = inputPcm[channel];
var logmdct = new OffsetArray<float>(pcm, pcmEnd/2);
floorPosts[channel] = new int[PsyGlobal.PacketBlobs][];
for (var j = 0; j < pcmEnd/2; j++)
logmdct[j] = gmdct[channel][j].ToDecibel() + DecibelOffset;
// first step; noise masking. Not only does 'noise masking'
// give us curves from which we can decide how much resolution
// to give noise parts of the spectrum, it also implicitly hands
// us a tonality estimate (the larger the value in the
// 'noise_depth' vector, the more tonal that area is)
psyLookup.NoiseMask(logmdct, noise);
var globalAmpMax = (int) _lookups.PsyGlobalLookup.AmpMax;
foreach (var ampMax in localAmpMax)
if (ampMax > globalAmpMax)
globalAmpMax = (int) ampMax;
// second step: 'all the other stuff'; all the stuff that isn't
// computed/fit for bitrate management goes in the second psy
// vector. This includes tone masking, peak limiting and ATH
psyLookup.ToneMask(
pcm,
tone,
globalAmpMax,
localAmpMax[channel]);
// third step; we offset the noise vectors, overlay tone
//masking. We then do a floor1-specific line fit. If we're
//performing bitrate management, the line fit is performed
//multiple times for up/down tweakage on demand.
psyLookup.OffsetAndMix(
noise,
tone,
1,
pcm,
gmdct[channel],
logmdct);
var floor = _lookups.FloorLookup[mapping.FloorSubMap[submap]];
floorPosts[channel][PsyGlobal.PacketBlobs/2] = floor.Fit(logmdct, pcm);
}
}
}
}
| |
using UnityEngine;
using UnityEngine.Serialization;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Fungus
{
/**
* Temp hidden object which lets us use the entire inspector window to inspect
* the block command list.
*/
public class BlockInspector : ScriptableObject
{
[FormerlySerializedAs("sequence")]
public Block block;
}
/**
* Custom editor for the temp hidden object.
*/
[CustomEditor (typeof(BlockInspector), true)]
public class BlockInspectorEditor : Editor
{
protected Vector2 blockScrollPos;
protected Vector2 commandScrollPos;
protected bool resize = false;
protected float topPanelHeight = 50;
// Cache the block and command editors so we only create and destroy them
// when a different block / command is selected.
protected BlockEditor activeBlockEditor;
protected CommandEditor activeCommandEditor;
protected Command activeCommand; // Command currently being inspected
// Cached command editors to avoid creating / destroying editors more than necessary
// This list is static so persists between
protected static List<CommandEditor> cachedCommandEditors = new List<CommandEditor>();
protected void OnDestroy()
{
ClearEditors();
}
protected void OnEnable()
{
ClearEditors();
}
protected void OnDisable()
{
ClearEditors();
}
protected void ClearEditors()
{
foreach (CommandEditor commandEditor in cachedCommandEditors)
{
DestroyImmediate(commandEditor);
}
cachedCommandEditors.Clear();
activeCommandEditor = null;
}
public override void OnInspectorGUI ()
{
BlockInspector blockInspector = target as BlockInspector;
Block block = blockInspector.block;
if (block == null)
{
return;
}
Flowchart flowchart = block.GetFlowchart();
if (activeBlockEditor == null ||
block != activeBlockEditor.target)
{
DestroyImmediate(activeBlockEditor);
activeBlockEditor = Editor.CreateEditor(block) as BlockEditor;
}
activeBlockEditor.DrawBlockName(flowchart);
// Using a custom rect area to get the correct 5px indent for the scroll views
Rect blockRect = new Rect(5, topPanelHeight, Screen.width - 6, Screen.height - 70);
GUILayout.BeginArea(blockRect);
blockScrollPos = GUILayout.BeginScrollView(blockScrollPos, GUILayout.Height(flowchart.blockViewHeight));
activeBlockEditor.DrawBlockGUI(flowchart);
GUILayout.EndScrollView();
Command inspectCommand = null;
if (flowchart.selectedCommands.Count == 1)
{
inspectCommand = flowchart.selectedCommands[0];
}
if (Application.isPlaying &&
inspectCommand != null &&
inspectCommand.parentBlock != block)
{
GUILayout.EndArea();
Repaint();
return;
}
// Only change the activeCommand at the start of the GUI call sequence
if (Event.current.type == EventType.Layout)
{
activeCommand = inspectCommand;
}
DrawCommandUI(flowchart, inspectCommand);
}
public void DrawCommandUI(Flowchart flowchart, Command inspectCommand)
{
ResizeScrollView(flowchart);
GUILayout.Space(7);
activeBlockEditor.DrawButtonToolbar();
commandScrollPos = GUILayout.BeginScrollView(commandScrollPos);
if (inspectCommand != null)
{
if (activeCommandEditor == null ||
inspectCommand != activeCommandEditor.target)
{
// See if we have a cached version of the command editor already,
var editors = (from e in cachedCommandEditors where (e.target == inspectCommand) select e);
if (editors.Count() > 0)
{
// Use cached editor
activeCommandEditor = editors.First();
}
else
{
// No cached editor, so create a new one.
activeCommandEditor = Editor.CreateEditor(inspectCommand) as CommandEditor;
cachedCommandEditors.Add(activeCommandEditor);
}
}
if (activeCommandEditor != null)
{
activeCommandEditor.DrawCommandInspectorGUI();
}
}
GUILayout.EndScrollView();
GUILayout.EndArea();
// Draw the resize bar after everything else has finished drawing
// This is mainly to avoid incorrect indenting.
Rect resizeRect = new Rect(0, topPanelHeight + flowchart.blockViewHeight + 1, Screen.width, 4f);
GUI.color = new Color(0.64f, 0.64f, 0.64f);
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
resizeRect.height = 1;
GUI.color = new Color32(132, 132, 132, 255);
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
resizeRect.y += 3;
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
Repaint();
}
private void ResizeScrollView(Flowchart flowchart)
{
Rect cursorChangeRect = new Rect(0, flowchart.blockViewHeight + 1, Screen.width, 4f);
EditorGUIUtility.AddCursorRect(cursorChangeRect, MouseCursor.ResizeVertical);
if (Event.current.type == EventType.mouseDown && cursorChangeRect.Contains(Event.current.mousePosition))
{
resize = true;
}
if (resize)
{
Undo.RecordObject(flowchart, "Resize view");
flowchart.blockViewHeight = Event.current.mousePosition.y;
}
// Make sure block view is always visible
float height = flowchart.blockViewHeight;
height = Mathf.Max(200, height);
height = Mathf.Min(Screen.height - 200,height);
flowchart.blockViewHeight = height;
// Stop resizing if mouse is outside inspector window.
// This isn't standard Unity UI behavior but it is robust and safe.
if (resize && Event.current.type == EventType.mouseDrag)
{
Rect windowRect = new Rect(0, 0, Screen.width, Screen.height);
if (!windowRect.Contains(Event.current.mousePosition))
{
resize = false;
}
}
if (Event.current.type == EventType.MouseUp)
{
resize = false;
}
}
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 32-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
uint size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub,
out global::System.IntPtr returnFloatingPointReturn4Thunk,
out global::System.IntPtr returnFloatingPointReturn8Thunk)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
global::System.IntPtr unsafe_returnFloatingPointReturn4Thunk;
global::System.IntPtr unsafe_returnFloatingPointReturn8Thunk;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub),
&(unsafe_returnFloatingPointReturn4Thunk),
&(unsafe_returnFloatingPointReturn8Thunk)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
returnFloatingPointReturn8Thunk = unsafe_returnFloatingPointReturn8Thunk;
returnFloatingPointReturn4Thunk = unsafe_returnFloatingPointReturn4Thunk;
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
uint size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub,
global::System.IntPtr* returnFloatingPointReturn4Thunk,
global::System.IntPtr* returnFloatingPointReturn8Thunk);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace HelloWorlds.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Authenticated.Areas.HelpPage.Models;
namespace Authenticated.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Common
{
using System;
using System.Diagnostics;
using System.Threading;
[DebuggerStepThrough]
struct TimeoutHelper
{
DateTime deadline;
bool deadlineSet;
TimeSpan originalTimeout;
public static readonly TimeSpan MaxWait = TimeSpan.FromMilliseconds(Int32.MaxValue);
public TimeoutHelper(TimeSpan timeout) :
this(timeout, false)
{
}
public TimeoutHelper(TimeSpan timeout, bool startTimeout)
{
Fx.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative");
this.originalTimeout = timeout;
this.deadline = DateTime.MaxValue;
this.deadlineSet = (timeout == TimeSpan.MaxValue);
if (startTimeout && !this.deadlineSet)
{
this.SetDeadline();
}
}
public TimeSpan OriginalTimeout
{
get { return this.originalTimeout; }
}
public static bool IsTooLarge(TimeSpan timeout)
{
return (timeout > TimeoutHelper.MaxWait) && (timeout != TimeSpan.MaxValue);
}
public static TimeSpan FromMilliseconds(int milliseconds)
{
if (milliseconds == Timeout.Infinite)
{
return TimeSpan.MaxValue;
}
else
{
return TimeSpan.FromMilliseconds(milliseconds);
}
}
public static int ToMilliseconds(TimeSpan timeout)
{
if (timeout == TimeSpan.MaxValue)
{
return Timeout.Infinite;
}
else
{
long ticks = Ticks.FromTimeSpan(timeout);
if (ticks / TimeSpan.TicksPerMillisecond > int.MaxValue)
{
return int.MaxValue;
}
return Ticks.ToMilliseconds(ticks);
}
}
public static TimeSpan Min(TimeSpan val1, TimeSpan val2)
{
if (val1 > val2)
{
return val2;
}
else
{
return val1;
}
}
public static DateTime Min(DateTime val1, DateTime val2)
{
if (val1 > val2)
{
return val2;
}
else
{
return val1;
}
}
public static TimeSpan Add(TimeSpan timeout1, TimeSpan timeout2)
{
return Ticks.ToTimeSpan(Ticks.Add(Ticks.FromTimeSpan(timeout1), Ticks.FromTimeSpan(timeout2)));
}
public static DateTime Add(DateTime time, TimeSpan timeout)
{
if (timeout >= TimeSpan.Zero && DateTime.MaxValue - time <= timeout)
{
return DateTime.MaxValue;
}
if (timeout <= TimeSpan.Zero && DateTime.MinValue - time >= timeout)
{
return DateTime.MinValue;
}
return time + timeout;
}
public static DateTime Subtract(DateTime time, TimeSpan timeout)
{
return Add(time, TimeSpan.Zero - timeout);
}
public static TimeSpan Divide(TimeSpan timeout, int factor)
{
if (timeout == TimeSpan.MaxValue)
{
return TimeSpan.MaxValue;
}
return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1);
}
public TimeSpan RemainingTime()
{
if (!this.deadlineSet)
{
this.SetDeadline();
return this.originalTimeout;
}
else if (this.deadline == DateTime.MaxValue)
{
return TimeSpan.MaxValue;
}
else
{
TimeSpan remaining = this.deadline - DateTime.UtcNow;
if (remaining <= TimeSpan.Zero)
{
return TimeSpan.Zero;
}
else
{
return remaining;
}
}
}
public TimeSpan ElapsedTime()
{
return this.originalTimeout - this.RemainingTime();
}
void SetDeadline()
{
Fx.Assert(!deadlineSet, "TimeoutHelper deadline set twice.");
this.deadline = DateTime.UtcNow + this.originalTimeout;
this.deadlineSet = true;
}
public static void ThrowIfNegativeArgument(TimeSpan timeout)
{
ThrowIfNegativeArgument(timeout, "timeout");
}
public static void ThrowIfNegativeArgument(TimeSpan timeout, string argumentName)
{
if (timeout < TimeSpan.Zero)
{
throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, CommonResources.GetString(CommonResources.TimeoutMustBeNonNegative, argumentName, timeout));
}
}
public static void ThrowIfNonPositiveArgument(TimeSpan timeout)
{
ThrowIfNonPositiveArgument(timeout, "timeout");
}
public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentName)
{
if (timeout <= TimeSpan.Zero)
{
throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, CommonResources.GetString(CommonResources.TimeoutMustBePositive, argumentName, timeout));
}
}
#if !WINDOWS_UWP
[Fx.Tag.Blocking]
public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout)
{
ThrowIfNegativeArgument(timeout);
if (timeout == TimeSpan.MaxValue)
{
waitHandle.WaitOne();
return true;
}
else
{
return waitHandle.WaitOne(timeout, false);
}
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//Inner Product of two 2D array
using System;
public class ArrayClass
{
public int[,] a2d;
public int[,,] a3d;
public ArrayClass(int size)
{
a2d = new int[size, size];
a3d = new int[size, size, size];
}
}
public class intmm
{
public static int size;
public static Random rand;
public static ArrayClass ima;
public static ArrayClass imb;
public static ArrayClass imr;
public static void Init2DMatrix(out ArrayClass m, out int[][] refm)
{
int i, j, temp;
i = 0;
//m = new int[size, size];
m = new ArrayClass(size);
refm = new int[size][];
for (int k = 0; k < refm.Length; k++)
refm[k] = new int[size];
while (i < size)
{
j = 0;
while (j < size)
{
temp = rand.Next();
m.a2d[i, j] = temp - (temp / 120) * 120 - 60;
refm[i][j] = temp - (temp / 120) * 120 - 60;
j++;
}
i++;
}
}
public static void InnerProduct2D(out int res, ref ArrayClass a2d, ref ArrayClass b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a2d.a2d[row, i] * b.a2d[i, col];
i++;
}
}
public static void InnerProduct2DRef(out int res, ref int[][] a2d, ref int[][] b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a2d[row][i] * b[i][col];
i++;
}
}
public static void Init3DMatrix(ArrayClass m, int[][] refm)
{
int i, j, temp;
i = 0;
while (i < size)
{
j = 0;
while (j < size)
{
temp = rand.Next();
m.a3d[i, j, 0] = temp - (temp / 120) * 120 - 60;
refm[i][j] = temp - (temp / 120) * 120 - 60;
j++;
}
i++;
}
}
public static void InnerProduct3D(out int res, ArrayClass a3d, ArrayClass b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a3d.a3d[row, i, 0] * b.a3d[i, col, 0];
i++;
}
}
public static void InnerProduct3DRef(out int res, int[][] a3d, int[][] b, int row, int col)
{
int i;
res = 0;
i = 0;
while (i < size)
{
res = res + a3d[row][i] * b[i][col];
i++;
}
}
public static int Main()
{
bool pass = false;
rand = new Random();
size = rand.Next(2, 10);
Console.WriteLine();
Console.WriteLine("2D Array");
Console.WriteLine("Testing inner product of {0} by {0} matrices", size);
Console.WriteLine("the matrices are members of class");
Console.WriteLine("Matrix element stores random integer");
Console.WriteLine("array set/get, ref/out param are used");
ima = new ArrayClass(size);
imb = new ArrayClass(size);
imr = new ArrayClass(size);
int[][] refa2d = new int[size][];
int[][] refb2d = new int[size][];
int[][] refr2d = new int[size][];
for (int k = 0; k < refr2d.Length; k++)
refr2d[k] = new int[size];
Init2DMatrix(out ima, out refa2d);
Init2DMatrix(out imb, out refb2d);
int m = 0;
int n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
InnerProduct2D(out imr.a2d[m, n], ref ima, ref imb, m, n);
InnerProduct2DRef(out refr2d[m][n], ref refa2d, ref refb2d, m, n);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (imr.a2d[i, j] != refr2d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr.a2d[i,j] {2}!=refr2d[i][j] {3}", i, j, imr.a2d[i, j], refr2d[i][j]);
pass = false;
}
}
Console.WriteLine();
Console.WriteLine("3D Array");
Console.WriteLine("Testing inner product of one slice of two {0} by {0} by {0} matrices", size);
Console.WriteLine("the matrices are members of class and matrix element stores random integer");
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
imr.a3d[i, j, 0] = 1;
int[][] refa3d = new int[size][];
int[][] refb3d = new int[size][];
int[][] refr3d = new int[size][];
for (int k = 0; k < refa3d.Length; k++)
refa3d[k] = new int[size];
for (int k = 0; k < refb3d.Length; k++)
refb3d[k] = new int[size];
for (int k = 0; k < refr3d.Length; k++)
refr3d[k] = new int[size];
Init3DMatrix(ima, refa3d);
Init3DMatrix(imb, refb3d);
m = 0;
n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
InnerProduct3D(out imr.a3d[m, n, 0], ima, imb, m, n);
InnerProduct3DRef(out refr3d[m][n], refa3d, refb3d, m, n);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (imr.a3d[i, j, 0] != refr3d[i][j])
{
Console.WriteLine("i={0}, j={1}, imr.a3d[i,j,0] {2}!=refr3d[i][j] {3}", i, j, imr.a3d[i, j, 0], refr3d[i][j]);
pass = false;
}
}
Console.WriteLine();
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
{
Console.WriteLine("FAILED");
return 1;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using Microsoft.Diagnostics.Tracing.Parsers.Symbol;
using System;
using System.Diagnostics;
using System.Text;
using Address = System.UInt64;
#pragma warning disable 1591 // disable warnings on XML comments not being present
namespace Microsoft.Diagnostics.Tracing.Parsers
{
/// <summary>
/// Kernel traces have information about images that are loaded, however they don't have enough information
/// in the events themselves to unambigously look up PDBs without looking at the data inside the images.
/// This means that symbols can't be resolved unless you are on the same machine on which you gathered the data.
///
/// XPERF solves this problem by adding new 'synthetic' events that it creates by looking at the trace and then
/// opening each DLL mentioned and extracting the information needed to look PDBS up on a symbol server (this
/// includes the PE file's TimeDateStamp as well as a PDB Guid, and 'pdbAge' that can be found in the DLLs header.
///
/// These new events are added when XPERF runs the 'merge' command (or -d flag is passed). It is also exposed
/// through the KernelTraceControl.dll!CreateMergedTraceFile API.
///
/// SymbolTraceEventParser is a parser for extra events.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("traceparsergen", "1.0")]
public sealed class SymbolTraceEventParser : TraceEventParser
{
public static readonly string ProviderName = "KernelTraceControl";
public static readonly Guid ProviderGuid = new Guid(0x28ad2447, 0x105b, 0x4fe2, 0x95, 0x99, 0xe5, 0x9b, 0x2a, 0xa9, 0xa6, 0x34);
public SymbolTraceEventParser(TraceEventSource source)
: base(source)
{
}
/// <summary>
/// The DbgIDRSDS event is added by XPERF for every Image load. It contains the 'PDB signature' for the DLL,
/// which is enough to unambiguously look the image's PDB up on a symbol server.
/// </summary>
public event Action<DbgIDRSDSTraceData> ImageIDDbgID_RSDS
{
add
{
source.RegisterEventTemplate(new DbgIDRSDSTraceData(value, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_RSDS, "DbgID_RSDS", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, DBGID_LOG_TYPE_RSDS, ImageIDTaskGuid);
}
}
/// <summary>
/// Every DLL has a Timestamp in the PE file itself that indicates when it is built. This event dumps this timestamp.
/// This timestamp is used to be as the 'signature' of the image and is used as a key to find the symbols, however
/// this has mostly be superseded by the DbgID/RSDS event.
/// </summary>
public event Action<ImageIDTraceData> ImageID
{
add
{
source.RegisterEventTemplate(new ImageIDTraceData(value, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_IMAGEID, "Info", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, DBGID_LOG_TYPE_IMAGEID, ImageIDTaskGuid);
}
}
/// <summary>
/// The FileVersion event contains information from the file version resource that most DLLs have that indicated
/// detailed information about the exact version of the DLL. (What is in the File->Properties->Version property
/// page)
/// </summary>
public event Action<FileVersionTraceData> ImageIDFileVersion
{
add
{
source.RegisterEventTemplate(new FileVersionTraceData(value, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_FILEVERSION, "FileVersion", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, DBGID_LOG_TYPE_FILEVERSION, ImageIDTaskGuid);
}
}
/// <summary>
/// I don't really care about this one, but I need a definition in order to exclude it because it
/// has the same timestamp as a imageLoad event, and two events with the same timestamp confuse the
/// association between a stack and the event for the stack.
/// </summary>
public event Action<EmptyTraceData> ImageIDNone
{
add
{
source.RegisterEventTemplate(new EmptyTraceData(value, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_NONE, "None", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, DBGID_LOG_TYPE_NONE, ImageIDTaskGuid);
}
}
public event Action<DbgIDILRSDSTraceData> ImageIDDbgID_ILRSDS
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new DbgIDILRSDSTraceData(value, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_ILRSDS, "DbgID_ILRSDS", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, DBGID_LOG_TYPE_ILRSDS, ImageIDTaskGuid);
}
}
public event Action<DbgPPDBTraceData> ImageIDDbgPPDB
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new DbgPPDBTraceData(value, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_PPDB, "DbgPPDB", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, DBGID_LOG_TYPE_PPDB, ImageIDTaskGuid);
}
}
public event Action<DbgDetermTraceData> ImageIDDbgDeterm
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new DbgDetermTraceData(value, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_DETERM, "DbgDeterm", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, DBGID_LOG_TYPE_DETERM, ImageIDTaskGuid);
}
}
// The WinSat events are generated by merging, and are full of useful machine-wide information
// encoded as a compressed XML blob.
public event Action<WinSatXmlTraceData> WinSatWinSPR
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new WinSatXmlTraceData(value, 0xFFFF, 0, "WinSat", WinSatTaskGuid, 33, "WinSPR", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, 33, WinSatTaskGuid);
}
}
public event Action<WinSatXmlTraceData> WinSatMetrics
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new WinSatXmlTraceData(value, 0xFFFF, 0, "WinSat", WinSatTaskGuid, 35, "Metrics", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, 35, WinSatTaskGuid);
}
}
public event Action<WinSatXmlTraceData> WinSatSystemConfig
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new WinSatXmlTraceData(value, 0xFFFF, 0, "WinSat", WinSatTaskGuid, 37, "SystemConfig", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, 37, WinSatTaskGuid);
}
}
/// <summary>
/// This event has a TRACE_EVENT_INFO as its payload, and allows you to decode an event
/// </summary>
public event Action<EmptyTraceData> MetaDataEventInfo
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new EmptyTraceData(value, 0xFFFF, 0, "MetaData", MetaDataTaskGuid, 32, "EventInfo", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, 32, MetaDataTaskGuid);
}
}
/// <summary>
/// The event describes a Map (bitmap or ValueMap), and has a payload as follows
///
/// GUID ProviderId;
/// EVENT_MAP_INFO EventMapInfo;
/// </summary>
public event Action<EmptyTraceData> MetaDataEventMapInfo
{
add
{
// action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
source.RegisterEventTemplate(new EmptyTraceData(value, 0xFFFF, 0, "MetaData", MetaDataTaskGuid, 33, "EventMapInfo", ProviderGuid, ProviderName));
}
remove
{
source.UnregisterEventTemplate(value, 33, MetaDataTaskGuid);
}
}
#region Private
protected override string GetProviderName() { return ProviderName; }
static private volatile TraceEvent[] s_templates;
protected internal override void EnumerateTemplates(Func<string, string, EventFilterResponse> eventsToObserve, Action<TraceEvent> callback)
{
if (s_templates == null)
{
s_templates = new TraceEvent[]
{
new DbgIDRSDSTraceData(null, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_RSDS, "DbgID_RSDS", ProviderGuid, ProviderName),
new ImageIDTraceData(null, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_IMAGEID, "Info", ProviderGuid, ProviderName),
new FileVersionTraceData(null, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_FILEVERSION, "FileVersion", ProviderGuid, ProviderName),
new EmptyTraceData(null, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_NONE, "None", ProviderGuid, ProviderName),
new DbgIDILRSDSTraceData(null, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_ILRSDS, "DbgID_ILRSDS", ProviderGuid, ProviderName),
new DbgPPDBTraceData(null, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_PPDB, "DbgPPDB", ProviderGuid, ProviderName),
new DbgDetermTraceData(null, 0xFFFF, 0, "ImageID", ImageIDTaskGuid, DBGID_LOG_TYPE_DETERM, "DbgDeterm", ProviderGuid, ProviderName),
new WinSatXmlTraceData(null, 0xFFFF, 0, "WinSat", WinSatTaskGuid, 33, "WinSPR", ProviderGuid, ProviderName),
new WinSatXmlTraceData(null, 0xFFFF, 0, "WinSat", WinSatTaskGuid, 35, "Metrics", ProviderGuid, ProviderName),
new WinSatXmlTraceData(null, 0xFFFF, 0, "WinSat", WinSatTaskGuid, 37, "SystemConfig", ProviderGuid, ProviderName),
new EmptyTraceData(null, 0xFFFF, 0, "MetaData", MetaDataTaskGuid, 32, "EventInfo", ProviderGuid, ProviderName),
new EmptyTraceData(null, 0xFFFF, 0, "MetaData", MetaDataTaskGuid, 33, "EventMapInfo", ProviderGuid, ProviderName)
};
}
foreach (var template in s_templates)
if (eventsToObserve == null || eventsToObserve(template.ProviderName, template.EventName) == EventFilterResponse.AcceptEvent)
callback(template);
}
// These are the Opcode numbers for various events
public const int DBGID_LOG_TYPE_IMAGEID = 0x00;
public const int DBGID_LOG_TYPE_NONE = 0x20;
public const int DBGID_LOG_TYPE_RSDS = 0x24;
public const int DBGID_LOG_TYPE_ILRSDS = 0x25;
public const int DBGID_LOG_TYPE_PPDB = 0x26;
public const int DBGID_LOG_TYPE_DETERM = 0x28;
public const int DBGID_LOG_TYPE_FILEVERSION = 0x40;
// Used to log meta-data about crimson events into the log.
internal static readonly Guid ImageIDTaskGuid = new Guid(unchecked((int)0xB3E675D7), 0x2554, 0x4f18, 0x83, 0x0B, 0x27, 0x62, 0x73, 0x25, 0x60, 0xDE);
internal static readonly Guid WinSatTaskGuid = new Guid(unchecked((int)0xed54dff8), unchecked((short)0xc409), 0x4cf6, 0xbf, 0x83, 0x05, 0xe1, 0xe6, 0x1a, 0x09, 0xc4);
internal static readonly Guid MetaDataTaskGuid = new Guid(unchecked((int)0xbbccf6c1), 0x6cd1, 0x48c4, 0x80, 0xff, 0x83, 0x94, 0x82, 0xe3, 0x76, 0x71);
internal static readonly Guid PerfTrackMetaDataTaskGuid = new Guid(unchecked((int)0xbf6ef1cb), unchecked((short)0x89b5), 0x490, 0x80, 0xac, 0xb1, 0x80, 0xcf, 0xbc, 0xff, 0x0f);
#endregion
}
}
namespace Microsoft.Diagnostics.Tracing.Parsers.Symbol
{
public sealed class FileVersionTraceData : TraceEvent
{
public int ImageSize { get { return GetInt32At(0); } }
public int TimeDateStamp { get { return GetInt32At(4); } }
public DateTime BuildTime { get { return PEFile.PEHeader.TimeDateStampToDate(TimeDateStamp); } }
public string OrigFileName { get { return GetUnicodeStringAt(8); } }
public string FileDescription { get { return GetUnicodeStringAt(SkipUnicodeString(8, 1)); } }
public string FileVersion { get { return GetUnicodeStringAt(SkipUnicodeString(8, 2)); } }
public string BinFileVersion { get { return GetUnicodeStringAt(SkipUnicodeString(8, 3)); } }
public string VerLanguage { get { return GetUnicodeStringAt(SkipUnicodeString(8, 4)); } }
public string ProductName { get { return GetUnicodeStringAt(SkipUnicodeString(8, 5)); } }
public string CompanyName { get { return GetUnicodeStringAt(SkipUnicodeString(8, 6)); } }
public string ProductVersion { get { return GetUnicodeStringAt(SkipUnicodeString(8, 7)); } }
public string FileId { get { return GetUnicodeStringAt(SkipUnicodeString(8, 8)); } }
public string ProgramId { get { return GetUnicodeStringAt(SkipUnicodeString(8, 9)); } }
#region Private
internal FileVersionTraceData(Action<FileVersionTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opCode, string opCodeName, Guid providerGuid, string providerName) :
base(eventID, task, taskName, taskGuid, opCode, opCodeName, providerGuid, providerName)
{
Action = action;
}
protected internal override void Dispatch()
{
Action(this);
}
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<FileVersionTraceData>)value; }
}
protected internal override void Validate()
{
Debug.Assert(EventDataLength == SkipUnicodeString(8, 10));
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
{
payloadNames = new string[] { "ImageSize", "TimeDateStamp", "BuildTime", "OrigFileName", "FileDescription", "FileVersion",
"BinFileVersion", "VerLanguage", "ProductName", "CompanyName", "ProductVersion", "FileId", "ProgramId" };
}
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImageSize;
case 1:
return TimeDateStamp;
case 2:
return BuildTime;
case 3:
return OrigFileName;
case 4:
return FileDescription;
case 5:
return FileVersion;
case 6:
return BinFileVersion;
case 7:
return VerLanguage;
case 8:
return ProductName;
case 9:
return CompanyName;
case 10:
return ProductVersion;
case 11:
return FileId;
case 12:
return ProgramId;
default:
Debug.Assert(false, "invalid index");
return null;
}
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttribHex(sb, "ImageSize", ImageSize);
XmlAttribHex(sb, "TimeDateStamp", TimeDateStamp);
XmlAttrib(sb, "OrigFileName", OrigFileName);
XmlAttrib(sb, "FileDescription", FileDescription);
XmlAttrib(sb, "FileVersion", FileVersion);
XmlAttrib(sb, "BinFileVersion", BinFileVersion);
XmlAttrib(sb, "VerLanguage", VerLanguage);
XmlAttrib(sb, "ProductName", ProductName);
XmlAttrib(sb, "CompanyName", CompanyName);
XmlAttrib(sb, "ProductVersion", ProductVersion);
XmlAttrib(sb, "FileId", FileId);
XmlAttrib(sb, "ProgramId", ProgramId);
sb.Append("/>");
return sb;
}
private Action<FileVersionTraceData> Action;
#endregion
}
public sealed class DbgIDRSDSTraceData : TraceEvent
{
public Address ImageBase { get { return GetAddressAt(0); } }
// public int ProcessID { get { return GetInt32At(HostOffset(4, 1)); } } // This seems to be redundant with the ProcessID in the event header
public Guid GuidSig { get { return GetGuidAt(HostOffset(8, 1)); } }
public int Age { get { return GetInt32At(HostOffset(24, 1)); } }
public string PdbFileName { get { return GetUTF8StringAt(HostOffset(28, 1)); } }
#region Private
internal DbgIDRSDSTraceData(Action<DbgIDRSDSTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opCode, string opCodeName, Guid providerGuid, string providerName) :
base(eventID, task, taskName, taskGuid, opCode, opCodeName, providerGuid, providerName)
{
Action = action;
}
protected internal override void Dispatch()
{
Action(this);
}
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<DbgIDRSDSTraceData>)value; }
}
protected internal override void Validate()
{
Debug.Assert(EventDataLength == SkipUTF8String(HostOffset(28, 1)));
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
{
payloadNames = new string[] { "ImageBase", "GuidSig", "Age", "PDBFileName" };
}
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImageBase;
case 1:
return GuidSig;
case 2:
return Age;
case 3:
return PdbFileName;
default:
Debug.Assert(false, "invalid index");
return null;
}
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttribHex(sb, "ImageBase", ImageBase);
XmlAttrib(sb, "GuidSig", GuidSig);
XmlAttrib(sb, "Age", Age);
XmlAttrib(sb, "PdbFileName", PdbFileName);
sb.Append("/>");
return sb;
}
private Action<DbgIDRSDSTraceData> Action;
#endregion
}
public sealed class ImageIDTraceData : TraceEvent
{
public Address ImageBase { get { return GetAddressAt(0); } }
public long ImageSize { get { return GetIntPtrAt(HostOffset(4, 1)); } }
// Seems to always be 0
// public int ProcessID { get { return GetInt32At(HostOffset(8, 2)); } }
public int TimeDateStamp { get { return GetInt32At(HostOffset(12, 2)); } }
public DateTime BuildTime { get { return PEFile.PEHeader.TimeDateStampToDate(TimeDateStamp); } }
public string OriginalFileName { get { return GetUnicodeStringAt(HostOffset(16, 2)); } }
#region Private
internal ImageIDTraceData(Action<ImageIDTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opCode, string opCodeName, Guid providerGuid, string providerName) :
base(eventID, task, taskName, taskGuid, opCode, opCodeName, providerGuid, providerName)
{
Action = action;
}
protected internal override void Dispatch()
{
Action(this);
}
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<ImageIDTraceData>)value; }
}
protected internal override void Validate()
{
Debug.Assert(EventDataLength == SkipUnicodeString(HostOffset(16, 2)));
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
{
payloadNames = new string[] { "ImageBase", "ImageSize", "ProcessID", "TimeDateStamp", "BuildTime", "OriginalFileName" };
}
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImageBase;
case 1:
return ImageSize;
case 2:
return 0;
case 3:
return TimeDateStamp;
case 4:
return BuildTime;
case 5:
return OriginalFileName;
default:
Debug.Assert(false, "bad index value");
return null;
}
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttribHex(sb, "ImageBase", ImageBase);
XmlAttribHex(sb, "ImageSize", ImageSize);
XmlAttribHex(sb, "TimeDateStamp", TimeDateStamp);
XmlAttrib(sb, "BuildTime", BuildTime);
XmlAttrib(sb, "OriginalFileName", OriginalFileName);
sb.Append("/>");
return sb;
}
private event Action<ImageIDTraceData> Action;
#endregion
}
public sealed class DbgIDILRSDSTraceData : TraceEvent
{
public Address ImageBase { get { return GetAddressAt(0); } }
// This seems to be redundant with the ProcessID in the event header
//public int ProcessID { get { return GetInt32At(HostOffset(4, 1)); } }
public Guid GuidSig { get { return GetGuidAt(HostOffset(8, 1)); } }
public int Age { get { return GetInt32At(HostOffset(24, 1)); } }
public string PdbFileName { get { return GetUTF8StringAt(HostOffset(28, 1)); } }
#region Private
internal DbgIDILRSDSTraceData(Action<DbgIDILRSDSTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opCode, string opCodeName, Guid providerGuid, string providerName) :
base(eventID, task, taskName, taskGuid, opCode, opCodeName, providerGuid, providerName)
{
Action = action;
}
protected internal override void Dispatch()
{
Action(this);
}
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<DbgIDILRSDSTraceData>)value; }
}
protected internal override void Validate()
{
Debug.Assert(EventDataLength == SkipUTF8String(HostOffset(32, 1)));
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
{
payloadNames = new string[] { "ImageBase", "GuidSig", "Age", "PDBFileName" };
}
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImageBase;
case 1:
return GuidSig;
case 2:
return Age;
case 3:
return PdbFileName;
default:
Debug.Assert(false, "invalid index");
return null;
}
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttribHex(sb, "ImageBase", ImageBase);
XmlAttrib(sb, "GuidSig", GuidSig);
XmlAttrib(sb, "Age", Age);
XmlAttrib(sb, "PdbFileName", PdbFileName);
sb.Append("/>");
return sb;
}
private event Action<DbgIDILRSDSTraceData> Action;
#endregion
}
public sealed class DbgPPDBTraceData : TraceEvent
{
public Address ImageBase { get { return GetAddressAt(0); } }
// This seems to be redundant with the ProcessID in the event header
//public int ProcessID { get { return GetInt32At(HostOffset(4, 1)); } }
public int TimeDateStamp { get { return GetInt32At(HostOffset(8, 1)); } }
public int MajorVersion { get { return GetByteAt(HostOffset(12, 1)); } }
public int MinorVersion { get { return GetByteAt(HostOffset(14, 1)); } }
#region Private
internal DbgPPDBTraceData(Action<DbgPPDBTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opCode, string opCodeName, Guid providerGuid, string providerName) :
base(eventID, task, taskName, taskGuid, opCode, opCodeName, providerGuid, providerName)
{
Action = action;
}
protected internal override void Dispatch()
{
Action(this);
}
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<DbgPPDBTraceData>)value; }
}
protected internal override void Validate()
{
Debug.Assert(EventDataLength == HostOffset(16, 1));
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
{
payloadNames = new string[] { "ImageBase", "TimeDateStamp", "MajorVersion", "MinorVersion" };
}
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImageBase;
case 1:
return TimeDateStamp;
case 2:
return MajorVersion;
case 3:
return MinorVersion;
default:
Debug.Assert(false, "bad index value");
return null;
}
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttribHex(sb, "ImageBase", ImageBase);
XmlAttribHex(sb, "TimeDateStamp", TimeDateStamp);
XmlAttrib(sb, "MajorVersion", MajorVersion);
XmlAttrib(sb, "MinorVersion", MinorVersion);
sb.Append("/>");
return sb;
}
private event Action<DbgPPDBTraceData> Action;
#endregion
}
public sealed class DbgDetermTraceData : TraceEvent
{
public Address ImageBase { get { return GetAddressAt(0); } }
// This seems to be redundant with the ProcessID in the event header
//public int ProcessID { get { return GetInt32At(HostOffset(4, 1)); } }
#region Private
internal DbgDetermTraceData(Action<DbgDetermTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opCode, string opCodeName, Guid providerGuid, string providerName) :
base(eventID, task, taskName, taskGuid, opCode, opCodeName, providerGuid, providerName)
{
Action = action;
}
protected internal override void Dispatch()
{
Action(this);
}
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<DbgDetermTraceData>)value; }
}
protected internal override void Validate()
{
Debug.Assert(EventDataLength == HostOffset(8, 1));
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
{
payloadNames = new string[] { "ImageBase" };
}
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImageBase;
default:
Debug.Assert(false, "bad index value");
return null;
}
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttribHex(sb, "ImageBase", ImageBase);
sb.Append("/>");
return sb;
}
private event Action<DbgDetermTraceData> Action;
#endregion
}
public sealed class WinSatXmlTraceData : TraceEvent
{
/// <summary>
/// The value of the one string payload property.
/// </summary>
public string Xml
{
get
{
if (m_xml == null)
{
m_xml = GetXml();
}
return m_xml;
}
}
/// <summary>
/// Construct a TraceEvent template which has one string payload field with the given metadata and action
/// </summary>
public WinSatXmlTraceData(Action<WinSatXmlTraceData> action, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
Action = action;
}
#region Private
/// <summary>
/// implementation of TraceEvent Interface.
/// </summary>
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
sb.Append(">");
sb.AppendLine(Xml);
sb.AppendLine("</Event>");
return sb;
}
/// <summary>
/// implementation of TraceEvent Interface.
/// </summary>
public override string[] PayloadNames
{
get
{
// We dont put the XML in the fields because it is too big (it does go in the ToXml).
if (payloadNames == null)
{
payloadNames = new string[] { };
}
return payloadNames;
}
}
/// <summary>
/// implementation of TraceEvent Interface.
/// </summary>
public override object PayloadValue(int index)
{
Debug.Assert(index < 1);
switch (index)
{
default:
return null;
}
}
private event Action<WinSatXmlTraceData> Action;
/// <summary>
/// implementation of TraceEvent Interface.
/// </summary>
protected internal override void Dispatch()
{
Action(this);
}
/// <summary>
/// override
/// </summary>
protected internal override Delegate Target
{
get { return Action; }
set { Action = (Action<WinSatXmlTraceData>)value; }
}
private unsafe string GetXml()
{
int uncompressedSize = GetInt32At(4);
if (0x10000 <= uncompressedSize)
{
return "";
}
byte[] uncompressedData = new byte[uncompressedSize];
fixed (byte* uncompressedPtr = uncompressedData)
{
byte* compressedData = ((byte*)DataStart) + 8; // Skip header (State + UncompressedLength)
int compressedSize = EventDataLength - 8; // Compressed size is total size minus header.
int resultSize = 0;
int hr = TraceEventNativeMethods.RtlDecompressBuffer(
TraceEventNativeMethods.COMPRESSION_FORMAT_LZNT1 | TraceEventNativeMethods.COMPRESSION_ENGINE_MAXIMUM,
uncompressedPtr,
uncompressedSize,
compressedData,
compressedSize,
out resultSize);
if (hr == 0 && resultSize == uncompressedSize)
{
var indent = 0;
// PrettyPrint the XML
char* charPtr = (Char*)uncompressedPtr;
StringBuilder sb = new StringBuilder();
char* charEnd = &charPtr[uncompressedSize / 2];
bool noChildren = true;
while (charPtr < charEnd)
{
char c = *charPtr;
if (c == 0)
{
break; // we will assume null termination
}
if (c == '<')
{
var c1 = charPtr[1];
bool newLine = false;
if (c1 == '/')
{
newLine = !noChildren;
noChildren = false;
}
else if (Char.IsLetter(c1))
{
noChildren = true;
newLine = true;
indent++;
}
if (newLine)
{
sb.AppendLine();
for (int i = 0; i < indent; i++)
{
sb.Append(' ');
}
}
if (c1 == '/')
{
--indent;
}
}
sb.Append(c);
charPtr++;
}
return sb.ToString();
}
}
return "";
}
private string m_xml;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace MS.Internal.Xml.XPath
{
internal sealed class StringFunctions : ValueQuery
{
private Function.FunctionType _funcType;
private IList<Query> _argList;
public StringFunctions(Function.FunctionType funcType, IList<Query> argList)
{
Debug.Assert(argList != null, "Use 'new Query[]{}' instead.");
_funcType = funcType;
_argList = argList;
}
private StringFunctions(StringFunctions other) : base(other)
{
_funcType = other._funcType;
Query[] tmp = new Query[other._argList.Count];
{
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = Clone(other._argList[i]);
}
}
_argList = tmp;
}
public override void SetXsltContext(XsltContext context)
{
for (int i = 0; i < _argList.Count; i++)
{
_argList[i].SetXsltContext(context);
}
}
public override object Evaluate(XPathNodeIterator nodeIterator)
{
switch (_funcType)
{
case Function.FunctionType.FuncString: return toString(nodeIterator);
case Function.FunctionType.FuncConcat: return Concat(nodeIterator);
case Function.FunctionType.FuncStartsWith: return StartsWith(nodeIterator);
case Function.FunctionType.FuncContains: return Contains(nodeIterator);
case Function.FunctionType.FuncSubstringBefore: return SubstringBefore(nodeIterator);
case Function.FunctionType.FuncSubstringAfter: return SubstringAfter(nodeIterator);
case Function.FunctionType.FuncSubstring: return Substring(nodeIterator);
case Function.FunctionType.FuncStringLength: return StringLength(nodeIterator);
case Function.FunctionType.FuncNormalize: return Normalize(nodeIterator);
case Function.FunctionType.FuncTranslate: return Translate(nodeIterator);
}
return string.Empty;
}
internal static string toString(double num)
{
return num.ToString("R", NumberFormatInfo.InvariantInfo);
}
internal static string toString(bool b)
{
return b ? "true" : "false";
}
private string toString(XPathNodeIterator nodeIterator)
{
if (_argList.Count > 0)
{
object argVal = _argList[0].Evaluate(nodeIterator);
switch (GetXPathType(argVal))
{
case XPathResultType.NodeSet:
XPathNavigator value = _argList[0].Advance();
return value != null ? value.Value : string.Empty;
case XPathResultType.String:
return (string)argVal;
case XPathResultType.Boolean:
return ((bool)argVal) ? "true" : "false";
case XPathResultType_Navigator:
return ((XPathNavigator)argVal).Value;
default:
Debug.Assert(GetXPathType(argVal) == XPathResultType.Number);
return toString((double)argVal);
}
}
return nodeIterator.Current.Value;
}
public override XPathResultType StaticType
{
get
{
if (_funcType == Function.FunctionType.FuncStringLength)
{
return XPathResultType.Number;
}
if (
_funcType == Function.FunctionType.FuncStartsWith ||
_funcType == Function.FunctionType.FuncContains
)
{
return XPathResultType.Boolean;
}
return XPathResultType.String;
}
}
private string Concat(XPathNodeIterator nodeIterator)
{
int count = 0;
StringBuilder s = new StringBuilder();
while (count < _argList.Count)
{
s.Append(_argList[count++].Evaluate(nodeIterator).ToString());
}
return s.ToString();
}
private bool StartsWith(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0;
}
private static readonly CompareInfo s_compareInfo = CultureInfo.InvariantCulture.CompareInfo;
private bool Contains(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
return s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0;
}
private string SubstringBefore(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s2; }
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 1) ? string.Empty : s1.Substring(0, idx);
}
private string SubstringAfter(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s1; }
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length);
}
private string Substring(XPathNodeIterator nodeIterator)
{
string str1 = _argList[0].Evaluate(nodeIterator).ToString();
double num = XmlConvert.XPathRound(XmlConvert.ToXPathDouble(_argList[1].Evaluate(nodeIterator))) - 1;
if (Double.IsNaN(num) || str1.Length <= num)
{
return string.Empty;
}
if (_argList.Count == 3)
{
double num1 = XmlConvert.XPathRound(XmlConvert.ToXPathDouble(_argList[2].Evaluate(nodeIterator)));
if (Double.IsNaN(num1))
{
return string.Empty;
}
if (num < 0 || num1 < 0)
{
num1 = num + num1;
// NOTE: condition is true for NaN
if (!(num1 > 0))
{
return string.Empty;
}
num = 0;
}
double maxlength = str1.Length - num;
if (num1 > maxlength)
{
num1 = maxlength;
}
return str1.Substring((int)num, (int)num1);
}
if (num < 0)
{
num = 0;
}
return str1.Substring((int)num);
}
private Double StringLength(XPathNodeIterator nodeIterator)
{
if (_argList.Count > 0)
{
return _argList[0].Evaluate(nodeIterator).ToString().Length;
}
return nodeIterator.Current.Value.Length;
}
private string Normalize(XPathNodeIterator nodeIterator)
{
string value;
if (_argList.Count > 0)
{
value = _argList[0].Evaluate(nodeIterator).ToString();
}
else
{
value = nodeIterator.Current.Value;
}
int modifyPos = -1;
char[] chars = value.ToCharArray();
bool firstSpace = false; // Start false to trim the beginning
XmlCharType xmlCharType = XmlCharType.Instance;
for (int comparePos = 0; comparePos < chars.Length; comparePos++)
{
if (!xmlCharType.IsWhiteSpace(chars[comparePos]))
{
firstSpace = true;
modifyPos++;
chars[modifyPos] = chars[comparePos];
}
else if (firstSpace)
{
firstSpace = false;
modifyPos++;
chars[modifyPos] = ' ';
}
}
// Trim end
if (modifyPos > -1 && chars[modifyPos] == ' ')
modifyPos--;
return new string(chars, 0, modifyPos + 1);
}
private string Translate(XPathNodeIterator nodeIterator)
{
string value = _argList[0].Evaluate(nodeIterator).ToString();
string mapFrom = _argList[1].Evaluate(nodeIterator).ToString();
string mapTo = _argList[2].Evaluate(nodeIterator).ToString();
int modifyPos = -1;
char[] chars = value.ToCharArray();
for (int comparePos = 0; comparePos < chars.Length; comparePos++)
{
int index = mapFrom.IndexOf(chars[comparePos]);
if (index != -1)
{
if (index < mapTo.Length)
{
modifyPos++;
chars[modifyPos] = mapTo[index];
}
}
else
{
modifyPos++;
chars[modifyPos] = chars[comparePos];
}
}
return new string(chars, 0, modifyPos + 1);
}
public override XPathNodeIterator Clone() { return new StringFunctions(this); }
public override void PrintQuery(XmlWriter w)
{
w.WriteStartElement(this.GetType().Name);
w.WriteAttributeString("name", _funcType.ToString());
foreach (Query arg in _argList)
{
arg.PrintQuery(w);
}
w.WriteEndElement();
}
}
}
| |
#pragma warning disable 1591
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Braintree
{
public enum CreditCardCustomerLocation
{
[Description("us")] US,
[Description("international")] INTERNATIONAL,
[Description("unrecognized")] UNRECOGNIZED
}
public enum CreditCardPrepaid
{
[Description("Yes")] YES,
[Description("No")] NO,
[Description("Unknown")] UNKNOWN
}
public enum CreditCardPayroll
{
[Description("Yes")] YES,
[Description("No")] NO,
[Description("Unknown")] UNKNOWN
}
public enum CreditCardDebit
{
[Description("Yes")] YES,
[Description("No")] NO,
[Description("Unknown")] UNKNOWN
}
public enum CreditCardCommercial
{
[Description("Yes")] YES,
[Description("No")] NO,
[Description("Unknown")] UNKNOWN
}
public enum CreditCardHealthcare
{
[Description("Yes")] YES,
[Description("No")] NO,
[Description("Unknown")] UNKNOWN
}
public enum CreditCardDurbinRegulated
{
[Description("Yes")] YES,
[Description("No")] NO,
[Description("Unknown")] UNKNOWN
}
public enum CreditCardCardType
{
[Description("American Express")] AMEX,
[Description("Carte Blanche")] CARTE_BLANCHE,
[Description("China UnionPay")] CHINA_UNION_PAY,
[Description("UnionPay")] UNION_PAY,
[Description("Diners Club")] DINERS_CLUB_INTERNATIONAL,
[Description("Discover")] DISCOVER,
[Description("Elo")] ELO,
[Description("JCB")] JCB,
[Description("Laser")] LASER,
[Description("UK Maestro")] UK_MAESTRO,
[Description("Maestro")] MAESTRO,
[Description("MasterCard")] MASTER_CARD,
[Description("Solo")] SOLO,
[Description("Switch")] SWITCH,
[Description("Visa")] VISA,
[Description("Unknown")] UNKNOWN,
[Description("Unrecognized")] UNRECOGNIZED
}
/// <summary>
/// A credit card returned by the Braintree Gateway
/// </summary>
/// <remarks>
/// A credit card can belong to:
/// <ul>
/// <li>a <see cref="Customer"/> as a stored credit card</li>
/// <li>a <see cref="Transaction"/> as the credit card used for the transaction</li>
/// </ul>
/// </remarks>
/// <example>
/// Credit Cards can be retrieved via the gateway using the associated credit card token:
/// <code>
/// CreditCard creditCard = gateway.CreditCard.Find("token");
/// </code>
/// For more information about Credit Cards, see <a href="https://developer.paypal.com/braintree/docs/reference/response/credit-card/dotnet" target="_blank">https://developer.paypal.com/braintree/docs/reference/response/credit-card/dotnet</a><br />
/// For more information about Credit Card Verifications, see <a href="https://developer.paypal.com/braintree/docs/reference/response/credit-card-verification/dotnet" target="_blank">https://developer.paypal.com/braintree/docs/reference/response/credit-card-verification/dotnet</a>
/// </example>
public class CreditCard : PaymentMethod
{
public static readonly string CountryOfIssuanceUnknown = "Unknown";
public static readonly string IssuingBankUnknown = "Unknown";
public static readonly string ProductIdUnknown = "Unknown";
public virtual string Bin { get; protected set; }
public virtual string CardholderName { get; protected set; }
public virtual CreditCardCardType CardType { get; protected set; }
public virtual DateTime? CreatedAt { get; protected set; }
public virtual string CustomerId { get; protected set; }
public virtual bool? IsDefault { get; protected set; }
public virtual bool? IsVenmoSdk { get; protected set; }
public virtual bool? IsExpired { get; protected set; }
public virtual bool? IsNetworkTokenized { get; protected set; }
public virtual CreditCardCustomerLocation CustomerLocation { get; protected set; }
public virtual string LastFour { get; protected set; }
public virtual string UniqueNumberIdentifier { get; protected set; }
public virtual Subscription[] Subscriptions { get; protected set; }
public virtual string Token { get; protected set; }
public virtual DateTime? UpdatedAt { get; protected set; }
public virtual Address BillingAddress { get; protected set; }
public virtual string ExpirationMonth { get; protected set; }
public virtual string ExpirationYear { get; protected set; }
public virtual CreditCardPrepaid Prepaid { get; protected set; }
public virtual CreditCardPayroll Payroll { get; protected set; }
public virtual CreditCardDebit Debit { get; protected set; }
public virtual CreditCardCommercial Commercial { get; protected set; }
public virtual CreditCardHealthcare Healthcare { get; protected set; }
public virtual CreditCardDurbinRegulated DurbinRegulated { get; protected set; }
public virtual string ImageUrl { get; protected set; }
public virtual CreditCardVerification Verification { get; protected set; }
public virtual string AccountType { get; protected set; }
private string _CountryOfIssuance;
public virtual string CountryOfIssuance
{
get
{
if (_CountryOfIssuance == "")
{
return CountryOfIssuanceUnknown;
}
else
{
return _CountryOfIssuance;
}
}
}
private string _IssuingBank;
public virtual string IssuingBank
{
get
{
if (_IssuingBank == "")
{
return IssuingBankUnknown;
}
else
{
return _IssuingBank;
}
}
}
private string _ProductId;
public virtual string ProductId
{
get
{
if (_ProductId == "")
{
return ProductIdUnknown;
}
else
{
return _ProductId;
}
}
}
public virtual string ExpirationDate
{
get => ExpirationMonth + "/" + ExpirationYear;
protected set
{
ExpirationMonth = value.Split('/')[0];
ExpirationYear = value.Split('/')[1];
}
}
public string MaskedNumber => $"{Bin}******{LastFour}";
protected internal CreditCard(NodeWrapper node, IBraintreeGateway gateway)
{
if (node == null) return;
Bin = node.GetString("bin");
CardholderName = node.GetString("cardholder-name");
CardType = node.GetEnum("card-type", CreditCardCardType.UNRECOGNIZED);
CustomerId = node.GetString("customer-id");
IsDefault = node.GetBoolean("default");
IsVenmoSdk = node.GetBoolean("venmo-sdk");
ExpirationMonth = node.GetString("expiration-month");
ExpirationYear = node.GetString("expiration-year");
IsExpired = node.GetBoolean("expired");
IsNetworkTokenized = node.GetBoolean("is-network-tokenized");
CustomerLocation = node.GetEnum("customer-location", CreditCardCustomerLocation.UNRECOGNIZED);
LastFour = node.GetString("last-4");
UniqueNumberIdentifier = node.GetString("unique-number-identifier");
Token = node.GetString("token");
CreatedAt = node.GetDateTime("created-at");
UpdatedAt = node.GetDateTime("updated-at");
BillingAddress = new Address(node.GetNode("billing-address"));
Prepaid = node.GetEnum("prepaid", CreditCardPrepaid.UNKNOWN);
Payroll = node.GetEnum("payroll", CreditCardPayroll.UNKNOWN);
DurbinRegulated = node.GetEnum("durbin-regulated", CreditCardDurbinRegulated.UNKNOWN);
Debit = node.GetEnum("debit", CreditCardDebit.UNKNOWN);
Commercial = node.GetEnum("commercial", CreditCardCommercial.UNKNOWN);
Healthcare = node.GetEnum("healthcare", CreditCardHealthcare.UNKNOWN);
AccountType = node.GetString("account-type");
_CountryOfIssuance = node.GetString("country-of-issuance");
_IssuingBank = node.GetString("issuing-bank");
_ProductId = node.GetString("product-id");
ImageUrl = node.GetString("image-url");
var subscriptionXmlNodes = node.GetList("subscriptions/subscription");
Subscriptions = new Subscription[subscriptionXmlNodes.Count];
for (int i = 0; i < subscriptionXmlNodes.Count; i++)
{
Subscriptions[i] = new Subscription(subscriptionXmlNodes[i], gateway);
}
var verificationNodes = node.GetList("verifications/verification");
Verification = FindLatestVerification(verificationNodes, gateway);
}
[Obsolete("Mock Use Only")]
protected internal CreditCard() { }
private CreditCardVerification FindLatestVerification(List<NodeWrapper> verificationNodes, IBraintreeGateway gateway) {
if(verificationNodes.Count > 0)
{
verificationNodes.Sort(delegate(NodeWrapper first, NodeWrapper second) {
DateTime time1 = (DateTime)first.GetDateTime("created-at");
DateTime time2 = (DateTime)second.GetDateTime("created-at");
return DateTime.Compare(time2, time1);
});
return new CreditCardVerification(verificationNodes[0], gateway);
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Xunit.Abstractions;
namespace Microsoft.DotNet.Docker.Tests
{
public class ImageScenarioVerifier
{
private readonly DockerHelper _dockerHelper;
private readonly ProductImageData _imageData;
private readonly bool _isWeb;
private readonly ITestOutputHelper _outputHelper;
private readonly string _testArtifactsDir = Path.Combine(Directory.GetCurrentDirectory(), "TestAppArtifacts");
public ImageScenarioVerifier(
ProductImageData imageData,
DockerHelper dockerHelper,
ITestOutputHelper outputHelper,
bool isWeb = false)
{
_dockerHelper = dockerHelper;
_imageData = imageData;
_isWeb = isWeb;
_outputHelper = outputHelper;
}
public async Task Execute()
{
string appDir = CreateTestAppWithSdkImage(_isWeb ? "web" : "console");
List<string> tags = new List<string>();
InjectCustomTestCode(appDir);
try
{
if (!_imageData.HasCustomSdk)
{
// Use `sdk` image to build and run test app
string buildTag = BuildTestAppImage("build", appDir);
tags.Add(buildTag);
string dotnetRunArgs = _isWeb ? " --urls http://0.0.0.0:80" : string.Empty;
await RunTestAppImage(buildTag, command: $"dotnet run{dotnetRunArgs}");
}
// Use `sdk` image to publish FX dependent app and run with `runtime` or `aspnet` image
string fxDepTag = BuildTestAppImage("fx_dependent_app", appDir);
tags.Add(fxDepTag);
bool runAsAdmin = _isWeb && !DockerHelper.IsLinuxContainerModeEnabled;
await RunTestAppImage(fxDepTag, runAsAdmin: runAsAdmin);
if (DockerHelper.IsLinuxContainerModeEnabled)
{
// Use `sdk` image to publish self contained app and run with `runtime-deps` image
string selfContainedTag = BuildTestAppImage("self_contained_app", appDir, customBuildArgs: $"rid={_imageData.Rid}");
tags.Add(selfContainedTag);
await RunTestAppImage(selfContainedTag, runAsAdmin: runAsAdmin);
}
}
finally
{
tags.ForEach(tag => _dockerHelper.DeleteImage(tag));
Directory.Delete(appDir, true);
}
}
private static void InjectCustomTestCode(string appDir)
{
string programFilePath = Path.Combine(appDir, "Program.cs");
SyntaxTree programTree = CSharpSyntaxTree.ParseText(File.ReadAllText(programFilePath));
MethodDeclarationSyntax mainMethod = programTree.GetRoot().DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.FirstOrDefault(method => method.Identifier.ValueText == "Main");
StatementSyntax testHttpsConnectivityStatement = SyntaxFactory.ParseStatement(
"var task = new System.Net.Http.HttpClient().GetAsync(\"https://www.microsoft.com\");" +
"task.Wait();" +
"task.Result.EnsureSuccessStatusCode();");
MethodDeclarationSyntax newMainMethod = mainMethod.InsertNodesBefore(
mainMethod.Body.ChildNodes().First(),
new SyntaxNode[] { testHttpsConnectivityStatement });
SyntaxNode newRoot = programTree.GetRoot().ReplaceNode(mainMethod, newMainMethod);
File.WriteAllText(programFilePath, newRoot.ToFullString());
}
private string BuildTestAppImage(string stageTarget, string contextDir, params string[] customBuildArgs)
{
string tag = _imageData.GetIdentifier(stageTarget);
List<string> buildArgs = new List<string>
{
$"sdk_image={_imageData.GetImage(DotNetImageType.SDK, _dockerHelper)}"
};
DotNetImageType runtimeImageType = _isWeb ? DotNetImageType.Aspnet : DotNetImageType.Runtime;
buildArgs.Add($"runtime_image={_imageData.GetImage(runtimeImageType, _dockerHelper)}");
if (DockerHelper.IsLinuxContainerModeEnabled)
{
buildArgs.Add($"runtime_deps_image={_imageData.GetImage(DotNetImageType.Runtime_Deps, _dockerHelper)}");
}
if (customBuildArgs != null)
{
buildArgs.AddRange(customBuildArgs);
}
_dockerHelper.Build(
tag: tag,
target: stageTarget,
contextDir: contextDir,
buildArgs: buildArgs.ToArray());
return tag;
}
private string CreateTestAppWithSdkImage(string appType)
{
string appDir = Path.Combine(Directory.GetCurrentDirectory(), $"{appType}App{DateTime.Now.ToFileTime()}");
string containerName = _imageData.GetIdentifier($"create-{appType}");
try
{
string targetFramework;
if (_imageData.Version.Major < 5)
{
targetFramework = $"netcoreapp{_imageData.Version}";
}
else
{
targetFramework = $"net{_imageData.Version}";
}
_dockerHelper.Run(
image: _imageData.GetImage(DotNetImageType.SDK, _dockerHelper),
name: containerName,
command: $"dotnet new {appType} --framework {targetFramework} --no-restore",
workdir: "/app",
skipAutoCleanup: true);
_dockerHelper.Copy($"{containerName}:/app", appDir);
string sourceDockerfileName = $"Dockerfile.{DockerHelper.DockerOS.ToLower()}";
File.Copy(
Path.Combine(_testArtifactsDir, sourceDockerfileName),
Path.Combine(appDir, "Dockerfile"));
string nuGetConfigFileName = "NuGet.config";
if (Config.IsNightlyRepo)
{
nuGetConfigFileName += ".nightly";
}
File.Copy(Path.Combine(_testArtifactsDir, nuGetConfigFileName), Path.Combine(appDir, "NuGet.config"));
File.Copy(Path.Combine(_testArtifactsDir, ".dockerignore"), Path.Combine(appDir, ".dockerignore"));
}
catch (Exception)
{
if (Directory.Exists(appDir))
{
Directory.Delete(appDir, true);
}
throw;
}
finally
{
_dockerHelper.DeleteContainer(containerName);
}
return appDir;
}
private async Task RunTestAppImage(string image, bool runAsAdmin = false, string command = null)
{
string containerName = _imageData.GetIdentifier("app-run");
try
{
_dockerHelper.Run(
image: image,
name: containerName,
detach: _isWeb,
optionalRunArgs: _isWeb ? "-p 80" : string.Empty,
runAsContainerAdministrator: runAsAdmin,
command: command);
if (_isWeb && !Config.IsHttpVerificationDisabled)
{
await VerifyHttpResponseFromContainerAsync(containerName, _dockerHelper, _outputHelper);
}
}
finally
{
_dockerHelper.DeleteContainer(containerName);
}
}
public static async Task VerifyHttpResponseFromContainerAsync(string containerName, DockerHelper dockerHelper, ITestOutputHelper outputHelper)
{
int retries = 30;
// Can't use localhost when running inside containers or Windows.
string url = !Config.IsRunningInContainer && DockerHelper.IsLinuxContainerModeEnabled
? $"http://localhost:{dockerHelper.GetContainerHostPort(containerName)}"
: $"http://{dockerHelper.GetContainerAddress(containerName)}";
using (HttpClient client = new HttpClient())
{
while (retries > 0)
{
retries--;
await Task.Delay(TimeSpan.FromSeconds(2));
try
{
using (HttpResponseMessage result = await client.GetAsync(url))
{
outputHelper.WriteLine($"HTTP {result.StatusCode}\n{(await result.Content.ReadAsStringAsync())}");
result.EnsureSuccessStatusCode();
}
return;
}
catch (Exception ex)
{
outputHelper.WriteLine($"Request to {url} failed - retrying: {ex}");
}
}
}
throw new TimeoutException($"Timed out attempting to access the endpoint {url} on container {containerName}");
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.DataStructures;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis.Caching
{
using Provenance = IEnumerable<ProofObligation>;
using Microsoft.Research.CodeAnalysis.Caching.Models;
/// <summary>
/// We box the inferred pre, post, oi so that serialization is faster and smaller
/// </summary>
[Serializable]
struct InferredExpr<Field, Method>
{
public Pair<BoxedExpression, Provenance>[] PreConditions;
public Pair<BoxedExpression, Provenance>[] PostConditions;
public Pair<BoxedExpression, Provenance>[] ObjectInvariants;
public Pair<Field, BoxedExpression>[] NonNullFields;
public ConditionList<Method> EntryAssumes;
public ConditionList<Method> CalleeAssumes; // Method: For each assume, which method is it a postcondition for?
public bool MayReturnNull;
public override string ToString()
{
return String.Format("Preconditions:\n{0}\nPostconditions:\n{1}\nObjectInvariants:\n{2}\nEntryAssumes:{3}\nCalleeAssumes:{4}MayReturnNull{5}",
JoinWithDefaultIfNull("\n", this.PreConditions),
JoinWithDefaultIfNull("\n", this.PostConditions),
JoinWithDefaultIfNull("\n", this.ObjectInvariants),
JoinWithDefaultIfNull("\n", this.NonNullFields),
JoinWithDefaultIfNull("\n", this.EntryAssumes),
JoinWithDefaultIfNull("\n", this.CalleeAssumes),
this.MayReturnNull);
// TODO: print Provenance properly
}
/// <summary>
/// exclude the entry and callee assumes from the hash as they might fail to deserialize we don't need an exact match.
/// </summary>
/// <returns></returns>
public string ToHashString()
{
return String.Format("Preconditions:\n{0}\nPostconditions:\n{1}\nObjectInvariants:\n{2}\n",
JoinWithDefaultIfNull("\n", this.PreConditions),
JoinWithDefaultIfNull("\n", this.PostConditions),
JoinWithDefaultIfNull("\n", this.ObjectInvariants));
// TODO: print Provenance properly
}
private string JoinWithDefaultIfNull<T>(string separator, IEnumerable<T> sequence)
{
if (sequence == null)
return "";
else
return String.Join(separator, sequence);
}
public bool HasAssumes
{
get
{
return this.EntryAssumes.Any() || this.CalleeAssumes.Any();
}
}
public int AssumeCount
{
get
{
return
this.EntryAssumes.Count() + this.CalleeAssumes.Count();
}
}
}
/// <summary>
/// These functions are only needed as long as we do not know how to serialize Provenance
/// </summary>
public static class ProvenanceExtensions
{
public static ConditionList<M> ToConditionList<M>(this IEnumerable<Pair<BoxedExpression, Provenance>> enumerable)
{
return new ConditionList<M>(enumerable.Select(p => Pair.For(p.One, default(M))));
}
public static ConditionList<M> ToConditionList<M>(this IEnumerable<STuple<BoxedExpression, Provenance, M>> enumerable)
{
return new ConditionList<M>(enumerable.Select(p => Pair.For(p.One, p.Three)));
}
public static IEnumerable<Pair<T, Provenance>> RemoveProvenance<T>(this IEnumerable<Pair<T, Provenance>> enumerable)
{
Contract.Ensures(Contract.Result<IEnumerable<Pair<T, Provenance>>>() != null);
return enumerable.Select(p => Pair.For(p.One, (Provenance)null));
}
public static IEnumerable<STuple<T1, Provenance, T2>> RemoveProvenance<T1, T2>(this IEnumerable<STuple<T1, Provenance, T2>> enumerable)
{
return enumerable.Select(t => STuple.For(t.One, (Provenance)null, t.Three));
}
}
internal static class CacheModelExtensions
{
#region ContextEdgeModel
public static STuple<CFGBlock, CFGBlock, string> GetContextEdge(this ContextEdge @this, BijectiveMap<Subroutine, int> subroutineLocalIds)
{
return new STuple<CFGBlock, CFGBlock, string>(
subroutineLocalIds.KeyForValue(@this.Block1SubroutineLocalId).Blocks.First(b => b.Index == @this.Block1Index),
subroutineLocalIds.KeyForValue(@this.Block2SubroutineLocalId).Blocks.First(b => b.Index == @this.Block2Index),
@this.Tag);
}
public static void SetContextEdge(this ContextEdge @this, BijectiveMap<Subroutine, int> subroutineLocalIds, STuple<CFGBlock, CFGBlock, string> edge)
{
@this.Block1SubroutineLocalId = subroutineLocalIds[edge.One.Subroutine];
@this.Block1Index = edge.One.Index;
@this.Block2SubroutineLocalId = subroutineLocalIds[edge.Two.Subroutine];
@this.Block2Index = edge.Two.Index;
@this.Tag = edge.Three;
}
#endregion
#region OutcomeOrSuggestionModel
public static APC GetAPC(this OutcomeOrSuggestion @this, BijectiveMap<Subroutine, int> subroutineLocalIds)
{
return new APC(
subroutineLocalIds.KeyForValue(@this.SubroutineLocalId).Blocks.First(b => b.Index == @this.BlockIndex),
@this.ApcIndex,
@this.ContextEdges
.OrderBy(edge => edge.Rank)
.Select(edge => edge.GetContextEdge(subroutineLocalIds))
.Aggregate((FList<STuple<CFGBlock, CFGBlock, string>>)null, (accu, edge) => accu.Cons(edge))
.Reverse());
}
/// <summary>
/// Must be called only once !
/// </summary>
public static void SetAPC(this IClousotCache @this, OutcomeOrSuggestion that, APC apc, BijectiveMap<Subroutine, int> subroutineLocalIds)
{
if (@that.ContextEdges.Any())
throw new InvalidOperationException();
@that.SubroutineLocalId = subroutineLocalIds[apc.Block.Subroutine];
@that.BlockIndex = apc.Block.Index;
@that.ApcIndex = apc.Index;
int rank = 0;
foreach (var edge in apc.SubroutineContext.GetEnumerable())
{
var added = @this.AddNewContextEdge(that, rank);
added.SetContextEdge(subroutineLocalIds, edge);
rank++;
}
}
/// <summary>
/// Must be called only once !
/// </summary>
public static void SetWitness(this IClousotCache @this, Outcome outcome, Witness witness, BijectiveMap<Subroutine, int> subroutineLocalIds)
{
if (@outcome.OutcomeContexts.Any())
throw new InvalidOperationException();
@outcome.ProofOutcome = witness.Outcome;
@outcome.WarningType = witness.Warning;
@this.SetAPC(outcome, witness.PC, subroutineLocalIds);
foreach (var c in witness.Context)
{
@this.AddNewOutcomeContext(outcome, c);
}
}
public static Witness GetWitness(this Outcome @this, BijectiveMap<Subroutine, int> subroutineLocalIds)
{
Contract.Ensures(Contract.Result<Witness>() != null);
return new Witness(
null, // F: The proof obligation ID is lost in the serialization/deserialization
@this.WarningType,
@this.ProofOutcome,
@this.GetAPC(subroutineLocalIds),
new Set<WarningContext>(@this.OutcomeContexts.Select(c => c.WarningContext)));
}
#endregion
#region pre/post conditions getter/deserialization
public static void SetInferredExpr<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(
this Microsoft.Research.CodeAnalysis.Caching.Models.Method @this,
InferredExpr<Field, Method> value,
Method currentMethod,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder,
bool trace,
bool traceHashing)
{
// To make the serialization happy
var state = StreamingContextStates.File | StreamingContextStates.Persistence;
var streamingContext = new StreamingContext(state);
// We do not want to serialize CCI types directly. We want the Serialization to call us and ask if we have a better way of serializing
var surrogateSelector = Serializers.SurrogateSelectorFor(streamingContext, currentMethod, mdDecoder, contractDecoder, trace);
// Create the serializer
var formatter = new BinaryFormatter(surrogateSelector, streamingContext);
var stream = new System.IO.MemoryStream();
try
{
// Now do the work!
formatter.Serialize(stream, value);
}
catch (SerializationException)
{
throw;
}
catch (NotImplementedException e)
{
throw new SerializationException("Some serialization implementation is missing, see inner exception", e);
}
catch (Exception e)
{
throw new SerializationException("Random exception while serializing, see inner exception", e);
}
@this.InferredExpr = stream.ToArray();
@this.InferredExprHash = DummyExpressionHasher.Hash(value, traceHashing);
if (trace)
{
@this.InferredExprString = value.ToString();
}
}
public static InferredExpr<Field, Method> GetInferredExpr<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>(
this Microsoft.Research.CodeAnalysis.Caching.Models.Method @this,
Method currentMethod,
IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder,
IDecodeContracts<Local, Parameter, Method, Field, Type> contractDecoder,
bool trace
)
{
if (@this.InferredExpr == null)
return default(InferredExpr<Field, Method>);
if (@this.InferredExprHash == null)
throw new SerializationException("Cannot check deserialization, hash null");
var state = StreamingContextStates.File | StreamingContextStates.Persistence;
var streamingContext = new StreamingContext(state);
var surrogateSelector = Serializers.SurrogateSelectorFor(streamingContext, currentMethod, mdDecoder, contractDecoder, trace);
var formatter = new BinaryFormatter(surrogateSelector, streamingContext);
var stream = new System.IO.MemoryStream(@this.InferredExpr);
try
{
// Fix for SerializationException below. Somehow deserialization does not find certain assemblies, so we help out
// the resolver to find currently loaded assemblies.
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(DeserializeAssemblyResolve);
var result = (InferredExpr<Field, Method>)formatter.Deserialize(stream);
var newHash = DummyExpressionHasher.Hash(result, trace);
if (@this.InferredExprHash.ContentEquals(newHash))
{
return result;
}
throw new SerializationException(String.Format("Deserialization failed: hash differs. Expected '{0}', got '{1}'.", @this.InferredExprString, result.ToString()));
}
catch (SerializationException)
{
// "Unable to find assembly 'ClousotMain, Version=1.1.1.1, Culture=neutral, PublicKeyToken=188286aac86319f9'." just means the Clousot has been recompiled (its version number should have changed)
// must not happen, please, please, please! ('cause the method hasn't changed)
// this happens because there are some types in ClousotMain that get serialized. But when we build an installer, these types are actually in cccheck.exe
// so a cache populated using Clousot does not interact well with a cache used with cccheck.
throw;
}
catch (NotImplementedException e)
{
throw new SerializationException("Some deserialization implementation is missing, see inner exception", e);
}
catch (Exception e)
{
// ArgumentException "Object of type '<type>' cannot be converted to type '<type>'." just means the type has changed
throw new SerializationException("Random exception while deserializing, see inner exception", e);
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(DeserializeAssemblyResolve);
}
}
/// <summary>
/// We use this weird fix to make sure during deserialization that we bind to the currently running assemblies. Somehow the
/// deserialization is buggy and fails occasionally to bind properly. Looks like this happens only once, then future deserializations
/// work.
/// </summary>
static private System.Reflection.Assembly DeserializeAssemblyResolve(object sender, ResolveEventArgs args)
{
var name = args.Name.Split(',')[0];
var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = FindInCurrentAssemblies(name, currentAssemblies);
return result;
}
private static System.Reflection.Assembly FindInCurrentAssemblies(string name, System.Reflection.Assembly[] currentAssemblies)
{
System.Reflection.Assembly result = null;
for (int i = 0; i < currentAssemblies.Length; i++)
{
var assembly = currentAssemblies[i];
if (name == assembly.FullName.Split(',')[0])
{
result = assembly;
break;
}
}
return result;
}
#endregion
}
}
| |
// 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.
#pragma warning disable SYSLIB0001 // UTF-7 code paths are obsolete in .NET 5
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using Microsoft.Scripting.Runtime;
using DisallowNullAttribute = System.Diagnostics.CodeAnalysis.DisallowNullAttribute;
[assembly: PythonModule("_codecs", typeof(IronPython.Modules.PythonCodecs))]
namespace IronPython.Modules {
public static class PythonCodecs {
public const string __doc__ = "Provides access to various codecs (ASCII, UTF7, UTF8, etc...)";
internal const int EncoderIndex = 0;
internal const int DecoderIndex = 1;
internal const int StreamReaderIndex = 2;
internal const int StreamWriterIndex = 3;
public static PythonTuple lookup(CodeContext/*!*/ context, [NotNull]string encoding)
=> PythonOps.LookupEncoding(context, encoding);
[LightThrowing]
public static object lookup_error(CodeContext/*!*/ context, [NotNull]string name)
=> PythonOps.LookupEncodingError(context, name);
public static void register(CodeContext/*!*/ context, object? search_function)
=> PythonOps.RegisterEncoding(context, search_function);
public static void register_error(CodeContext/*!*/ context, [NotNull]string name, object? handler)
=> PythonOps.RegisterEncodingError(context, name, handler);
#region ASCII Encoding
public static PythonTuple ascii_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null) {
using var buffer = input.GetBuffer();
return DoDecode(context, "ascii", Encoding.ASCII, buffer, errors).ToPythonTuple();
}
public static PythonTuple ascii_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "ascii", Encoding.ASCII, input, errors).ToPythonTuple();
#endregion
#region Charmap Encoding
/// <summary>
/// Creates an optimized encoding mapping that can be consumed by an optimized version of charmap_encode/charmap_decode.
/// </summary>
public static EncodingMap charmap_build([NotNull]string decoding_table) {
if (decoding_table.Length == 0) {
throw PythonOps.TypeError("charmap_build expected non-empty string");
}
return new EncodingMap(decoding_table, compileForDecoding: false, compileForEncoding: true);
}
/// <summary>
/// Encodes the input string with the specified optimized encoding map.
/// </summary>
public static PythonTuple charmap_encode(CodeContext context, [NotNull]string input, string? errors, [NotNull]EncodingMap map) {
return DoEncode(context, "charmap", new EncodingMapEncoding(map), input, errors).ToPythonTuple();
}
public static PythonTuple charmap_encode(CodeContext context, [NotNull]string input, string? errors = null, IDictionary<object, object>? map = null) {
if (map != null) {
return DoEncode(context, "charmap", new CharmapEncoding(map), input, errors).ToPythonTuple();
} else {
return latin_1_encode(context, input, errors);
}
}
/// <summary>
/// Decodes the input string using the provided string mapping.
/// </summary>
public static PythonTuple charmap_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors, [NotNull]string map) {
EncodingMap em = new EncodingMap(map, compileForDecoding: true, compileForEncoding: false);
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "charmap", new EncodingMapEncoding(em), buffer, errors).ToPythonTuple();
}
public static PythonTuple charmap_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, IDictionary<object, object>? map = null) {
if (map != null) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "charmap", new CharmapEncoding(map), buffer, errors).ToPythonTuple();
} else {
return latin_1_decode(context, input, errors);
}
}
#endregion
#region Generic Encoding
public static object decode(CodeContext/*!*/ context, object? obj, [NotNull, DisallowNull]string? encoding = null!, [NotNull]string errors = "strict") {
if (encoding == null) {
PythonContext lc = context.LanguageContext;
if (obj is IBufferProtocol bp) {
using IPythonBuffer buffer = bp.GetBuffer();
return StringOps.DoDecode(context, buffer, errors, lc.GetDefaultEncodingName(), lc.DefaultEncoding);
} else {
throw PythonOps.TypeError("expected bytes-like object, got {0}", PythonOps.GetPythonTypeName(obj));
}
} else {
object? decoder = lookup(context, encoding)[DecoderIndex];
if (!PythonOps.IsCallable(context, decoder)) {
throw PythonOps.TypeError("decoding with '{0}' codec failed; decoder must be callable ('{1}' object is not callable)", encoding, PythonOps.GetPythonTypeName(decoder));
}
return PythonOps.GetIndex(context, PythonCalls.Call(context, decoder, obj, errors), 0);
}
}
public static object encode(CodeContext/*!*/ context, object? obj, [NotNull, DisallowNull]string? encoding = null!, [NotNull]string errors = "strict") {
if (encoding == null) {
if (obj is string str) {
PythonContext lc = context.LanguageContext;
return StringOps.DoEncode(context, str, errors, lc.GetDefaultEncodingName(), lc.DefaultEncoding, includePreamble: true);
} else {
throw PythonOps.TypeError("expected str, got {0}", PythonOps.GetPythonTypeName(obj));
}
} else {
object? encoder = lookup(context, encoding)[EncoderIndex];
if (!PythonOps.IsCallable(context, encoder)) {
throw PythonOps.TypeError("encoding with '{0}' codec failed; encoder must be callable ('{1}' object is not callable)", encoding, PythonOps.GetPythonTypeName(encoder));
}
return PythonOps.GetIndex(context, PythonCalls.Call(context, encoder, obj, errors), 0);
}
}
#endregion
#region Escape Encoding
public static PythonTuple escape_decode(CodeContext/*!*/ context, [NotNull]string data, string? errors = null)
=> escape_decode(StringOps.DoEncodeUtf8(context, data), errors);
public static PythonTuple escape_decode([NotNull]IBufferProtocol data, string? errors = null) {
using IPythonBuffer buffer = data.GetBuffer();
var span = buffer.AsReadOnlySpan();
var res = LiteralParser.ParseBytes(span, isRaw: false, isAscii: false, normalizeLineEndings: false, getErrorHandler(errors));
return PythonTuple.MakeTuple(Bytes.Make(res.ToArray()), span.Length);
static LiteralParser.ParseBytesErrorHandler<byte>? getErrorHandler(string? errors) {
if (errors == null) return default;
Func<int, IReadOnlyList<byte>?>? eh = null;
return delegate (in ReadOnlySpan<byte> data, int start, int end, string message) {
eh ??= errors switch
{
"strict" => idx => throw PythonOps.ValueError(@"invalid \x escape at position {0}", idx),
"replace" => idx => _replacementMarker ??= new[] { (byte)'?' },
"ignore" => idx => null,
_ => idx => throw PythonOps.ValueError("decoding error; unknown error handling code: " + errors),
};
return eh(start);
};
}
}
[DisallowNull]
private static byte[]? _replacementMarker;
public static PythonTuple/*!*/ escape_encode([NotNull]Bytes data, string? errors = null) {
using IPythonBuffer buffer = ((IBufferProtocol)data).GetBuffer();
var span = buffer.AsReadOnlySpan();
var result = new List<byte>(span.Length);
for (int i = 0; i < span.Length; i++) {
byte b = span[i];
switch (b) {
case (byte)'\n': result.Add((byte)'\\'); result.Add((byte)'n'); break;
case (byte)'\r': result.Add((byte)'\\'); result.Add((byte)'r'); break;
case (byte)'\t': result.Add((byte)'\\'); result.Add((byte)'t'); break;
case (byte)'\\': result.Add((byte)'\\'); result.Add((byte)'\\'); break;
case (byte)'\'': result.Add((byte)'\\'); result.Add((byte)'\''); break;
default:
if (b < 0x20 || b >= 0x7f) {
result.AddRange($"\\x{b:x2}".Select(c => unchecked((byte)c)));
} else {
result.Add(b);
}
break;
}
}
return PythonTuple.MakeTuple(Bytes.Make(result.ToArray()), span.Length);
}
#endregion
#region Latin-1 Functions
public static PythonTuple latin_1_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "latin-1", StringOps.Latin1Encoding, buffer, errors).ToPythonTuple();
}
public static PythonTuple latin_1_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "latin-1", StringOps.Latin1Encoding, input, errors).ToPythonTuple();
#endregion
#region MBCS Functions
[SupportedOSPlatform("windows"), PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static PythonTuple mbcs_decode(CodeContext/*!*/ context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "mbcs", StringOps.CodecsInfo.MbcsEncoding, buffer, errors).ToPythonTuple();
}
[SupportedOSPlatform("windows"), PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static PythonTuple mbcs_encode(CodeContext/*!*/ context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "mbcs", StringOps.CodecsInfo.MbcsEncoding, input, errors).ToPythonTuple();
#endregion
#region Code Page Functions
[SupportedOSPlatform("windows"), PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static PythonTuple code_page_decode(CodeContext context, int codepage, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
// TODO: Use Win32 API MultiByteToWideChar https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar
string encodingName = $"cp{codepage}";
Encoding encoding = Encoding.GetEncoding(codepage);
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, encodingName, encoding, buffer, errors).ToPythonTuple();
}
[SupportedOSPlatform("windows"), PythonHidden(PlatformsAttribute.PlatformFamily.Unix)]
public static PythonTuple code_page_encode(CodeContext context, int codepage, [NotNull]string input, string? errors = null) {
// TODO: Use Win32 API WideCharToMultiByte https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-widechartomultibyte
string encodingName = $"cp{codepage}";
Encoding encoding = Encoding.GetEncoding(codepage);
return DoEncode(context, encodingName, encoding, input, errors, includePreamble: true).ToPythonTuple();
}
#endregion
#region Raw Unicode Escape Encoding Functions
public static PythonTuple raw_unicode_escape_decode(CodeContext/*!*/ context, [NotNull]string input, string? errors = null) {
// Encoding with UTF-8 is probably a bug or at least a mistake, as it mutilates non-ASCII characters,
// but this is what CPython does. Probably encoding with "raw-unicode-escape" would be more reasonable.
return raw_unicode_escape_decode(context, StringOps.DoEncodeUtf8(context, input), errors);
}
public static PythonTuple raw_unicode_escape_decode(CodeContext/*!*/ context, [NotNull]IBufferProtocol input, string? errors = null) {
using IPythonBuffer buffer = input.GetBuffer();
return PythonTuple.MakeTuple(
StringOps.DoDecode(context, buffer, errors, "raw-unicode-escape", StringOps.CodecsInfo.RawUnicodeEscapeEncoding),
buffer.NumBytes()
);
}
public static PythonTuple raw_unicode_escape_encode(CodeContext/*!*/ context, [NotNull]string input, string? errors = null) {
return PythonTuple.MakeTuple(
StringOps.DoEncode(context, input, errors, "raw-unicode-escape", StringOps.CodecsInfo.RawUnicodeEscapeEncoding, includePreamble: false),
input.Length
);
}
#endregion
#region Unicode Escape Encoding Functions
public static PythonTuple unicode_escape_decode(CodeContext/*!*/ context, [NotNull]string input, string? errors = null) {
// Encoding with UTF-8 is probably a bug or at least a mistake, as it mutilates non-ASCII characters,
// but this is what CPython does. Probably encoding with "unicode-escape" would be more reasonable.
return unicode_escape_decode(context, StringOps.DoEncodeUtf8(context, input), errors);
}
public static PythonTuple unicode_escape_decode(CodeContext/*!*/ context, [NotNull]IBufferProtocol input, string? errors = null) {
using IPythonBuffer buffer = input.GetBuffer();
return PythonTuple.MakeTuple(
StringOps.DoDecode(context, buffer, errors, "unicode-escape", StringOps.CodecsInfo.UnicodeEscapeEncoding),
buffer.NumBytes()
);
}
public static PythonTuple unicode_escape_encode(CodeContext/*!*/ context, [NotNull]string input, string? errors = null) {
return PythonTuple.MakeTuple(
StringOps.DoEncode(context, input, errors, "unicode-escape", StringOps.CodecsInfo.UnicodeEscapeEncoding, includePreamble: false),
input.Length
);
}
#endregion
#region Readbuffer Functions
public static PythonTuple readbuffer_encode(CodeContext/*!*/ context, [NotNull]string input, string? errors = null)
=> readbuffer_encode(StringOps.DoEncodeUtf8(context, input), errors);
public static PythonTuple readbuffer_encode([NotNull]IBufferProtocol input, string? errors = null) {
using IPythonBuffer buffer = input.GetBuffer();
var bytes = Bytes.Make(buffer.AsReadOnlySpan().ToArray());
return PythonTuple.MakeTuple(bytes, bytes.Count);
}
#endregion
#region Unicode Internal Encoding Functions
public static PythonTuple unicode_internal_decode(CodeContext context, [NotNull]string input, string? errors = null) {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "unicode_internal codec has been deprecated");
return PythonTuple.MakeTuple(input, input.Length);
}
public static PythonTuple unicode_internal_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null) {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "unicode_internal codec has been deprecated");
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "unicode-internal", Encoding.Unicode, buffer, errors).ToPythonTuple();
}
public static PythonTuple unicode_internal_encode(CodeContext context, [NotNull]string input, string? errors = null) {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "unicode_internal codec has been deprecated");
return DoEncode(context, "unicode-internal", Encoding.Unicode, input, errors, false).ToPythonTuple();
}
public static PythonTuple unicode_internal_encode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null) {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "unicode_internal codec has been deprecated");
using IPythonBuffer buffer = input.GetBuffer();
var bytes = Bytes.Make(buffer.AsReadOnlySpan().ToArray());
return PythonTuple.MakeTuple(bytes, bytes.Count);
}
#endregion
#region Utf-16 Functions
public static PythonTuple utf_16_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
PythonTuple res = utf_16_ex_decode(context, input, errors, 0, final);
return PythonTuple.MakeTuple(res[0], res[1]);
}
public static PythonTuple utf_16_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-16", Utf16LeBomEncoding, input, errors, true).ToPythonTuple();
public static PythonTuple utf_16_ex_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, int byteorder = 0, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
var span = buffer.AsReadOnlySpan();
Tuple<string, int> res;
if (byteorder != 0) {
res = (byteorder > 0) ?
DoDecode(context, "utf-16-be", Utf16BeEncoding, buffer, errors, NumEligibleUtf16Bytes(span, final, false))
:
DoDecode(context, "utf-16-le", Utf16LeEncoding, buffer, errors, NumEligibleUtf16Bytes(span, final, true));
} else {
byteorder = Utf16DetectByteorder(span);
res = (byteorder > 0) ?
DoDecode(context, "utf-16-be", Utf16BeBomEncoding, buffer, errors, NumEligibleUtf16Bytes(span, final, false))
:
DoDecode(context, "utf-16-le", Utf16LeBomEncoding, buffer, errors, NumEligibleUtf16Bytes(span, final, true));
}
return PythonTuple.MakeTuple(res.Item1, res.Item2, byteorder);
}
private static int Utf16DetectByteorder(ReadOnlySpan<byte> input) {
if (input.StartsWith(BOM_UTF16_LE)) return -1;
if (input.StartsWith(BOM_UTF16_BE)) return 1;
return 0;
}
private static int NumEligibleUtf16Bytes(ReadOnlySpan<byte> input, bool final, bool isLE) {
int numBytes = input.Length;
if (!final) {
numBytes -= numBytes % 2;
if (numBytes >= 2 && (input[numBytes - (isLE ? 1 : 2)] & 0xFC) == 0xD8) { // high surrogate
numBytes -= 2;
}
}
return numBytes;
}
#endregion
#region Utf-16-LE Functions
private static Encoding Utf16LeEncoding => _utf16LeEncoding ??= new UnicodeEncoding(bigEndian: false, byteOrderMark: false);
[DisallowNull] private static Encoding? _utf16LeEncoding;
private static Encoding Utf16LeBomEncoding => Encoding.Unicode; // same as new UnicodeEncoding(bigEndian: false, byteOrderMark: true);
private static byte[] BOM_UTF16_LE => _bom_utf16_le ??= Utf16LeBomEncoding.GetPreamble();
[DisallowNull] private static byte[]? _bom_utf16_le;
public static PythonTuple utf_16_le_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "utf-16-le", Utf16LeEncoding, buffer, errors, NumEligibleUtf16Bytes(buffer.AsReadOnlySpan(), final, isLE: true)).ToPythonTuple();
}
public static PythonTuple utf_16_le_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-16-le", Utf16LeEncoding, input, errors).ToPythonTuple();
#endregion
#region Utf-16-BE Functions
private static Encoding Utf16BeEncoding => _utf16BeEncoding ??= new UnicodeEncoding(bigEndian: true, byteOrderMark: false);
[DisallowNull] private static Encoding? _utf16BeEncoding;
private static Encoding Utf16BeBomEncoding => Encoding.BigEndianUnicode; // same as new UnicodeEncoding(bigEndian: true, byteOrderMark: true);
private static byte[] BOM_UTF16_BE => _bom_utf16_be ??= Utf16BeBomEncoding.GetPreamble();
[DisallowNull] private static byte[]? _bom_utf16_be;
public static PythonTuple utf_16_be_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "utf-16-be", Utf16BeEncoding, buffer, errors, NumEligibleUtf16Bytes(buffer.AsReadOnlySpan(), final, isLE: false)).ToPythonTuple();
}
public static PythonTuple utf_16_be_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-16-be", Utf16BeEncoding, input, errors).ToPythonTuple();
#endregion
#region Utf-7 Functions
public static PythonTuple utf_7_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "utf-7", Encoding.UTF7, buffer, errors, NumEligibleUtf7Bytes(buffer.AsReadOnlySpan(), final)).ToPythonTuple();
}
public static PythonTuple utf_7_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-7", Encoding.UTF7, input, errors).ToPythonTuple();
private static int NumEligibleUtf7Bytes(ReadOnlySpan<byte> input, bool final) {
int numBytes = input.Length;
if (!final) {
int blockStart = -1;
for (int i = 0; i < numBytes; i++) {
byte b = input[i];
if (blockStart < 0 && b == '+') {
blockStart = i;
} else if (blockStart >= 0 && !b.IsLetter() && !b.IsDigit() && b != '+' && b != '/' && !b.IsWhiteSpace()) {
blockStart = -1;
}
}
if (blockStart >= 0) numBytes = blockStart;
}
return numBytes;
}
#endregion
#region Utf-8 Functions
private static Encoding Utf8Encoding => _utf8Encoding ??= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
[DisallowNull] private static Encoding? _utf8Encoding;
public static PythonTuple utf_8_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "utf-8", Utf8Encoding, buffer, errors, NumEligibleUtf8Bytes(buffer.AsReadOnlySpan(), final)).ToPythonTuple();
}
public static PythonTuple utf_8_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-8", Encoding.UTF8, input, errors).ToPythonTuple();
private static int NumEligibleUtf8Bytes(ReadOnlySpan<byte> input, bool final) {
int numBytes = input.Length;
if (!final) {
// scan for incomplete but valid sequence at the end
for (int i = 1; i < 4; i++) { // 4 is the max length of a valid sequence
int pos = numBytes - i;
if (pos < 0) break;
byte b = input[pos];
if ((b & 0b10000000) == 0) return numBytes; // ASCII
if ((b & 0b11000000) == 0b11000000) { // start byte
if ((b | 0b00011111) == 0b11011111 && i < 2) return pos; // 2-byte seq start
if ((b | 0b00001111) == 0b11101111 && i < 3) return pos; // 3-byte seq start
if ((b | 0b00000111) == 0b11110111) { // 4-byte seq start
if (b < 0b11110100) return pos; // chars up to U+FFFFF
if ((b == 0b11110100) && (i == 1 || input[numBytes - i + 1] < 0x90)) return pos; // U+100000 to U+10FFFF
}
return numBytes; // invalid sequence or valid but complete
}
// else continuation byte (0b10xxxxxx) hence continue scanning
}
}
return numBytes;
}
#endregion
#region Utf-32 Functions
public static PythonTuple utf_32_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
PythonTuple res = utf_32_ex_decode(context, input, errors, 0, final);
return PythonTuple.MakeTuple(res[0], res[1]);
}
public static PythonTuple utf_32_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-32", Utf32LeBomEncoding, input, errors, includePreamble: true).ToPythonTuple();
public static PythonTuple utf_32_ex_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, int byteorder = 0, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
var span = buffer.AsReadOnlySpan();
int numBytes = NumEligibleUtf32Bytes(span, final);
Tuple<string, int> res;
if (byteorder != 0) {
res = (byteorder > 0) ?
DoDecode(context, "utf-32-be", Utf32BeEncoding, buffer, errors, numBytes)
:
DoDecode(context, "utf-32-le", Utf32LeEncoding, buffer, errors, numBytes);
} else {
byteorder = Utf32DetectByteorder(span);
res = (byteorder > 0) ?
DoDecode(context, "utf-32-be", Utf32BeBomEncoding, buffer, errors, numBytes)
:
DoDecode(context, "utf-32-le", Utf32LeBomEncoding, buffer, errors, numBytes);
}
return PythonTuple.MakeTuple(res.Item1, res.Item2, byteorder);
}
private static int Utf32DetectByteorder(ReadOnlySpan<byte> input) {
if (input.StartsWith(BOM_UTF32_LE)) return -1;
if (input.StartsWith(BOM_UTF32_BE)) return 1;
return 0;
}
private static int NumEligibleUtf32Bytes(ReadOnlySpan<byte> input, bool final) {
int numBytes = input.Length;
if (!final) numBytes -= numBytes % 4;
return numBytes;
}
#endregion
#region Utf-32-LE Functions
private static Encoding Utf32LeEncoding => _utf32LeEncoding ??= new UTF32Encoding(bigEndian: false, byteOrderMark: false);
[DisallowNull] private static Encoding? _utf32LeEncoding;
private static Encoding Utf32LeBomEncoding => Encoding.UTF32; // same as new UTF32Encoding(bigEndian: false, byteOrderMark: true);
private static byte[] BOM_UTF32_LE => _bom_utf32_le ??= Utf32LeBomEncoding.GetPreamble();
[DisallowNull] private static byte[]? _bom_utf32_le;
public static PythonTuple utf_32_le_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "utf-32-le", Utf32LeEncoding, buffer, errors, NumEligibleUtf32Bytes(buffer.AsReadOnlySpan(), final)).ToPythonTuple();
}
public static PythonTuple utf_32_le_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-32-le", Utf32LeEncoding, input, errors).ToPythonTuple();
#endregion
#region Utf-32-BE Functions
private static Encoding Utf32BeEncoding => _utf32BeEncoding ??= new UTF32Encoding(bigEndian: true, byteOrderMark: false);
[DisallowNull] private static Encoding? _utf32BeEncoding;
private static Encoding Utf32BeBomEncoding => _utf32BeBomEncoding ??= new UTF32Encoding(bigEndian: true, byteOrderMark: true);
[DisallowNull] private static Encoding? _utf32BeBomEncoding;
private static byte[] BOM_UTF32_BE => _bom_utf32_be ??= Utf32BeBomEncoding.GetPreamble();
[DisallowNull] private static byte[]? _bom_utf32_be;
public static PythonTuple utf_32_be_decode(CodeContext context, [NotNull]IBufferProtocol input, string? errors = null, bool final = false) {
using IPythonBuffer buffer = input.GetBuffer();
return DoDecode(context, "utf-32-be", Utf32BeEncoding, buffer, errors, NumEligibleUtf32Bytes(buffer.AsReadOnlySpan(), final)).ToPythonTuple();
}
public static PythonTuple utf_32_be_encode(CodeContext context, [NotNull]string input, string? errors = null)
=> DoEncode(context, "utf-32-be", Utf32BeEncoding, input, errors).ToPythonTuple();
#endregion
#region Private implementation
private static Tuple<string, int> DoDecode(CodeContext context, string encodingName, Encoding encoding, IPythonBuffer input, string? errors, int numBytes = -1) {
var decoded = StringOps.DoDecode(context, input, errors, encodingName, encoding, numBytes);
return Tuple.Create(decoded, numBytes >= 0 ? numBytes : input.NumBytes());
}
private static Tuple<Bytes, int> DoEncode(CodeContext context, string encodingName, Encoding encoding, string input, string? errors, bool includePreamble = false) {
var res = StringOps.DoEncode(context, input, errors, encodingName, encoding, includePreamble);
return Tuple.Create(res, input.Length);
}
#endregion
}
/// <summary>
/// Optimized encoding mapping that can be consumed by charmap_encode/EncodingMapEncoding.
/// </summary>
[PythonHidden]
public class EncodingMap {
private readonly string _smap;
[DisallowNull] private Dictionary<byte, int>? _dmap;
[DisallowNull] private Dictionary<int, byte>? _emap;
internal EncodingMap(string stringMap, bool compileForDecoding, bool compileForEncoding) {
_smap = stringMap;
if (compileForDecoding) CompileDecodingMap();
if (compileForEncoding) CompileEncodingMap();
}
private void CompileEncodingMap() {
if (_emap == null) {
_emap = new Dictionary<int, byte>(Math.Min(_smap.Length, 256));
for (int i = 0, cp = 0; i < _smap.Length && cp < 256; i++, cp++) {
if (char.IsHighSurrogate(_smap[i]) && i < _smap.Length - 1 && char.IsLowSurrogate(_smap[i + 1])) {
_emap[char.ConvertToUtf32(_smap[i], _smap[i + 1])] = unchecked((byte)cp);
i++;
} else if (_smap[i] != '\uFFFE') {
_emap[_smap[i]] = unchecked((byte)cp);
}
}
}
}
private void CompileDecodingMap() {
// scan for a surrogate pair
bool spFound = false;
for (int i = 0; i < _smap.Length && !spFound; i++) {
spFound = char.IsHighSurrogate(_smap[i]) && i < _smap.Length - 1 && char.IsLowSurrogate(_smap[i + 1]);
}
if (spFound) {
_dmap = new Dictionary<byte, int>(Math.Min(_smap.Length, 256));
for (int i = 0, cp = 0; i < _smap.Length && cp < 256; i++, cp++) {
if (char.IsHighSurrogate(_smap[i]) && i < _smap.Length - 1 && char.IsLowSurrogate(_smap[i + 1])) {
_dmap[unchecked((byte)cp)] = char.ConvertToUtf32(_smap[i], _smap[i + 1]);
i++;
} else if (_smap[i] != '\uFFFE') {
_dmap[unchecked((byte)cp)] = _smap[i];
}
}
}
}
public bool TryGetCharValue(byte b, out int val) {
if (_dmap != null) {
return _dmap.TryGetValue(b, out val);
} else if (b < _smap.Length) {
val = _smap[b];
return val != '\uFFFE';
} else {
val = '\0';
return false;
}
}
public bool TryGetByteValue(int c, out byte val) {
CompileEncodingMap();
if (_emap != null) {
return _emap.TryGetValue(c, out val);
} else {
val = 0;
return false;
}
}
}
/// <remarks>
/// This implementation is not suitable for incremental encoding.
/// </remarks>
internal class EncodingMapEncoding : Encoding {
private readonly EncodingMap _map;
public EncodingMapEncoding(EncodingMap map) {
_map = map;
}
public override string EncodingName => "charmap";
public override int GetByteCount(char[] chars, int index, int count)
=> GetBytes(chars, index, count, null, 0);
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[]? bytes, int byteIndex) {
if (chars == null) throw new ArgumentNullException(nameof(chars));
int charEnd = charIndex + charCount;
int byteStart = byteIndex;
EncoderFallbackBuffer? efb = null;
while (charIndex < charEnd) {
int codepoint;
char c = chars[charIndex];
int nextIndex = charIndex + 1;
if (char.IsHighSurrogate(c) && nextIndex < charEnd && char.IsLowSurrogate(chars[nextIndex])) {
codepoint = char.ConvertToUtf32(c, chars[nextIndex++]);
} else {
codepoint = c;
}
if (!_map.TryGetByteValue(codepoint, out byte val)) {
efb ??= EncoderFallback.CreateFallbackBuffer();
try {
if (efb.Fallback(c, charIndex)) {
while (efb.Remaining != 0) {
c = efb.GetNextChar();
int fbCodepoint = c;
if (char.IsHighSurrogate(c) && efb.Remaining != 0) {
char d = efb.GetNextChar();
if (char.IsLowSurrogate(d)) {
fbCodepoint = char.ConvertToUtf32(c, d);
} else {
efb.MovePrevious();
}
}
if (!_map.TryGetByteValue(fbCodepoint, out val)) {
throw new EncoderFallbackException(); // no recursive fallback
}
if (bytes != null) bytes[byteIndex] = val;
byteIndex++;
}
}
} catch (EncoderFallbackException) {
throw PythonOps.UnicodeEncodeError(EncodingName, new string(chars), charIndex, charIndex + 1, "character maps to <undefined>");
}
} else {
if (bytes != null) bytes[byteIndex] = val;
byteIndex++;
}
charIndex = nextIndex;
}
return byteIndex - byteStart;
}
public override int GetCharCount(byte[] bytes, int index, int count)
=> GetChars(bytes, index, count, null, 0);
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[]? chars, int charIndex) {
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
int byteEnd = byteIndex + byteCount;
int charStart = charIndex;
DecoderFallbackBuffer? dfb = null;
while (byteIndex < byteEnd) {
byte b = bytes[byteIndex];
if (!_map.TryGetCharValue(b, out int val)) {
dfb ??= DecoderFallback.CreateFallbackBuffer();
byte[] bytesUnknown = new[] { b };
try {
if (dfb.Fallback(bytesUnknown, byteIndex)) {
while (dfb.Remaining != 0) {
char c = dfb.GetNextChar();
if (chars != null) {
chars[charIndex] = c;
}
charIndex++;
}
}
} catch (DecoderFallbackException) {
throw PythonOps.UnicodeDecodeError("character maps to <undefined>", bytesUnknown, byteIndex);
}
} else {
if (val >= 0x10000) {
string s32 = char.ConvertFromUtf32(val);
if (chars != null) {
chars[charIndex] = s32[0];
chars[charIndex + 1] = s32[1];
}
charIndex += 2;
} else {
if (chars != null) chars[charIndex] = unchecked((char)val);
charIndex++;
}
}
byteIndex++;
}
return charIndex - charStart;
}
public override int GetMaxByteCount(int charCount) {
return charCount;
}
public override int GetMaxCharCount(int byteCount) {
return byteCount * 2; // account for surrogate pairs
}
}
/// <remarks>
/// This implementation is not suitable for incremental encoding.
/// </remarks>
internal class CharmapEncoding : Encoding {
private readonly IDictionary<object, object> _map;
private int _maxEncodingReplacementLength;
private int _maxDecodingReplacementLength;
public CharmapEncoding(IDictionary<object, object> map) {
_map = map;
}
public override string EncodingName => "charmap";
public override int GetByteCount(char[] chars, int index, int count)
=> GetBytes(chars, index, count, null, 0);
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[]? bytes, int byteIndex) {
if (chars == null) throw new ArgumentNullException(nameof(chars));
int charEnd = charIndex + charCount;
int byteStart = byteIndex;
EncoderFallbackBuffer? efb = null;
while (charIndex < charEnd) {
object charObj;
char c = chars[charIndex];
int nextIndex = charIndex + 1;
if (char.IsHighSurrogate(c) && nextIndex < charEnd && char.IsLowSurrogate(chars[nextIndex])) {
charObj = ScriptingRuntimeHelpers.Int32ToObject(char.ConvertToUtf32(c, chars[nextIndex++]));
} else {
charObj = ScriptingRuntimeHelpers.Int32ToObject(c);
}
if (!_map.TryGetValue(charObj, out object? val) || val == null) {
efb ??= EncoderFallback.CreateFallbackBuffer();
try {
for (int idx = charIndex; idx < nextIndex; idx++) {
if (efb.Fallback(chars[idx], idx)) {
while (efb.Remaining != 0) {
c = efb.GetNextChar();
object fbCharObj = ScriptingRuntimeHelpers.Int32ToObject(c);
if (char.IsHighSurrogate(c) && efb.Remaining != 0) {
char d = efb.GetNextChar();
if (char.IsLowSurrogate(d)) {
fbCharObj = ScriptingRuntimeHelpers.Int32ToObject(char.ConvertToUtf32(c, d));
} else {
efb.MovePrevious();
}
}
if (!_map.TryGetValue(fbCharObj, out val) || val == null) {
throw new EncoderFallbackException(); // no recursive fallback
}
byteIndex += ProcessEncodingReplacementValue(val, bytes, byteIndex);
}
}
}
} catch (EncoderFallbackException) {
throw PythonOps.UnicodeEncodeError(EncodingName, new string(chars), charIndex, nextIndex, "character maps to <undefined>");
}
charIndex = nextIndex;
} else {
byteIndex += ProcessEncodingReplacementValue(val, bytes, byteIndex);
charIndex = nextIndex;
}
}
return byteIndex - byteStart;
}
private static int ProcessEncodingReplacementValue(object replacement, byte[]? bytes, int byteIndex) {
Debug.Assert(replacement != null);
switch (replacement) {
case IList<byte> b:
if (bytes != null) {
for (int i = 0; i < b.Count; i++, byteIndex++) {
bytes[byteIndex] = b[i];
}
}
return b.Count;
case int n:
if (n < 0 || n > 0xFF) throw PythonOps.TypeError("character mapping must be in range(256)");
if (bytes != null) {
bytes[byteIndex] = unchecked((byte)n);
}
return 1;
default:
throw PythonOps.TypeError("character mapping must return integer, bytes or None, not {0}", PythonOps.GetPythonTypeName(replacement));
}
}
public override int GetCharCount(byte[] bytes, int index, int count)
=> GetChars(bytes, index, count, null, 0);
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[]? chars, int charIndex) {
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
int byteEnd = byteIndex + byteCount;
int charStart = charIndex;
DecoderFallbackBuffer? dfb = null;
while (byteIndex < byteEnd) {
byte b = bytes[byteIndex++];
object byteObj = ScriptingRuntimeHelpers.Int32ToObject(b);
if (_map.TryGetValue(byteObj, out object? val) && val != null) {
if (val is string s) {
if (s.Length == 0 || s[0] != '\uFFFE') {
for (int i = 0; i < s.Length; i++) {
if (chars != null) chars[charIndex] = s[i];
charIndex++;
}
continue;
}
} else if (val is int n) {
if (n < 0 || n > 0x10FFFF) {
throw PythonOps.TypeError("character mapping must be in range(0x110000)");
} else if (n > 0xFFFF) {
var sp = char.ConvertFromUtf32(n);
if (chars != null) chars[charIndex] = sp[0];
charIndex++;
if (chars != null) chars[charIndex] = sp[1];
charIndex++;
continue;
} else if (n != 0xFFFE) {
if (chars != null) chars[charIndex] = unchecked((char)n);
charIndex++;
continue;
}
} else {
throw PythonOps.TypeError("character mapping must return integer, None or str, not {0}", PythonOps.GetPythonTypeName(val));
}
}
// byte unhandled, try fallback
dfb ??= DecoderFallback.CreateFallbackBuffer();
byte[] bytesUnknown = new[] { b };
try {
if (dfb.Fallback(bytesUnknown, byteIndex - 1)) {
while (dfb.Remaining != 0) {
char c = dfb.GetNextChar();
if (chars != null) chars[charIndex] = c;
charIndex++;
}
}
} catch (DecoderFallbackException) {
throw PythonOps.UnicodeDecodeError("character maps to <undefined>", bytesUnknown, byteIndex - 1);
}
}
return charIndex - charStart;
}
public override int GetMaxByteCount(int charCount) {
if (_maxEncodingReplacementLength == 0) {
_maxEncodingReplacementLength = 1;
foreach (object val in _map.Values) {
if (val is IList<byte> b && b.Count > _maxEncodingReplacementLength) {
_maxEncodingReplacementLength = b.Count;
}
}
}
return charCount * _maxEncodingReplacementLength;
}
public override int GetMaxCharCount(int byteCount) {
if (_maxDecodingReplacementLength == 0) {
_maxDecodingReplacementLength = 2; // surrogate pair for codepoint
foreach (object val in _map.Values) {
if (val is string s && s.Length > _maxDecodingReplacementLength) {
_maxDecodingReplacementLength = s.Length;
};
}
}
return byteCount * _maxDecodingReplacementLength;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
/*
* 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.
*/
/*
* SequentialStructuredDataStream (java and c#)
* ------------------------------
* author: chitta.pardeshi@gmail.com
* May 2014
*/
public class SequentialStructuredDataStream : IDisposable {
private static string CURRENT_VERSION = "ssds0";
private const int RAW_TYPE_VARINT = 0;
private const int RAW_TYPE_FIXED64 = 1;
private const int RAW_TYPE_LENGTH_DELIMITED = 2;
private const int RAW_TYPE_START_GROUP = 3;
private const int RAW_TYPE_END_GROUP = 4;
private const int RAW_TYPE_FIXED32 = 5;
private const int RAW_TYPE_SCHEMA = 6;
private static int TAG_TYPE_BITS = 3;
private static int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1;
private const byte ITM_TYPE_BOOLEAN = (int)'b'; // 'b' - bool
private const byte ITM_TYPE_ENUM = (int)'e'; // 'e' - enumeration
private const byte ITM_TYPE_UINT32 = (int)'i'; // 'i' - uint32
private const byte ITM_TYPE_UINT64 = (int)'j'; // 'j' - uint64
private const byte ITM_TYPE_SINT32 = (int)'u'; // 'u' - sint32
private const byte ITM_TYPE_SINT64 = (int)'v'; // 'v' - sint64
private const byte ITM_TYPE_FIXED32 = (int)'q'; // 'q' - fixed32
private const byte ITM_TYPE_FIXED64 = (int)'r'; // 'r' - fixed64
private const byte ITM_TYPE_SINGLE = (int)'f'; // 'f' - single
private const byte ITM_TYPE_DOUBLE = (int)'d'; // 'd' - double
private const byte ITM_TYPE_STRING = (int)'s'; // 's' - string
private const byte ITM_TYPE_BYTES = (int)'a'; // 'a' - bytes
private const byte ITM_TYPE_STRUCT = (int)'m'; // 'm' - structure
private class Itm{
public byte type;
public string name;
public int id;
public Grp isa = null;
}
private class Grp{
public byte type;
public string name;
public int count = 0;
public Dictionary<string, Itm> namedItems = new Dictionary<string, Itm>();
public Dictionary<int, Itm> indexedItems = new Dictionary<int, Itm>();
}
private Dictionary<string, Grp> namedGroups = new Dictionary<string, Grp>();
private Stack<Itm> stack = new Stack<Itm>();
private readonly Stream inputStream ;
private readonly Stream outputStream;
private bool eos = false;
private Grp version = null;
public static SequentialStructuredDataStream createReader(Stream stream)
{
return new SequentialStructuredDataStream (null, stream) ;
}
public static SequentialStructuredDataStream createWriter(Stream stream)
{
return new SequentialStructuredDataStream (stream, null) ;
}
private SequentialStructuredDataStream(Stream outputStream, Stream inputStream)
{
this.inputStream = inputStream;
this.outputStream = outputStream;
}
private Grp ensureGroup( bool write, string groupName, byte groupType)
{
Grp g = null;
if (namedGroups.ContainsKey(groupName))
{
g = namedGroups[groupName];
if (g.type != groupType) {
throw new Exception ("bad group type") ;
}
}
else
{
g = new Grp();
write_raw_varint32((1 << TAG_TYPE_BITS) | RAW_TYPE_SCHEMA);
write_rawbyte(groupType);
write_rawstring(groupName) ;
g.type = groupType;
g.name = groupName;
namedGroups.Add(g.name, g);
}
if (version == null)
{
version = g;
}
return g;
}
private Grp peekIsa( bool write)
{
if (stack.Count > 0)
{
return stack.Peek().isa;
}
else if (version == null && write == true)
{
return ensureGroup(write, CURRENT_VERSION, ITM_TYPE_STRUCT);
}
else
{
return version;
}
}
private Itm ensureItem( bool write, string parentName, byte parentType, string itemName, byte itemType, string isaName, byte isaType)
{
Grp parent = ensureGroup(write, parentName, parentType);
return ensureItem(write, parent, itemName, itemType, isaName, isaType);
}
private Itm ensureItem( bool write, Grp parent, string itemName, byte itemType, string isaName, byte isaType)
{
Grp isa = null;
if (!string.IsNullOrEmpty(isaName))
{
isa = ensureGroup(write, isaName, isaType);
}
return ensureItem(write, parent, itemName, itemType, isa);
}
private Itm ensureItem( bool write, Grp parent, string itemName, byte itemType, Grp isa)
{
Itm item = null;
if (parent.namedItems.ContainsKey(itemName))
{
item = parent.namedItems[itemName];
if (itemType != item.type)
{
throw new Exception("itemtypemismatch");
}
}
else
{
item = new Itm();
item.id = ++parent.count;
item.name = itemName;
item.type = itemType;
item.isa = isa;
parent.namedItems.Add(item.name, item);
parent.indexedItems.Add(item.id, item);
{
if (item.isa == null) {
write_raw_varint32((2 << TAG_TYPE_BITS) | RAW_TYPE_SCHEMA);
}
else {
write_raw_varint32((3 << TAG_TYPE_BITS) | RAW_TYPE_SCHEMA);
}
write_rawbyte(item.type);
write_rawstring(item.name);
write_rawstring(parent.name);
if (item.isa != null) {
write_rawstring(item.isa.name);
}
}
}
return item;
}
public void writeStart( string itemName)
{
writeStart(itemName, itemName);
}
public void writeStart( string itemName, string isaName)
{
stack.Push(ensureItem(true, peekIsa(true), itemName, ITM_TYPE_STRUCT, isaName, ITM_TYPE_STRUCT));
write_raw_varint32((stack.Peek().id << TAG_TYPE_BITS) | RAW_TYPE_START_GROUP);
}
public void writeString( string itemName, string value)
{
if (value == null) return;
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_STRING, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_LENGTH_DELIMITED);
write_rawstring(value) ;
}
public void writeUInt32( string itemName, int value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_UINT32, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_VARINT);
write_raw_varint32(value);
}
public void writeUInt64( string itemName, long value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_UINT64, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_VARINT);
write_raw_varint64(value);
}
public void writeSInt32( string itemName, int value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_SINT32, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_VARINT);
write_raw_varint32((value << 1) ^ (value >> 31));
}
public void writeSInt64( string itemName, long value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_SINT64, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_VARINT);
write_raw_varint64((value << 1) ^ (value >> 63));
}
public void writeFixed32( string itemName, int value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_FIXED32, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_FIXED32);
write_raw_littleendian32(value);
}
public void writeFixed64( string itemName, long value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_UINT64, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_FIXED64);
write_raw_littleendian64(value);
}
public void writeDouble( string itemName, double value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_DOUBLE, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_FIXED64);
//write_raw_littleendian64(Double.doubleToRawLongBits(value));
write_raw_littleendian64(BitConverter.DoubleToInt64Bits(value));
}
public void writeSingle( string itemName, float value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_SINGLE, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_FIXED32);
//write_raw_littleendian32(Float.floatToRawIntBits(value));
write_raw_littleendian32(BitConverter.ToInt32(BitConverter.GetBytes(value), 0));
}
public void writeBool( string itemName, bool value)
{
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_BOOLEAN, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_VARINT);
write_rawbyte(value ? 1 : 0);
}
public void writeBytes( string itemName, byte[] value)
{
if (value == null) return;
writeBytes(itemName, value, 0, value.Length);
}
public void writeBytes( string itemName, byte[] value, int start, int count)
{
if (value == null) return;
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_BOOLEAN, null);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_LENGTH_DELIMITED);
write_raw_varint32(count);
write_rawbytes(value, start, count);
}
public void writeEnum( string itemName, string enumValue)
{
writeEnum(itemName, itemName, enumValue);
}
public void writeEnum( string itemName, string isaName, string enumValue)
{
if (enumValue == null) return;
if (version == null) ensureGroup(true, CURRENT_VERSION, ITM_TYPE_STRUCT);
Itm enm = ensureItem(true, isaName, ITM_TYPE_ENUM, enumValue, ITM_TYPE_STRING, isaName, ITM_TYPE_ENUM);
Itm item = ensureItem(true, peekIsa(true), itemName, ITM_TYPE_ENUM, enm.isa);
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_VARINT);
write_raw_varint32(enm.id);
}
public void writeEnd()
{
Itm item = stack.Pop();
write_raw_varint32((item.id << TAG_TYPE_BITS) | RAW_TYPE_END_GROUP);
}
private void write_raw_varint32(int value)
{
while (true)
{
if ((value & ~0x7F) == 0)
{
write_rawbyte(value);
return;
}
else
{
write_rawbyte((value & 0x7F) | 0x80);
value = (int)((uint)value >> 7);
}
}
}
private void write_raw_littleendian64( long value)
{
write_rawbyte((int)(value) & 0xFF);
write_rawbyte((int)(value >> 8) & 0xFF);
write_rawbyte((int)(value >> 16) & 0xFF);
write_rawbyte((int)(value >> 24) & 0xFF);
write_rawbyte((int)(value >> 32) & 0xFF);
write_rawbyte((int)(value >> 40) & 0xFF);
write_rawbyte((int)(value >> 48) & 0xFF);
write_rawbyte((int)(value >> 56) & 0xFF);
}
private void write_raw_varint64(long value)
{
while (true)
{
if ((value & ~0x7FL) == 0)
{
write_rawbyte((int)value);
return;
}
else
{
write_rawbyte(((int)value & 0x7F) | 0x80);
value = (long)((ulong)value >> 7);
}
}
}
private void write_raw_littleendian32( int value)
{
write_rawbyte((value) & 0xFF);
write_rawbyte((value >> 8) & 0xFF);
write_rawbyte((value >> 16) & 0xFF);
write_rawbyte((value >> 24) & 0xFF);
}
private void write_rawbyte( int value)
{
if (outputStream != null)
{
try {
outputStream.WriteByte((byte)value);
} catch (IOException e) {
throw new Exception ("cannot write") ;
}
}
}
private void write_rawbytes( byte[] value, int offset, int length)
{
if (outputStream != null)
{
try {
outputStream.Write(value, offset, length);
} catch (IOException e) {
throw new Exception ("cannot write") ;
}
}
}
private void write_rawstring ( string value) {
try {
byte[] bytes = Encoding.UTF8.GetBytes(value);
write_raw_varint32(bytes.Length);
write_rawbytes(bytes, 0, bytes.Length);
} catch (Exception e) {
throw new Exception ("utf-8 not supported") ;
}
}
private class Fld
{
public bool is_start;
public bool is_end;
public string name;
public int index;
public int level;
public string type_name;
public string isa_name;
public Object value;
public Fld()
{
this.clear();
}
public void clear()
{
this.is_start = false;
this.is_end = false;
this.name = "";
this.index = 0;
this.level = 0;
this.type_name = "";
this.isa_name = "";
this.value = null;
}
}
private Fld scannedField = null;
public bool readItem()
{
int wireTag;
int wireType;
int wireFieldNumber;
Grp group = null;
Itm item = null;
if (scannedField == null)
{
scannedField = new Fld();
}
do
{
scannedField.clear();
if (this.eos)
{
return false;
}
wireTag = read_rawvarint32();
if (wireTag == 0)
{
return false;
}
wireType = wireTag & TAG_TYPE_MASK;
//wireFieldNumber = wireTag >>> TAG_TYPE_BITS;
wireFieldNumber = (int)((uint)wireTag >> TAG_TYPE_BITS);
item = null;
switch (wireType)
{
case RAW_TYPE_END_GROUP:
{
item = stack.Pop();
scannedField.name = item.name;
scannedField.level = stack.Count;
scannedField.index = item.id;
scannedField.isa_name = item.isa.name;
scannedField.type_name = "end_group";
scannedField.is_end = true;
}
break;
case RAW_TYPE_FIXED32:
{
item = peekIsa(false).indexedItems[wireFieldNumber];
scannedField.name = item.name;
scannedField.level = stack.Count;
scannedField.index = item.id;
switch (item.type)
{
case ITM_TYPE_FIXED32:
scannedField.type_name = "fixed32";
scannedField.value = read_rawlittleendian32();
break;
case ITM_TYPE_SINGLE:
scannedField.type_name = "single";
//scannedField.value = Float.intBitsToFloat(read_rawlittleendian32());
scannedField.value = BitConverter.ToSingle(BitConverter.GetBytes(read_rawlittleendian32()), 0);
break;
default:
throw new Exception("bad type for fixed32");
}
}
break;
case RAW_TYPE_FIXED64:
{
item = peekIsa(false).indexedItems[wireFieldNumber];
scannedField.name = item.name;
scannedField.level = stack.Count;
scannedField.index = item.id;
switch (item.type)
{
case ITM_TYPE_FIXED64:
scannedField.type_name = "fixed64";
scannedField.value = read_rawlittleendian64();
break;
case ITM_TYPE_DOUBLE:
scannedField.type_name = "double";
//scannedField.value = Double.longBitsToDouble(read_rawlittleendian64());
scannedField.value = BitConverter.Int64BitsToDouble(read_rawlittleendian64());
break;
default:
throw new Exception("bad type for fixed64");
}
}
break;
case RAW_TYPE_LENGTH_DELIMITED:
{
item = peekIsa(false).indexedItems[wireFieldNumber];
scannedField.name = item.name;
scannedField.level = stack.Count;
scannedField.index = item.id;
switch (item.type)
{
case ITM_TYPE_STRING:
{
scannedField.type_name = "string";
scannedField.value = read_rawstring() ;
}
break;
case ITM_TYPE_BYTES:
{
scannedField.type_name = "bytes";
int size = read_rawvarint32();
byte[] bytes = read_rawbytes(size);
scannedField.value = bytes;
}
break;
default:
throw new Exception("bad type for length delimited");
}
}
break;
case RAW_TYPE_SCHEMA:
switch (wireFieldNumber)
{
case 1:
{
group = new Grp();
group.type = (byte)read_rawbyte();
group.name = read_rawstring() ;
namedGroups.Add(group.name, group);
if (version == null)
{
version = group;
}
}
break;
case 2:
{
item = new Itm();
item.type = (byte)read_rawbyte();
item.name = read_rawstring() ;
group = namedGroups[read_rawstring()] ;
item.id = ++group.count;
group.namedItems.Add(item.name, item);
group.indexedItems.Add(item.id, item);
}
break;
case 3:
{
item = new Itm();
item.type = (byte)read_rawbyte();
item.name = read_rawstring() ;
group = namedGroups[read_rawstring()] ;
item.id = ++group.count;
item.isa = namedGroups[read_rawstring()];
group.namedItems.Add(item.name, item);
group.indexedItems.Add(item.id, item);
}
break;
default:
throw new Exception("bad field number for reserved");
}
break;
case RAW_TYPE_START_GROUP:
{
item = peekIsa(false).indexedItems[wireFieldNumber];
scannedField.name = item.name;
scannedField.index = item.id;
scannedField.level = stack.Count;
scannedField.type_name = "start_group";
scannedField.is_start = true;
stack.Push(item);
}
break;
case RAW_TYPE_VARINT:
{
item = peekIsa(false).indexedItems[wireFieldNumber];
scannedField.name = item.name;
scannedField.level = stack.Count;
scannedField.index = item.id;
switch (item.type)
{
case ITM_TYPE_BOOLEAN:
scannedField.type_name = "bool";
scannedField.value = read_rawvarint32() != 0;
break;
case ITM_TYPE_ENUM:
scannedField.type_name = "enum";
scannedField.isa_name = item.isa.name;
scannedField.value = item.isa.indexedItems[read_rawvarint32()].name;
break;
case ITM_TYPE_UINT32:
scannedField.type_name = "uint32";
scannedField.value = read_rawvarint32();
break;
case ITM_TYPE_UINT64:
scannedField.type_name = "uint64";
scannedField.value = read_rawvarint64();
break;
case ITM_TYPE_SINT32:
scannedField.type_name = "sint32";
{
int n = read_rawvarint32();
scannedField.value = ((int)((uint)n >> 1)) ^ -(n & 1);
}
break;
case ITM_TYPE_SINT64:
scannedField.type_name = "sint64";
{
long n = read_rawvarint64();
scannedField.value = ((long)((ulong)n >> 1)) ^ -(n & 1);
}
break;
default:
throw new Exception("bad type for readVarint");
}
}
break;
default:
throw new Exception("invalidwiretype");
}
} while (wireType == RAW_TYPE_SCHEMA);
return true;
}
public bool isStartItem()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.is_start;
}
public bool isEndItem()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.is_end;
}
public string itemTypeName()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.type_name;
}
public string itemTypeIsaName()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.isa_name;
}
public string itemName()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.name;
}
public int itemIndex()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.index;
}
public int itemLevel()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.level;
}
public Object itemValue()
{
if (scannedField == null) throw new Exception("no item read");
return scannedField.value;
}
private int read_rawvarint32()
{
byte tmp = read_rawbyte();
if ((tmp & 0x80) == 0)
{
return tmp;
}
int result = tmp & 0x7f;
if (((tmp = read_rawbyte()) & 0x80) == 0)
{
result |= tmp << 7;
}
else
{
result |= (tmp & 0x7f) << 7;
if (((tmp = read_rawbyte()) & 0x80) == 0)
{
result |= tmp << 14;
}
else
{
result |= (tmp & 0x7f) << 14;
if (((tmp = read_rawbyte()) & 0x80) == 0)
{
result |= tmp << 21;
}
else
{
result |= (tmp & 0x7f) << 21;
result |= (tmp = read_rawbyte()) << 28;
if ((tmp & 0x80) != 0)
{
for (int i = 0; i < 5; i++)
{
if ((((tmp = read_rawbyte()) & 0x80) == 0))
{
return result;
}
}
throw new Exception("malformd varint32");
}
}
}
}
return result;
}
private long read_rawvarint64()
{
int shift = 0;
long result = 0;
while (shift < 64)
{
byte b = read_rawbyte();
result |= (long)(b & 0x7F) << shift;
if ((b & 0x80) == 0)
{
return result;
}
shift += 7;
}
throw new Exception("malformed varint64");
}
private int read_rawlittleendian32()
{
byte b1 = read_rawbyte();
byte b2 = read_rawbyte();
byte b3 = read_rawbyte();
byte b4 = read_rawbyte();
return (((int)b1 & 0xff)) |
(((int)b2 & 0xff) << 8) |
(((int)b3 & 0xff) << 16) |
(((int)b4 & 0xff) << 24);
}
private long read_rawlittleendian64()
{
byte b1 = read_rawbyte();
byte b2 = read_rawbyte();
byte b3 = read_rawbyte();
byte b4 = read_rawbyte();
byte b5 = read_rawbyte();
byte b6 = read_rawbyte();
byte b7 = read_rawbyte();
byte b8 = read_rawbyte();
return (((long)b1 & 0xff)) |
(((long)b2 & 0xff) << 8) |
(((long)b3 & 0xff) << 16) |
(((long)b4 & 0xff) << 24) |
(((long)b5 & 0xff) << 32) |
(((long)b6 & 0xff) << 40) |
(((long)b7 & 0xff) << 48) |
(((long)b8 & 0xff) << 56);
}
private byte read_rawbyte()
{
int b;
try {
b = inputStream.ReadByte();
} catch (IOException e) {
b = -1 ;
}
if (b < 0)
{
this.eos = true;
return 0;
}
return (byte)b;
}
private byte[] read_rawbytes( int size)
{
byte[] a = new byte[size];
int c;
try {
c = inputStream.Read(a, 0, size);
} catch (IOException e) {
c = -1 ;
}
if (c != size)
{
this.eos = true;
throw new Exception("not enough bytes");
}
return a;
}
private string read_rawstring() {
int size = read_rawvarint32();
byte[] bytes = read_rawbytes(size);
try {
return Encoding.UTF8.GetString(bytes) ;
} catch (Exception e) {
throw new Exception ("utf-8 not supported") ;
}
}
public void clear()
{
try
{
if (namedGroups != null)
{
foreach (Grp g in namedGroups.Values)
{
g.indexedItems.Clear();
g.namedItems.Clear();
g.indexedItems = null;
g.namedItems = null;
}
namedGroups.Clear();
}
if (stack != null)
{
stack.Clear();
stack = null;
}
if (scannedField != null)
{
scannedField.clear();
scannedField = null;
}
}
catch (Exception e)
{
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~SequentialStructuredDataStream()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
this.clear();
}
}
| |
namespace Xbehave.Execution
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xbehave.Execution.Extensions;
using Xbehave.Sdk;
using Xunit.Abstractions;
using Xunit.Sdk;
public class ScenarioInvoker
{
private readonly IScenario scenario;
private readonly IMessageBus messageBus;
private readonly Type scenarioClass;
private readonly object[] constructorArguments;
private readonly MethodInfo scenarioMethod;
private readonly object[] scenarioMethodArguments;
private readonly IReadOnlyList<BeforeAfterTestAttribute> beforeAfterScenarioAttributes;
private readonly ExceptionAggregator aggregator;
private readonly CancellationTokenSource cancellationTokenSource;
private readonly ExecutionTimer timer = new ExecutionTimer();
private readonly Stack<BeforeAfterTestAttribute> beforeAfterScenarioAttributesRun =
new Stack<BeforeAfterTestAttribute>();
public ScenarioInvoker(
IScenario scenario,
IMessageBus messageBus,
Type scenarioClass,
object[] constructorArguments,
MethodInfo scenarioMethod,
object[] scenarioMethodArguments,
IReadOnlyList<BeforeAfterTestAttribute> beforeAfterScenarioAttributes,
ExceptionAggregator aggregator,
CancellationTokenSource cancellationTokenSource)
{
Guard.AgainstNullArgument(nameof(scenario), scenario);
Guard.AgainstNullArgument(nameof(messageBus), messageBus);
Guard.AgainstNullArgument(nameof(scenarioClass), scenarioClass);
Guard.AgainstNullArgument(nameof(scenarioMethod), scenarioMethod);
Guard.AgainstNullArgument(nameof(beforeAfterScenarioAttributes), beforeAfterScenarioAttributes);
Guard.AgainstNullArgument(nameof(aggregator), aggregator);
Guard.AgainstNullArgument(nameof(cancellationTokenSource), cancellationTokenSource);
this.scenario = scenario;
this.messageBus = messageBus;
this.scenarioClass = scenarioClass;
this.constructorArguments = constructorArguments;
this.scenarioMethod = scenarioMethod;
this.scenarioMethodArguments = scenarioMethodArguments;
this.beforeAfterScenarioAttributes = beforeAfterScenarioAttributes;
this.aggregator = aggregator;
this.cancellationTokenSource = cancellationTokenSource;
}
public async Task<RunSummary> RunAsync()
{
var summary = new RunSummary();
await this.aggregator.RunAsync(async () =>
{
if (!this.cancellationTokenSource.IsCancellationRequested)
{
var testClassInstance = this.CreateScenarioClass();
if (!this.cancellationTokenSource.IsCancellationRequested)
{
await this.BeforeScenarioMethodInvokedAsync();
if (!this.cancellationTokenSource.IsCancellationRequested && !this.aggregator.HasExceptions)
{
summary.Aggregate(await this.InvokeScenarioMethodAsync(testClassInstance));
}
await this.AfterScenarioMethodInvokedAsync();
}
if (testClassInstance is IDisposable disposable)
{
this.timer.Aggregate(() => this.aggregator.Run(disposable.Dispose));
}
}
summary.Time += this.timer.Total;
});
return summary;
}
private static string GetStepDisplayName(
string scenarioDisplayName, int stepNumber, string stepDisplayText) =>
string.Format(
CultureInfo.InvariantCulture,
"{0} [{1}] {2}",
scenarioDisplayName,
stepNumber.ToString("D2", CultureInfo.InvariantCulture),
stepDisplayText);
private object CreateScenarioClass()
{
object testClass = null;
if (!this.scenarioMethod.IsStatic && !this.aggregator.HasExceptions)
{
this.timer.Aggregate(() => testClass = Activator.CreateInstance(this.scenarioClass, this.constructorArguments));
}
return testClass;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions are collected in the aggregator.")]
private Task BeforeScenarioMethodInvokedAsync()
{
foreach (var beforeAfterAttribute in this.beforeAfterScenarioAttributes)
{
try
{
this.timer.Aggregate(() => beforeAfterAttribute.Before(this.scenarioMethod));
this.beforeAfterScenarioAttributesRun.Push(beforeAfterAttribute);
}
catch (Exception ex)
{
this.aggregator.Add(ex);
break;
}
if (this.cancellationTokenSource.IsCancellationRequested)
{
break;
}
}
return Task.FromResult(0);
}
private Task AfterScenarioMethodInvokedAsync()
{
foreach (var beforeAfterAttribute in this.beforeAfterScenarioAttributesRun)
{
this.aggregator.Run(() => this.timer.Aggregate(() => beforeAfterAttribute.After(this.scenarioMethod)));
}
return Task.FromResult(0);
}
private async Task<RunSummary> InvokeScenarioMethodAsync(object scenarioClassInstance)
{
var backgroundStepDefinitions = new List<IStepDefinition>();
var scenarioStepDefinitions = new List<IStepDefinition>();
await this.aggregator.RunAsync(async () =>
{
using (CurrentThread.EnterStepDefinitionContext())
{
foreach (var backgroundMethod in this.scenario.TestCase.TestMethod.TestClass.Class
.GetMethods(false)
.Where(candidate => candidate.GetCustomAttributes(typeof(BackgroundAttribute)).Any())
.Select(method => method.ToRuntimeMethod()))
{
await this.timer.AggregateAsync(() =>
backgroundMethod.InvokeAsync(scenarioClassInstance, null));
}
backgroundStepDefinitions.AddRange(CurrentThread.StepDefinitions);
}
using (CurrentThread.EnterStepDefinitionContext())
{
await this.timer.AggregateAsync(() =>
this.scenarioMethod.InvokeAsync(scenarioClassInstance, this.scenarioMethodArguments));
scenarioStepDefinitions.AddRange(CurrentThread.StepDefinitions);
}
});
var runSummary = new RunSummary { Time = this.timer.Total };
if (!this.aggregator.HasExceptions)
{
runSummary.Aggregate(await this.InvokeStepsAsync(backgroundStepDefinitions, scenarioStepDefinitions));
}
return runSummary;
}
private async Task<RunSummary> InvokeStepsAsync(
ICollection<IStepDefinition> backGroundStepDefinitions, ICollection<IStepDefinition> scenarioStepDefinitions)
{
var scenarioTypeInfo = this.scenarioClass.GetTypeInfo();
var filters = scenarioTypeInfo.Assembly.GetCustomAttributes(typeof(Attribute))
.Concat(scenarioTypeInfo.GetCustomAttributes(typeof(Attribute)))
.Concat(this.scenarioMethod.GetCustomAttributes(typeof(Attribute)))
.OfType<IFilter<IStepDefinition>>();
var summary = new RunSummary();
string skipReason = null;
var scenarioTeardowns = new List<Tuple<StepContext, Func<IStepContext, Task>>>();
var stepNumber = 0;
foreach (var stepDefinition in filters.Aggregate(
backGroundStepDefinitions.Concat(scenarioStepDefinitions),
(current, filter) => filter.Filter(current)))
{
stepDefinition.SkipReason = stepDefinition.SkipReason ?? skipReason;
var stepDisplayName = GetStepDisplayName(
this.scenario.DisplayName,
++stepNumber,
stepDefinition.DisplayTextFunc?.Invoke(stepDefinition.Text, stepNumber <= backGroundStepDefinitions.Count));
var step = new StepTest(this.scenario, stepDisplayName);
var interceptingBus = new DelegatingMessageBus(
this.messageBus,
message =>
{
if (message is ITestFailed && stepDefinition.FailureBehavior == RemainingSteps.Skip)
{
skipReason = $"Failed to execute preceding step: {step.DisplayName}";
}
});
var stepContext = new StepContext(step);
var stepRunner = new StepTestRunner(
stepContext,
stepDefinition.Body,
step,
interceptingBus,
this.scenarioClass,
this.constructorArguments,
this.scenarioMethod,
this.scenarioMethodArguments,
stepDefinition.SkipReason,
new BeforeAfterTestAttribute[0],
new ExceptionAggregator(this.aggregator),
this.cancellationTokenSource);
summary.Aggregate(await stepRunner.RunAsync());
var stepTeardowns = stepContext.Disposables
.Where(disposable => disposable != null)
.Select((Func<IDisposable, Func<IStepContext, Task>>)(disposable =>
context =>
{
disposable.Dispose();
return Task.FromResult(0);
}))
.Concat(stepDefinition.Teardowns)
.Where(teardown => teardown != null)
.Select(teardown => Tuple.Create(stepContext, teardown));
scenarioTeardowns.AddRange(stepTeardowns);
}
if (scenarioTeardowns.Any())
{
scenarioTeardowns.Reverse();
var teardownTimer = new ExecutionTimer();
var teardownAggregator = new ExceptionAggregator();
foreach (var teardown in scenarioTeardowns)
{
await Invoker.Invoke(() => teardown.Item2(teardown.Item1), teardownAggregator, teardownTimer);
}
summary.Time += teardownTimer.Total;
if (teardownAggregator.HasExceptions)
{
summary.Failed++;
summary.Total++;
var stepDisplayName = GetStepDisplayName(this.scenario.DisplayName, ++stepNumber, "(Teardown)");
this.messageBus.Queue(
new StepTest(this.scenario, stepDisplayName),
test => new TestFailed(test, teardownTimer.Total, null, teardownAggregator.ToException()),
this.cancellationTokenSource);
}
}
return summary;
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IProductTypeApi
{
#region Synchronous Operations
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ProductType</returns>
ProductType GetProductTypeById (string productTypeId);
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> GetProductTypeByIdWithHttpInfo (string productTypeId);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ProductType></returns>
List<ProductType> GetProductTypeBySearchText (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ProductType></returns>
ApiResponse<List<ProductType>> GetProductTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> GetProductTypeByIdAsync (string productTypeId);
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> GetProductTypeByIdAsyncWithHttpInfo (string productTypeId);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ProductType></returns>
System.Threading.Tasks.Task<List<ProductType>> GetProductTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ProductType>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ProductType>>> GetProductTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class ProductTypeApi : IProductTypeApi
{
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeApi"/> class.
/// </summary>
/// <returns></returns>
public ProductTypeApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ProductTypeApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ProductType</returns>
public ProductType GetProductTypeById (string productTypeId)
{
ApiResponse<ProductType> localVarResponse = GetProductTypeByIdWithHttpInfo(productTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > GetProductTypeByIdWithHttpInfo (string productTypeId)
{
// verify the required parameter 'productTypeId' is set
if (productTypeId == null)
throw new ApiException(400, "Missing required parameter 'productTypeId' when calling ProductTypeApi->GetProductTypeById");
var localVarPath = "/beta/productType/{productTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (productTypeId != null) localVarPathParams.Add("productTypeId", Configuration.ApiClient.ParameterToString(productTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> GetProductTypeByIdAsync (string productTypeId)
{
ApiResponse<ProductType> localVarResponse = await GetProductTypeByIdAsyncWithHttpInfo(productTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> GetProductTypeByIdAsyncWithHttpInfo (string productTypeId)
{
// verify the required parameter 'productTypeId' is set
if (productTypeId == null) throw new ApiException(400, "Missing required parameter 'productTypeId' when calling GetProductTypeById");
var localVarPath = "/beta/productType/{productTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (productTypeId != null) localVarPathParams.Add("productTypeId", Configuration.ApiClient.ParameterToString(productTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeById: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ProductType></returns>
public List<ProductType> GetProductTypeBySearchText (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ProductType>> localVarResponse = GetProductTypeBySearchTextWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ProductType></returns>
public ApiResponse< List<ProductType> > GetProductTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/productType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<ProductType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductType>)));
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ProductType></returns>
public async System.Threading.Tasks.Task<List<ProductType>> GetProductTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ProductType>> localVarResponse = await GetProductTypeBySearchTextAsyncWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ProductType>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ProductType>>> GetProductTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/beta/productType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeBySearchText: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling GetProductTypeBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<List<ProductType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductType>)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Crossroads.Gateway.Areas.HelpPage.Models;
namespace Crossroads.Gateway.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// 5.2.45. Fundamental IFF atc data
/// </summary>
[Serializable]
[XmlRoot]
public partial class FundamentalParameterDataIff
{
/// <summary>
/// ERP
/// </summary>
private float _erp;
/// <summary>
/// frequency
/// </summary>
private float _frequency;
/// <summary>
/// pgrf
/// </summary>
private float _pgrf;
/// <summary>
/// Pulse width
/// </summary>
private float _pulseWidth;
/// <summary>
/// Burst length
/// </summary>
private uint _burstLength;
/// <summary>
/// Applicable modes enumeration
/// </summary>
private byte _applicableModes;
/// <summary>
/// padding
/// </summary>
private ushort _pad2;
/// <summary>
/// padding
/// </summary>
private byte _pad3;
/// <summary>
/// Initializes a new instance of the <see cref="FundamentalParameterDataIff"/> class.
/// </summary>
public FundamentalParameterDataIff()
{
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(FundamentalParameterDataIff left, FundamentalParameterDataIff right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(FundamentalParameterDataIff left, FundamentalParameterDataIff right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public virtual int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize += 4; // this._erp
marshalSize += 4; // this._frequency
marshalSize += 4; // this._pgrf
marshalSize += 4; // this._pulseWidth
marshalSize += 4; // this._burstLength
marshalSize += 1; // this._applicableModes
marshalSize += 2; // this._pad2
marshalSize += 1; // this._pad3
return marshalSize;
}
/// <summary>
/// Gets or sets the ERP
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "erp")]
public float Erp
{
get
{
return this._erp;
}
set
{
this._erp = value;
}
}
/// <summary>
/// Gets or sets the frequency
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "frequency")]
public float Frequency
{
get
{
return this._frequency;
}
set
{
this._frequency = value;
}
}
/// <summary>
/// Gets or sets the pgrf
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "pgrf")]
public float Pgrf
{
get
{
return this._pgrf;
}
set
{
this._pgrf = value;
}
}
/// <summary>
/// Gets or sets the Pulse width
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "pulseWidth")]
public float PulseWidth
{
get
{
return this._pulseWidth;
}
set
{
this._pulseWidth = value;
}
}
/// <summary>
/// Gets or sets the Burst length
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "burstLength")]
public uint BurstLength
{
get
{
return this._burstLength;
}
set
{
this._burstLength = value;
}
}
/// <summary>
/// Gets or sets the Applicable modes enumeration
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "applicableModes")]
public byte ApplicableModes
{
get
{
return this._applicableModes;
}
set
{
this._applicableModes = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "pad2")]
public ushort Pad2
{
get
{
return this._pad2;
}
set
{
this._pad2 = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "pad3")]
public byte Pad3
{
get
{
return this._pad3;
}
set
{
this._pad3 = value;
}
}
/// <summary>
/// Occurs when exception when processing PDU is caught.
/// </summary>
public event EventHandler<PduExceptionEventArgs> ExceptionOccured;
/// <summary>
/// Called when exception occurs (raises the <see cref="Exception"/> event).
/// </summary>
/// <param name="e">The exception.</param>
protected void RaiseExceptionOccured(Exception e)
{
if (Pdu.FireExceptionEvents && this.ExceptionOccured != null)
{
this.ExceptionOccured(this, new PduExceptionEventArgs(e));
}
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Marshal(DataOutputStream dos)
{
if (dos != null)
{
try
{
dos.WriteFloat((float)this._erp);
dos.WriteFloat((float)this._frequency);
dos.WriteFloat((float)this._pgrf);
dos.WriteFloat((float)this._pulseWidth);
dos.WriteUnsignedInt((uint)this._burstLength);
dos.WriteUnsignedByte((byte)this._applicableModes);
dos.WriteUnsignedShort((ushort)this._pad2);
dos.WriteUnsignedByte((byte)this._pad3);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Unmarshal(DataInputStream dis)
{
if (dis != null)
{
try
{
this._erp = dis.ReadFloat();
this._frequency = dis.ReadFloat();
this._pgrf = dis.ReadFloat();
this._pulseWidth = dis.ReadFloat();
this._burstLength = dis.ReadUnsignedInt();
this._applicableModes = dis.ReadUnsignedByte();
this._pad2 = dis.ReadUnsignedShort();
this._pad3 = dis.ReadUnsignedByte();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public virtual void Reflection(StringBuilder sb)
{
sb.AppendLine("<FundamentalParameterDataIff>");
try
{
sb.AppendLine("<erp type=\"float\">" + this._erp.ToString(CultureInfo.InvariantCulture) + "</erp>");
sb.AppendLine("<frequency type=\"float\">" + this._frequency.ToString(CultureInfo.InvariantCulture) + "</frequency>");
sb.AppendLine("<pgrf type=\"float\">" + this._pgrf.ToString(CultureInfo.InvariantCulture) + "</pgrf>");
sb.AppendLine("<pulseWidth type=\"float\">" + this._pulseWidth.ToString(CultureInfo.InvariantCulture) + "</pulseWidth>");
sb.AppendLine("<burstLength type=\"uint\">" + this._burstLength.ToString(CultureInfo.InvariantCulture) + "</burstLength>");
sb.AppendLine("<applicableModes type=\"byte\">" + this._applicableModes.ToString(CultureInfo.InvariantCulture) + "</applicableModes>");
sb.AppendLine("<pad2 type=\"ushort\">" + this._pad2.ToString(CultureInfo.InvariantCulture) + "</pad2>");
sb.AppendLine("<pad3 type=\"byte\">" + this._pad3.ToString(CultureInfo.InvariantCulture) + "</pad3>");
sb.AppendLine("</FundamentalParameterDataIff>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as FundamentalParameterDataIff;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(FundamentalParameterDataIff obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
if (this._erp != obj._erp)
{
ivarsEqual = false;
}
if (this._frequency != obj._frequency)
{
ivarsEqual = false;
}
if (this._pgrf != obj._pgrf)
{
ivarsEqual = false;
}
if (this._pulseWidth != obj._pulseWidth)
{
ivarsEqual = false;
}
if (this._burstLength != obj._burstLength)
{
ivarsEqual = false;
}
if (this._applicableModes != obj._applicableModes)
{
ivarsEqual = false;
}
if (this._pad2 != obj._pad2)
{
ivarsEqual = false;
}
if (this._pad3 != obj._pad3)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ this._erp.GetHashCode();
result = GenerateHash(result) ^ this._frequency.GetHashCode();
result = GenerateHash(result) ^ this._pgrf.GetHashCode();
result = GenerateHash(result) ^ this._pulseWidth.GetHashCode();
result = GenerateHash(result) ^ this._burstLength.GetHashCode();
result = GenerateHash(result) ^ this._applicableModes.GetHashCode();
result = GenerateHash(result) ^ this._pad2.GetHashCode();
result = GenerateHash(result) ^ this._pad3.GetHashCode();
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertToVector256Int32Single()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int32Single();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ConvertToVector256Int32Single
{
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector256<Single> _clsVar;
private Vector256<Single> _fld;
private SimpleUnaryOpTest__DataTable<Int32, Single> _dataTable;
static SimpleUnaryOpTest__ConvertToVector256Int32Single()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleUnaryOpTest__ConvertToVector256Int32Single()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int32, Single>(_data, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.ConvertToVector256Int32(
Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.ConvertToVector256Int32(
Avx.LoadVector256((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.ConvertToVector256Int32(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Int32), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Int32), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.ConvertToVector256Int32), new Type[] { typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.ConvertToVector256Int32(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr);
var result = Avx.ConvertToVector256Int32(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Single*)(_dataTable.inArrayPtr));
var result = Avx.ConvertToVector256Int32(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr));
var result = Avx.ConvertToVector256Int32(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ConvertToVector256Int32Single();
var result = Avx.ConvertToVector256Int32(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.ConvertToVector256Int32(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Int32[] result, [CallerMemberName] string method = "")
{
if (result[0] != (Int32)(MathF.Round(firstOp[0])))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (Int32)(MathF.Round(firstOp[i])))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.ConvertToVector256Int32)}(Vector256<Single>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Symbology library.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 5/1/2009 9:07:49 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// DashControl
/// </summary>
public class DashControl : Control
{
#region Events
/// <summary>
/// Occurs any time any action has occurred that changes the pattern.
/// </summary>
public event EventHandler PatternChanged;
#endregion
#region Private Variables
private readonly Timer _highlightTimer;
private SizeF _blockSize;
private Color _buttonDownDarkColor;
private Color _buttonDownLitColor;
private Color _buttonUpDarkColor;
private Color _butttonUpLitColor;
private List<SquareButton> _horizontalButtons;
DashSliderHorizontal _horizontalSlider;
private Color _lineColor;
private double _lineWidth;
private List<SquareButton> _verticalButtons;
DashSliderVertical _verticalSlider;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of DashControl
/// </summary>
public DashControl()
{
_blockSize.Width = 10F;
_blockSize.Height = 10F;
_horizontalSlider = new DashSliderHorizontal();
_horizontalSlider.Size = new SizeF(_blockSize.Width, _blockSize.Height * 3 / 2);
_verticalSlider = new DashSliderVertical();
_verticalSlider.Size = new SizeF(_blockSize.Width * 3 / 2, _blockSize.Height);
_buttonDownDarkColor = SystemColors.ControlDark;
_buttonDownLitColor = SystemColors.ControlDark;
_buttonUpDarkColor = SystemColors.Control;
_butttonUpLitColor = SystemColors.Control;
_highlightTimer = new Timer();
_highlightTimer.Interval = 100;
_highlightTimer.Tick += HighlightTimerTick;
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the boolean pattern for the horizontal patterns that control the custom
/// dash style.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool[] DashButtons
{
get
{
bool[] result = new bool[_horizontalButtons.Count];
for (int i = 0; i < _horizontalButtons.Count; i++)
{
result[i] = _horizontalButtons[i].IsDown;
}
return result;
}
set
{
SetHorizontalPattern(value);
}
}
/// <summary>
/// Gets or sets the boolean pattern for the vertical patterns that control the custom
/// compound array.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool[] CompoundButtons
{
get
{
bool[] result = new bool[_verticalButtons.Count];
for (int i = 0; i < _verticalButtons.Count; i++)
{
result[i] = _verticalButtons[i].IsDown;
}
return result;
}
set
{
SetVerticalPattern(value);
}
}
/// <summary>
/// Gets or sets the color for all the buttons when they are pressed and inactive
/// </summary>
[Description("Gets or sets the base color for all the buttons when they are pressed and inactive")]
public Color ButtonDownDarkColor
{
get { return _buttonDownDarkColor; }
set { _buttonDownDarkColor = value; }
}
/// <summary>
/// Gets or sets the base color for all the buttons when they are pressed and active
/// </summary>
[Description("Gets or sets the base color for all the buttons when they are pressed and active")]
public Color ButtonDownLitColor
{
get { return _buttonDownLitColor; }
set { _buttonDownLitColor = value; }
}
/// <summary>
/// Gets or sets the base color for all the buttons when they are not pressed and not active.
/// </summary>
[Description("Gets or sets the base color for all the buttons when they are not pressed and not active.")]
public Color ButtonUpDarkColor
{
get { return _buttonUpDarkColor; }
set { _buttonUpDarkColor = value; }
}
/// <summary>
/// Gets or sets the base color for all the buttons when they are not pressed but are active.
/// </summary>
[Description("Gets or sets the base color for all the buttons when they are not pressed but are active.")]
public Color ButtonUpLitColor
{
get { return _butttonUpLitColor; }
set { _butttonUpLitColor = value; }
}
/// <summary>
/// Gets or sets the line width for the actual line being described, regardless of scale mode.
/// </summary>
public double LineWidth
{
get { return _lineWidth; }
set { _lineWidth = value; }
}
/// <summary>
/// Gets the width of a square in the same units used for the line width.
/// </summary>
public double SquareWidth
{
get { return _lineWidth * Width / _blockSize.Width; }
}
/// <summary>
/// Gets the height of the square
/// </summary>
public double SquareHeight
{
get { return _lineWidth * Height / _blockSize.Height; }
}
/// <summary>
/// Gets or sets the position of the sliders. The X describes the horizontal placement
/// of the horizontal slider, while the Y describes the vertical placement of the vertical slider.
/// </summary>
[Description("Gets or sets the position of the sliders. The X describes the horizontal placement of the horizontal slider, while the Y describes the vertical placement of the vertical slider."),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DashSliderHorizontal HorizontalSlider
{
get { return _horizontalSlider; }
set { _horizontalSlider = value; }
}
/// <summary>
/// Gets or sets the floating point size of each block in pixels.
/// </summary>
[Description("Gets or sets the floating point size of each block in pixels.")]
public SizeF BlockSize
{
get { return _blockSize; }
set
{
_blockSize = value;
if (HorizontalSlider != null) HorizontalSlider.Size = new SizeF(_blockSize.Width, _blockSize.Height * 3 / 2);
if (VerticalSlider != null) VerticalSlider.Size = new SizeF(_blockSize.Width * 3 / 2, _blockSize.Height);
}
}
/// <summary>
/// Gets or sets the color of the line
/// </summary>
[Description("Gets or sets the color that should be used for the filled sections of the line.")]
public Color LineColor
{
get { return _lineColor; }
set { _lineColor = value; }
}
/// <summary>
/// Gets or sets the vertical Slider
/// </summary>
[Description("Gets or sets the image to use as the vertical slider. If this is null, a simple triangle will be used."),
DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DashSliderVertical VerticalSlider
{
get { return _verticalSlider; }
set { _verticalSlider = value; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public float[] GetDashPattern()
{
bool pressed = true;
List<float> pattern = new List<float>();
float previousPosition = 0F;
int i = 0;
foreach (SquareButton button in _horizontalButtons)
{
if (button.IsDown != pressed)
{
float position = (i / ((float)_verticalButtons.Count));
if (position == 0) position = .0000001f;
pattern.Add(position - previousPosition);
previousPosition = position;
pressed = !pressed;
}
i++;
}
float final = (i / (float)_verticalButtons.Count);
if (final == 0) final = 0.000001F;
pattern.Add(final - previousPosition);
if (pattern.Count % 2 == 1) pattern.Add(.00001F);
if (pattern.Count == 0) return null;
return pattern.ToArray();
}
/// <summary>
///
/// </summary>
public float[] GetCompoundArray()
{
bool pressed = false;
List<float> pattern = new List<float>();
int i = 0;
foreach (SquareButton button in _verticalButtons)
{
if (button.IsDown != pressed)
{
float position = i / (float)_verticalButtons.Count;
pattern.Add(position);
pressed = !pressed;
}
i++;
}
if (pressed)
{
pattern.Add(1F);
}
if (pattern.Count == 0) return null;
return pattern.ToArray();
}
/// <summary>
/// Sets the pattern of squares for this pen by working with the given dash and compound patterns.
/// </summary>
/// <param name="stroke">Completely defines the ICartographicStroke that is being used to set the pattern.</param>
public void SetPattern(ICartographicStroke stroke)
{
_lineColor = stroke.Color;
_lineWidth = stroke.Width;
if (stroke.DashButtons == null)
{
_horizontalButtons = null;
_horizontalSlider.Position = new PointF(50F, 0F);
}
else
{
SetHorizontalPattern(stroke.DashButtons);
}
if (stroke.CompoundButtons == null)
{
_verticalButtons = null;
_verticalSlider.Position = new PointF(0F, 20F);
}
else
{
SetVerticalPattern(stroke.CompoundButtons);
}
CalculatePattern();
Invalidate();
}
/// <summary>
/// Sets the horizontal pattern for this control
/// </summary>
/// <param name="buttonPattern"></param>
protected virtual void SetHorizontalPattern(bool[] buttonPattern)
{
_horizontalSlider.Position = new PointF((buttonPattern.Length + 1) * _blockSize.Width, 0);
_horizontalButtons = new List<SquareButton>();
for (int i = 0; i < buttonPattern.Length; i++)
{
SquareButton sq = new SquareButton();
sq.Bounds = new RectangleF((i + 1) * _blockSize.Width, 0, _blockSize.Width, _blockSize.Height);
sq.ColorDownDark = _buttonDownDarkColor;
sq.ColorDownLit = _buttonDownLitColor;
sq.ColorUpDark = _buttonUpDarkColor;
sq.ColorUpLit = _butttonUpLitColor;
sq.IsDown = buttonPattern[i];
_horizontalButtons.Add(sq);
}
}
/// <summary>
/// Sets the vertical pattern for this control
/// </summary>
/// <param name="buttonPattern"></param>
protected virtual void SetVerticalPattern(bool[] buttonPattern)
{
_verticalSlider.Position = new PointF(0, (buttonPattern.Length + 1) * _blockSize.Width);
_verticalButtons = new List<SquareButton>();
for (int i = 0; i < buttonPattern.Length; i++)
{
SquareButton sq = new SquareButton();
sq.Bounds = new RectangleF(0, (i + 1) * _blockSize.Width, _blockSize.Width, _blockSize.Height);
sq.ColorDownDark = _buttonDownDarkColor;
sq.ColorDownLit = _buttonDownLitColor;
sq.ColorUpDark = _buttonUpDarkColor;
sq.ColorUpLit = _butttonUpLitColor;
sq.IsDown = buttonPattern[i];
_verticalButtons.Add(sq);
}
}
#endregion
#region Protected Methods
/// <summary>
/// Occurs when the dash control needs to calculate the pattern
/// </summary>
protected override void OnCreateControl()
{
base.OnCreateControl();
CalculatePattern();
}
/// <summary>
/// Prevent flicker
/// </summary>
/// <param name="pevent"></param>
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
/// <summary>
/// Creates a bitmap to draw to instead of drawing directly to the image.
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
Rectangle clip = new Rectangle();
if (clip.IsEmpty) clip = ClientRectangle;
Bitmap bmp = new Bitmap(clip.Width, clip.Height);
Graphics g = Graphics.FromImage(bmp);
g.TranslateTransform(clip.X, clip.Y);
g.Clear(BackColor);
OnDraw(g, e.ClipRectangle);
g.Dispose();
e.Graphics.DrawImage(bmp, clip, clip, GraphicsUnit.Pixel);
}
/// <summary>
/// Actually controls the basic drawing control.
/// </summary>
/// <param name="g"></param>
/// <param name="clipRectangle"></param>
protected virtual void OnDraw(Graphics g, Rectangle clipRectangle)
{
Brush b = new SolidBrush(LineColor);
foreach (SquareButton vButton in _verticalButtons)
{
foreach (SquareButton hButton in _horizontalButtons)
{
float x = hButton.Bounds.X;
float y = vButton.Bounds.Y;
if (hButton.IsDown && vButton.IsDown)
{
g.FillRectangle(b, x, y, _blockSize.Width, _blockSize.Height);
}
else
{
g.FillRectangle(Brushes.White, x, y, _blockSize.Width, _blockSize.Height);
}
g.DrawRectangle(Pens.Gray, x, y, _blockSize.Width, _blockSize.Height);
}
}
for (int v = 0; v < Height / _blockSize.Height; v++)
{
float y = v * _blockSize.Height;
if (y < clipRectangle.Y - _blockSize.Height) continue;
if (y > clipRectangle.Bottom + _blockSize.Height) continue;
for (int u = 0; u < Width / _blockSize.Width; u++)
{
float x = u * _blockSize.Width;
if (x < clipRectangle.X - _blockSize.Width) continue;
if (x > clipRectangle.Right + _blockSize.Width) continue;
g.DrawRectangle(Pens.Gray, x, y, _blockSize.Width, _blockSize.Height);
}
}
foreach (SquareButton button in _horizontalButtons)
{
button.Draw(g, clipRectangle);
}
foreach (SquareButton button in _verticalButtons)
{
button.Draw(g, clipRectangle);
}
_horizontalSlider.Draw(g, clipRectangle);
_verticalSlider.Draw(g, clipRectangle);
}
/// <summary>
/// Handles the mouse down event
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
// Sliders have priority over buttons
if (e.Button != MouseButtons.Left) return;
if (VerticalSlider.Bounds.Contains(new PointF(e.X, e.Y)))
{
VerticalSlider.IsDragging = true;
return;
// Vertical is drawn on top, so if they are both selected, select vertical
}
if (HorizontalSlider.Bounds.Contains(new PointF(e.X, e.Y)))
{
HorizontalSlider.IsDragging = true;
return;
}
base.OnMouseDown(e);
}
/// <summary>
/// Handles mouse movement
/// </summary>
/// <param name="e"></param>
protected override void OnMouseMove(MouseEventArgs e)
{
_highlightTimer.Stop();
// Activate buttons only if the mouse is over them. Inactivate them otherwise.
bool invalid = UpdateHighlight(e.Location);
// Sliders
RectangleF area = new RectangleF();
if (HorizontalSlider.IsDragging)
{
area = HorizontalSlider.Bounds;
PointF loc = HorizontalSlider.Position;
loc.X = e.X;
HorizontalSlider.Position = loc;
area = RectangleF.Union(area, HorizontalSlider.Bounds);
}
area.Inflate(10F, 10F);
if (invalid == false) Invalidate(new Region(area));
if (VerticalSlider.IsDragging)
{
area = VerticalSlider.Bounds;
PointF loc = VerticalSlider.Position;
loc.Y = e.Y;
VerticalSlider.Position = loc;
area = RectangleF.Union(area, VerticalSlider.Bounds);
}
area.Inflate(10F, 10F);
if (invalid == false) Invalidate(new Region(area));
if (invalid) Invalidate();
base.OnMouseMove(e);
_highlightTimer.Start();
}
/// <summary>
/// Handles the mouse up event
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Right) return;
bool invalid = false;
bool handled = false;
if (_horizontalSlider.IsDragging)
{
CalculatePattern();
_horizontalSlider.IsDragging = false;
invalid = true;
handled = true;
}
if (_verticalSlider.IsDragging)
{
CalculatePattern();
_verticalSlider.IsDragging = false;
invalid = true;
handled = true;
}
if (handled == false)
{
foreach (SquareButton button in _horizontalButtons)
{
invalid = invalid || button.UpdatePressed(e.Location);
}
foreach (SquareButton button in _verticalButtons)
{
invalid = invalid || button.UpdatePressed(e.Location);
}
}
if (invalid)
{
Invalidate();
OnPatternChanged();
}
base.OnMouseUp(e);
}
/// <summary>
/// Fires the pattern changed event.
/// </summary>
protected virtual void OnPatternChanged()
{
if (PatternChanged != null) PatternChanged(this, EventArgs.Empty);
}
/// <summary>
/// Forces a calculation during the resizing that changes the pattern squares.
/// </summary>
/// <param name="e"></param>
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
CalculatePattern();
}
#endregion
#region Event Handlers
private void HighlightTimerTick(object sender, EventArgs e)
{
Point pt = PointToClient(MousePosition);
// If the mouse is still in the control, then the mouse move is enough
// to update the highlight.
if (ClientRectangle.Contains(pt) == false)
{
_highlightTimer.Stop();
UpdateHighlight(pt);
}
}
#endregion
#region Private Functions
/// <summary>
/// Updates the highlight based on mouse position.
/// </summary>
/// <returns></returns>
private bool UpdateHighlight(Point location)
{
bool invalid = false;
foreach (SquareButton button in _horizontalButtons)
{
invalid = invalid || button.UpdateLight(location);
}
foreach (SquareButton button in _verticalButtons)
{
invalid = invalid || button.UpdateLight(location);
}
return invalid;
}
private void CalculatePattern()
{
// Horizontal
PointF loc = HorizontalSlider.Position;
if (loc.X > Width) loc.X = Width;
int hCount = (int)Math.Ceiling(loc.X / _blockSize.Width);
loc.X = hCount * _blockSize.Width;
HorizontalSlider.Position = loc;
List<SquareButton> newButtonsH = new List<SquareButton>();
int start = 1;
if (_horizontalButtons != null)
{
int minLen = Math.Min(_horizontalButtons.Count, hCount - 1);
for (int i = 0; i < minLen; i++)
{
newButtonsH.Add(_horizontalButtons[i]);
}
start = minLen + 1;
}
for (int j = start; j < hCount; j++)
{
SquareButton sq = new SquareButton();
sq.Bounds = new RectangleF(j * _blockSize.Width, 0, _blockSize.Width, _blockSize.Height);
sq.ColorDownDark = _buttonDownDarkColor;
sq.ColorDownLit = _buttonDownLitColor;
sq.ColorUpDark = _buttonUpDarkColor;
sq.ColorUpLit = _butttonUpLitColor;
sq.IsDown = true;
newButtonsH.Add(sq);
}
_horizontalButtons = newButtonsH;
// Vertical
loc = VerticalSlider.Position;
if (loc.Y > Height) loc.Y = Height;
int vCount = (int)Math.Ceiling(loc.Y / _blockSize.Height);
loc.Y = (vCount) * _blockSize.Height;
VerticalSlider.Position = loc;
List<SquareButton> buttons = new List<SquareButton>();
start = 1;
if (_verticalButtons != null)
{
int minLen = Math.Min(_verticalButtons.Count, vCount - 1);
for (int i = 0; i < minLen; i++)
{
buttons.Add(_verticalButtons[i]);
}
start = minLen + 1;
}
for (int j = start; j < vCount; j++)
{
SquareButton sq = new SquareButton();
sq.Bounds = new RectangleF(0, j * _blockSize.Height, _blockSize.Width, _blockSize.Height);
sq.ColorDownDark = _buttonDownDarkColor;
sq.ColorDownLit = _buttonDownLitColor;
sq.ColorUpDark = _buttonUpDarkColor;
sq.ColorUpLit = _butttonUpLitColor;
sq.IsDown = true;
buttons.Add(sq);
}
_verticalButtons = buttons;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Sprite/Clipped Sprite")]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]
public class tk2dClippedSprite : tk2dBaseSprite
{
Mesh mesh;
Vector2[] meshUvs;
Vector3[] meshVertices;
Color32[] meshColors;
int[] meshIndices;
public Vector2 _clipBottomLeft = new Vector2(0, 0);
public Vector2 _clipTopRight = new Vector2(1, 1);
// Temp cached variables
Rect _clipRect = new Rect(0, 0, 0, 0);
/// <summary>
/// Sets the clip rectangle
/// 0, 0, 1, 1 = display the entire sprite
/// </summary>
public Rect ClipRect {
get {
_clipRect.Set( _clipBottomLeft.x, _clipBottomLeft.y, _clipTopRight.x - _clipBottomLeft.x, _clipTopRight.y - _clipBottomLeft.y );
return _clipRect;
}
set {
Vector2 v = new Vector2( value.x, value.y );
clipBottomLeft = v;
v.x += value.width;
v.y += value.height;
clipTopRight = v;
}
}
/// <summary>
/// Sets the bottom left clip area.
/// 0, 0 = display full sprite
/// </summary>
public Vector2 clipBottomLeft
{
get { return _clipBottomLeft; }
set
{
if (value != _clipBottomLeft)
{
_clipBottomLeft = new Vector2(value.x, value.y);
Build();
UpdateCollider();
}
}
}
/// <summary>
/// Sets the top right clip area
/// 1, 1 = display full sprite
/// </summary>
public Vector2 clipTopRight
{
get { return _clipTopRight; }
set
{
if (value != _clipTopRight)
{
_clipTopRight = new Vector2(value.x, value.y);
Build();
UpdateCollider();
}
}
}
[SerializeField]
protected bool _createBoxCollider = false;
/// <summary>
/// Create a trimmed box collider for this sprite
/// </summary>
public bool CreateBoxCollider {
get { return _createBoxCollider; }
set {
if (_createBoxCollider != value) {
_createBoxCollider = value;
UpdateCollider();
}
}
}
new void Awake()
{
base.Awake();
// Create mesh, independently to everything else
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
GetComponent<MeshFilter>().mesh = mesh;
// This will not be set when instantiating in code
// In that case, Build will need to be called
if (Collection)
{
// reset spriteId if outside bounds
// this is when the sprite collection data is corrupt
if (_spriteId < 0 || _spriteId >= Collection.Count)
_spriteId = 0;
Build();
}
}
protected void OnDestroy()
{
if (mesh)
{
#if UNITY_EDITOR
DestroyImmediate(mesh);
#else
Destroy(mesh);
#endif
}
}
new protected void SetColors(Color32[] dest)
{
Color c = _color;
if (collectionInst.premultipliedAlpha) { c.r *= c.a; c.g *= c.a; c.b *= c.a; }
Color32 c32 = c;
for (int i = 0; i < dest.Length; ++i)
dest[i] = c32;
}
// Calculated center and extents
Vector3 boundsCenter = Vector3.zero, boundsExtents = Vector3.zero;
protected void SetGeometry(Vector3[] vertices, Vector2[] uvs)
{
var sprite = collectionInst.spriteDefinitions[spriteId];
// Only do this when there are exactly 4 polys to a sprite (i.e. the sprite isn't diced, and isnt a more complex mesh)
if (sprite.positions.Length == 4)
{
// This is how the default quad is set up
// Indices are 0, 3, 1, 2, 3, 0
// 2--------3
// | |
// | |
// | |
// | |
// 0--------1
// index 0 = top left
// index 3 = bottom right
// clipBottomLeft is the fraction to start from the bottom left (0,0 - full sprite)
// clipTopRight is the fraction to start from the top right (1,1 - full sprite)
Vector2 fracBottomLeft = new Vector2( Mathf.Clamp01( _clipBottomLeft.x ), Mathf.Clamp01( _clipBottomLeft.y ) );
Vector2 fracTopRight = new Vector2( Mathf.Clamp01( _clipTopRight.x ), Mathf.Clamp01( _clipTopRight.y ) );
// find the fraction of positions, but fold in the scale multiply as well
Vector3 bottomLeft = new Vector3(Mathf.Lerp(sprite.positions[0].x, sprite.positions[3].x, fracBottomLeft.x) * _scale.x,
Mathf.Lerp(sprite.positions[0].y, sprite.positions[3].y, fracBottomLeft.y) * _scale.y,
sprite.positions[0].z * _scale.z);
Vector3 topRight = new Vector3(Mathf.Lerp(sprite.positions[0].x, sprite.positions[3].x, fracTopRight.x) * _scale.x,
Mathf.Lerp(sprite.positions[0].y, sprite.positions[3].y, fracTopRight.y) * _scale.y,
sprite.positions[0].z * _scale.z);
float colliderOffsetZ = ( boxCollider != null ) ? ( boxCollider.center.z ) : 0.0f;
float colliderExtentZ = ( boxCollider != null ) ? ( boxCollider.size.z * 0.5f ) : 0.5f;
boundsCenter.Set( bottomLeft.x + (topRight.x - bottomLeft.x) * 0.5f, bottomLeft.y + (topRight.y - bottomLeft.y) * 0.5f, colliderOffsetZ );
boundsExtents.Set( (topRight.x - bottomLeft.x) * 0.5f, (topRight.y - bottomLeft.y) * 0.5f, colliderExtentZ );
// The z component only needs to be consistent
meshVertices[0] = new Vector3(bottomLeft.x, bottomLeft.y, bottomLeft.z);
meshVertices[1] = new Vector3(topRight.x, bottomLeft.y, bottomLeft.z);
meshVertices[2] = new Vector3(bottomLeft.x, topRight.y, bottomLeft.z);
meshVertices[3] = new Vector3(topRight.x, topRight.y, bottomLeft.z);
// find the fraction of UV
// This can be done without a branch, but will end up with loads of unnecessary interpolations
if (sprite.flipped == tk2dSpriteDefinition.FlipMode.Tk2d)
{
Vector2 v0 = new Vector2(Mathf.Lerp(sprite.uvs[0].x, sprite.uvs[3].x, fracBottomLeft.y),
Mathf.Lerp(sprite.uvs[0].y, sprite.uvs[3].y, fracBottomLeft.x));
Vector2 v1 = new Vector2(Mathf.Lerp(sprite.uvs[0].x, sprite.uvs[3].x, fracTopRight.y),
Mathf.Lerp(sprite.uvs[0].y, sprite.uvs[3].y, fracTopRight.x));
meshUvs[0] = new Vector2(v0.x, v0.y);
meshUvs[1] = new Vector2(v0.x, v1.y);
meshUvs[2] = new Vector2(v1.x, v0.y);
meshUvs[3] = new Vector2(v1.x, v1.y);
}
else if (sprite.flipped == tk2dSpriteDefinition.FlipMode.TPackerCW)
{
Vector2 v0 = new Vector2(Mathf.Lerp(sprite.uvs[0].x, sprite.uvs[3].x, fracBottomLeft.y),
Mathf.Lerp(sprite.uvs[0].y, sprite.uvs[3].y, fracBottomLeft.x));
Vector2 v1 = new Vector2(Mathf.Lerp(sprite.uvs[0].x, sprite.uvs[3].x, fracTopRight.y),
Mathf.Lerp(sprite.uvs[0].y, sprite.uvs[3].y, fracTopRight.x));
meshUvs[0] = new Vector2(v0.x, v0.y);
meshUvs[2] = new Vector2(v1.x, v0.y);
meshUvs[1] = new Vector2(v0.x, v1.y);
meshUvs[3] = new Vector2(v1.x, v1.y);
}
else
{
Vector2 v0 = new Vector2(Mathf.Lerp(sprite.uvs[0].x, sprite.uvs[3].x, fracBottomLeft.x),
Mathf.Lerp(sprite.uvs[0].y, sprite.uvs[3].y, fracBottomLeft.y));
Vector2 v1 = new Vector2(Mathf.Lerp(sprite.uvs[0].x, sprite.uvs[3].x, fracTopRight.x),
Mathf.Lerp(sprite.uvs[0].y, sprite.uvs[3].y, fracTopRight.y));
meshUvs[0] = new Vector2(v0.x, v0.y);
meshUvs[1] = new Vector2(v1.x, v0.y);
meshUvs[2] = new Vector2(v0.x, v1.y);
meshUvs[3] = new Vector2(v1.x, v1.y);
}
}
else
{
// Only supports normal sprites
for (int i = 0; i < vertices.Length; ++i)
vertices[i] = Vector3.zero;
}
}
public override void Build()
{
meshUvs = new Vector2[4];
meshVertices = new Vector3[4];
meshColors = new Color32[4];
SetGeometry(meshVertices, meshUvs);
SetColors(meshColors);
if (mesh == null)
{
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
}
else
{
mesh.Clear();
}
mesh.vertices = meshVertices;
mesh.colors32 = meshColors;
mesh.uv = meshUvs;
mesh.triangles = new int[6] { 0, 3, 1, 2, 3, 0 };
mesh.RecalculateBounds();
GetComponent<MeshFilter>().mesh = mesh;
UpdateCollider();
UpdateMaterial();
}
protected override void UpdateGeometry() { UpdateGeometryImpl(); }
protected override void UpdateColors() { UpdateColorsImpl(); }
protected override void UpdateVertices() { UpdateGeometryImpl(); }
protected void UpdateColorsImpl()
{
if (meshColors == null || meshColors.Length == 0) {
Build();
}
else {
SetColors(meshColors);
mesh.colors32 = meshColors;
}
}
protected void UpdateGeometryImpl()
{
#if UNITY_EDITOR
// This can happen with prefabs in the inspector
if (mesh == null)
return;
#endif
if (meshVertices == null || meshVertices.Length == 0) {
Build();
}
else {
SetGeometry(meshVertices, meshUvs);
mesh.vertices = meshVertices;
mesh.uv = meshUvs;
mesh.RecalculateBounds();
}
}
#region Collider
protected override void UpdateCollider()
{
if (CreateBoxCollider) {
if (boxCollider == null) {
boxCollider = GetComponent<BoxCollider>();
if (boxCollider == null) {
boxCollider = gameObject.AddComponent<BoxCollider>();
}
}
boxCollider.extents = boundsExtents;
boxCollider.center = boundsCenter;
} else {
#if UNITY_EDITOR
boxCollider = GetComponent<BoxCollider>();
if (boxCollider != null) {
DestroyImmediate(boxCollider);
}
#else
if (boxCollider != null) {
Destroy(boxCollider);
}
#endif
}
}
protected override void CreateCollider() {
UpdateCollider();
}
#if UNITY_EDITOR
public override void EditMode__CreateCollider() {
UpdateCollider();
}
#endif
#endregion
protected override void UpdateMaterial()
{
if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].material)
renderer.material = collectionInst.spriteDefinitions[spriteId].material;
}
protected override int GetCurrentVertexCount()
{
#if UNITY_EDITOR
if (meshVertices == null)
return 0;
#endif
return 4;
}
}
| |
// 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;
using Microsoft.Scripting.Runtime;
using IronPython.Modules;
using IronPython.Runtime.Exceptions;
using System.Numerics;
namespace IronPython.Runtime.Types {
public static class TypeCache {
#region Generated TypeCache Storage
// *** BEGIN GENERATED CODE ***
// generated by function: gen_typecache_storage from: generate_typecache.py
private static PythonType array;
private static PythonType builtinfunction;
private static PythonType pythondictionary;
private static PythonType frozensetcollection;
private static PythonType pythonfunction;
private static PythonType builtin;
private static PythonType obj;
private static PythonType setcollection;
private static PythonType pythontype;
private static PythonType str;
private static PythonType bytes;
private static PythonType pythontuple;
private static PythonType weakreference;
private static PythonType pythonlist;
private static PythonType pythonmodule;
private static PythonType method;
private static PythonType enumerate;
private static PythonType intType;
private static PythonType singleType;
private static PythonType doubleType;
private static PythonType biginteger;
private static PythonType complex;
private static PythonType super;
private static PythonType nullType;
private static PythonType boolType;
private static PythonType baseException;
// *** END GENERATED CODE ***
#endregion
#region Generated TypeCache Entries
// *** BEGIN GENERATED CODE ***
// generated by function: gen_typecache from: generate_typecache.py
public static PythonType Array {
get {
if (array == null) array = DynamicHelpers.GetPythonTypeFromType(typeof(Array));
return array;
}
}
public static PythonType BuiltinFunction {
get {
if (builtinfunction == null) builtinfunction = DynamicHelpers.GetPythonTypeFromType(typeof(BuiltinFunction));
return builtinfunction;
}
}
public static PythonType Dict {
get {
if (pythondictionary == null) pythondictionary = DynamicHelpers.GetPythonTypeFromType(typeof(PythonDictionary));
return pythondictionary;
}
}
public static PythonType FrozenSet {
get {
if (frozensetcollection == null) frozensetcollection = DynamicHelpers.GetPythonTypeFromType(typeof(FrozenSetCollection));
return frozensetcollection;
}
}
public static PythonType Function {
get {
if (pythonfunction == null) pythonfunction = DynamicHelpers.GetPythonTypeFromType(typeof(PythonFunction));
return pythonfunction;
}
}
public static PythonType Builtin {
get {
if (builtin == null) builtin = DynamicHelpers.GetPythonTypeFromType(typeof(Builtin));
return builtin;
}
}
public static PythonType Object {
get {
if (obj == null) obj = DynamicHelpers.GetPythonTypeFromType(typeof(Object));
return obj;
}
}
public static PythonType Set {
get {
if (setcollection == null) setcollection = DynamicHelpers.GetPythonTypeFromType(typeof(SetCollection));
return setcollection;
}
}
public static PythonType PythonType {
get {
if (pythontype == null) pythontype = DynamicHelpers.GetPythonTypeFromType(typeof(PythonType));
return pythontype;
}
}
public static PythonType String {
get {
if (str == null) str = DynamicHelpers.GetPythonTypeFromType(typeof(String));
return str;
}
}
public static PythonType Bytes {
get {
if (bytes == null) bytes = DynamicHelpers.GetPythonTypeFromType(typeof(Bytes));
return bytes;
}
}
public static PythonType PythonTuple {
get {
if (pythontuple == null) pythontuple = DynamicHelpers.GetPythonTypeFromType(typeof(PythonTuple));
return pythontuple;
}
}
public static PythonType WeakReference {
get {
if (weakreference == null) weakreference = DynamicHelpers.GetPythonTypeFromType(typeof(WeakReference));
return weakreference;
}
}
public static PythonType PythonList {
get {
if (pythonlist == null) pythonlist = DynamicHelpers.GetPythonTypeFromType(typeof(PythonList));
return pythonlist;
}
}
public static PythonType Module {
get {
if (pythonmodule == null) pythonmodule = DynamicHelpers.GetPythonTypeFromType(typeof(PythonModule));
return pythonmodule;
}
}
public static PythonType Method {
get {
if (method == null) method = DynamicHelpers.GetPythonTypeFromType(typeof(Method));
return method;
}
}
public static PythonType Enumerate {
get {
if (enumerate == null) enumerate = DynamicHelpers.GetPythonTypeFromType(typeof(Enumerate));
return enumerate;
}
}
public static PythonType Int32 {
get {
if (intType == null) intType = DynamicHelpers.GetPythonTypeFromType(typeof(Int32));
return intType;
}
}
public static PythonType Single {
get {
if (singleType == null) singleType = DynamicHelpers.GetPythonTypeFromType(typeof(Single));
return singleType;
}
}
public static PythonType Double {
get {
if (doubleType == null) doubleType = DynamicHelpers.GetPythonTypeFromType(typeof(Double));
return doubleType;
}
}
public static PythonType BigInteger {
get {
if (biginteger == null) biginteger = DynamicHelpers.GetPythonTypeFromType(typeof(BigInteger));
return biginteger;
}
}
public static PythonType Complex {
get {
if (complex == null) complex = DynamicHelpers.GetPythonTypeFromType(typeof(Complex));
return complex;
}
}
public static PythonType Super {
get {
if (super == null) super = DynamicHelpers.GetPythonTypeFromType(typeof(Super));
return super;
}
}
public static PythonType Null {
get {
if (nullType == null) nullType = DynamicHelpers.GetPythonTypeFromType(typeof(DynamicNull));
return nullType;
}
}
public static PythonType Boolean {
get {
if (boolType == null) boolType = DynamicHelpers.GetPythonTypeFromType(typeof(Boolean));
return boolType;
}
}
public static PythonType BaseException {
get {
if (baseException == null) baseException = DynamicHelpers.GetPythonTypeFromType(typeof(PythonExceptions.BaseException));
return baseException;
}
}
// *** END GENERATED CODE ***
#endregion
}
}
| |
using System;
using System.Globalization;
using Microsoft.Win32;
using NetSparkleUpdater.AssemblyAccessors;
using NetSparkleUpdater.Interfaces;
namespace NetSparkleUpdater.Configurations
{
/// <summary>
/// This class handles all registry values which are used from sparkle to handle
/// update intervalls. All values are stored in HKCU\Software\Vendor\AppName which
/// will be read ot from the assembly information. All values are of the REG_SZ
/// type, no matter what their "logical" type is.
/// This should only be used on Windows!
/// </summary>
public class RegistryConfiguration : Configuration
{
private const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
private string _registryPath;
/// <summary>
/// Constructor for a configuration that saves and loads information from the Windows registry.
/// This should only be used on Windows!
/// </summary>
/// <param name="assemblyAccessor">Object that accesses version, title, etc. info for the application
/// you would like to check for updates for</param>
public RegistryConfiguration(IAssemblyAccessor assemblyAccessor)
: this(assemblyAccessor, "")
{ }
/// <summary>
/// Constructor for a configuration that saves and loads information from the Windows registry.
/// This should only be used on Windows!
/// </summary>
/// <param name="assemblyAccessor">Object that accesses version, title, etc. info for the application
/// you would like to check for updates for</param>
/// <param name="registryPath">Location in the registry where configuration data should be stored and
/// loaded from</param>
public RegistryConfiguration(IAssemblyAccessor assemblyAccessor, string registryPath)
: base(assemblyAccessor)
{
_registryPath = registryPath;
try
{
// build the reg path
string regPath = BuildRegistryPath();
// load the values
LoadValuesFromPath(regPath);
}
catch (NetSparkleException e)
{
// disable update checks when exception occurred -- can't read/save necessary update file
CheckForUpdate = false;
throw new NetSparkleException("Can't read/save configuration data: " + e.Message);
}
}
/// <inheritdoc/>
public override void TouchProfileTime()
{
base.TouchProfileTime();
// save the values
SaveValuesToPath(BuildRegistryPath());
}
/// <inheritdoc/>
public override void TouchCheckTime()
{
base.TouchCheckTime();
// save the values
SaveValuesToPath(BuildRegistryPath());
}
/// <inheritdoc/>
public override void SetVersionToSkip(string version)
{
base.SetVersionToSkip(version);
SaveValuesToPath(BuildRegistryPath());
}
/// <inheritdoc/>
public override void Reload()
{
LoadValuesFromPath(BuildRegistryPath());
}
/// <summary>
/// Generate the path in the registry where data will be saved to/loaded from.
/// </summary>
/// <exception cref="NetSparkleException">Thrown when the assembly accessor does not have the company or product name
/// information available</exception>
public virtual string BuildRegistryPath()
{
if (!string.IsNullOrEmpty(_registryPath))
{
return _registryPath;
}
else
{
if (string.IsNullOrEmpty(AssemblyAccessor.AssemblyCompany) || string.IsNullOrEmpty(AssemblyAccessor.AssemblyProduct))
{
throw new NetSparkleException("Error: NetSparkleUpdater is missing the company or productname tag in the assembly accessor ("
+ AssemblyAccessor.GetType() + ")");
}
_registryPath = "Software\\";
if (!string.IsNullOrWhiteSpace(AssemblyAccessor.AssemblyCompany))
{
_registryPath += AssemblyAccessor.AssemblyCompany + "\\";
}
if (!string.IsNullOrWhiteSpace(AssemblyAccessor.AssemblyProduct))
{
_registryPath += AssemblyAccessor.AssemblyProduct + "\\";
}
_registryPath += "AutoUpdate";
return _registryPath;
}
}
private string ConvertDateToString(DateTime dt)
{
return dt.ToString(DateTimeFormat, CultureInfo.InvariantCulture);
}
private DateTime ConvertStringToDate(string str)
{
return DateTime.ParseExact(str, DateTimeFormat, CultureInfo.InvariantCulture);
}
/// <summary>
/// Load values from the provided registry path
/// </summary>
/// <param name="regPath">the registry path</param>
/// <returns><c>true</c> if the items were loaded successfully; false otherwise</returns>
private bool LoadValuesFromPath(string regPath)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(regPath);
if (key == null)
{
SaveDidRunOnceAsTrue(regPath);
return false;
}
else
{
// read out
string strCheckForUpdate = key.GetValue("CheckForUpdate", "True") as string;
string strLastCheckTime = key.GetValue("LastCheckTime", ConvertDateToString(new DateTime(0))) as string;
string strSkipThisVersion = key.GetValue("SkipThisVersion", "") as string;
string strDidRunOnc = key.GetValue("DidRunOnce", "False") as string;
string strProfileTime = key.GetValue("LastProfileUpdate", ConvertDateToString(new DateTime(0))) as string;
string strPreviousVersion = key.GetValue("PreviousVersionRun", "") as string;
// convert the right datatypes
CheckForUpdate = Convert.ToBoolean(strCheckForUpdate);
try
{
LastCheckTime = ConvertStringToDate(strLastCheckTime);
}
catch (FormatException)
{
LastCheckTime = new DateTime(0);
}
LastVersionSkipped = strSkipThisVersion;
DidRunOnce = Convert.ToBoolean(strDidRunOnc);
IsFirstRun = !DidRunOnce;
PreviousVersionOfSoftwareRan = strPreviousVersion;
if (IsFirstRun)
{
SaveDidRunOnceAsTrue(regPath);
}
else
{
SaveValuesToPath(regPath); // so PreviousVersionRun is saved
}
try
{
LastConfigUpdate = ConvertStringToDate(strProfileTime);
}
catch (FormatException)
{
LastConfigUpdate = new DateTime(0);
}
}
return true;
}
private void SaveDidRunOnceAsTrue(string regPath)
{
var initialValue = DidRunOnce;
DidRunOnce = true;
SaveValuesToPath(regPath); // save it so next time we load DidRunOnce is true
DidRunOnce = initialValue; // so data is correct to user of Configuration class
}
/// <summary>
/// Stores the configuration data into the registry at the given path
/// </summary>
/// <param name="regPath">the registry path</param>
/// <returns><c>true</c> if the values were saved to the registry; false otherwise</returns>
private bool SaveValuesToPath(string regPath)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(regPath);
if (key == null)
{
return false;
}
// convert to regsz
string strCheckForUpdate = true.ToString(); // always check for updates next time!
string strLastCheckTime = ConvertDateToString(LastCheckTime);
string strSkipThisVersion = LastVersionSkipped;
string strDidRunOnc = DidRunOnce.ToString();
string strProfileTime = ConvertDateToString(LastConfigUpdate);
string strPreviousVersion = InstalledVersion;
// set the values
key.SetValue("CheckForUpdate", strCheckForUpdate, RegistryValueKind.String);
key.SetValue("LastCheckTime", strLastCheckTime, RegistryValueKind.String);
key.SetValue("SkipThisVersion", strSkipThisVersion, RegistryValueKind.String);
key.SetValue("DidRunOnce", strDidRunOnc, RegistryValueKind.String);
key.SetValue("LastProfileUpdate", strProfileTime, RegistryValueKind.String);
key.SetValue("PreviousVersionRun", strPreviousVersion, RegistryValueKind.String);
return true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Scheduler
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobCollectionsOperations operations.
/// </summary>
public partial interface IJobCollectionsOperations
{
/// <summary>
/// Gets all job collections under specified subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<JobCollectionDefinition>>> ListBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all job collections under specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<JobCollectionDefinition>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<JobCollectionDefinition>> GetWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Provisions a new job collection or updates an existing job
/// collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='jobCollection'>
/// The job collection definition.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<JobCollectionDefinition>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, JobCollectionDefinition jobCollection, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patches an existing job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='jobCollection'>
/// The job collection definition.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<JobCollectionDefinition>> PatchWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, JobCollectionDefinition jobCollection, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enables all of the jobs in the job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> EnableWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Enables all of the jobs in the job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginEnableWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disables all of the jobs in the job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DisableWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disables all of the jobs in the job collection.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='jobCollectionName'>
/// The job collection name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> BeginDisableWithHttpMessagesAsync(string resourceGroupName, string jobCollectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all job collections under specified subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<JobCollectionDefinition>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all job collections under specified resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<JobCollectionDefinition>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Helper class with properties and methods that supply
/// a number of constraints used in Asserts.
/// </summary>
public class ConstraintFactory
{
#region Not
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression Not
{
get { return Is.Not; }
}
/// <summary>
/// Returns a ConstraintExpression that negates any
/// following constraint.
/// </summary>
public ConstraintExpression No
{
get { return Has.No; }
}
#endregion
#region All
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them succeed.
/// </summary>
public ConstraintExpression All
{
get { return Is.All; }
}
#endregion
#region Some
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if at least one of them succeeds.
/// </summary>
public ConstraintExpression Some
{
get { return Has.Some; }
}
#endregion
#region None
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding if all of them fail.
/// </summary>
public ConstraintExpression None
{
get { return Has.None; }
}
#endregion
#region Exactly(n)
/// <summary>
/// Returns a ConstraintExpression, which will apply
/// the following constraint to all members of a collection,
/// succeeding only if a specified number of them succeed.
/// </summary>
public static ConstraintExpression Exactly(int expectedCount)
{
return Has.Exactly(expectedCount);
}
#endregion
#region Property
/// <summary>
/// Returns a new PropertyConstraintExpression, which will either
/// test for the existence of the named property on the object
/// being tested or apply any following constraint to that property.
/// </summary>
public ResolvableConstraintExpression Property(string name)
{
return Has.Property(name);
}
#endregion
#region Length
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Length property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Length
{
get { return Has.Length; }
}
#endregion
#region Count
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Count property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Count
{
get { return Has.Count; }
}
#endregion
#region Message
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the Message property of the object being tested.
/// </summary>
public ResolvableConstraintExpression Message
{
get { return Has.Message; }
}
#endregion
#region InnerException
/// <summary>
/// Returns a new ConstraintExpression, which will apply the following
/// constraint to the InnerException property of the object being tested.
/// </summary>
public ResolvableConstraintExpression InnerException
{
get { return Has.InnerException; }
}
#endregion
#region Attribute
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute(Type expectedType)
{
return Has.Attribute(expectedType);
}
/// <summary>
/// Returns a new AttributeConstraint checking for the
/// presence of a particular attribute on an object.
/// </summary>
public ResolvableConstraintExpression Attribute<TExpected>()
{
return Attribute(typeof(TExpected));
}
#endregion
#region Null
/// <summary>
/// Returns a constraint that tests for null
/// </summary>
public NullConstraint Null
{
get { return new NullConstraint(); }
}
#endregion
#region True
/// <summary>
/// Returns a constraint that tests for True
/// </summary>
public TrueConstraint True
{
get { return new TrueConstraint(); }
}
#endregion
#region False
/// <summary>
/// Returns a constraint that tests for False
/// </summary>
public FalseConstraint False
{
get { return new FalseConstraint(); }
}
#endregion
#region Positive
/// <summary>
/// Returns a constraint that tests for a positive value
/// </summary>
public GreaterThanConstraint Positive
{
get { return new GreaterThanConstraint(0); }
}
#endregion
#region Negative
/// <summary>
/// Returns a constraint that tests for a negative value
/// </summary>
public LessThanConstraint Negative
{
get { return new LessThanConstraint(0); }
}
#endregion
#region NaN
/// <summary>
/// Returns a constraint that tests for NaN
/// </summary>
public NaNConstraint NaN
{
get { return new NaNConstraint(); }
}
#endregion
#region Empty
/// <summary>
/// Returns a constraint that tests for empty
/// </summary>
public EmptyConstraint Empty
{
get { return new EmptyConstraint(); }
}
#endregion
#region Unique
/// <summary>
/// Returns a constraint that tests whether a collection
/// contains all unique items.
/// </summary>
public UniqueItemsConstraint Unique
{
get { return new UniqueItemsConstraint(); }
}
#endregion
#region BinarySerializable
#if !NETCF && !SILVERLIGHT && !PORTABLE
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in binary format.
/// </summary>
public BinarySerializableConstraint BinarySerializable
{
get { return new BinarySerializableConstraint(); }
}
#endif
#endregion
#region XmlSerializable
#if !SILVERLIGHT && !PORTABLE
/// <summary>
/// Returns a constraint that tests whether an object graph is serializable in xml format.
/// </summary>
public XmlSerializableConstraint XmlSerializable
{
get { return new XmlSerializableConstraint(); }
}
#endif
#endregion
#region EqualTo
/// <summary>
/// Returns a constraint that tests two items for equality
/// </summary>
public EqualConstraint EqualTo(object expected)
{
return new EqualConstraint(expected);
}
#endregion
#region SameAs
/// <summary>
/// Returns a constraint that tests that two references are the same object
/// </summary>
public SameAsConstraint SameAs(object expected)
{
return new SameAsConstraint(expected);
}
#endregion
#region GreaterThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than the supplied argument
/// </summary>
public GreaterThanConstraint GreaterThan(object expected)
{
return new GreaterThanConstraint(expected);
}
#endregion
#region GreaterThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is greater than or equal to the supplied argument
/// </summary>
public GreaterThanOrEqualConstraint AtLeast(object expected)
{
return new GreaterThanOrEqualConstraint(expected);
}
#endregion
#region LessThan
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than the supplied argument
/// </summary>
public LessThanConstraint LessThan(object expected)
{
return new LessThanConstraint(expected);
}
#endregion
#region LessThanOrEqualTo
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint LessThanOrEqualTo(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
/// <summary>
/// Returns a constraint that tests whether the
/// actual value is less than or equal to the supplied argument
/// </summary>
public LessThanOrEqualConstraint AtMost(object expected)
{
return new LessThanOrEqualConstraint(expected);
}
#endregion
#region TypeOf
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf(Type expectedType)
{
return new ExactTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual
/// value is of the exact type supplied as an argument.
/// </summary>
public ExactTypeConstraint TypeOf<TExpected>()
{
return new ExactTypeConstraint(typeof(TExpected));
}
#endregion
#region InstanceOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf(Type expectedType)
{
return new InstanceOfTypeConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is of the type supplied as an argument or a derived type.
/// </summary>
public InstanceOfTypeConstraint InstanceOf<TExpected>()
{
return new InstanceOfTypeConstraint(typeof(TExpected));
}
#endregion
#region AssignableFrom
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom(Type expectedType)
{
return new AssignableFromConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableFromConstraint AssignableFrom<TExpected>()
{
return new AssignableFromConstraint(typeof(TExpected));
}
#endregion
#region AssignableTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo(Type expectedType)
{
return new AssignableToConstraint(expectedType);
}
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is assignable from the type supplied as an argument.
/// </summary>
public AssignableToConstraint AssignableTo<TExpected>()
{
return new AssignableToConstraint(typeof(TExpected));
}
#endregion
#region EquivalentTo
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a collection containing the same elements as the
/// collection supplied as an argument.
/// </summary>
public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected)
{
return new CollectionEquivalentConstraint(expected);
}
#endregion
#region SubsetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a subset of the collection supplied as an argument.
/// </summary>
public CollectionSubsetConstraint SubsetOf(IEnumerable expected)
{
return new CollectionSubsetConstraint(expected);
}
#endregion
#region SupersetOf
/// <summary>
/// Returns a constraint that tests whether the actual value
/// is a superset of the collection supplied as an argument.
/// </summary>
public CollectionSupersetConstraint SupersetOf(IEnumerable expected)
{
return new CollectionSupersetConstraint(expected);
}
#endregion
#region Ordered
/// <summary>
/// Returns a constraint that tests whether a collection is ordered
/// </summary>
public CollectionOrderedConstraint Ordered
{
get { return new CollectionOrderedConstraint(); }
}
#endregion
#region Member
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Member(object expected)
{
return new CollectionContainsConstraint(expected);
}
/// <summary>
/// Returns a new CollectionContainsConstraint checking for the
/// presence of a particular object in the collection.
/// </summary>
public CollectionContainsConstraint Contains(object expected)
{
return new CollectionContainsConstraint(expected);
}
#endregion
#region Contains
/// <summary>
/// Returns a new ContainsConstraint. This constraint
/// will, in turn, make use of the appropriate second-level
/// constraint, depending on the type of the actual argument.
/// This overload is only used if the item sought is a string,
/// since any other type implies that we are looking for a
/// collection member.
/// </summary>
public ContainsConstraint Contains(string expected)
{
return new ContainsConstraint(expected);
}
#endregion
#region StringContaining
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint StringContaining(string expected)
{
return new SubstringConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Contains")]
public SubstringConstraint ContainsSubstring(string expected)
{
return new SubstringConstraint(expected);
}
#endregion
#region DoesNotContain
/// <summary>
/// Returns a constraint that fails if the actual
/// value contains the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.Contain")]
public SubstringConstraint DoesNotContain(string expected)
{
return new ConstraintExpression().Not.ContainsSubstring(expected);
}
#endregion
#region StartsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
public StartsWithConstraint StartsWith(string expected)
{
return new StartsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.StartWith or StartsWith")]
public StartsWithConstraint StringStarting(string expected)
{
return new StartsWithConstraint(expected);
}
#endregion
#region DoesNotStartWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value starts with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.StartWith")]
public StartsWithConstraint DoesNotStartWith(string expected)
{
return new ConstraintExpression().Not.StartsWith(expected);
}
#endregion
#region EndsWith
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
public EndsWithConstraint EndsWith(string expected)
{
return new EndsWithConstraint(expected);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.EndWith or EndsWith")]
public EndsWithConstraint StringEnding(string expected)
{
return new EndsWithConstraint(expected);
}
#endregion
#region DoesNotEndWith
/// <summary>
/// Returns a constraint that fails if the actual
/// value ends with the substring supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.EndWith")]
public EndsWithConstraint DoesNotEndWith(string expected)
{
return new ConstraintExpression().Not.EndsWith(expected);
}
#endregion
#region Matches
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Match(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
public RegexConstraint Matches(string pattern)
{
return new RegexConstraint(pattern);
}
/// <summary>
/// Returns a constraint that succeeds if the actual
/// value matches the regular expression supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Match or Matches")]
public RegexConstraint StringMatching(string pattern)
{
return new RegexConstraint(pattern);
}
#endregion
#region DoesNotMatch
/// <summary>
/// Returns a constraint that fails if the actual
/// value matches the pattern supplied as an argument.
/// </summary>
[Obsolete("Deprecated, use Does.Not.Match")]
public RegexConstraint DoesNotMatch(string pattern)
{
return new ConstraintExpression().Not.Matches(pattern);
}
#endregion
#if !PORTABLE
#region SamePath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same as an expected path after canonicalization.
/// </summary>
public SamePathConstraint SamePath(string expected)
{
return new SamePathConstraint(expected);
}
#endregion
#region SubPath
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is a subpath of the expected path after canonicalization.
/// </summary>
public SubPathConstraint SubPathOf(string expected)
{
return new SubPathConstraint(expected);
}
#endregion
#region SamePathOrUnder
/// <summary>
/// Returns a constraint that tests whether the path provided
/// is the same path or under an expected path after canonicalization.
/// </summary>
public SamePathOrUnderConstraint SamePathOrUnder(string expected)
{
return new SamePathOrUnderConstraint(expected);
}
#endregion
#endif
#region InRange
/// <summary>
/// Returns a constraint that tests whether the actual value falls
/// within a specified range.
/// </summary>
public RangeConstraint InRange(IComparable from, IComparable to)
{
return new RangeConstraint(from, to);
}
#endregion
}
}
| |
using System.Collections.ObjectModel;
using System.ComponentModel;
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
namespace Signum.Entities.DynamicQuery;
public abstract class BaseQueryRequest
{
public object QueryName { get; set; }
public List<Filter> Filters { get; set; }
public string? QueryUrl { get; set; }
public override string ToString()
{
return "{0} {1}".FormatWith(GetType().Name, QueryName);
}
}
public class QueryRequest : BaseQueryRequest
{
public bool GroupResults { get; set; }
public List<Column> Columns { get; set; }
public List<Order> Orders { get; set; }
public Pagination Pagination { get; set; }
public SystemTime? SystemTime { get; set; }
public List<CollectionElementToken> Multiplications()
{
HashSet<QueryToken> allTokens = new HashSet<QueryToken>(this.AllTokens());
return CollectionElementToken.GetElements(allTokens);
}
public List<QueryToken> AllTokens()
{
var allTokens = Columns.Select(a => a.Token).ToList();
if (Filters != null)
allTokens.AddRange(Filters.SelectMany(a => a.GetFilterConditions()).Select(a => a.Token));
if (Orders != null)
allTokens.AddRange(Orders.Select(a => a.Token));
return allTokens;
}
public QueryRequest Clone() => new QueryRequest
{
QueryName = QueryName,
GroupResults = GroupResults,
Columns = Columns,
Filters = Filters,
Orders = Orders,
Pagination = Pagination,
SystemTime = SystemTime,
};
}
[DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description), InTypeScript(true)]
public enum PaginationMode
{
All,
[Description("First")]
Firsts,
[Description("Pages")]
Paginate
}
[DescriptionOptions(DescriptionOptions.Members), InTypeScript(true)]
public enum RefreshMode
{
Auto,
Manual
}
[DescriptionOptions(DescriptionOptions.Members), InTypeScript(true)]
public enum SystemTimeMode
{
AsOf,
Between,
ContainedIn,
All
}
[DescriptionOptions(DescriptionOptions.Members), InTypeScript(true)]
public enum SystemTimeJoinMode
{
Current,
FirstCompatible,
AllCompatible,
}
[DescriptionOptions(DescriptionOptions.Members)]
public enum SystemTimeProperty
{
SystemValidFrom,
SystemValidTo,
}
public abstract class Pagination : IEquatable<Pagination>
{
public abstract PaginationMode GetMode();
public abstract int? GetElementsPerPage();
public abstract int? MaxElementIndex { get; }
public abstract bool Equals(Pagination? other);
public class All : Pagination
{
public override PaginationMode GetMode() => PaginationMode.All;
public override int? GetElementsPerPage() => null;
public override int? MaxElementIndex => null;
public override bool Equals(Pagination? other) => other is All;
}
public class Firsts : Pagination
{
public static int DefaultTopElements = 20;
public Firsts(int topElements)
{
this.TopElements = topElements;
}
public int TopElements { get; }
public override PaginationMode GetMode() => PaginationMode.Firsts;
public override int? GetElementsPerPage() => TopElements;
public override int? MaxElementIndex => TopElements;
public override bool Equals(Pagination? other) => other is Firsts f && f.TopElements == this.TopElements;
}
public class Paginate : Pagination
{
public Paginate(int elementsPerPage, int currentPage = 1)
{
if (elementsPerPage <= 0)
throw new InvalidOperationException("elementsPerPage should be greater than zero");
if (currentPage <= 0)
throw new InvalidOperationException("currentPage should be greater than zero");
this.ElementsPerPage = elementsPerPage;
this.CurrentPage = currentPage;
}
public int ElementsPerPage { get; private set; }
public int CurrentPage { get; private set; }
public int StartElementIndex() => (ElementsPerPage * (CurrentPage - 1)) + 1;
public int EndElementIndex(int rows) => StartElementIndex() + rows - 1;
public int TotalPages(int totalElements) => (totalElements + ElementsPerPage - 1) / ElementsPerPage; //Round up
public Paginate WithCurrentPage(int newPage) => new Paginate(this.ElementsPerPage, newPage);
public override PaginationMode GetMode() => PaginationMode.Paginate;
public override int? GetElementsPerPage() => ElementsPerPage;
public override int? MaxElementIndex => (ElementsPerPage * (CurrentPage + 1)) - 1;
public override bool Equals(Pagination? other) => other is Paginate p && p.ElementsPerPage == ElementsPerPage && p.CurrentPage == CurrentPage;
}
}
public class QueryValueRequest : BaseQueryRequest
{
public QueryToken? ValueToken { get; set; }
public bool MultipleValues { get; set; }
public SystemTime? SystemTime { get; set; }
public List<CollectionElementToken> Multiplications
{
get
{
return CollectionElementToken.GetElements(Filters
.SelectMany(a => a.GetFilterConditions())
.Select(fc => fc.Token)
.PreAnd(ValueToken)
.NotNull()
.ToHashSet());
}
}
}
public class UniqueEntityRequest : BaseQueryRequest
{
List<Order> orders;
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
UniqueType uniqueType;
public UniqueType UniqueType
{
get { return uniqueType; }
set { uniqueType = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
var allTokens = Filters
.SelectMany(a => a.GetFilterConditions())
.Select(a => a.Token)
.Concat(Orders.Select(a => a.Token))
.ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
}
public class QueryEntitiesRequest: BaseQueryRequest
{
List<Order> orders = new List<Order>();
public List<Order> Orders
{
get { return orders; }
set { orders = value; }
}
public List<CollectionElementToken> Multiplications
{
get
{
var allTokens = Filters.SelectMany(a=>a.GetFilterConditions()).Select(a => a.Token)
.Concat(Orders.Select(a => a.Token)).ToHashSet();
return CollectionElementToken.GetElements(allTokens);
}
}
public int? Count { get; set; }
public override string ToString() => QueryName.ToString()!;
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Game.Beatmaps;
using osu.Game.IO.Archives;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Tests.Resources;
using osu.Game.Users;
namespace osu.Game.Tests.Scores.IO
{
public class ImportScoreTest
{
[Test]
public async Task TestBasicImport()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost("TestBasicImport"))
{
try
{
var osu = await loadOsu(host);
var toImport = new ScoreInfo
{
Rank = ScoreRank.B,
TotalScore = 987654,
Accuracy = 0.8,
MaxCombo = 500,
Combo = 250,
User = new User { Username = "Test user" },
Date = DateTimeOffset.Now,
OnlineScoreID = 12345,
};
var imported = await loadIntoOsu(osu, toImport);
Assert.AreEqual(toImport.Rank, imported.Rank);
Assert.AreEqual(toImport.TotalScore, imported.TotalScore);
Assert.AreEqual(toImport.Accuracy, imported.Accuracy);
Assert.AreEqual(toImport.MaxCombo, imported.MaxCombo);
Assert.AreEqual(toImport.Combo, imported.Combo);
Assert.AreEqual(toImport.User.Username, imported.User.Username);
Assert.AreEqual(toImport.Date, imported.Date);
Assert.AreEqual(toImport.OnlineScoreID, imported.OnlineScoreID);
}
finally
{
host.Exit();
}
}
}
[Test]
public async Task TestImportMods()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost("TestImportMods"))
{
try
{
var osu = await loadOsu(host);
var toImport = new ScoreInfo
{
Mods = new Mod[] { new OsuModHardRock(), new OsuModDoubleTime() },
};
var imported = await loadIntoOsu(osu, toImport);
Assert.IsTrue(imported.Mods.Any(m => m is OsuModHardRock));
Assert.IsTrue(imported.Mods.Any(m => m is OsuModDoubleTime));
}
finally
{
host.Exit();
}
}
}
[Test]
public async Task TestImportStatistics()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost("TestImportStatistics"))
{
try
{
var osu = await loadOsu(host);
var toImport = new ScoreInfo
{
Statistics = new Dictionary<HitResult, int>
{
{ HitResult.Perfect, 100 },
{ HitResult.Miss, 50 }
}
};
var imported = await loadIntoOsu(osu, toImport);
Assert.AreEqual(toImport.Statistics[HitResult.Perfect], imported.Statistics[HitResult.Perfect]);
Assert.AreEqual(toImport.Statistics[HitResult.Miss], imported.Statistics[HitResult.Miss]);
}
finally
{
host.Exit();
}
}
}
[Test]
public async Task TestImportWithDeletedBeatmapSet()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost("TestImportWithDeletedBeatmapSet"))
{
try
{
var osu = await loadOsu(host);
var toImport = new ScoreInfo
{
Hash = Guid.NewGuid().ToString(),
Statistics = new Dictionary<HitResult, int>
{
{ HitResult.Perfect, 100 },
{ HitResult.Miss, 50 }
}
};
var imported = await loadIntoOsu(osu, toImport);
var beatmapManager = osu.Dependencies.Get<BeatmapManager>();
var scoreManager = osu.Dependencies.Get<ScoreManager>();
beatmapManager.Delete(beatmapManager.QueryBeatmapSet(s => s.Beatmaps.Any(b => b.ID == imported.Beatmap.ID)));
Assert.That(scoreManager.Query(s => s.ID == imported.ID).DeletePending, Is.EqualTo(true));
var secondImport = await loadIntoOsu(osu, imported);
Assert.That(secondImport, Is.Null);
}
finally
{
host.Exit();
}
}
}
[Test]
public async Task TestOnlineScoreIsAvailableLocally()
{
using (HeadlessGameHost host = new CleanRunHeadlessGameHost("TestOnlineScoreIsAvailableLocally"))
{
try
{
var osu = await loadOsu(host);
await loadIntoOsu(osu, new ScoreInfo { OnlineScoreID = 2 }, new TestArchiveReader());
var scoreManager = osu.Dependencies.Get<ScoreManager>();
// Note: A new score reference is used here since the import process mutates the original object to set an ID
Assert.That(scoreManager.IsAvailableLocally(new ScoreInfo { OnlineScoreID = 2 }));
}
finally
{
host.Exit();
}
}
}
private async Task<ScoreInfo> loadIntoOsu(OsuGameBase osu, ScoreInfo score, ArchiveReader archive = null)
{
var beatmapManager = osu.Dependencies.Get<BeatmapManager>();
if (score.Beatmap == null)
score.Beatmap = beatmapManager.GetAllUsableBeatmapSets().First().Beatmaps.First();
if (score.Ruleset == null)
score.Ruleset = new OsuRuleset().RulesetInfo;
var scoreManager = osu.Dependencies.Get<ScoreManager>();
await scoreManager.Import(score, archive);
return scoreManager.GetAllUsableScores().FirstOrDefault();
}
private async Task<OsuGameBase> loadOsu(GameHost host)
{
var osu = new OsuGameBase();
#pragma warning disable 4014
Task.Run(() => host.Run(osu));
#pragma warning restore 4014
waitForOrAssert(() => osu.IsLoaded, @"osu! failed to start in a reasonable amount of time");
var beatmapFile = TestResources.GetTestBeatmapForImport();
var beatmapManager = osu.Dependencies.Get<BeatmapManager>();
await beatmapManager.Import(beatmapFile);
return osu;
}
private void waitForOrAssert(Func<bool> result, string failureMessage, int timeout = 60000)
{
Task task = Task.Run(() =>
{
while (!result()) Thread.Sleep(200);
});
Assert.IsTrue(task.Wait(timeout), failureMessage);
}
private class TestArchiveReader : ArchiveReader
{
public TestArchiveReader()
: base("test_archive")
{
}
public override Stream GetStream(string name) => new MemoryStream();
public override void Dispose()
{
}
public override IEnumerable<string> Filenames => new[] { "test_file.osr" };
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: BitConverter.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Java.Lang;
using Java.Nio;
namespace System
{
public static class BitConverter
{
private static ByteBuffer GetReversedBuffer(byte[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException("value");
if (startIndex < 0 || (startIndex > value.Length - 1))
throw new ArgumentOutOfRangeException("startIndex", "Index was out of range. Must be non-negative and less than the size of the collection.");
if (length < 0 || (startIndex + length > value.Length ))
throw new ArgumentException("length", "Index was out of range. Collection does not contain enough data to process the request.");
byte[] newArray = new byte[length];
for (int i = 0 ; i < length ; i++)
{
newArray[i] = value[startIndex + length - i - 1];
}
return ByteBuffer.Wrap(newArray, 0, length);
}
public static bool IsLittleEndian
{
get { return ByteOrder.NativeOrder() == ByteOrder.LITTLE_ENDIAN; }
}
public static long DoubleToInt64Bits(double value)
{
return double.DoubleToLongBits(value);
}
public static double Int64BitsToDouble(long value)
{
byte[] b = BitConverter.GetBytes(value);
return BitConverter.ToDouble(b, 0);
}
public static byte[] GetBytes(bool value)
{
return new[] { (byte)(value ? 1 : 0) };
}
public static byte[] GetBytes(byte value)
{
return new[] { value };
}
public static byte[] GetBytes(char value)
{
var buf = ByteBuffer.Allocate(2).Order(ByteOrder.NativeOrder());
buf.PutChar(value);
return buf.ToByteArray();
}
public static byte[] GetBytes(short value)
{
var buf = ByteBuffer.Allocate(2).Order(ByteOrder.NativeOrder());
buf.PutShort(value);
return buf.ToByteArray();
}
public static byte[] GetBytes(int value)
{
var buf = ByteBuffer.Allocate(4).Order(ByteOrder.NativeOrder());
buf.PutInt(value);
return buf.ToByteArray();
}
public static byte[] GetBytes(float value)
{
var buf = ByteBuffer.Allocate(4).Order(ByteOrder.NativeOrder());
buf.PutFloat(value);
return buf.ToByteArray();
}
public static byte[] GetBytes(long value)
{
var buf = ByteBuffer.Allocate(8).Order(ByteOrder.NativeOrder());
buf.PutLong(value);
return buf.ToByteArray();
}
public static byte[] GetBytes(double value)
{
var buf = ByteBuffer.Allocate(8).Order(ByteOrder.NativeOrder());
buf.PutDouble(value);
return buf.ToByteArray();
}
public static bool ToBoolean(byte[] value, int startIndex)
{
if (value == null)
throw new ArgumentNullException("value");
if (startIndex < 0 || (startIndex > value.Length - 1))
throw new ArgumentOutOfRangeException("startIndex", "Index was out of range. Must be non-negative and less than the size of the collection.");
return value[startIndex] != 0;
}
public static char ToChar(byte[] value, int startIndex)
{
if (value == null)
throw new ArgumentNullException("value");
if (startIndex < 0 || (startIndex > value.Length - 1))
throw new ArgumentOutOfRangeException("startIndex", "Index was out of range. Must be non-negative and less than the size of the collection.");
return (char)(value[startIndex]);
}
public static short ToInt16(byte[] value, int startIndex)
{
var buf = GetReversedBuffer(value, startIndex, 2);
return buf.GetShort();
}
public static int ToInt32(byte[] value, int startIndex)
{
var buf = GetReversedBuffer(value, startIndex, 4);
return buf.GetInt();
}
public static long ToInt64(byte[] value, int startIndex)
{
var buf = GetReversedBuffer(value, startIndex, 8);
return buf.GetLong();
}
public static ushort ToUInt16(byte[] value, int startIndex)
{
return (ushort)(((int) ToInt16(value, startIndex)) & 0xFFFF);
}
public static uint ToUInt32(byte[] value, int startIndex)
{
return (uint)(((long)ToInt32(value, startIndex)) & 0xFFFFFFFF);
}
public static ulong ToUInt64(byte[] value, int startIndex)
{
return (ulong)(ToInt64(value, startIndex));
}
public static double ToDouble(byte[] value, int startIndex)
{
var buf = GetReversedBuffer(value, startIndex, 8);
return buf.GetDouble();
}
public static float ToSingle(byte[] value, int startIndex)
{
var buf = GetReversedBuffer(value, startIndex, 4);
return buf.GetFloat();
}
/// <summary>
/// Convert the numeric value of each array element to a hex string divided by '-'.
/// </summary>
public static string ToString(byte[] value)
{
if (value == null)
throw new ArgumentNullException("value");
return ToString(value, 0, value.Length);
}
/// <summary>
/// Convert the numeric value of each array element to a hex string divided by '-'.
/// </summary>
public static string ToString(byte[] value, int startIndex)
{
if (value == null)
throw new ArgumentNullException("value");
return ToString(value, startIndex, value.Length - startIndex);
}
/// <summary>
/// Convert the numeric value of each array element to a hex string divided by '-'.
/// </summary>
public static string ToString(byte[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException("value");
if ((startIndex < 0) || (startIndex >= value.Length))
throw new ArgumentOutOfRangeException("index");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if (startIndex + length > value.Length)
throw new ArgumentException("length");
var buffer = new StringBuffer();
for (var i = 0; i < length; i++)
{
if (i > 0)
buffer.Append('-');
var hex = int.ToHexString((int) value[startIndex + i]).ToUpper();
if (hex.Length == 1)
buffer.Append('0');
buffer.Append(hex);
}
return buffer.ToString();
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Web.SessionState;
namespace Jam
{
/// <summary>
/// Summary description for CaptchaImage.
/// </summary>
public class CaptchaImage
{
// Public properties (all read-only).
public string Text
{
get { return this.text; }
}
public Bitmap Image
{
get { return this.image; }
}
public int Width
{
get { return this.width; }
}
public int Height
{
get { return this.height; }
}
// Internal properties.
private string text;
private int width;
private int height;
private string familyName;
private Bitmap image;
// For generating random numbers.
private Random random = new Random();
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width and height.
// ====================================================================
public CaptchaImage(string s, int width, int height)
{
this.text = s;
this.SetDimensions(width, height);
this.GenerateImage();
}
// ====================================================================
// Initializes a new instance of the CaptchaImage class using the
// specified text, width, height and font family.
// ====================================================================
public CaptchaImage(string s, int width, int height, string familyName)
{
this.text = s;
this.SetDimensions(width, height);
this.SetFamilyName(familyName);
this.GenerateImage();
}
// ====================================================================
// This member overrides Object.Finalize.
// ====================================================================
~CaptchaImage()
{
Dispose(false);
}
// ====================================================================
// Releases all resources used by this object.
// ====================================================================
public void Dispose()
{
GC.SuppressFinalize(this);
this.Dispose(true);
}
// ====================================================================
// Custom Dispose method to clean up unmanaged resources.
// ====================================================================
protected virtual void Dispose(bool disposing)
{
if (disposing)
// Dispose of the bitmap.
this.image.Dispose();
}
// ====================================================================
// Sets the image width and height.
// ====================================================================
private void SetDimensions(int width, int height)
{
// Check the width and height.
if (width <= 0)
throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
if (height <= 0)
throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
this.width = width;
this.height = height;
}
// ====================================================================
// Sets the font used for the image text.
// ====================================================================
private void SetFamilyName(string familyName)
{
// If the named font is not installed, default to a system font.
try
{
Font font = new Font(this.familyName, 12F);
this.familyName = familyName;
font.Dispose();
}
catch (Exception ex)
{
this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
}
}
// ====================================================================
// Creates the bitmap image.
// ====================================================================
private void GenerateImage()
{
// Create a new 32-bit bitmap image.
Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);
// Create a graphics object for drawing.
Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle rect = new Rectangle(0, 0, this.width, this.height);
// Fill in the background.
HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
g.FillRectangle(hatchBrush, rect);
// Set up the text font.
SizeF size;
float fontSize = rect.Height + 1;
Font font;
// Adjust the font size until the text fits within the image.
do
{
fontSize--;
font = new Font(this.familyName, fontSize, FontStyle.Bold);
size = g.MeasureString(this.text, font);
} while (size.Width > rect.Width);
// Set up the text format.
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
// Create a path using the text and warp it randomly.
GraphicsPath path = new GraphicsPath();
path.AddString(this.text, font.FontFamily, (int) font.Style, font.Size, rect, format);
float v = 4F;
PointF[] points =
{
new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
};
Matrix matrix = new Matrix();
matrix.Translate(0F, 0F);
path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);
// Draw the text.
hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
g.FillPath(hatchBrush, path);
// Add some random noise.
int m = Math.Max(rect.Width, rect.Height);
for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
{
int x = this.random.Next(rect.Width);
int y = this.random.Next(rect.Height);
int w = this.random.Next(m / 50);
int h = this.random.Next(m / 50);
g.FillEllipse(hatchBrush, x, y, w, h);
}
// Clean up.
font.Dispose();
hatchBrush.Dispose();
g.Dispose();
// Set the image.
this.image = bitmap;
}
static public string GenerateText(HttpSessionState Session)
{
string s = "";
int[,] arLim = new int[,] { { 48, 57 }, { 63, 90 }, { 97, 122 } };
Random rnd = new Random((int)DateTime.Now.ToFileTime());
for (int i = 0; i < 8; i++)
{
int nFirstIndex = rnd.Next(0, 2);
s += Char.ConvertFromUtf32(rnd.Next(arLim[nFirstIndex, 0], arLim[nFirstIndex, 1]));
}
Session["CaptchaImageText"] = s;
return s;
}
static public bool CheckCaptcha(string sAnswer, HttpSessionState Session)
{
if (sAnswer == Session["CaptchaImageText"].ToString())
{
return true;
}
else
{
GenerateText(Session);//reset capture in session
return false;
}
}
}
}
| |
/* ====================================================================
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 NPOI.HWPF.Model
{
using NPOI.Util;
using System;
/**
*
*/
public class ListLevel
{
private static int RGBXCH_NUMS_SIZE = 9;
private int _iStartAt;
private byte _nfc;
private byte _info;
private static BitField _jc;
private static BitField _fLegal;
private static BitField _fNoRestart;
private static BitField _fPrev;
private static BitField _fPrevSpace;
private static BitField _fWord6;
private byte[] _rgbxchNums;
private byte _ixchFollow;
private int _dxaSpace;
private int _dxaIndent;
private int _cbGrpprlChpx;
private int _cbGrpprlPapx;
private short _reserved;
private byte[] _grpprlPapx;
private byte[] _grpprlChpx;
private char[] _numberText = null;
public ListLevel(int startAt, int numberFormatCode, int alignment,
byte[] numberProperties, byte[] entryProperties,
String numberText)
{
_iStartAt = startAt;
_nfc = (byte)numberFormatCode;
_jc.SetValue(_info, alignment);
_grpprlChpx = numberProperties;
_grpprlPapx = entryProperties;
_numberText = numberText.ToCharArray();
}
public ListLevel(int level, bool numbered)
{
_iStartAt = 1;
_grpprlPapx = new byte[0];
_grpprlChpx = new byte[0];
_numberText = new char[0];
_rgbxchNums = new byte[RGBXCH_NUMS_SIZE];
if (numbered)
{
_rgbxchNums[0] = 1;
_numberText = new char[] { (char)level, '.' };
}
else
{
_numberText = new char[] { '\u2022' };
}
}
public ListLevel(byte[] buf, int offset)
{
_iStartAt = LittleEndian.GetInt(buf, offset);
offset += LittleEndianConsts.INT_SIZE;
_nfc = buf[offset++];
_info = buf[offset++];
_rgbxchNums = new byte[RGBXCH_NUMS_SIZE];
Array.Copy(buf, offset, _rgbxchNums, 0, RGBXCH_NUMS_SIZE);
offset += RGBXCH_NUMS_SIZE;
_ixchFollow = buf[offset++];
_dxaSpace = LittleEndian.GetInt(buf, offset);
offset += LittleEndianConsts.INT_SIZE;
_dxaIndent = LittleEndian.GetInt(buf, offset);
offset += LittleEndianConsts.INT_SIZE;
_cbGrpprlChpx = LittleEndian.GetUByte(buf, offset++);
_cbGrpprlPapx = LittleEndian.GetUByte(buf, offset++);
_reserved = LittleEndian.GetShort(buf, offset);
offset += LittleEndianConsts.SHORT_SIZE;
_grpprlPapx = new byte[_cbGrpprlPapx];
_grpprlChpx = new byte[_cbGrpprlChpx];
Array.Copy(buf, offset, _grpprlPapx, 0, _cbGrpprlPapx);
offset += _cbGrpprlPapx;
Array.Copy(buf, offset, _grpprlChpx, 0, _cbGrpprlChpx);
offset += _cbGrpprlChpx;
int numberTextLength = LittleEndian.GetShort(buf, offset);
/* sometimes numberTextLength<0 */
/* by derjohng */
if (numberTextLength > 0)
{
_numberText = new char[numberTextLength];
offset += LittleEndianConsts.SHORT_SIZE;
for (int x = 0; x < numberTextLength; x++)
{
_numberText[x] = (char)LittleEndian.GetShort(buf, offset);
offset += LittleEndianConsts.SHORT_SIZE;
}
}
}
public int GetStartAt()
{
return _iStartAt;
}
public int GetNumberFormat()
{
return _nfc;
}
public int GetAlignment()
{
return _jc.GetValue(_info);
}
public String GetNumberText()
{
if (_numberText != null)
return new String(_numberText);
else
return null;
}
/**
* "The type of character following the number text for the paragraph: 0 == tab, 1 == space, 2 == nothing."
*/
public byte GetTypeOfCharFollowingTheNumber()
{
return this._ixchFollow;
}
public void SetStartAt(int startAt)
{
_iStartAt = startAt;
}
public void SetNumberFormat(int numberFormatCode)
{
_nfc = (byte)numberFormatCode;
}
public void SetAlignment(int alignment)
{
_jc.SetValue(_info, alignment);
}
public void SetNumberProperties(byte[] grpprl)
{
_grpprlChpx = grpprl;
}
public void SetLevelProperties(byte[] grpprl)
{
_grpprlPapx = grpprl;
}
public byte[] GetLevelProperties()
{
return _grpprlPapx;
}
public override bool Equals(Object obj)
{
if (obj == null)
{
return false;
}
ListLevel lvl = (ListLevel)obj;
return _cbGrpprlChpx == lvl._cbGrpprlChpx && lvl._cbGrpprlPapx == _cbGrpprlPapx &&
lvl._dxaIndent == _dxaIndent && lvl._dxaSpace == _dxaSpace &&
Arrays.Equals(lvl._grpprlChpx, _grpprlChpx) &&
Arrays.Equals(lvl._grpprlPapx, _grpprlPapx) &&
lvl._info == _info && lvl._iStartAt == _iStartAt &&
lvl._ixchFollow == _ixchFollow && lvl._nfc == _nfc &&
Arrays.Equals(lvl._numberText, _numberText) &&
Arrays.Equals(lvl._rgbxchNums, _rgbxchNums) &&
lvl._reserved == _reserved;
}
public byte[] ToArray()
{
byte[] buf = new byte[GetSizeInBytes()];
int offset = 0;
LittleEndian.PutInt(buf, offset, _iStartAt);
offset += LittleEndianConsts.INT_SIZE;
buf[offset++] = _nfc;
buf[offset++] = _info;
Array.Copy(_rgbxchNums, 0, buf, offset, RGBXCH_NUMS_SIZE);
offset += RGBXCH_NUMS_SIZE;
buf[offset++] = _ixchFollow;
LittleEndian.PutInt(buf, offset, _dxaSpace);
offset += LittleEndianConsts.INT_SIZE;
LittleEndian.PutInt(buf, offset, _dxaIndent);
offset += LittleEndianConsts.INT_SIZE;
buf[offset++] = (byte)_cbGrpprlChpx;
buf[offset++] = (byte)_cbGrpprlPapx;
LittleEndian.PutShort(buf, offset, _reserved);
offset += LittleEndianConsts.SHORT_SIZE;
Array.Copy(_grpprlPapx, 0, buf, offset, _cbGrpprlPapx);
offset += _cbGrpprlPapx;
Array.Copy(_grpprlChpx, 0, buf, offset, _cbGrpprlChpx);
offset += _cbGrpprlChpx;
if (_numberText == null)
{
// TODO - write junit to test this flow
LittleEndian.PutUShort(buf, offset, 0);
}
else
{
LittleEndian.PutUShort(buf, offset, _numberText.Length);
offset += LittleEndianConsts.SHORT_SIZE;
for (int x = 0; x < _numberText.Length; x++)
{
LittleEndian.PutUShort(buf, offset, _numberText[x]);
offset += LittleEndianConsts.SHORT_SIZE;
}
}
return buf;
}
public int GetSizeInBytes()
{
int result =
6 // int byte byte
+ RGBXCH_NUMS_SIZE
+ 13 // byte int int byte byte short
+ _cbGrpprlChpx
+ _cbGrpprlPapx
+ 2; // numberText length
if (_numberText != null)
{
result += _numberText.Length * LittleEndianConsts.SHORT_SIZE;
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#if (WINDOWS && !WINRT)
using BitMiracle.LibTiff.Classic;
#endif
namespace CocosSharp
{
#region Enums and structs
public enum CCImageFormat
{
Jpg = 0,
Png,
Tiff,
Webp,
Gif,
RawData,
UnKnown
}
public enum CCSurfaceFormat
{
Color = 0,
Bgr565 = 1,
Bgra5551 = 2,
Bgra4444 = 3,
Dxt1 = 4,
Dxt3 = 5,
Dxt5 = 6,
NormalizedByte2 = 7,
NormalizedByte4 = 8,
Rgba1010102 = 9,
Rg32 = 10,
Rgba64 = 11,
Alpha8 = 12,
Single = 13,
CCVector2 = 14,
Vector4 = 15,
HalfSingle = 16,
HalfCCVector2 = 17,
HalfVector4 = 18,
HdrBlendable = 19,
// BGRA formats are required for compatibility with WPF D3DImage.
Bgr32 = 20, // B8G8R8X8
Bgra32 = 21, // B8G8R8A8
// Good explanation of compressed formats for mobile devices (aimed at Android, but describes PVRTC)
// http://developer.motorola.com/docstools/library/understanding-texture-compression/
// PowerVR texture compression (iOS and Android)
RgbPvrtc2Bpp = 50,
RgbPvrtc4Bpp = 51,
RgbaPvrtc2Bpp = 52,
RgbaPvrtc4Bpp = 53,
// Ericcson Texture Compression (Android)
RgbEtc1 = 60,
// DXT1 also has a 1-bit alpha form
Dxt1a = 70,
}
internal enum CCTextureCacheType
{
None,
AssetFile,
Data,
RawData,
String
}
internal struct CCStringCache
{
public String Text;
public CCSize Dimensions;
public CCTextAlignment HAlignment;
public CCVerticalTextAlignment VAlignment;
public String FontName;
public float FontSize;
}
internal struct CCTextureCacheInfo
{
public CCTextureCacheType CacheType;
public Object Data;
}
#endregion Enums and structs
public class CCTexture2D : CCGraphicsResource
{
public static CCSurfaceFormat DefaultAlphaPixelFormat = CCSurfaceFormat.Color;
public static bool OptimizeForPremultipliedAlpha = true;
public static bool DefaultIsAntialiased = true;
bool hasMipmaps;
bool managed;
bool antialiased;
CCTextureCacheInfo cacheInfo;
Texture2D texture2D;
#region Properties
public bool HasPremultipliedAlpha { get; private set; }
public int PixelsWide { get; private set; }
public int PixelsHigh { get; private set; }
public CCSize ContentSizeInPixels { get; private set; }
public CCSurfaceFormat PixelFormat { get; set; }
public SamplerState SamplerState { get; set; }
public bool IsTextureDefined
{
get { return (texture2D != null && !texture2D.IsDisposed); }
}
public bool IsAntialiased
{
get { return antialiased; }
set
{
if (antialiased != value)
{
antialiased = value;
RefreshAntialiasSetting();
}
}
}
public uint BitsPerPixelForFormat
{
//from MG: Microsoft.Xna.Framework.Graphics.GraphicsExtensions
get
{
switch (PixelFormat)
{
case CCSurfaceFormat.Dxt1:
#if !WINDOWS && !WINDOWS_PHONE
case CCSurfaceFormat.Dxt1a:
case CCSurfaceFormat.RgbPvrtc2Bpp:
case CCSurfaceFormat.RgbaPvrtc2Bpp:
case CCSurfaceFormat.RgbEtc1:
#endif
// One texel in DXT1, PVRTC 2bpp and ETC1 is a minimum 4x4 block, which is 8 bytes
return 8;
case CCSurfaceFormat.Dxt3:
case CCSurfaceFormat.Dxt5:
#if !WINDOWS && !WINDOWS_PHONE
case CCSurfaceFormat.RgbPvrtc4Bpp:
case CCSurfaceFormat.RgbaPvrtc4Bpp:
#endif
// One texel in DXT3, DXT5 and PVRTC 4bpp is a minimum 4x4 block, which is 16 bytes
return 16;
case CCSurfaceFormat.Alpha8:
return 1;
case CCSurfaceFormat.Bgr565:
case CCSurfaceFormat.Bgra4444:
case CCSurfaceFormat.Bgra5551:
case CCSurfaceFormat.HalfSingle:
case CCSurfaceFormat.NormalizedByte2:
return 2;
case CCSurfaceFormat.Color:
case CCSurfaceFormat.Single:
case CCSurfaceFormat.Rg32:
case CCSurfaceFormat.HalfCCVector2:
case CCSurfaceFormat.NormalizedByte4:
case CCSurfaceFormat.Rgba1010102:
return 4;
case CCSurfaceFormat.HalfVector4:
case CCSurfaceFormat.Rgba64:
case CCSurfaceFormat.CCVector2:
return 8;
case CCSurfaceFormat.Vector4:
return 16;
default:
throw new NotImplementedException();
}
}
}
public Texture2D Name
{
get { return XNATexture; }
}
public Texture2D XNATexture
{
get
{
if (texture2D != null && texture2D.IsDisposed)
{
ReinitResource();
}
return texture2D;
}
}
#endregion Properties
#region Constructors and initialization
public CCTexture2D()
{
SamplerState = SamplerState.LinearClamp;
IsAntialiased = DefaultIsAntialiased;
RefreshAntialiasSetting();
}
public CCTexture2D (int pixelsWide, int pixelsHigh, CCSurfaceFormat pixelFormat=CCSurfaceFormat.Color, bool premultipliedAlpha=true, bool mipMap=false)
: this(new Texture2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, pixelsWide, pixelsHigh, mipMap, (SurfaceFormat)pixelFormat), pixelFormat, premultipliedAlpha)
{
cacheInfo.CacheType = CCTextureCacheType.None;
cacheInfo.Data = null;
}
public CCTexture2D(byte[] data, CCSurfaceFormat pixelFormat=CCSurfaceFormat.Color, bool mipMap=false)
: this()
{
InitWithData(data, pixelFormat, mipMap);
}
public CCTexture2D(Stream stream, CCSurfaceFormat pixelFormat=CCSurfaceFormat.Color)
: this()
{
InitWithStream(stream, pixelFormat);
}
public CCTexture2D(string text, CCSize dimensions, CCTextAlignment hAlignment,
CCVerticalTextAlignment vAlignment, string fontName, float fontSize)
: this()
{
InitWithString(text, dimensions, hAlignment, vAlignment, fontName, fontSize);
}
public CCTexture2D(string text, string fontName, float fontSize)
: this(text, CCSize.Zero, CCTextAlignment.Center, CCVerticalTextAlignment.Top, fontName, fontSize)
{
}
public CCTexture2D(string file)
: this()
{
InitWithFile(file);
}
public CCTexture2D(Texture2D texture, CCSurfaceFormat format, bool premultipliedAlpha=true, bool managed=false)
: this()
{
InitWithTexture(texture, format, premultipliedAlpha, managed);
}
public CCTexture2D(Texture2D texture)
: this(texture, (CCSurfaceFormat)texture.Format)
{
}
internal void InitWithRawData<T>(T[] data, CCSurfaceFormat pixelFormat, int pixelsWide, int pixelsHigh, bool premultipliedAlpha, bool mipMap)
where T : struct
{
InitWithRawData(data, pixelFormat, pixelsWide, pixelsHigh, premultipliedAlpha, mipMap, new CCSize(pixelsWide, pixelsHigh));
}
internal void InitWithRawData<T>(T[] data, CCSurfaceFormat pixelFormat, int pixelsWide, int pixelsHigh,
bool premultipliedAlpha, bool mipMap, CCSize ContentSizeInPixelsIn) where T : struct
{
var texture = LoadRawData(data, pixelsWide, pixelsHigh, (SurfaceFormat)pixelFormat, mipMap);
InitWithTexture(texture, pixelFormat, premultipliedAlpha, false);
ContentSizeInPixels = ContentSizeInPixelsIn;
cacheInfo.CacheType = CCTextureCacheType.RawData;
cacheInfo.Data = data;
}
void InitWithData(byte[] data, CCSurfaceFormat pixelFormat, bool mipMap)
{
if (data == null)
{
return;
}
#if WINDOWS_PHONE8
/*
byte[] cloneOfData = new byte[data.Length];
data.CopyTo(cloneOfData, 0);
data = cloneOfData;
*/
#endif
var texture = LoadTexture(new MemoryStream(data, false));
if (texture != null)
{
InitWithTexture(texture, pixelFormat, true, false);
cacheInfo.CacheType = CCTextureCacheType.Data;
cacheInfo.Data = data;
if (mipMap)
{
GenerateMipmap();
}
}
}
void InitWithStream(Stream stream, CCSurfaceFormat pixelFormat)
{
Texture2D texture;
try
{
texture = LoadTexture(stream);
InitWithTexture(texture, pixelFormat, false, false);
return;
}
catch (Exception)
{
}
}
void InitWithFile(string file)
{
managed = false;
Texture2D texture = null;
cacheInfo.CacheType = CCTextureCacheType.AssetFile;
cacheInfo.Data = file;
//TODO: may be move this functional to CCContentManager?
var contentManager = CCContentManager.SharedContentManager;
var loadedFile = file;
// first try to download xnb
if (Path.HasExtension(loadedFile))
{
loadedFile = Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file));
}
// use WeakReference. Link for regular textures are stored in CCTextureCache
texture = contentManager.TryLoad<Texture2D>(loadedFile, true);
if (texture != null)
{
// usually xnb texture prepared as PremultipliedAlpha
InitWithTexture(texture, DefaultAlphaPixelFormat, true, true);
return;
}
// try load raw image
if (loadedFile != file)
{
texture = contentManager.TryLoad<Texture2D>(file, true);
if (texture != null)
{
// not premultiplied alpha
InitWithTexture(texture, DefaultAlphaPixelFormat, false, true);
return;
}
}
// try load not supported format (for example tga)
try
{
using (var stream = contentManager.GetAssetStream(file))
{
InitWithStream(stream, DefaultAlphaPixelFormat);
}
}
catch (Exception)
{
}
CCLog.Log("Texture {0} was not found.", file);
}
void InitWithString(string text, CCSize dimensions, CCTextAlignment hAlignment, CCVerticalTextAlignment vAlignment, string fontName, float fontSize)
{
try
{
Debug.Assert(dimensions.Width >= 0 || dimensions.Height >= 0);
if (string.IsNullOrEmpty(text))
{
return;
}
float loadedSize = fontSize;
SpriteFont font = CCSpriteFontCache.SharedInstance.TryLoadFont(fontName, fontSize, out loadedSize);
if (font == null)
{
CCLog.Log("Failed to load default font. No font supported.");
return;
}
float scale = 1f;
if (loadedSize != 0)
{
scale = fontSize / loadedSize * CCSpriteFontCache.FontScale;
}
if (dimensions.Equals(CCSize.Zero))
{
CCVector2 temp = font.MeasureString(text).ToCCVector2();
dimensions.Width = temp.X * scale;
dimensions.Height = temp.Y * scale;
}
var textList = new List<String>();
var nextText = new StringBuilder();
string[] lineList = text.Split('\n');
float spaceWidth = font.MeasureString(" ").X * scale;
for (int j = 0; j < lineList.Length; ++j)
{
string[] wordList = lineList[j].Split(' ');
float lineWidth = 0;
bool firstWord = true;
for (int i = 0; i < wordList.Length; ++i)
{
float wordWidth = font.MeasureString(wordList[i]).X * scale;
if ((lineWidth + wordWidth) > dimensions.Width)
{
lineWidth = wordWidth;
if (nextText.Length > 0)
{
firstWord = true;
textList.Add(nextText.ToString());
nextText.Length = 0;
}
else
{
lineWidth += wordWidth;
firstWord = false;
textList.Add(wordList[i]);
continue;
}
}
else
{
lineWidth += wordWidth;
}
if (!firstWord)
{
nextText.Append(' ');
lineWidth += spaceWidth;
}
nextText.Append(wordList[i]);
firstWord = false;
}
textList.Add(nextText.ToString());
nextText.Clear();
}
if (dimensions.Height == 0)
{
dimensions.Height = textList.Count * font.LineSpacing * scale;
}
//* for render to texture
RenderTarget2D renderTarget = CCDrawManager.SharedDrawManager.CreateRenderTarget(
(int)dimensions.Width, (int)dimensions.Height,
DefaultAlphaPixelFormat, CCRenderTargetUsage.DiscardContents
);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = renderTarget;
CCDrawManager.SharedDrawManager.Clear(CCColor4B.Transparent);
SpriteBatch sb = CCDrawManager.SharedDrawManager.SpriteBatch;
sb.Begin();
float textHeight = textList.Count * font.LineSpacing * scale;
float nextY = 0;
if (vAlignment == CCVerticalTextAlignment.Bottom)
{
nextY = dimensions.Height - textHeight;
}
else if (vAlignment == CCVerticalTextAlignment.Center)
{
nextY = (dimensions.Height - textHeight) / 2.0f;
}
for (int j = 0; j < textList.Count; ++j)
{
string line = textList[j];
var position = new CCVector2(0, nextY);
if (hAlignment == CCTextAlignment.Right)
{
position.X = dimensions.Width - font.MeasureString(line).X * scale;
}
else if (hAlignment == CCTextAlignment.Center)
{
position.X = (dimensions.Width - font.MeasureString(line).X * scale) / 2.0f;
}
sb.DrawString(font, line, position.ToVector2(), Color.White, 0f, Vector2.Zero, scale, SpriteEffects.None, 0);
nextY += font.LineSpacing * scale;
}
sb.End();
CCDrawManager.SharedDrawManager.XnaGraphicsDevice.RasterizerState = RasterizerState.CullNone;
CCDrawManager.SharedDrawManager.DepthStencilState = DepthStencilState.Default;
CCDrawManager.SharedDrawManager.CurrentRenderTarget = (RenderTarget2D)null;
InitWithTexture(renderTarget, (CCSurfaceFormat)renderTarget.Format, true, false);
cacheInfo.CacheType = CCTextureCacheType.String;
cacheInfo.Data = new CCStringCache()
{
Dimensions = dimensions,
Text = text,
FontName = fontName,
FontSize = fontSize,
HAlignment = hAlignment,
VAlignment = vAlignment
};
}
catch (Exception ex)
{
CCLog.Log(ex.ToString());
}
}
// Method called externally by CCDrawManager
internal void InitWithTexture(Texture2D texture, CCSurfaceFormat format, bool premultipliedAlpha, bool managedIn)
{
managed = managedIn;
if (null == texture)
{
return;
}
if (OptimizeForPremultipliedAlpha && !premultipliedAlpha)
{
texture2D = ConvertToPremultiplied(texture, (SurfaceFormat)format);
if (!managed)
{
texture.Dispose();
managed = false;
}
}
else
{
if (texture.Format != (SurfaceFormat)format)
{
texture2D = ConvertSurfaceFormat(texture, (SurfaceFormat)format);
if (!managed)
{
texture.Dispose();
managed = false;
}
}
else
{
texture2D = texture;
}
}
PixelFormat = (CCSurfaceFormat)texture.Format;
PixelsWide = texture.Width;
PixelsHigh = texture.Height;
ContentSizeInPixels = new CCSize(texture.Width, texture.Height);
hasMipmaps = texture.LevelCount > 1;
HasPremultipliedAlpha = premultipliedAlpha;
}
public override void ReinitResource()
{
CCLog.Log("reinit called on texture '{0}' {1}x{2}", Name, ContentSizeInPixels.Width, ContentSizeInPixels.Height);
Texture2D textureToDispose = null;
if (texture2D != null && !texture2D.IsDisposed && !managed)
{
textureToDispose = texture2D;
// texture2D.Dispose();
}
managed = false;
texture2D = null;
switch (cacheInfo.CacheType)
{
case CCTextureCacheType.None:
return;
case CCTextureCacheType.AssetFile:
InitWithFile((string)cacheInfo.Data);
break;
case CCTextureCacheType.Data:
InitWithData((byte[])cacheInfo.Data, (CCSurfaceFormat)PixelFormat, hasMipmaps);
break;
case CCTextureCacheType.RawData:
#if NETFX_CORE
var methodInfo = typeof(CCTexture2D).GetType().GetTypeInfo().GetDeclaredMethod("InitWithRawData");
#else
var methodInfo = typeof(CCTexture2D).GetMethod("InitWithRawData", BindingFlags.Public | BindingFlags.Instance);
#endif
var genericMethod = methodInfo.MakeGenericMethod(cacheInfo.Data.GetType());
genericMethod.Invoke(this, new object[]
{
Convert.ChangeType(cacheInfo.Data, cacheInfo.Data.GetType(),System.Globalization.CultureInfo.InvariantCulture),
PixelFormat, PixelsWide, PixelsHigh,
HasPremultipliedAlpha, hasMipmaps, ContentSizeInPixels
});
// InitWithRawData((byte[])cacheInfo.Data, PixelFormat, PixelsWide, PixelsHigh,
// HasPremultipliedAlpha, hasMipmaps, ContentSizeInPixels);
break;
case CCTextureCacheType.String:
var si = (CCStringCache)cacheInfo.Data;
InitWithString(si.Text, si.Dimensions, si.HAlignment, si.VAlignment, si.FontName, si.FontSize);
if (hasMipmaps)
{
hasMipmaps = false;
GenerateMipmap();
}
break;
default:
throw new ArgumentOutOfRangeException();
}
if (textureToDispose != null && !textureToDispose.IsDisposed)
{
textureToDispose.Dispose();
}
}
#endregion Constructors and initialization
public override string ToString()
{
return String.Format("<CCTexture2D | Dimensions = {0} x {1})>", PixelsWide, PixelsHigh);
}
#region Cleanup
void RefreshAntialiasSetting()
{
var saveState = SamplerState;
if (antialiased && SamplerState.Filter != TextureFilter.Linear)
{
if (SamplerState == SamplerState.PointClamp)
{
SamplerState = SamplerState.LinearClamp;
return;
}
SamplerState = new SamplerState
{
Filter = TextureFilter.Linear
};
}
else if (!antialiased && SamplerState.Filter != TextureFilter.Point)
{
if (SamplerState == SamplerState.LinearClamp)
{
SamplerState = SamplerState.PointClamp;
return;
}
SamplerState = new SamplerState
{
Filter = TextureFilter.Point
};
}
else
{
return;
}
SamplerState.AddressU = saveState.AddressU;
SamplerState.AddressV = saveState.AddressV;
SamplerState.AddressW = saveState.AddressW;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && texture2D != null && !texture2D.IsDisposed && !managed)
{
texture2D.Dispose();
}
texture2D = null;
}
#endregion Cleanup
#region Saving texture
public void SaveAsJpeg(Stream stream, int width, int height)
{
if (texture2D != null)
{
texture2D.SaveAsJpeg(stream, width, height);
}
}
public void SaveAsPng(Stream stream, int width, int height)
{
if (texture2D != null)
{
texture2D.SaveAsPng(stream, width, height);
}
}
#endregion Saving texture
#region Conversion
public void GenerateMipmap()
{
if (!hasMipmaps)
{
var target = new RenderTarget2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, PixelsWide, PixelsHigh, true, (SurfaceFormat)PixelFormat,
DepthFormat.None, 0, RenderTargetUsage.DiscardContents);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = target;
SpriteBatch sb = CCDrawManager.SharedDrawManager.SpriteBatch;
sb.Begin();
sb.Draw(texture2D, Vector2.Zero, Color.White);
sb.End();
if (!managed)
{
texture2D.Dispose();
}
managed = false;
texture2D = target;
hasMipmaps = true;
}
}
Texture2D ConvertSurfaceFormat(Texture2D texture, SurfaceFormat format)
{
if (texture.Format == format)
{
return texture;
}
var renderTarget = new RenderTarget2D(
CCDrawManager.SharedDrawManager.XnaGraphicsDevice,
texture.Width, texture.Height, hasMipmaps, format,
DepthFormat.None, 0, RenderTargetUsage.DiscardContents
);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = renderTarget;
CCDrawManager.SharedDrawManager.SpriteBatch.Begin();
CCDrawManager.SharedDrawManager.SpriteBatch.Draw(texture, Vector2.Zero, Color.White);
CCDrawManager.SharedDrawManager.SpriteBatch.End();
CCDrawManager.SharedDrawManager.SetRenderTarget((CCTexture2D)null);
return renderTarget;
}
Texture2D ConvertToPremultiplied(Texture2D texture, SurfaceFormat format)
{
//Jake Poznanski - Speeding up XNA Content Load
//http://jakepoz.com/jake_poznanski__speeding_up_xna.html
//Setup a render target to hold our final texture which will have premulitplied alpha values
var result = new RenderTarget2D(
CCDrawManager.SharedDrawManager.XnaGraphicsDevice,
texture.Width, texture.Height, hasMipmaps, format,
DepthFormat.None, 0, RenderTargetUsage.DiscardContents
);
CCDrawManager.SharedDrawManager.CurrentRenderTarget = result;
CCDrawManager.SharedDrawManager.Clear(CCColor4B.Transparent);
var spriteBatch = CCDrawManager.SharedDrawManager.SpriteBatch;
if (format != SurfaceFormat.Alpha8)
{
//Multiply each color by the source alpha, and write in just the color values into the final texture
var blendColor = new BlendState();
blendColor.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green |
ColorWriteChannels.Blue;
blendColor.AlphaDestinationBlend = Blend.Zero;
blendColor.ColorDestinationBlend = Blend.Zero;
blendColor.AlphaSourceBlend = Blend.SourceAlpha;
blendColor.ColorSourceBlend = Blend.SourceAlpha;
spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
spriteBatch.Draw(texture, texture.Bounds, Color.White);
spriteBatch.End();
}
//Now copy over the alpha values from the PNG source texture to the final one, without multiplying them
var blendAlpha = new BlendState();
blendAlpha.ColorWriteChannels = ColorWriteChannels.Alpha;
blendAlpha.AlphaDestinationBlend = Blend.Zero;
blendAlpha.ColorDestinationBlend = Blend.Zero;
blendAlpha.AlphaSourceBlend = Blend.One;
blendAlpha.ColorSourceBlend = Blend.One;
spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
spriteBatch.Draw(texture, texture.Bounds, Color.White);
spriteBatch.End();
//Release the GPU back to drawing to the screen
CCDrawManager.SharedDrawManager.SetRenderTarget((CCTexture2D) null);
return result;
}
#endregion Conversion
#region Loading Texture
public static CCImageFormat DetectImageFormat(Stream stream)
{
var data = new byte[8];
var pos = stream.Position;
var dataLen = stream.Read(data, 0, 8);
stream.Position = pos;
if (dataLen >= 8)
{
if (data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47
&& data[4] == 0x0D && data[5] == 0x0A && data[6] == 0x1A && data[7] == 0x0A)
{
return CCImageFormat.Png;
}
}
if (dataLen >= 3)
{
if (data[0] == 0x47 && data[1] == 0x49 && data[1] == 0x46)
{
return CCImageFormat.Gif;
}
}
if (dataLen >= 2)
{
if ((data[0] == 0x49 && data[1] == 0x49) || (data[0] == 0x4d && data[1] == 0x4d))
{
return CCImageFormat.Tiff;
}
}
if (dataLen >= 2)
{
if (data[0] == 0xff && data[1] == 0xd8)
{
return CCImageFormat.Jpg;
}
}
return CCImageFormat.UnKnown;
}
Texture2D LoadTexture(Stream stream)
{
return LoadTexture(stream, CCImageFormat.UnKnown);
}
Texture2D LoadRawData<T>(T[] data, int width, int height, SurfaceFormat pixelFormat, bool mipMap) where T : struct
{
var result = new Texture2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, width, height, mipMap, pixelFormat);
result.SetData(data);
return result;
}
Texture2D LoadTexture(Stream stream, CCImageFormat imageFormat)
{
Texture2D result = null;
if (imageFormat == CCImageFormat.UnKnown)
{
imageFormat = DetectImageFormat(stream);
}
if (imageFormat == CCImageFormat.Tiff)
{
result = LoadTextureFromTiff(stream);
}
if (imageFormat == CCImageFormat.Jpg || imageFormat == CCImageFormat.Png || imageFormat == CCImageFormat.Gif)
{
result = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, stream);
}
return result;
}
Texture2D LoadTextureFromTiff(Stream stream)
{
#if (WINDOWS && !WINRT)
var tiff = Tiff.ClientOpen("file.tif", "r", stream, new TiffStream());
var w = tiff.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
var h = tiff.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
var raster = new int[w * h];
if (tiff.ReadRGBAImageOriented(w, h, raster, Orientation.LEFTTOP))
{
var result = new Texture2D(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, w, h, false, SurfaceFormat.Color);
result.SetData(raster);
return result;
}
else
{
return null;
}
#elif MACOS || IOS
return Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, stream);
#else
return null;
#endif
}
#endregion Loading Texture
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows.Data;
using NAudio.Midi;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using SharpSynth;
using SharpSynth.Input;
namespace SynthTest
{
public class MainWindowViewModel : IDisposable
{
private float pitch;
private readonly PoliLfo lfo = new PoliLfo();
private readonly Vco vco1 = new Vco();
private readonly Vco vco2 = new Vco();
private readonly PoliMixer mixer = new PoliMixer();
private readonly PoliFilter filter = new PoliFilter();
private readonly PoliAmp amp = new PoliAmp();
private readonly Triggerizer triggerizer = new Triggerizer();
private readonly Oscillator oscillator = new Oscillator();
private readonly TriggerGenerator trigger = new TriggerGenerator();
private readonly StepSequencer sequencer = new StepSequencer(8);
private readonly Delay delay = new Delay { FeedbackAmount = new RangeValue(0, 1) { Value = 0.2f } };
private readonly Reverb reverb = new Reverb();
private readonly Clipper clipper = new Clipper { ClippingType = ClippingType.Soft, Threshold = new FixedValue(0.65f) };
private MidiDeviceInput midi;
private WaveOut waveOut;
public ObservableCollection<object> ControllableComponents { get; } = new ObservableCollection<object>();
public float TriggerLength
{
get { return trigger.TriggerLength.BaseValue; }
set { trigger.TriggerLength.BaseValue = value; }
}
private float[] scale = { 0, 2 / 12f, 4 / 12f, 5 / 12f, 7 / 12f, 9 / 12f, 11 / 12f };
private int[] seq = new int[8];
private void SetSequencer(int index, int value)
{
seq[index] = value;
var neg = value < 0;
var diff = Math.Abs(value);
var oct = diff / 7;
var note = diff % 7;
sequencer.ControlValues[index].BaseValue = neg ? -(oct + scale[note]) : oct + scale[note];
}
public int Sequencer0
{
get { return seq[0]; }
set { SetSequencer(0, value); }
}
public int Sequencer1
{
get { return seq[1]; }
set { SetSequencer(1, value); }
}
public int Sequencer2
{
get { return seq[2]; }
set { SetSequencer(2, value); }
}
public int Sequencer3
{
get { return seq[3]; }
set { SetSequencer(3, value); }
}
public int Sequencer4
{
get { return seq[4]; }
set { SetSequencer(4, value); }
}
public int Sequencer5
{
get { return seq[5]; }
set { SetSequencer(5, value); }
}
public int Sequencer6
{
get { return seq[6]; }
set { SetSequencer(6, value); }
}
public int Sequencer7
{
get { return seq[7]; }
set { SetSequencer(7, value); }
}
public void Play()
{
if (waveOut != null)
return;
waveOut = new WaveOut();
waveOut.DesiredLatency = 80;
waveOut.NumberOfBuffers = 4;
ControllableComponents.Add(lfo);
ControllableComponents.Add(vco1);
ControllableComponents.Add(vco2);
ControllableComponents.Add(mixer);
ControllableComponents.Add(triggerizer);
ControllableComponents.Add(filter);
ControllableComponents.Add(amp);
ControllableComponents.Add(delay);
ControllableComponents.Add(oscillator);
vco1.LfoInput = lfo.Output;
vco1.XModInput = vco2.Output;
vco2.LfoInput = lfo.Output;
mixer.Osc1 = vco1.Output;
mixer.Osc2 = vco2.Output;
midi = new MidiDeviceInput();
filter.Input = mixer.Output;
filter.TriggerInput = midi.GateOutput;//trigger;
filter.LfoInput = lfo.Output;
amp.LfoInput = lfo.Output;
amp.TriggerInput = midi.GateOutput;//trigger;
amp.Input = filter.Output;
sequencer.TriggerSource.Control = trigger;
vco1.ControlInput = midi.ControlOutput;//sequencer;
vco2.ControlInput = midi.ControlOutput;//sequencer;
delay.Input = amp.Output;
clipper.Input = delay;
reverb.Input = amp.Output;
trigger.Input = oscillator;
trigger.TriggerThreshold.BaseValue = 0;
trigger.TriggerLength.BaseValue = .5f;
//cutoff.Input = Osc1;
//cutoff.CutoffThreshold.Control = envelope;
waveOut.Init(new SampleToWaveProvider16(new SynthToSampleProvider(reverb)));
waveOut.Play();
midi.ControlEvent += MidiOnControlEvent;
}
enum BankSelect
{
Adsr,
Misc
}
BankSelect bank = BankSelect.Adsr;
private void MidiOnControlEvent(int i, float f)
{
bool handled = false;
switch (bank)
{
case BankSelect.Adsr:
handled = AdsrMidiControl(i, f);
break;
case BankSelect.Misc:
handled = MiscMidiControl(i, f);
break;
}
if (!handled)
switch (i)
{
case 97:
bank = BankSelect.Adsr;
break;
case 96:
bank = BankSelect.Misc;
break;
case 7:
amp.Gain = f;
break;
}
}
private bool AdsrMidiControl(int i, float f)
{
switch (i)
{
case 91:
filter.Attack = f * 5 + 0.01f;
break;
case 93:
filter.Decay = f * 3;
break;
case 74:
filter.Sustain = f * 2;
break;
case 71:
filter.Release = f * 3;
break;
case 73:
amp.Attack = f * 5 + 0.01f;
break;
case 75:
amp.Decay = f * 3;
break;
case 72:
amp.Sustain = f * 2;
break;
case 10:
amp.Release = f * 3;
break;
default:
return false;
}
return true;
}
private bool MiscMidiControl(int i, float f)
{
switch (i)
{
case 91:
mixer.Osc1Level = f;
break;
case 93:
mixer.Osc2Level = f;
break;
case 74:
mixer.NoiseLevel = f;
break;
case 71:
lfo.Frequency = f * 20;
break;
case 73:
filter.LfoLevel = f * 5;
break;
case 75:
filter.AdsrLevel = f * 5;
break;
case 72:
filter.Cutoff = f * 8 - 4;
break;
case 10:
filter.Resonance = f * 20 + 1;
break;
default:
return false;
}
return true;
}
public void Dispose()
{
waveOut.Dispose();
}
}
public class EnumDataConverter : IValueConverter
{
#region Implementation of IValueConverter
/// <summary>Converts a value. </summary>
/// <returns>A converted value. If the method returns null, the valid null value is used.</returns>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!value.GetType().IsEnum)
throw new InvalidOperationException("Target type must be an enum");
return value;
}
/// <summary>Converts a value. </summary>
/// <returns>A converted value. If the method returns null, the valid null value is used.</returns>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
#endregion
}
}
| |
using LiveLinq.List;
using LiveLinq.Dictionary;
namespace WpfApplication1.Common.ViewModel.Properties
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using System.Windows.Controls;
using LiveLinq;
using Reactive.ViewModels;
public class Validator<T> : IEnumerable
{
private bool calledYet = false;
private readonly ISubject<Func<IObservable<T>, IObservable<string>>> validateFunc = new Subject<Func<IObservable<T>, IObservable<string>>>();
public IObservable<Func<IObservable<T>, IObservable<string>>> ValidateFunc => this.validateFunc;
public void Add(Func<T, string> validate)
{
if (calledYet)
throw new InvalidOperationException("There can only be one validate");
calledYet = true;
validateFunc.OnNext(obs => obs.Select(val => validate(val)));
}
public void Add(Func<IObservable<T>, IObservable<string>> validate)
{
if (calledYet)
throw new InvalidOperationException("There can only be one validate");
calledYet = true;
validateFunc.OnNext(validate);
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
public class ViewModelProperty<T> : ReactiveDataErrorInfo, IViewModelProperty<T>, IObservable<T>, IObserver<T>
{
#region Backing fields
private T backupValue;
private T value;
private string error;
private int cleanValueHashCode;
private bool isDirty;
private bool isEditing;
private bool areDescendantsDirty;
private bool areDescendantsEditing;
#endregion
public ViewModelProperty()
{
DescendantsErrors = Errors.SelectMany((key, value) => value).ToReadOnlyObservableList();
Validator.ValidateFunc.Subscribe(func => this.Validate(func));
}
public Validator<T> Validator { get; } = new Validator<T>();
public IObservable<T> Source
{
set
{
value.Subscribe(this);
}
}
public T DefaultPropertyValue => Value;
public string GetDefaultPropertyName() => nameof(Value);
#region Validation
/// <summary>
/// Sets an observable stream of property errors for the Value property. If there the event is a Nothing,
/// then the Value property is considered valid. This will throw an <see cref="InvalidOperationException"/>
/// if the Value property has already had Validate called on it.
/// </summary>
/// <param name="propertyErrors">The observable error (or no error) for Value</param>
public virtual void Validate(IObservable<string> propertyErrors)
{
this.Validate(nameof(Value), propertyErrors);
}
/// <summary>
/// Sets an observable list of property errors for the Value property. If there aren't any property
/// errors, then the Value property is considered valid. This will throw an <see cref="InvalidOperationException"/>
/// if the Value property has already had Validate called on it.
/// </summary>
/// <param name="propertyErrors">The observable list of errors for Value</param>
public virtual void Validate(IListChanges<string> propertyErrors)
{
this.Validate(nameof(Value), propertyErrors);
}
#endregion
#region Public properties
public PropertyInfo Property { get; set; }
public bool EffectsDirtiness { get; set; } = true;
public bool EffectsIsEditing { get; set; } = true;
public bool EffectsValidation { get; set; } = true;
public bool StartsEditingWithParent { get; set; } = true;
public bool AutoEdit { get; set; } = true;
public IReadOnlyObservableList<string> DescendantsErrors { get; }
public bool AreDescendantsDirty
{
get
{
return this.areDescendantsDirty;
}
private set
{
if (this.areDescendantsDirty == value) return;
this.areDescendantsDirty = value;
this.OnPropertyChanged();
}
}
public bool AreDescendantsEditing
{
get
{
return this.areDescendantsEditing;
}
private set
{
if (this.areDescendantsEditing == value) return;
this.areDescendantsEditing = value;
this.OnPropertyChanged();
}
}
public bool IsEditing
{
get
{
return this.isEditing;
}
protected set
{
if (this.isEditing == value) return;
this.isEditing = value;
this.OnPropertyChanged();
this.AreDescendantsEditing = value;
}
}
public object ObjectValue
{
get
{
return this.Value;
}
set
{
this.Value = (T)value;
}
}
public T Value
{
get
{
return this.value;
}
set
{
if (this.value == null && value == null) return;
if (this.value != null && this.value.Equals(value)) return;
this.value = value;
this.OnPropertyChanged();
this.UpdateIsDirty();
if (AutoEdit)
this.BeginEdit();
}
}
public bool IsDirty
{
get
{
return this.isDirty;
}
protected set
{
if (this.isDirty == value) return;
this.isDirty = value;
this.OnPropertyChanged();
this.AreDescendantsDirty = value;
}
}
public string Error
{
get
{
return this.error;
}
protected set
{
if (this.error == value) return;
this.error = value;
this.OnPropertyChanged();
}
}
public int CleanValueHashCode
{
get
{
return this.cleanValueHashCode;
}
protected set
{
if (this.cleanValueHashCode == value) return;
this.cleanValueHashCode = value;
this.OnPropertyChanged();
this.UpdateIsDirty();
}
}
#endregion
#region IEditableObject
public void BeginEdit()
{
if (this.IsEditing) return;
this.backupValue = this.value;
this.IsEditing = true;
}
public void EndEdit()
{
if (!this.IsEditing) return;
this.IsEditing = false;
}
public void CancelEdit()
{
if (!this.IsEditing) return;
this.value = this.backupValue;
this.IsEditing = false;
}
public void RecursiveEndEdit()
{
this.EndEdit();
}
#endregion
#region Clean/dirty
private void UpdateIsDirty()
{
if (this.cleanValueHashCode == 0 && this.value == null)
{
this.IsDirty = false;
}
else if (this.value != null && this.cleanValueHashCode == this.value.GetHashCode())
{
this.IsDirty = false;
}
else
{
this.IsDirty = true;
}
}
public void CleanChildViewModels()
{
this.CleanValueHashCode = this.Value != null ? this.Value.GetHashCode() : 0;
}
#endregion
#region IObservable
public IDisposable Subscribe(IObserver<T> observer)
{
return this.ObserveProperty(x => x.Value).Subscribe(observer);
}
#endregion
#region IObserver
public void OnNext(T value)
{
Value = value;
}
public void OnError(Exception error)
{
Error = error.ToString();
}
public void OnCompleted()
{
}
#endregion
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.IO;
using fyiReporting.RDL;
namespace fyiReporting.RDL
{
///<summary>
/// Handle SQL configuration and connections
///</summary>
public class RdlEngineConfig
{
static internal IDictionary SqlEntries = null; // list of entries
static internal Dictionary<string, CustomReportItemEntry> CustomReportItemEntries = null;
static DateTime _InitFileCreationTime = DateTime.MinValue;
// Compression entries
static CompressionConfig _Compression = null;
static string _DirectoryLoadedFrom = null;
static public string DirectoryLoadedFrom
{
get
{
return _DirectoryLoadedFrom;
}
}
// initializes when no init available
static public void RdlEngineConfigInit()
{
string d1, d2;
d1 = AppDomain.CurrentDomain.BaseDirectory;
d2 = AppDomain.CurrentDomain.RelativeSearchPath;
if (d2 != null && d2 != string.Empty)
d2 = (d2.Contains(":") ? "" : AppDomain.CurrentDomain.BaseDirectory) + d2 + Path.DirectorySeparatorChar;
RdlEngineConfigInit(d1, d2);
}
// initialize configuration
static public void RdlEngineConfigInit(params string[] dirs)
{
bool bLoaded = false;
XmlDocument xDoc = new XmlDocument();
xDoc.PreserveWhitespace = false;
string file = null;
DateTime fileTime = DateTime.MinValue;
foreach (string dir in dirs)
{
if (dir == null)
continue;
file = dir + "RdlEngineConfig.xml";
try
{
FileInfo fi = new FileInfo(file);
fileTime = fi.CreationTime;
if (_InitFileCreationTime == fileTime && SqlEntries != null)
return; // we've already inited with this file
xDoc.Load(file);
bLoaded = true;
_DirectoryLoadedFrom = dir;
}
catch (Exception ex)
{ // can't do much about failures; no place to report them
System.Console.WriteLine("Error opening RdlEngineConfig.xml: {0}", ex.Message);
}
if (bLoaded)
break;
}
if (!bLoaded) // we couldn't find the configuration so we'll use internal one
{
if (SqlEntries != null) // we don't need to reinit with internal one
return;
xDoc.InnerXml = @"
<config>
<DataSources>
<DataSource>
<DataProvider>SQL</DataProvider>
<TableSelect>SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1</TableSelect>
<Interface>SQL</Interface>
</DataSource>
<DataSource>
<DataProvider>ODBC</DataProvider>
<TableSelect>SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1</TableSelect>
<Interface>SQL</Interface>
<ReplaceParameters>true</ReplaceParameters>
</DataSource>
<DataSource>
<DataProvider>OLEDB</DataProvider>
<TableSelect>SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1</TableSelect>
<Interface>SQL</Interface>
</DataSource>
<DataSource>
<DataProvider>XML</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.XmlConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
<DataSource>
<DataProvider>WebService</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.WebServiceConnection</ClassName>
<TableSelect></TableSelect>
<Interface>WebService</Interface>
</DataSource>
<DataSource>
<DataProvider>WebLog</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.LogConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
<DataSource>
<DataProvider>Text</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.TxtConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
<DataSource>
<DataProvider>FileDirectory</DataProvider>
<CodeModule>DataProviders.dll</CodeModule>
<ClassName>fyiReporting.Data.FileDirConnection</ClassName>
<TableSelect></TableSelect>
<Interface>File</Interface>
</DataSource>
</DataSources>
<Compression>
<CodeModule>ICSharpCode.SharpZipLib.dll</CodeModule>
<ClassName>ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream</ClassName>
<Finish>Finish</Finish>
<Enable>true</Enable>
</Compression>
<CustomReportItems>
<CustomReportItem>
<Type>BarCode</Type>
<CodeModule>RdlCri.dll</CodeModule>
<ClassName>fyiReporting.CRI.BarCode</ClassName>
</CustomReportItem>
</CustomReportItems>
</config>";
}
XmlNode xNode;
xNode = xDoc.SelectSingleNode("//config");
IDictionary dsDir = new ListDictionary();
Dictionary<string, CustomReportItemEntry> crieDir =
new Dictionary<string, CustomReportItemEntry>(); // list of entries
// Loop thru all the child nodes
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "DataSources":
GetDataSources(dsDir, xNodeLoop);
break;
case "Compression":
GetCompression(xNodeLoop);
break;
case "CustomReportItems":
GetCustomReportItems(crieDir, xNodeLoop);
break;
default:
break;
}
}
SqlEntries = dsDir;
CustomReportItemEntries = crieDir;
_InitFileCreationTime = fileTime; // save initialization time
return;
}
internal static CompressionConfig GetCompression()
{
if (SqlEntries == null)
RdlEngineConfigInit(); // init if necessary
return _Compression;
}
static void GetCompression(XmlNode xNode)
{
// loop thru looking to process all the datasource elements
string cm = null;
string cn = null;
string fn = null;
bool bEnable = true;
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "CodeModule":
if (xNodeLoop.InnerText.Length > 0)
cm = xNodeLoop.InnerText;
break;
case "ClassName":
if (xNodeLoop.InnerText.Length > 0)
cn = xNodeLoop.InnerText;
break;
case "Finish":
if (xNodeLoop.InnerText.Length > 0)
fn = xNodeLoop.InnerText;
break;
case "Enable":
if (xNodeLoop.InnerText.ToLower() == "false")
bEnable = false;
break;
}
}
if (bEnable)
_Compression = new CompressionConfig(cm, cn, fn);
else
_Compression = null;
}
static void GetDataSources(IDictionary dsDir, XmlNode xNode)
{
// loop thru looking to process all the datasource elements
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
if (xNodeLoop.Name != "DataSource")
continue;
GetDataSource(dsDir, xNodeLoop);
}
}
static void GetDataSource(IDictionary dsDir, XmlNode xNode)
{
string provider = null;
string codemodule = null;
string cname = null;
string inter = "SQL";
string tselect = null;
bool replaceparameters = false;
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "DataProvider":
provider = xNodeLoop.InnerText;
break;
case "CodeModule":
codemodule = xNodeLoop.InnerText;
break;
case "Interface":
inter = xNodeLoop.InnerText;
break;
case "ClassName":
cname = xNodeLoop.InnerText;
break;
case "TableSelect":
tselect = xNodeLoop.InnerText;
break;
case "ReplaceParameters":
if (xNodeLoop.InnerText.ToLower() == "true")
replaceparameters = true;
break;
default:
break;
}
}
if (provider == null)
return; // nothing to do if no provider specified
SqlConfigEntry sce;
try
{ // load the module early; saves problems with concurrency later
string msg = null;
Assembly la = null;
if (codemodule != null && cname != null)
{
// check to see if the DLL has been previously loaded
// many of the DataProvider done by fyiReporting are in a single code module
foreach (SqlConfigEntry sc in dsDir.Values)
{
if (sc.FileName == codemodule &&
sc.CodeModule != null)
{
la = sc.CodeModule;
break;
}
}
if (la == null)
la = XmlUtil.AssemblyLoadFrom(codemodule);
if (la == null)
msg = string.Format("{0} could not be loaded", codemodule);
}
sce = new SqlConfigEntry(provider, codemodule, cname, la, tselect, msg);
dsDir.Add(provider, sce);
}
catch (Exception e)
{ // keep exception; if this DataProvided is ever useed we will see the message
sce = new SqlConfigEntry(provider, codemodule, cname, null, tselect, e.Message);
dsDir.Add(provider, sce);
}
sce.ReplaceParameters = replaceparameters;
}
public static IDbConnection GetConnection(string provider, string cstring)
{
IDbConnection cn = null;
switch (provider.ToLower())
{
case "sql":
// can't connect unless information provided;
// when user wants to set the connection programmatically this they should do this
if (cstring.Length > 0)
cn = new SqlConnection(cstring);
break;
case "odbc":
cn = new OdbcConnection(cstring);
break;
case "oledb":
cn = new OleDbConnection(cstring);
break;
default:
if (SqlEntries == null) // if never initialized; we should init
RdlEngineConfigInit();
SqlConfigEntry sce = SqlEntries[provider] as SqlConfigEntry;
if (sce == null || sce.CodeModule == null)
{
if (sce != null && sce.ErrorMsg != null) // error during initialization??
throw new Exception(sce.ErrorMsg);
break;
}
object[] args = new object[] { cstring };
Assembly asm = sce.CodeModule;
object o = asm.CreateInstance(sce.ClassName, false,
BindingFlags.CreateInstance, null, args, null, null);
if (o == null)
throw new Exception(string.Format("Unable to create instance of '{0}' for provider '{1}'", sce.ClassName, provider));
cn = o as IDbConnection;
break;
}
return cn;
}
static public string GetTableSelect(string provider)
{
return GetTableSelect(provider, null);
}
static public bool DoParameterReplacement(string provider, IDbConnection cn)
{
if (SqlEntries == null)
RdlEngineConfigInit();
SqlConfigEntry sce = SqlEntries[provider] as SqlConfigEntry;
return sce == null ? false : sce.ReplaceParameters;
}
static public string GetTableSelect(string provider, IDbConnection cn)
{
if (SqlEntries == null)
RdlEngineConfigInit();
SqlConfigEntry sce = SqlEntries[provider] as SqlConfigEntry;
if (sce == null)
{
if (cn != null)
{
OdbcConnection oc = cn as OdbcConnection;
if (oc != null && oc.Driver.ToLower().IndexOf("my") >= 0) // not a good way but ...
return "show tables"; // mysql syntax is non-standard
}
return "SELECT TABLE_NAME, TABLE_TYPE FROM INFORMATION_SCHEMA.TABLES ORDER BY 2, 1";
}
if (cn != null)
{
OdbcConnection oc = cn as OdbcConnection;
if (oc != null && oc.Driver.ToLower().IndexOf("my") >= 0) // not a good way but ...
return "show tables"; // mysql syntax is non-standard
}
return sce.TableSelect;
}
static public string[] GetProviders()
{
if (SqlEntries == null)
RdlEngineConfigInit();
if (SqlEntries.Count == 0)
return null;
string[] items = new string[SqlEntries.Count];
int i = 0;
foreach (SqlConfigEntry sce in SqlEntries.Values)
{
items[i++] = sce.Provider;
}
return items;
}
static public string[] GetCustomReportTypes()
{
if (CustomReportItemEntries == null)
RdlEngineConfigInit();
if (CustomReportItemEntries.Count == 0)
return null;
string[] items = new string[CustomReportItemEntries.Count];
int i = 0;
foreach (CustomReportItemEntry crie in CustomReportItemEntries.Values)
{
items[i++] = crie.ItemName;
}
return items;
}
static void GetCustomReportItems(Dictionary<string, CustomReportItemEntry> crieDir, XmlNode xNode)
{
// loop thru looking to process all the datasource elements
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
if (xNodeLoop.Name != "CustomReportItem")
continue;
GetCustomReportItem(crieDir, xNodeLoop);
}
}
static void GetCustomReportItem(Dictionary<string, CustomReportItemEntry> crieDir, XmlNode xNode)
{
string friendlyTypeName = null;
string codemodule = null;
string classname = null;
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Type":
friendlyTypeName = xNodeLoop.InnerText;
break;
case "CodeModule":
codemodule = xNodeLoop.InnerText;
break;
case "ClassName":
classname = xNodeLoop.InnerText;
break;
default:
break;
}
}
if (friendlyTypeName == null)
return; // nothing to do if no provider specified
CustomReportItemEntry crie;
try
{ // load the module early; saves problems with concurrency later
string msg = null;
Type dotNetType = null;
Assembly la = null;
if (codemodule != null && classname != null)
{
// Check to see if previously loaded. Many CustomReportItems share same CodeModule.
Assembly[] allLoadedAss = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly ass in allLoadedAss)
if (ass.Location.Equals(codemodule, StringComparison.CurrentCultureIgnoreCase))
{
la = ass;
break;
}
if (la == null) // not previously loaded?
la = XmlUtil.AssemblyLoadFrom(codemodule);
if (la == null)
msg = string.Format("{0} could not be loaded", codemodule);
else
dotNetType = la.GetType(classname);
}
crie = new CustomReportItemEntry(friendlyTypeName, dotNetType, msg);
crieDir.Add(friendlyTypeName, crie);
}
catch (Exception e)
{ // keep exception; if this CustomReportItem is ever used we will see the message
crie = new CustomReportItemEntry(friendlyTypeName, null, e.Message);
crieDir.Add(friendlyTypeName, crie);
}
}
public static ICustomReportItem CreateCustomReportItem(string friendlyTypeName)
{
CustomReportItemEntry crie = null;
if (!CustomReportItemEntries.TryGetValue(friendlyTypeName, out crie))
throw new Exception(string.Format("{0} is not a known CustomReportItem type", friendlyTypeName));
if (crie.Type == null)
throw new Exception(crie.ErrorMsg ??
string.Format("{0} is not a known CustomReportItem type", friendlyTypeName));
ICustomReportItem item = (ICustomReportItem)Activator.CreateInstance(crie.Type);
return item;
}
public static void DeclareNewCustomReportItem(string itemName, Type type)
{
if (!typeof(ICustomReportItem).IsAssignableFrom(type))
throw new ArgumentException("The type does not implement the ICustomReportItem interface: " +
type == null ? "null" : type.Name);
if (CustomReportItemEntries == null)
RdlEngineConfigInit();
// Let's manage doublons, if any.
CustomReportItemEntry item;
if (!CustomReportItemEntries.TryGetValue(itemName, out item))
CustomReportItemEntries[itemName] = new CustomReportItemEntry(itemName, type, null);
else if (!item.Type.Equals(type))
throw new ArgumentException("A different type of CustomReportItem with the same has already been declared.");
}
}
internal class CompressionConfig
{
int _UseCompression = -1;
Assembly _Assembly = null;
string _CodeModule;
string _ClassName;
string _Finish;
MethodInfo _FinishMethodInfo; // if there is a finish method
string _ErrorMsg; // error encountered loading compression
internal CompressionConfig(string cm, string cn, string fn)
{
_CodeModule = cm;
_ClassName = cn;
_Finish = fn;
if (cm == null || cn == null || fn == null)
_UseCompression = 2;
}
internal bool CanCompress
{
get
{
if (_UseCompression >= 1) // we've already successfully inited
return true;
if (_UseCompression == 0) // we've tried to init and failed
return false;
Init(); // initialize compression
return _UseCompression == 1; // and return the status
}
}
internal void CallStreamFinish(Stream strm)
{
if (_UseCompression == 2)
{
strm.Close();
return;
}
if (_FinishMethodInfo == null)
return;
object returnVal = _FinishMethodInfo.Invoke(strm, null);
return;
}
internal byte[] GetArray(MemoryStream ms)
{
byte[] cmpData = ms.ToArray();
if (_UseCompression == 1)
return cmpData;
// we're using the MS routines; need to prefix by 2 bytes;
// see http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=97064
// see http://www.faqs.org/rfcs/rfc1950.html
// bit of magic:
// DeflateStream follows RFC1951, so the info I have is based on what I've read about RFC1950.
//First byte:
//Bits 0-3: those will always be 8 for the Deflate compression method.
//Bits 4-7: Our window size is 8K so I think this should be 5. The compression info value is
// log base 2 of the window size minus 8 => 8K = 2^13, so 13-8. If you're having problems with
// this, note that I've seen some comments indicating this is interpreted as max window size,
// so you might also try setting this to 7, corresponding to a window size of 32K.
//The next byte consists of some checksums and flags which may be optional?
byte[] wa = new byte[cmpData.Length + 2 + 4]; // length = data length + prefix length + checksum length
// These values don't actally work for all since some compressions go wrong???
// (may have been corrected: kas 9/16/08 but didn't do exhaustive tests since ziplib is better in any case)
wa[0] = 0x58; // 78
wa[1] = 0x85; // 9c
cmpData.CopyTo(wa, 2);
uint c = adler(cmpData); // this is the checksum
wa[2 + cmpData.Length + 0] = (byte)(c >> 24);
wa[2 + cmpData.Length + 1] = (byte)(c >> 16);
wa[2 + cmpData.Length + 2] = (byte)(c >> 8);
wa[2 + cmpData.Length + 3] = (byte)(c);
return wa;
}
/// <summary>
/// Adler 32 checksum routine comes from http://en.wikipedia.org/wiki/Adler-32
/// </summary>
/// <param name="cmpData"></param>
/// <returns></returns>
private uint adler(byte[] cmpData)
{
const int MOD_ADLER = 65521;
int len = cmpData.Length;
uint a = 1, b = 0;
int i = 0;
while (len > 0)
{
int tlen = len > 5552 ? 5552 : len;
len -= tlen;
do
{
a += cmpData[i++];
b += a;
} while (--tlen > 0);
a %= MOD_ADLER;
b %= MOD_ADLER;
}
return (b << 16) | a;
}
internal Stream GetStream(Stream str)
{
if (_UseCompression == 2)
{ // use the built-in compression .NET 2 provides
//System.IO.Compression.GZipStream cs =
// new System.IO.Compression.GZipStream(str, System.IO.Compression.CompressionMode.Compress);
System.IO.Compression.DeflateStream cs =
new System.IO.Compression.DeflateStream(str, System.IO.Compression.CompressionMode.Compress);
return cs;
}
if (_UseCompression == 0)
return null;
if (_UseCompression == -1) // make sure we're init'ed
{
Init();
if (_UseCompression != 1)
return null;
}
try
{
object[] args = new object[] { str };
Stream so = _Assembly.CreateInstance(_ClassName, false,
BindingFlags.CreateInstance, null, args, null, null) as Stream;
return so;
}
catch
{
return null;
}
}
internal string ErrorMsg
{
get { return _ErrorMsg; }
}
void Init()
{
lock (this)
{
if (_UseCompression != -1)
return;
_UseCompression = 0; // assume failure; and use the builtin MS routines
try
{
// Load the assembly
_Assembly = XmlUtil.AssemblyLoadFrom(_CodeModule);
// Load up a test stream to make sure it will work
object[] args = new object[] { new MemoryStream() };
Stream so = _Assembly.CreateInstance(_ClassName, false,
BindingFlags.CreateInstance, null, args, null, null) as Stream;
if (so != null)
{ // we've successfully inited
so.Close();
_UseCompression = 1;
}
else
_Assembly = null;
if (_Finish != null)
{
Type theClassType = so.GetType();
this._FinishMethodInfo = theClassType.GetMethod(_Finish);
}
}
catch (Exception e)
{
_ErrorMsg = e.InnerException == null ? e.Message : e.InnerException.Message;
_UseCompression = 0; // failure; force use the builtin MS routines
}
}
}
}
internal class SqlConfigEntry
{
internal string Provider;
internal Assembly CodeModule;
internal string ClassName;
internal string TableSelect;
internal string ErrorMsg;
internal bool ReplaceParameters;
internal string FileName;
internal SqlConfigEntry(string provider, string file, string cname, Assembly codemodule, string tselect, string msg)
{
Provider = provider;
CodeModule = codemodule;
ClassName = cname;
TableSelect = tselect;
ErrorMsg = msg;
ReplaceParameters = false;
FileName = file;
}
}
internal class CustomReportItemEntry
{
internal string ItemName;
internal Type Type;
internal string ErrorMsg;
internal CustomReportItemEntry(string itemName, Type type, string msg)
{
Type = type;
ItemName = itemName;
ErrorMsg = msg;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
#pragma warning disable 0414
namespace System.Reflection.Tests
{
public class MemberInfoTests
{
[Fact]
public void MetadataToken()
{
Assert.Equal(GetMetadataTokens(typeof(SampleClass)), GetMetadataTokens(typeof(SampleClass)));
Assert.Equal(GetMetadataTokens(new MemberInfoTests().GetType()), GetMetadataTokens(new MemberInfoTests().GetType()));
Assert.Equal(GetMetadataTokens(new Dictionary<int, string>().GetType()), GetMetadataTokens(new Dictionary<int, int>().GetType()));
Assert.Equal(GetMetadataTokens(typeof(int)), GetMetadataTokens(typeof(int)));
Assert.Equal(GetMetadataTokens(typeof(Dictionary<,>)), GetMetadataTokens(typeof(Dictionary<,>)));
}
[Fact]
public void ReflectedType()
{
Type t = typeof(Derived);
MemberInfo[] members = t.GetMembers();
foreach (MemberInfo member in members)
{
Assert.Equal(t, member.ReflectedType);
}
}
[Fact]
public void PropertyReflectedType()
{
Type t = typeof(Base);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.NotNull(p.SetMethod);
}
[Fact]
public void InheritedPropertiesHidePrivateAccessorMethods()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.Null(p.SetMethod);
}
[Fact]
public void GenericMethodsInheritTheReflectedTypeOfTheirTemplate()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
MethodInfo mooInst = moo.MakeGenericMethod(typeof(int));
Assert.Equal(t, mooInst.ReflectedType);
}
[Fact]
public void DeclaringMethodOfTypeParametersOfInheritedMethods()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(Base), reflectedTypeOfMoo1);
}
[Fact]
public void DeclaringMethodOfTypeParametersOfInheritedMethods2()
{
Type t = typeof(GDerived<int>);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1);
}
[Fact]
public void InheritedPropertyAccessors()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty));
MethodInfo getter = p.GetMethod;
MethodInfo setter = p.SetMethod;
Assert.Equal(t, getter.ReflectedType);
Assert.Equal(t, setter.ReflectedType);
}
[Fact]
public void InheritedEventAccessors()
{
Type t = typeof(Derived);
EventInfo e = t.GetEvent(nameof(Base.MyEvent));
MethodInfo adder = e.AddMethod;
MethodInfo remover = e.RemoveMethod;
Assert.Equal(t, adder.ReflectedType);
Assert.Equal(t, remover.ReflectedType);
}
[Fact]
public void ReflectedTypeIsPartOfIdentity()
{
Type b = typeof(Base);
Type d = typeof(Derived);
{
EventInfo e = b.GetEvent(nameof(Base.MyEvent));
EventInfo ei = d.GetEvent(nameof(Derived.MyEvent));
Assert.False(e.Equals(ei));
}
{
FieldInfo f = b.GetField(nameof(Base.MyField));
FieldInfo fi = d.GetField(nameof(Derived.MyField));
Assert.False(f.Equals(fi));
}
{
MethodInfo m = b.GetMethod(nameof(Base.Moo));
MethodInfo mi = d.GetMethod(nameof(Derived.Moo));
Assert.False(m.Equals(mi));
}
{
PropertyInfo p = b.GetProperty(nameof(Base.MyProperty));
PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty));
Assert.False(p.Equals(pi));
}
}
[Fact]
public void FieldInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
FieldInfo f = t.GetField(nameof(Base.MyField));
Assert.Equal(typeof(Derived), f.ReflectedType);
RuntimeFieldHandle h = f.FieldHandle;
FieldInfo f2 = FieldInfo.GetFieldFromHandle(h);
Assert.Equal(typeof(Base), f2.ReflectedType);
}
[Fact]
public void MethodInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
MethodInfo m = t.GetMethod(nameof(Base.Moo));
Assert.Equal(typeof(Derived), m.ReflectedType);
RuntimeMethodHandle h = m.MethodHandle;
MethodBase m2 = MethodBase.GetMethodFromHandle(h);
Assert.Equal(typeof(Base), m2.ReflectedType);
}
[Fact]
public void GetCustomAttributesData()
{
MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass");
Assert.Equal(1, m.Count());
foreach (CustomAttributeData cad in m[0].GetCustomAttributesData())
{
if (cad.AttributeType == typeof(ComVisibleAttribute))
{
ConstructorInfo c = cad.Constructor;
Assert.False(c.IsStatic);
Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType);
ParameterInfo[] p = c.GetParameters();
Assert.Equal(1, p.Length);
Assert.Equal(typeof(bool), p[0].ParameterType);
return;
}
}
Assert.True(false, "Expected to find ComVisibleAttribute");
}
public static IEnumerable<object[]> EqualityOperator_TestData()
{
yield return new object[] { typeof(SampleClass) };
yield return new object[] { new MemberInfoTests().GetType() };
yield return new object[] { typeof(int) };
yield return new object[] { typeof(Dictionary<,>) };
}
[Theory]
[MemberData(nameof(EqualityOperator_TestData))]
public void EqualityOperator_Equal_ReturnsTrue(Type type)
{
MemberInfo[] members1 = GetOrderedMembers(type);
MemberInfo[] members2 = GetOrderedMembers(type);
Assert.Equal(members1.Length, members2.Length);
for (int i = 0; i < members1.Length; i++)
{
Assert.True(members1[i] == members2[i]);
Assert.False(members1[i] != members2[i]);
}
}
private MemberInfo[] GetMembers(Type type)
{
return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
private IEnumerable<int> GetMetadataTokens(Type type)
{
return type.GetTypeInfo().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.HasMetadataToken() ? m.MetadataToken : 0);
}
private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray();
private class Base
{
public event Action MyEvent { add { } remove { } }
#pragma warning disable 0649
public int MyField;
#pragma warning restore 0649
public int MyProperty { get; set; }
public int MyProperty1 { get; private set; }
public int MyProperty2 { private get; set; }
public void Moo<M>() { }
}
private class Derived : Base
{
}
private class GBase<T>
{
public void Moo<M>() { }
}
private class GDerived<T> : GBase<T>
{
}
#pragma warning disable 0067, 0169
#pragma warning disable 0067, 0169
[ComVisible(false)]
public class SampleClass
{
public int PublicField;
private int PrivateField;
public SampleClass(bool y) { }
private SampleClass(int x) { }
public void PublicMethod() { }
private void PrivateMethod() { }
public int PublicProp { get; set; }
private int PrivateProp { get; set; }
public event EventHandler PublicEvent;
private event EventHandler PrivateEvent;
}
#pragma warning restore 0067, 0169
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using SwqlStudio.Metadata;
namespace SwqlStudio
{
internal class TreeNodesBuilder
{
public EntityGroupingMode EntityGroupingMode { get; set; }
private readonly Font _defaultFont;
private Font NodeFont(IObsoleteMetadata entity) => entity.IsObsolete ? new Font(_defaultFont, FontStyle.Strikeout) : null;
public TreeNodesBuilder(Font defaultFont)
{
_defaultFont = defaultFont;
}
private TreeNodeWithConnectionInfo MakeEntityTreeNode(IMetadataProvider provider, Entity entity)
{
var entityNode = CreateEntityNode(provider, entity);
// Add keys
AddPropertiesToNode(provider, entityNode, entity.Properties.Where(c => c.IsKey));
// Add the simple Properties
AddPropertiesToNode(provider, entityNode, entity.Properties.Where(c => !c.IsInherited && !c.IsNavigable && !c.IsKey));
// Add the inherited Properties
AddPropertiesToNode(provider, entityNode, entity.Properties.Where(c => c.IsInherited && !c.IsNavigable && !c.IsKey));
// Add the Navigation Properties
AddPropertiesToNode(provider, entityNode, entity.Properties.Where(c => c.IsNavigable));
AddVerbsToNode(entityNode, entity, provider);
return entityNode;
}
private void AddVerbsToNode(TreeNode entityNode, Entity entity, IMetadataProvider provider)
{
foreach (var verb in entity.Verbs.OrderBy(v => v.Name))
{
TreeNode verbNode = CreateNode(provider, verb.Name, ImageKeys.Verb, verb);
verbNode.ToolTipText = DocumentationBuilder.ToToolTip(verb);
var argumentsPlaceholder = new ArgumentsPlaceholderTreeNode(verb, provider);
verbNode.Nodes.Add(argumentsPlaceholder);
verbNode.NodeFont = NodeFont(verb);
entityNode.Nodes.Add(verbNode);
}
}
private void AddPropertiesToNode(IMetadataProvider provider, TreeNode entityNode, IEnumerable<Property> properties)
{
foreach (Property property in properties.OrderBy(c => c.Name))
{
string name = DocumentationBuilder.ToNodeText(property);
var imageKey = ImageKeys.GetImageKey(property);
TreeNode node = CreateNode(provider, name, imageKey, property);
node.ToolTipText = DocumentationBuilder.ToToolTip(property, property);
node.NodeFont = NodeFont(property);
entityNode.Nodes.Add(node);
}
}
public static void RebuildVerbArguments(TreeNode verbNode, IMetadataProvider provider)
{
verbNode.Nodes.Clear();
var verb = verbNode.Tag as Verb;
foreach (var argument in provider.GetVerbArguments(verb))
{
var argNode = CreateVerbArgumentNode(provider, argument);
verbNode.Nodes.Add(argNode);
}
}
private TreeNodeWithConnectionInfo[] MakeEntityTreeNodes(IMetadataProvider provider, IEnumerable<Entity> entities)
{
return entities.Select(e => MakeEntityTreeNode(provider, e)).ToArray();
}
public void RebuildDatabaseNode(TreeNode databaseNode, IMetadataProvider provider)
{
databaseNode.Nodes.Clear();
switch (EntityGroupingMode)
{
case EntityGroupingMode.Flat:
databaseNode.Nodes.AddRange(MakeEntityTreeNodes(provider, provider.Tables.OrderBy(e => e.FullName)));
break;
case EntityGroupingMode.ByNamespace:
foreach (var group in provider.Tables.GroupBy(e => e.Namespace).OrderBy(g => g.Key))
{
TreeNode[] entityNodes = MakeEntityTreeNodes(provider, group.OrderBy(e => e.FullName));
var namespaceNode = CreateNamespaceNode(provider, entityNodes, group.Key);
databaseNode.Nodes.Add(namespaceNode);
}
break;
case EntityGroupingMode.ByBaseType:
foreach (var group in provider.Tables.Where(e => e.BaseEntity != null).GroupBy(
e => e.BaseEntity,
(key, group) => new { Key = key, Entities = group }).OrderBy(item => item.Key.FullName))
{
TreeNode[] childNodes = MakeEntityTreeNodes(provider, group.Entities.OrderBy(e => e.FullName));
var entityNode = CreateEntityNode(provider, group.Key, childNodes);
databaseNode.Nodes.Add(entityNode);
}
break;
case EntityGroupingMode.ByHierarchy:
GroupByHierarchy(provider, databaseNode);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private void GroupByHierarchy(IMetadataProvider provider, TreeNode baseNode)
{
Entity baseEntity = baseNode != null ? baseNode.Tag as Entity : null;
var entities = provider.Tables.Where(e => baseEntity == null ? e.BaseEntity == null : e.BaseEntity == baseEntity);
if (entities.Any())
{
TreeNode[] childNodes = MakeEntityTreeNodes(provider, entities.OrderBy(e => e.FullName));
baseNode.Nodes.AddRange(childNodes);
if (baseEntity != null)
{
baseNode.Text = DocumentationBuilder.ToBaseNodeText(baseNode, childNodes.Length);
}
foreach (var node in childNodes)
{
GroupByHierarchy(provider, node);
}
if (baseEntity == null)
{
foreach (var node in childNodes)
{
node.Expand();
}
baseNode.Expand();
}
}
}
public static TreeNodeWithConnectionInfo CreateDatabaseNode(TreeView treeView, IMetadataProvider provider,
ConnectionInfo connection)
{
TreeNodeWithConnectionInfo node = CreateNode(provider, provider.Name, ImageKeys.Database, provider);
node.Name = node.Text;
treeView.Nodes.Add(node);
treeView.SelectedNode = node;
return node;
}
public static TreeNodeWithConnectionInfo CreateNamespaceNode(IMetadataProvider provider, TreeNode[] entityNodes, string namespaceName)
{
var name = DocumentationBuilder.ToNodeText(namespaceName, entityNodes.Length);
var namespaceNode = CreateNode(provider, name, ImageKeys.Namespace, namespaceName);
namespaceNode.Nodes.AddRange(entityNodes);
return namespaceNode;
}
private static TreeNodeWithConnectionInfo CreateEntityNode(IMetadataProvider provider, Entity entity, TreeNode[] childNodes)
{
var imageKey = !entity.IsAbstract ? ImageKeys.BaseType : ImageKeys.BaseTypeAbstract;
var name = DocumentationBuilder.ToNodeText(entity.FullName, childNodes.Length);
var entityNode = CreateNode(provider, name, imageKey, entity);
entityNode.Nodes.AddRange(childNodes);
return entityNode;
}
private TreeNodeWithConnectionInfo CreateEntityNode(IMetadataProvider provider, Entity entity)
{
var imageKey = ImageKeys.GetImageKey(entity);
var node = CreateNode(provider, entity.FullName, imageKey, entity);
node.ToolTipText = DocumentationBuilder.ToToolTip(provider.ConnectionInfo, entity);
node.NodeFont = NodeFont(entity);
return node;
}
private static TreeNodeWithConnectionInfo CreateVerbArgumentNode(IMetadataProvider provider, VerbArgument argument)
{
string text = DocumentationBuilder.ToNodeText(argument);
var argNode = CreateNode(provider, text, ImageKeys.Argument, argument);
argNode.ToolTipText = DocumentationBuilder.ToToolTip(argument);
return argNode;
}
private static TreeNodeWithConnectionInfo CreateNode(IMetadataProvider provider, string name, string imageKey, object data)
{
var node = new TreeNodeWithConnectionInfo(name, provider);
node.ImageKey = imageKey;
node.SelectedImageKey = imageKey;
node.Tag = data;
return node;
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus
{
/// <summary>
/// Display story text in a visual novel style dialog box.
/// </summary>
public class SayDialog : MonoBehaviour
{
[Tooltip("Duration to fade dialogue in/out")]
[SerializeField] protected float fadeDuration = 0.25f;
[Tooltip("The continue button UI object")]
[SerializeField] protected Button continueButton;
[Tooltip("The canvas UI object")]
[SerializeField] protected Canvas dialogCanvas;
[Tooltip("The name text UI object")]
[SerializeField] protected Text nameText;
[Tooltip("The story text UI object")]
[SerializeField] protected Text storyText;
public virtual Text StoryText { get { return storyText; } }
[Tooltip("The character UI object")]
[SerializeField] protected Image characterImage;
public virtual Image CharacterImage { get { return characterImage; } }
[Tooltip("Adjust width of story text when Character Image is displayed (to avoid overlapping)")]
[SerializeField] protected bool fitTextWithImage = true;
[Tooltip("Close any other open Say Dialogs when this one is active")]
[SerializeField] protected bool closeOtherDialogs;
protected float startStoryTextWidth;
protected float startStoryTextInset;
protected WriterAudio writerAudio;
protected Writer writer;
protected CanvasGroup canvasGroup;
protected bool fadeWhenDone = true;
protected float targetAlpha = 0f;
protected float fadeCoolDownTimer = 0f;
protected Sprite currentCharacterImage;
// Most recent speaking character
protected static Character speakingCharacter;
protected StringSubstituter stringSubstituter = new StringSubstituter();
// Cache active Say Dialogs to avoid expensive scene search
protected static List<SayDialog> activeSayDialogs = new List<SayDialog>();
protected void Awake()
{
if (!activeSayDialogs.Contains(this))
{
activeSayDialogs.Add(this);
}
}
protected void OnDestroy()
{
activeSayDialogs.Remove(this);
}
protected Writer GetWriter()
{
if (writer != null)
{
return writer;
}
writer = GetComponent<Writer>();
if (writer == null)
{
writer = gameObject.AddComponent<Writer>();
}
return writer;
}
protected CanvasGroup GetCanvasGroup()
{
if (canvasGroup != null)
{
return canvasGroup;
}
canvasGroup = GetComponent<CanvasGroup>();
if (canvasGroup == null)
{
canvasGroup = gameObject.AddComponent<CanvasGroup>();
}
return canvasGroup;
}
protected WriterAudio GetWriterAudio()
{
if (writerAudio != null)
{
return writerAudio;
}
writerAudio = GetComponent<WriterAudio>();
if (writerAudio == null)
{
writerAudio = gameObject.AddComponent<WriterAudio>();
}
return writerAudio;
}
protected void Start()
{
// Dialog always starts invisible, will be faded in when writing starts
GetCanvasGroup().alpha = 0f;
// Add a raycaster if none already exists so we can handle dialog input
GraphicRaycaster raycaster = GetComponent<GraphicRaycaster>();
if (raycaster == null)
{
gameObject.AddComponent<GraphicRaycaster>();
}
// It's possible that SetCharacterImage() has already been called from the
// Start method of another component, so check that no image has been set yet.
// Same for nameText.
if (nameText != null && nameText.text == "")
{
SetCharacterName("", Color.white);
}
if (currentCharacterImage == null)
{
// Character image is hidden by default.
SetCharacterImage(null);
}
}
protected void OnEnable()
{
// We need to update the cached list every time the Say Dialog is enabled
// due to an initialization order issue after loading scenes.
stringSubstituter.CacheSubstitutionHandlers();
}
protected virtual void LateUpdate()
{
UpdateAlpha();
if (continueButton != null)
{
continueButton.gameObject.SetActive( GetWriter().IsWaitingForInput );
}
}
protected virtual void UpdateAlpha()
{
if (GetWriter().IsWriting)
{
targetAlpha = 1f;
fadeCoolDownTimer = 0.1f;
}
else if (fadeWhenDone && Mathf.Approximately(fadeCoolDownTimer, 0f))
{
targetAlpha = 0f;
}
else
{
// Add a short delay before we start fading in case there's another Say command in the next frame or two.
// This avoids a noticeable flicker between consecutive Say commands.
fadeCoolDownTimer = Mathf.Max(0f, fadeCoolDownTimer - Time.deltaTime);
}
CanvasGroup canvasGroup = GetCanvasGroup();
if (fadeDuration <= 0f)
{
canvasGroup.alpha = targetAlpha;
}
else
{
float delta = (1f / fadeDuration) * Time.deltaTime;
float alpha = Mathf.MoveTowards(canvasGroup.alpha, targetAlpha, delta);
canvasGroup.alpha = alpha;
if (alpha <= 0f)
{
// Deactivate dialog object once invisible
gameObject.SetActive(false);
}
}
}
protected virtual void ClearStoryText()
{
if (storyText != null)
{
storyText.text = "";
}
}
#region Public members
/// <summary>
/// Currently active Say Dialog used to display Say text
/// </summary>
public static SayDialog ActiveSayDialog { get; set; }
/// <summary>
/// Returns a SayDialog by searching for one in the scene or creating one if none exists.
/// </summary>
public static SayDialog GetSayDialog()
{
if (ActiveSayDialog == null)
{
SayDialog sd = null;
// Use first active Say Dialog in the scene (if any)
if (activeSayDialogs.Count > 0)
{
sd = activeSayDialogs[0];
}
if (sd != null)
{
ActiveSayDialog = sd;
}
if (ActiveSayDialog == null)
{
// Auto spawn a say dialog object from the prefab
GameObject prefab = Resources.Load<GameObject>("Prefabs/SayDialog");
if (prefab != null)
{
GameObject go = Instantiate(prefab) as GameObject;
go.SetActive(false);
go.name = "SayDialog";
ActiveSayDialog = go.GetComponent<SayDialog>();
}
}
}
return ActiveSayDialog;
}
/// <summary>
/// Stops all active portrait tweens.
/// </summary>
public static void StopPortraitTweens()
{
// Stop all tweening portraits
var activeCharacters = Character.ActiveCharacters;
for (int i = 0; i < activeCharacters.Count; i++)
{
var c = activeCharacters[i];
if (c.State.portraitImage != null)
{
if (LeanTween.isTweening(c.State.portraitImage.gameObject))
{
LeanTween.cancel(c.State.portraitImage.gameObject, true);
PortraitController.SetRectTransform(c.State.portraitImage.rectTransform, c.State.position);
if (c.State.dimmed == true)
{
c.State.portraitImage.color = new Color(0.5f, 0.5f, 0.5f, 1f);
}
else
{
c.State.portraitImage.color = Color.white;
}
}
}
}
}
/// <summary>
/// Sets the active state of the Say Dialog gameobject.
/// </summary>
public virtual void SetActive(bool state)
{
gameObject.SetActive(state);
}
/// <summary>
/// Sets the active speaking character.
/// </summary>
/// <param name="character">The active speaking character.</param>
public virtual void SetCharacter(Character character)
{
if (character == null)
{
if (characterImage != null)
{
characterImage.gameObject.SetActive(false);
}
if (nameText != null)
{
nameText.text = "";
}
speakingCharacter = null;
}
else
{
var prevSpeakingCharacter = speakingCharacter;
speakingCharacter = character;
// Dim portraits of non-speaking characters
var activeStages = Stage.ActiveStages;
for (int i = 0; i < activeStages.Count; i++)
{
var stage = activeStages[i];
if (stage.DimPortraits)
{
var charactersOnStage = stage.CharactersOnStage;
for (int j = 0; j < charactersOnStage.Count; j++)
{
var c = charactersOnStage[j];
if (prevSpeakingCharacter != speakingCharacter)
{
if (c != null && !c.Equals(speakingCharacter))
{
stage.SetDimmed(c, true);
}
else
{
stage.SetDimmed(c, false);
}
}
}
}
}
string characterName = character.NameText;
if (characterName == "")
{
// Use game object name as default
characterName = character.GetObjectName();
}
SetCharacterName(characterName, character.NameColor);
}
}
/// <summary>
/// Sets the character image to display on the Say Dialog.
/// </summary>
public virtual void SetCharacterImage(Sprite image)
{
if (characterImage == null)
{
return;
}
if (image != null)
{
characterImage.sprite = image;
characterImage.gameObject.SetActive(true);
currentCharacterImage = image;
}
else
{
characterImage.gameObject.SetActive(false);
if (startStoryTextWidth != 0)
{
storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth);
}
}
// Adjust story text box to not overlap image rect
if (fitTextWithImage &&
storyText != null &&
characterImage.gameObject.activeSelf)
{
if (Mathf.Approximately(startStoryTextWidth, 0f))
{
startStoryTextWidth = storyText.rectTransform.rect.width;
startStoryTextInset = storyText.rectTransform.offsetMin.x;
}
// Clamp story text to left or right depending on relative position of the character image
if (storyText.rectTransform.position.x < characterImage.rectTransform.position.x)
{
storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
else
{
storyText.rectTransform.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right,
startStoryTextInset,
startStoryTextWidth - characterImage.rectTransform.rect.width);
}
}
}
/// <summary>
/// Sets the character name to display on the Say Dialog.
/// Supports variable substitution e.g. John {$surname}
/// </summary>
public virtual void SetCharacterName(string name, Color color)
{
if (nameText != null)
{
var subbedName = stringSubstituter.SubstituteStrings(name);
nameText.text = subbedName;
nameText.color = color;
}
}
/// <summary>
/// Write a line of story text to the Say Dialog. Starts coroutine automatically.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual void Say(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, AudioClip voiceOverClip, Action onComplete)
{
StartCoroutine(DoSay(text, clearPrevious, waitForInput, fadeWhenDone, stopVoiceover, voiceOverClip, onComplete));
}
/// <summary>
/// Write a line of story text to the Say Dialog. Must be started as a coroutine.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param>
/// <param name="waitForInput">Wait for player input before continuing once text is written.</param>
/// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param>
/// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param>
/// <param name="voiceOverClip">Voice over audio clip to play.</param>
/// <param name="onComplete">Callback to execute when writing and player input have finished.</param>
public virtual IEnumerator DoSay(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, AudioClip voiceOverClip, Action onComplete)
{
var writer = GetWriter();
if (writer.IsWriting || writer.IsWaitingForInput)
{
writer.Stop();
while (writer.IsWriting || writer.IsWaitingForInput)
{
yield return null;
}
}
if (closeOtherDialogs)
{
for (int i = 0; i < activeSayDialogs.Count; i++)
{
var sd = activeSayDialogs[i];
if (sd.gameObject != gameObject)
{
sd.SetActive(false);
}
}
}
gameObject.SetActive(true);
this.fadeWhenDone = fadeWhenDone;
// Voice over clip takes precedence over a character sound effect if provided
AudioClip soundEffectClip = null;
if (voiceOverClip != null)
{
WriterAudio writerAudio = GetWriterAudio();
writerAudio.OnVoiceover(voiceOverClip);
}
else if (speakingCharacter != null)
{
soundEffectClip = speakingCharacter.SoundEffect;
}
yield return StartCoroutine(writer.Write(text, clearPrevious, waitForInput, stopVoiceover, soundEffectClip, onComplete));
}
/// <summary>
/// Tell the Say Dialog to fade out once writing and player input have finished.
/// </summary>
public virtual bool FadeWhenDone { set { fadeWhenDone = value; } }
/// <summary>
/// Stop the Say Dialog while its writing text.
/// </summary>
public virtual void Stop()
{
fadeWhenDone = true;
GetWriter().Stop();
}
/// <summary>
/// Stops writing text and clears the Say Dialog.
/// </summary>
public virtual void Clear()
{
ClearStoryText();
// Kill any active write coroutine
StopAllCoroutines();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using aspnetcoredemo.Models;
using aspnetcoredemo.Services;
using aspnetcoredemo.ViewModels.Account;
namespace aspnetcoredemo.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction(nameof(ManageController.Index), "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
//
// PlaybackControllerService.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Hyena;
using Hyena.Collections;
using Banshee.Base;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.MediaEngine;
namespace Banshee.PlaybackController
{
public class PlaybackControllerService : IRequiredService, ICanonicalPlaybackController,
IPlaybackController, IPlaybackControllerService
{
private enum Direction
{
Next,
Previous
}
private IStackProvider<TrackInfo> previous_stack;
private IStackProvider<TrackInfo> next_stack;
private TrackInfo current_track;
private TrackInfo prior_track;
private TrackInfo changing_to_track;
private bool raise_started_after_transition = false;
private bool transition_track_started = false;
private bool last_was_skipped = true;
private int consecutive_errors;
private uint error_transition_id;
private DateTime source_auto_set_at = DateTime.MinValue;
private string shuffle_mode;
private PlaybackRepeatMode repeat_mode;
private bool stop_when_finished = false;
private PlayerEngineService player_engine;
private ITrackModelSource source;
private ITrackModelSource next_source;
private event PlaybackControllerStoppedHandler dbus_stopped;
event PlaybackControllerStoppedHandler IPlaybackControllerService.Stopped {
add { dbus_stopped += value; }
remove { dbus_stopped -= value; }
}
public event EventHandler Stopped;
public event EventHandler SourceChanged;
public event EventHandler NextSourceChanged;
public event EventHandler TrackStarted;
public event EventHandler Transition;
public event EventHandler<EventArgs<string>> ShuffleModeChanged;
public event EventHandler<EventArgs<PlaybackRepeatMode>> RepeatModeChanged;
public PlaybackControllerService ()
{
InstantiateStacks ();
player_engine = ServiceManager.PlayerEngine;
player_engine.PlayWhenIdleRequest += OnPlayerEnginePlayWhenIdleRequest;
player_engine.ConnectEvent (OnPlayerEvent,
PlayerEvent.RequestNextTrack |
PlayerEvent.EndOfStream |
PlayerEvent.StartOfStream |
PlayerEvent.StateChange |
PlayerEvent.Error,
true);
ServiceManager.SourceManager.ActiveSourceChanged += delegate {
ITrackModelSource active_source = ServiceManager.SourceManager.ActiveSource as ITrackModelSource;
if (active_source != null && source_auto_set_at == source_set_at && !player_engine.IsPlaying ()) {
Source = active_source;
source_auto_set_at = source_set_at;
}
};
}
protected virtual void InstantiateStacks ()
{
previous_stack = new PlaybackControllerDatabaseStack ();
next_stack = new PlaybackControllerDatabaseStack ();
}
private void OnPlayerEnginePlayWhenIdleRequest (object o, EventArgs args)
{
ITrackModelSource next_source = NextSource;
if (next_source != null && next_source.TrackModel.Selection.Count > 0) {
Source = NextSource;
CancelErrorTransition ();
CurrentTrack = next_source.TrackModel[next_source.TrackModel.Selection.FirstIndex];
QueuePlayTrack ();
} else {
Next ();
}
}
private void OnPlayerEvent (PlayerEventArgs args)
{
switch (args.Event) {
case PlayerEvent.StartOfStream:
CurrentTrack = player_engine.CurrentTrack;
consecutive_errors = 0;
break;
case PlayerEvent.EndOfStream:
EosTransition ();
break;
case PlayerEvent.Error:
if (++consecutive_errors >= 5) {
consecutive_errors = 0;
player_engine.Close (false);
OnStopped ();
break;
}
CancelErrorTransition ();
// TODO why is this so long? any reason not to be instantaneous?
error_transition_id = Application.RunTimeout (250, delegate {
EosTransition ();
RequestTrackHandler ();
return true;
});
break;
case PlayerEvent.StateChange:
if (((PlayerEventStateChangeArgs)args).Current != PlayerState.Loading) {
break;
}
TrackInfo track = player_engine.CurrentTrack;
if (changing_to_track != track && track != null) {
CurrentTrack = track;
}
changing_to_track = null;
if (!raise_started_after_transition) {
transition_track_started = false;
OnTrackStarted ();
} else {
transition_track_started = true;
}
break;
case PlayerEvent.RequestNextTrack:
RequestTrackHandler ();
break;
}
}
private void CancelErrorTransition ()
{
if (error_transition_id > 0) {
Application.IdleTimeoutRemove (error_transition_id);
error_transition_id = 0;
}
}
private bool EosTransition ()
{
player_engine.IncrementLastPlayed ();
return true;
}
private bool RequestTrackHandler ()
{
if (!StopWhenFinished) {
if (RepeatMode == PlaybackRepeatMode.RepeatSingle) {
QueuePlayTrack ();
} else {
last_was_skipped = false;
Next (RepeatMode == PlaybackRepeatMode.RepeatAll, false);
}
} else {
OnStopped ();
}
StopWhenFinished = false;
return false;
}
public void First ()
{
CancelErrorTransition ();
Source = NextSource;
// This and OnTransition() below commented out b/c of BGO #524556
//raise_started_after_transition = true;
if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).First ()) {
} else {
((IBasicPlaybackController)this).First ();
}
//OnTransition ();
}
public void Next ()
{
Next (RepeatMode == PlaybackRepeatMode.RepeatAll, true);
}
public void Next (bool restart)
{
Next (restart, true);
}
public void Next (bool restart, bool changeImmediately)
{
CancelErrorTransition ();
Source = NextSource;
raise_started_after_transition = true;
if (changeImmediately) {
player_engine.IncrementLastPlayed ();
}
if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).Next (restart, changeImmediately)) {
} else {
((IBasicPlaybackController)this).Next (restart, changeImmediately);
}
OnTransition ();
}
public void Previous ()
{
Previous (RepeatMode == PlaybackRepeatMode.RepeatAll);
}
public void Previous (bool restart)
{
CancelErrorTransition ();
Source = NextSource;
raise_started_after_transition = true;
player_engine.IncrementLastPlayed ();
if (Source is IBasicPlaybackController && ((IBasicPlaybackController)Source).Previous (restart)) {
} else {
((IBasicPlaybackController)this).Previous (restart);
}
OnTransition ();
}
public void RestartOrPrevious ()
{
RestartOrPrevious (RepeatMode == PlaybackRepeatMode.RepeatAll);
}
public void RestartOrPrevious (bool restart)
{
const int delay = 4000; // ms
if (player_engine.Position < delay) {
Previous ();
} else {
var track = player_engine.CurrentTrack;
if (track != null) {
player_engine.Close ();
player_engine.OpenPlay (track);
}
}
}
bool IBasicPlaybackController.First ()
{
if (Source.Count > 0) {
if (ShuffleMode == "off") {
CurrentTrack = Source.TrackModel[0];
player_engine.OpenPlay (CurrentTrack);
} else {
((IBasicPlaybackController)this).Next (false, true);
}
}
return true;
}
bool IBasicPlaybackController.Next (bool restart, bool changeImmediately)
{
if (CurrentTrack != null) {
previous_stack.Push (CurrentTrack);
}
CurrentTrack = CalcNextTrack (Direction.Next, restart);
if (!changeImmediately) {
// A RequestNextTrack event should always result in SetNextTrack being called. null is acceptable.
player_engine.SetNextTrack (CurrentTrack);
} else if (CurrentTrack != null) {
QueuePlayTrack ();
}
return true;
}
bool IBasicPlaybackController.Previous (bool restart)
{
if (CurrentTrack != null && previous_stack.Count > 0) {
next_stack.Push (current_track);
}
CurrentTrack = CalcNextTrack (Direction.Previous, restart);
if (CurrentTrack != null) {
QueuePlayTrack ();
}
return true;
}
private TrackInfo CalcNextTrack (Direction direction, bool restart)
{
if (direction == Direction.Previous) {
if (previous_stack.Count > 0) {
return previous_stack.Pop ();
}
} else if (direction == Direction.Next) {
if (next_stack.Count > 0) {
return next_stack.Pop ();
}
}
return QueryTrack (direction, restart);
}
private TrackInfo QueryTrack (Direction direction, bool restart)
{
Log.DebugFormat ("Querying model for track to play in {0}:{1} mode", ShuffleMode, direction);
return ShuffleMode == "off"
? QueryTrackLinear (direction, restart)
: QueryTrackRandom (ShuffleMode, restart);
}
private TrackInfo QueryTrackLinear (Direction direction, bool restart)
{
if (Source.TrackModel.Count == 0)
return null;
int index = Source.TrackModel.IndexOf (PriorTrack);
// Clear the PriorTrack after using it, it's only meant to be used for a single Query
PriorTrack = null;
if (index == -1) {
return Source.TrackModel[0];
} else {
index += (direction == Direction.Next ? 1 : -1);
if (index >= 0 && index < Source.TrackModel.Count) {
return Source.TrackModel[index];
} else if (!restart) {
return null;
} else if (index < 0) {
return Source.TrackModel[Source.TrackModel.Count - 1];
} else {
return Source.TrackModel[0];
}
}
}
private TrackInfo QueryTrackRandom (string shuffle_mode, bool restart)
{
var track_shuffler = Source.TrackModel as Banshee.Collection.Database.DatabaseTrackListModel;
TrackInfo track = track_shuffler == null
? Source.TrackModel.GetRandom (source_set_at)
: track_shuffler.GetRandom (source_set_at, shuffle_mode, restart, last_was_skipped, Banshee.Collection.Database.Shuffler.Playback);
// Reset to default of true, only ever set to false by EosTransition
last_was_skipped = true;
return track;
}
private void QueuePlayTrack ()
{
changing_to_track = CurrentTrack;
player_engine.OpenPlay (CurrentTrack);
}
protected virtual void OnStopped ()
{
player_engine.IncrementLastPlayed ();
EventHandler handler = Stopped;
if (handler != null) {
handler (this, EventArgs.Empty);
}
PlaybackControllerStoppedHandler dbus_handler = dbus_stopped;
if (dbus_handler != null) {
dbus_handler ();
}
}
protected virtual void OnTransition ()
{
EventHandler handler = Transition;
if (handler != null) {
handler (this, EventArgs.Empty);
}
if (raise_started_after_transition && transition_track_started) {
OnTrackStarted ();
}
raise_started_after_transition = false;
transition_track_started = false;
}
protected virtual void OnSourceChanged ()
{
EventHandler handler = SourceChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected void OnNextSourceChanged ()
{
EventHandler handler = NextSourceChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
protected virtual void OnTrackStarted ()
{
EventHandler handler = TrackStarted;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
public TrackInfo CurrentTrack {
get { return current_track; }
protected set { current_track = value; }
}
public TrackInfo PriorTrack {
get { return prior_track ?? CurrentTrack; }
set { prior_track = value; }
}
protected DateTime source_set_at = DateTime.MinValue;
public ITrackModelSource Source {
get {
if (source == null && ServiceManager.SourceManager.DefaultSource is ITrackModelSource) {
return (ITrackModelSource)ServiceManager.SourceManager.DefaultSource;
}
return source;
}
set {
if (source != value) {
NextSource = value;
source = value;
source_set_at = DateTime.Now;
OnSourceChanged ();
}
}
}
public ITrackModelSource NextSource {
get { return next_source ?? Source; }
set {
if (next_source != value) {
next_source = value;
OnNextSourceChanged ();
if (!player_engine.IsPlaying ()) {
Source = next_source;
}
}
}
}
public string ShuffleMode {
get { return shuffle_mode; }
set {
shuffle_mode = value;
// If the user changes the shuffle mode, she expects the "Next"
// button to behave according to the new selection. See bgo#528809
next_stack.Clear ();
var handler = ShuffleModeChanged;
if (handler != null) {
handler (this, new EventArgs<string> (shuffle_mode));
}
}
}
public PlaybackRepeatMode RepeatMode {
get { return repeat_mode; }
set {
repeat_mode = value;
EventHandler<EventArgs<PlaybackRepeatMode>> handler = RepeatModeChanged;
if (handler != null) {
handler (this, new EventArgs<PlaybackRepeatMode> (repeat_mode));
}
}
}
public bool StopWhenFinished {
get { return stop_when_finished; }
set { stop_when_finished = value; }
}
string IService.ServiceName {
get { return "PlaybackController"; }
}
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using System.Text;
using Encog.Util;
using Encog.Util.CSV;
namespace Encog.ML.Data.Buffer.CODEC
{
/// <summary>
/// A CODEC used to read/write data from/to a CSV data file. There are two
/// constructors provided, one is for reading, the other for writing. Make sure
/// you use the correct one for your intended purpose.
///
/// This CODEC is typically used with the BinaryDataLoader, to load external data
/// into the Encog binary training format.
/// </summary>
public class CSVDataCODEC : IDataSetCODEC
{
/// <summary>
/// The external CSV file.
/// </summary>
private readonly String _file;
/// <summary>
/// The CSV format to use.
/// </summary>
private readonly CSVFormat _format;
/// <summary>
/// True, if headers are present in the CSV file.
/// </summary>
private readonly bool _headers;
/// <summary>
/// The size of the ideal data.
/// </summary>
private int _idealCount;
/// <summary>
/// The size of the input data.
/// </summary>
private int _inputCount;
/// <summary>
/// A file used to output the CSV file.
/// </summary>
private TextWriter _output;
/// <summary>
/// The utility to assist in reading the CSV file.
/// </summary>
private ReadCSV _readCSV;
/// <summary>
/// Should a significance column be expected.
/// </summary>
private bool _significance;
/// <summary>
/// Create a CODEC to load data from CSV to binary.
/// </summary>
/// <param name="file">The CSV file to load.</param>
/// <param name="format">The format that the CSV file is in.</param>
/// <param name="headers">True, if there are headers.</param>
/// <param name="inputCount">The number of input columns.</param>
/// <param name="idealCount">The number of ideal columns.</param>
/// <param name="significance">Is there a signficance column.</param>
public CSVDataCODEC(
String file,
CSVFormat format,
bool headers,
int inputCount, int idealCount, bool significance)
{
if (_inputCount != 0)
{
throw new BufferedDataError(
"To export CSV, you must use the CSVDataCODEC constructor that does not specify input or ideal sizes.");
}
_file = file;
_format = format;
_inputCount = inputCount;
_idealCount = idealCount;
_headers = headers;
_significance = significance;
}
/// <summary>
/// Constructor to create CSV from binary.
/// </summary>
/// <param name="file">The CSV file to create.</param>
/// <param name="format">The format for that CSV file.</param>
public CSVDataCODEC(String file, CSVFormat format, bool significance)
{
_file = file;
_format = format;
_significance = significance;
}
#region IDataSetCODEC Members
/// <inheritdoc/>
public bool Read(double[] input, double[] ideal, ref double significance)
{
if (_readCSV.Next())
{
int index = 0;
for (int i = 0; i < input.Length; i++)
{
input[i] = _readCSV.GetDouble(index++);
}
for (int i = 0; i < ideal.Length; i++)
{
ideal[i] = _readCSV.GetDouble(index++);
}
if( _significance )
{
significance = _readCSV.GetDouble(index++);
}
else
{
significance = 1;
}
return true;
}
return false;
}
/// <inheritdoc/>
public void Write(double[] input, double[] ideal, double significance)
{
if (_significance)
{
var record = new double[input.Length + ideal.Length + 1];
EngineArray.ArrayCopy(input, record);
EngineArray.ArrayCopy(ideal, 0, record, input.Length, ideal.Length);
record[record.Length - 1] = significance;
var result = new StringBuilder();
NumberList.ToList(_format, result, record);
_output.WriteLine(result.ToString());
}
else
{
var record = new double[input.Length + ideal.Length];
EngineArray.ArrayCopy(input, record);
EngineArray.ArrayCopy(ideal, 0, record, input.Length, ideal.Length);
var result = new StringBuilder();
NumberList.ToList(_format, result, record);
_output.WriteLine(result.ToString());
}
}
/// <summary>
/// Prepare to write to a CSV file.
/// </summary>
/// <param name="recordCount">The total record count, that will be written.</param>
/// <param name="inputSize">The input size.</param>
/// <param name="idealSize">The ideal size.</param>
public void PrepareWrite(
int recordCount,
int inputSize,
int idealSize)
{
try
{
_inputCount = inputSize;
_idealCount = idealSize;
_output = new StreamWriter(new FileStream(_file, FileMode.Create));
}
catch (IOException ex)
{
throw new BufferedDataError(ex);
}
}
/// <summary>
/// Prepare to read from the CSV file.
/// </summary>
public void PrepareRead()
{
if (_inputCount == 0)
{
throw new BufferedDataError(
"To import CSV, you must use the CSVDataCODEC constructor that specifies input and ideal sizes.");
}
_readCSV = new ReadCSV(_file, _headers,
_format);
}
/// <inheritDoc/>
public int InputSize
{
get { return _inputCount; }
}
/// <inheritDoc/>
public int IdealSize
{
get { return _idealCount; }
}
/// <inheritDoc/>
public void Close()
{
if (_readCSV != null)
{
_readCSV.Close();
_readCSV = null;
}
if (_output != null)
{
_output.Close();
_output = null;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// DefaultSecurityRulesOperations operations.
/// </summary>
internal partial class DefaultSecurityRulesOperations : IServiceOperations<NetworkManagementClient>, IDefaultSecurityRulesOperations
{
/// <summary>
/// Initializes a new instance of the DefaultSecurityRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DefaultSecurityRulesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Gets all default security rules in a network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get the specified default network security rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='defaultSecurityRuleName'>
/// The name of the default security rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<SecurityRule>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string defaultSecurityRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkSecurityGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkSecurityGroupName");
}
if (defaultSecurityRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "defaultSecurityRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkSecurityGroupName", networkSecurityGroupName);
tracingParameters.Add("defaultSecurityRuleName", defaultSecurityRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/defaultSecurityRules/{defaultSecurityRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkSecurityGroupName}", System.Uri.EscapeDataString(networkSecurityGroupName));
_url = _url.Replace("{defaultSecurityRuleName}", System.Uri.EscapeDataString(defaultSecurityRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<SecurityRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SecurityRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all default security rules in a network security group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<SecurityRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<SecurityRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SecurityRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Runtime.Serialization;
using System.Web;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceModel.Serialization;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Extensions;
using HttpRequestExtensions = ServiceStack.WebHost.Endpoints.Extensions.HttpRequestExtensions;
using HttpRequestWrapper = ServiceStack.WebHost.Endpoints.Extensions.HttpRequestWrapper;
using HttpResponseWrapper = ServiceStack.WebHost.Endpoints.Extensions.HttpResponseWrapper;
namespace ServiceStack.WebHost.Endpoints.Support
{
public abstract class EndpointHandlerBase
: IServiceStackHttpHandler, IHttpHandler
{
internal static readonly ILog Log = LogManager.GetLogger(typeof(EndpointHandlerBase));
internal static readonly Dictionary<byte[], byte[]> NetworkInterfaceIpv4Addresses = new Dictionary<byte[], byte[]>();
internal static readonly byte[][] NetworkInterfaceIpv6Addresses = new byte[0][];
public string RequestName { get; set; }
static EndpointHandlerBase()
{
try
{
IPAddressExtensions.GetAllNetworkInterfaceIpv4Addresses().ForEach((x, y) => NetworkInterfaceIpv4Addresses[x.GetAddressBytes()] = y.GetAddressBytes());
NetworkInterfaceIpv6Addresses = IPAddressExtensions.GetAllNetworkInterfaceIpv6Addresses().ConvertAll(x => x.GetAddressBytes()).ToArray();
}
catch (Exception ex)
{
Log.Warn("Failed to retrieve IP Addresses, some security restriction features may not work: " + ex.Message, ex);
}
}
public EndpointAttributes HandlerAttributes { get; set; }
public bool IsReusable
{
get { return false; }
}
public abstract object CreateRequest(IHttpRequest request, string operationName);
public abstract object GetResponse(IHttpRequest httpReq, IHttpResponse httpRes, object request);
public virtual void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
{
throw new NotImplementedException();
}
public static object DeserializeHttpRequest(Type operationType, IHttpRequest httpReq, string contentType)
{
var httpMethod = httpReq.HttpMethod;
var queryString = httpReq.QueryString;
if (httpMethod == HttpMethods.Get || httpMethod == HttpMethods.Delete || httpMethod == HttpMethods.Options)
{
try
{
return KeyValueDataContractDeserializer.Instance.Parse(queryString, operationType);
}
catch (Exception ex)
{
var msg = "Could not deserialize '{0}' request using KeyValueDataContractDeserializer: '{1}'.\nError: '{2}'"
.Fmt(operationType, queryString, ex);
throw new SerializationException(msg);
}
}
var isFormData = httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData);
if (isFormData)
{
try
{
return KeyValueDataContractDeserializer.Instance.Parse(httpReq.FormData, operationType);
}
catch (Exception ex)
{
throw new SerializationException("Error deserializing FormData: " + httpReq.FormData, ex);
}
}
var request = CreateContentTypeRequest(httpReq, operationType, contentType);
return request;
}
protected static object CreateContentTypeRequest(IHttpRequest httpReq, Type requestType, string contentType)
{
try
{
if (!string.IsNullOrEmpty(contentType) && httpReq.ContentLength > 0)
{
var deserializer = EndpointHost.AppHost.ContentTypeFilters.GetStreamDeserializer(contentType);
if (deserializer != null)
{
return deserializer(requestType, httpReq.InputStream);
}
}
}
catch (Exception ex)
{
var msg = "Could not deserialize '{0}' request using {1}'\nError: {2}"
.Fmt(contentType, requestType, ex);
throw new SerializationException(msg);
}
return requestType.CreateInstance(); //Return an empty DTO, even for empty request bodies
}
protected static object GetCustomRequestFromBinder(IHttpRequest httpReq, Type requestType)
{
Func<IHttpRequest, object> requestFactoryFn;
(ServiceManager ?? EndpointHost.ServiceManager).ServiceController.RequestTypeFactoryMap.TryGetValue(
requestType, out requestFactoryFn);
return requestFactoryFn != null ? requestFactoryFn(httpReq) : null;
}
protected static bool DefaultHandledRequest(HttpListenerContext context)
{
return false;
}
protected static bool DefaultHandledRequest(HttpContext context)
{
return false;
}
public virtual void ProcessRequest(HttpContext context)
{
var operationName = this.RequestName ?? context.Request.GetOperationName();
if (string.IsNullOrEmpty(operationName)) return;
if (DefaultHandledRequest(context)) return;
ProcessRequest(
new HttpRequestWrapper(operationName, context.Request),
new HttpResponseWrapper(context.Response),
operationName);
}
public virtual void ProcessRequest(HttpListenerContext context)
{
var operationName = this.RequestName ?? context.Request.GetOperationName();
if (string.IsNullOrEmpty(operationName)) return;
if (DefaultHandledRequest(context)) return;
ProcessRequest(
new HttpListenerRequestWrapper(operationName, context.Request),
new HttpListenerResponseWrapper(context.Response),
operationName);
}
public static ServiceManager ServiceManager { get; set; }
public static Type GetOperationType(string operationName)
{
return ServiceManager != null
? ServiceManager.Metadata.GetOperationType(operationName)
: EndpointHost.Metadata.GetOperationType(operationName);
}
protected static object ExecuteService(object request, EndpointAttributes endpointAttributes,
IHttpRequest httpReq, IHttpResponse httpRes)
{
return EndpointHost.ExecuteService(request, endpointAttributes, httpReq, httpRes);
}
public EndpointAttributes GetEndpointAttributes(System.ServiceModel.OperationContext operationContext)
{
if (!EndpointHost.Config.EnableAccessRestrictions) return default(EndpointAttributes);
var portRestrictions = default(EndpointAttributes);
var ipAddress = GetIpAddress(operationContext);
portRestrictions |= HttpRequestExtensions.GetAttributes(ipAddress);
//TODO: work out if the request was over a secure channel
//portRestrictions |= request.IsSecureConnection ? PortRestriction.Secure : PortRestriction.InSecure;
return portRestrictions;
}
public static IPAddress GetIpAddress(System.ServiceModel.OperationContext context)
{
#if !MONO
var prop = context.IncomingMessageProperties;
if (context.IncomingMessageProperties.ContainsKey(System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name))
{
var endpoint = prop[System.ServiceModel.Channels.RemoteEndpointMessageProperty.Name]
as System.ServiceModel.Channels.RemoteEndpointMessageProperty;
if (endpoint != null)
{
return IPAddress.Parse(endpoint.Address);
}
}
#endif
return null;
}
protected static void AssertOperationExists(string operationName, Type type)
{
if (type == null)
{
throw new NotImplementedException(
string.Format("The operation '{0}' does not exist for this service", operationName));
}
}
protected void HandleException(IHttpRequest httpReq, IHttpResponse httpRes, string operationName, Exception ex)
{
var errorMessage = string.Format("Error occured while Processing Request: {0}", ex.Message);
Log.Error(errorMessage, ex);
try
{
EndpointHost.ExceptionHandler(httpReq, httpRes, operationName, ex);
}
catch (Exception writeErrorEx)
{
//Exception in writing to response should not hide the original exception
Log.Info("Failed to write error to response: {0}", writeErrorEx);
//rethrow the original exception
throw ex;
}
finally
{
httpRes.EndRequest(skipHeaders: true);
}
}
protected bool AssertAccess(IHttpRequest httpReq, IHttpResponse httpRes, Feature feature, string operationName)
{
if (operationName == null)
throw new ArgumentNullException("operationName");
if (EndpointHost.Config.EnableFeatures != Feature.All)
{
if (!EndpointHost.Config.HasFeature(feature))
{
EndpointHost.Config.HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Feature Not Available");
return false;
}
}
var format = feature.ToFormat();
if (!EndpointHost.Metadata.CanAccess(httpReq, format, operationName))
{
EndpointHost.Config.HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Service Not Available");
return false;
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Need to use "extern alias", because both the writer and reader define types with same names.
extern alias reader;
extern alias writer;
using System;
using System.IO;
using System.Linq;
using Xunit;
using Reader = reader.Internal.Metadata.NativeFormat;
using Writer = writer.Internal.Metadata.NativeFormat.Writer;
using TypeAttributes = System.Reflection.TypeAttributes;
using MethodAttributes = System.Reflection.MethodAttributes;
using CallingConventions = System.Reflection.CallingConventions;
namespace System.Private.Reflection.Metadata.Tests
{
/// <summary>
/// Tests for metadata roundtripping. We emit a metadata blob, and read it back
/// to check if it has expected values.
/// </summary>
public class RoundTripTests
{
/// <summary>
/// Builds a graph of simple metadata test data.
/// </summary>
private static Writer.ScopeDefinition BuildSimpleTestData()
{
// Scope for System.Runtime, 4.0.0.0
var systemRuntimeScope = new Writer.ScopeDefinition
{
Name = (Writer.ConstantStringValue)"System.Runtime",
MajorVersion = 4,
};
// Root namespace (".")
var rootNamespaceDefinition = new Writer.NamespaceDefinition
{
ParentScopeOrNamespace = systemRuntimeScope,
};
systemRuntimeScope.RootNamespaceDefinition = rootNamespaceDefinition;
// The <Module> type
var moduleTypeDefinition = new Writer.TypeDefinition
{
Flags = TypeAttributes.Abstract | TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"<Module>",
NamespaceDefinition = rootNamespaceDefinition,
};
rootNamespaceDefinition.TypeDefinitions.Add(moduleTypeDefinition);
// System namespace
var systemNamespaceDefinition = new Writer.NamespaceDefinition
{
Name = (Writer.ConstantStringValue)"System",
ParentScopeOrNamespace = rootNamespaceDefinition,
};
rootNamespaceDefinition.NamespaceDefinitions.Add(systemNamespaceDefinition);
// System.Object type
var objectType = new Writer.TypeDefinition
{
Flags = TypeAttributes.Public | TypeAttributes.SequentialLayout,
Name = (Writer.ConstantStringValue)"Object",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(objectType);
// System.ValueType type
var valueTypeType = new Writer.TypeDefinition
{
BaseType = objectType,
Flags = TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"ValueType",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(valueTypeType);
// System.Void type
var voidType = new Writer.TypeDefinition
{
BaseType = valueTypeType,
Flags = TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"Void",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(voidType);
// System.String type
var stringType = new Writer.TypeDefinition
{
BaseType = objectType,
Flags = TypeAttributes.Public,
Name = (Writer.ConstantStringValue)"String",
NamespaceDefinition = systemNamespaceDefinition
};
systemNamespaceDefinition.TypeDefinitions.Add(stringType);
// System.Object..ctor() method
var objectCtorMethod = new Writer.Method
{
Flags = MethodAttributes.Public
| MethodAttributes.RTSpecialName
| MethodAttributes.SpecialName,
Name = (Writer.ConstantStringValue)".ctor",
Signature = new Writer.MethodSignature
{
CallingConvention = CallingConventions.HasThis,
ReturnType = new Writer.ReturnTypeSignature
{
Type = voidType
}
},
};
objectType.Methods.Add(objectCtorMethod);
// System.String..ctor() method
var stringCtorMethod = new Writer.Method
{
Flags = MethodAttributes.Public
| MethodAttributes.RTSpecialName
| MethodAttributes.SpecialName,
Name = (Writer.ConstantStringValue)".ctor",
Signature = new Writer.MethodSignature
{
CallingConvention = CallingConventions.HasThis,
ReturnType = new Writer.ReturnTypeSignature
{
Type = voidType
}
},
};
stringType.Methods.Add(stringCtorMethod);
return systemRuntimeScope;
}
[Fact]
public unsafe static void TestSimpleRoundTripping()
{
var wr = new Writer.MetadataWriter();
wr.ScopeDefinitions.Add(BuildSimpleTestData());
var ms = new MemoryStream();
wr.Write(ms);
fixed (byte* pBuffer = ms.ToArray())
{
var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);
// Validate the System.Runtime scope
Reader.ScopeDefinitionHandle scopeHandle = rd.ScopeDefinitions.Single();
Reader.ScopeDefinition systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
Assert.Equal(4, systemRuntimeScope.MajorVersion);
Assert.Equal("System.Runtime", systemRuntimeScope.Name.GetConstantStringValue(rd).Value);
// Validate the root namespace and <Module> type
Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
Assert.Equal(1, rootNamespace.TypeDefinitions.Count());
Reader.TypeDefinition moduleType = rootNamespace.TypeDefinitions.Single().GetTypeDefinition(rd);
Assert.Equal("<Module>", moduleType.Name.GetConstantStringValue(rd).Value);
Assert.Equal(1, rootNamespace.NamespaceDefinitions.Count());
// Validate the System namespace
Reader.NamespaceDefinition systemNamespace = rootNamespace.NamespaceDefinitions.Single().GetNamespaceDefinition(rd);
Assert.Equal(4, systemNamespace.TypeDefinitions.Count());
foreach (var typeHandle in systemNamespace.TypeDefinitions)
{
Reader.TypeDefinition type = typeHandle.GetTypeDefinition(rd);
string typeName = type.Name.GetConstantStringValue(rd).Value;
string baseTypeName = null;
if (!type.BaseType.IsNull(rd))
{
baseTypeName = type.BaseType.ToTypeDefinitionHandle(rd).GetTypeDefinition(rd).Name.GetConstantStringValue(rd).Value;
}
switch (typeName)
{
case "Object":
Assert.Null(baseTypeName);
Assert.Equal(1, type.Methods.Count());
break;
case "Void":
Assert.Equal("ValueType", baseTypeName);
Assert.Equal(0, type.Methods.Count());
break;
case "String":
Assert.Equal("Object", baseTypeName);
Assert.Equal(1, type.Methods.Count());
break;
case "ValueType":
Assert.Equal("Object", baseTypeName);
Assert.Equal(0, type.Methods.Count());
break;
default:
throw new NotImplementedException();
}
}
}
}
[Fact]
public unsafe static void TestCommonTailOptimization()
{
var wr = new Writer.MetadataWriter();
wr.ScopeDefinitions.Add(BuildSimpleTestData());
var ms = new MemoryStream();
wr.Write(ms);
fixed (byte* pBuffer = ms.ToArray())
{
var rd = new Reader.MetadataReader((IntPtr)pBuffer, (int)ms.Length);
Reader.ScopeDefinitionHandle scopeHandle = rd.ScopeDefinitions.Single();
Reader.ScopeDefinition systemRuntimeScope = scopeHandle.GetScopeDefinition(rd);
Reader.NamespaceDefinition rootNamespace = systemRuntimeScope.RootNamespaceDefinition.GetNamespaceDefinition(rd);
Reader.NamespaceDefinition systemNamespace =
rootNamespace.NamespaceDefinitions.Single(
ns => ns.GetNamespaceDefinition(rd).Name.StringEquals("System", rd)
).GetNamespaceDefinition(rd);
// This validates the common tail optimization.
// Since both System.Object and System.String define a default constructor and the
// records are structurally equivalent, there should only be one metadata record
// representing a default .ctor in the blob.
Reader.TypeDefinition objectType = systemNamespace.TypeDefinitions.Single(
t => t.GetTypeDefinition(rd).Name.StringEquals("Object", rd)
).GetTypeDefinition(rd);
Reader.TypeDefinition stringType = systemNamespace.TypeDefinitions.Single(
t => t.GetTypeDefinition(rd).Name.StringEquals("String", rd)
).GetTypeDefinition(rd);
Reader.MethodHandle objectCtor = objectType.Methods.Single();
Reader.MethodHandle stringCtor = stringType.Methods.Single();
Assert.True(objectCtor.Equals(stringCtor));
}
}
}
}
| |
// 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 sys = System;
namespace Google.Cloud.Dialogflow.V2
{
/// <summary>Resource name for the <c>Session</c> resource.</summary>
public sealed partial class SessionName : gax::IResourceName, sys::IEquatable<SessionName>
{
/// <summary>The possible contents of <see cref="SessionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/agent/sessions/{session}</c>.</summary>
ProjectSession = 1,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </summary>
ProjectEnvironmentUserSession = 2,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </summary>
ProjectLocationSession = 3,
/// <summary>
/// A resource name with pattern
/// <c>
/// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </summary>
ProjectLocationEnvironmentUserSession = 4,
}
private static gax::PathTemplate s_projectSession = new gax::PathTemplate("projects/{project}/agent/sessions/{session}");
private static gax::PathTemplate s_projectEnvironmentUserSession = new gax::PathTemplate("projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}");
private static gax::PathTemplate s_projectLocationSession = new gax::PathTemplate("projects/{project}/locations/{location}/agent/sessions/{session}");
private static gax::PathTemplate s_projectLocationEnvironmentUserSession = new gax::PathTemplate("projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}");
/// <summary>Creates a <see cref="SessionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SessionName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static SessionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SessionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern <c>projects/{project}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectSession(string projectId, string sessionId) =>
new SessionName(ResourceNameType.ProjectSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectEnvironmentUserSession(string projectId, string environmentId, string userId, string sessionId) =>
new SessionName(ResourceNameType.ProjectEnvironmentUserSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectLocationSession(string projectId, string locationId, string sessionId) =>
new SessionName(ResourceNameType.ProjectLocationSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Creates a <see cref="SessionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns>
public static SessionName FromProjectLocationEnvironmentUserSession(string projectId, string locationId, string environmentId, string userId, string sessionId) =>
new SessionName(ResourceNameType.ProjectLocationEnvironmentUserSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </returns>
public static string Format(string projectId, string sessionId) => FormatProjectSession(projectId, sessionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/sessions/{session}</c>.
/// </returns>
public static string FormatProjectSession(string projectId, string sessionId) =>
s_projectSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>.
/// </returns>
public static string FormatProjectEnvironmentUserSession(string projectId, string environmentId, string userId, string sessionId) =>
s_projectEnvironmentUserSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/sessions/{session}</c>.
/// </returns>
public static string FormatProjectLocationSession(string projectId, string locationId, string sessionId) =>
s_projectLocationSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SessionName"/> with pattern
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// .
/// </returns>
public static string FormatProjectLocationEnvironmentUserSession(string projectId, string locationId, string environmentId, string userId, string sessionId) =>
s_projectLocationEnvironmentUserSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)));
/// <summary>Parses the given resource name string into a new <see cref="SessionName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SessionName"/> if successful.</returns>
public static SessionName Parse(string sessionName) => Parse(sessionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SessionName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SessionName"/> if successful.</returns>
public static SessionName Parse(string sessionName, bool allowUnparsed) =>
TryParse(sessionName, allowUnparsed, out SessionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sessionName, out SessionName result) => TryParse(sessionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/agent/sessions/{session}</c></description></item>
/// <item>
/// <description>
/// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// <item>
/// <description><c>projects/{project}/locations/{location}/agent/sessions/{session}</c></description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string sessionName, bool allowUnparsed, out SessionName result)
{
gax::GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName));
gax::TemplatedResourceName resourceName;
if (s_projectSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectSession(resourceName[0], resourceName[1]);
return true;
}
if (s_projectEnvironmentUserSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectEnvironmentUserSession(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (s_projectLocationSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectLocationSession(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectLocationEnvironmentUserSession.TryParseName(sessionName, out resourceName))
{
result = FromProjectLocationEnvironmentUserSession(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(sessionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SessionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string environmentId = null, string locationId = null, string projectId = null, string sessionId = null, string userId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
EnvironmentId = environmentId;
LocationId = locationId;
ProjectId = projectId;
SessionId = sessionId;
UserId = userId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SessionName"/> class from the component parts of pattern
/// <c>projects/{project}/agent/sessions/{session}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param>
public SessionName(string projectId, string sessionId) : this(ResourceNameType.ProjectSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Environment</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string EnvironmentId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Session</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string SessionId { get; }
/// <summary>
/// The <c>User</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string UserId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectSession: return s_projectSession.Expand(ProjectId, SessionId);
case ResourceNameType.ProjectEnvironmentUserSession: return s_projectEnvironmentUserSession.Expand(ProjectId, EnvironmentId, UserId, SessionId);
case ResourceNameType.ProjectLocationSession: return s_projectLocationSession.Expand(ProjectId, LocationId, SessionId);
case ResourceNameType.ProjectLocationEnvironmentUserSession: return s_projectLocationEnvironmentUserSession.Expand(ProjectId, LocationId, EnvironmentId, UserId, SessionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SessionName);
/// <inheritdoc/>
public bool Equals(SessionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SessionName a, SessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SessionName a, SessionName b) => !(a == b);
}
public partial class DetectIntentRequest
{
/// <summary>
/// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property.
/// </summary>
public SessionName SessionAsSessionName
{
get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true);
set => Session = value?.ToString() ?? "";
}
}
public partial class StreamingDetectIntentRequest
{
/// <summary>
/// <see cref="SessionName"/>-typed view over the <see cref="Session"/> resource name property.
/// </summary>
public SessionName SessionAsSessionName
{
get => string.IsNullOrEmpty(Session) ? null : SessionName.Parse(Session, allowUnparsed: true);
set => Session = value?.ToString() ?? "";
}
}
}
| |
// 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 Xunit;
using Xunit.Abstractions;
namespace System.Slices.Tests
{
public class UsageScenarioTests
{
private readonly ITestOutputHelper output;
public UsageScenarioTests(ITestOutputHelper output)
{
this.output = output;
}
private struct MyByte
{
public MyByte(byte value)
{
Value = value;
}
public byte Value { get; private set; }
}
[Theory]
[InlineData(new byte[] { })]
[InlineData(new byte[] { 0 })]
[InlineData(new byte[] { 0, 1 })]
[InlineData(new byte[] { 0, 1, 2 })]
[InlineData(new byte[] { 0, 1, 2, 3 })]
[InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })]
public void CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
Span<byte> span = new Span<byte>(array);
Assert.Equal(array.Length, span.Length);
Assert.NotSame(array, span.CreateArray());
Assert.False(span.Equals(array));
Span<byte>.Enumerator it = span.GetEnumerator();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
span.Slice(i).Write<byte>(unchecked((byte)(array[i] + 1)));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
span.Slice(i).Write<MyByte>(unchecked(new MyByte((byte)(array[i] + 1))));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
Assert.False(it.MoveNext());
it.Reset();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
}
Assert.False(it.MoveNext());
}
[Theory]
[InlineData(new byte[] { })]
[InlineData(new byte[] { 0 })]
[InlineData(new byte[] { 0, 1 })]
[InlineData(new byte[] { 0, 1, 2 })]
[InlineData(new byte[] { 0, 1, 2, 3 })]
[InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })]
public void CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(array);
Assert.Equal(array.Length, span.Length);
Assert.NotSame(array, span.CreateArray());
Assert.False(span.Equals(array));
ReadOnlySpan<byte>.Enumerator it = span.GetEnumerator();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], it.Current);
Assert.Equal(array[i], span.Slice(i).Read<byte>());
Assert.Equal(array[i], span.Slice(i).Read<MyByte>().Value);
}
Assert.False(it.MoveNext());
it.Reset();
for (int i = 0; i < span.Length; i++)
{
Assert.True(it.MoveNext());
Assert.Equal(array[i], it.Current);
}
Assert.False(it.MoveNext());
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)]
// copy first half to first half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)]
// copy second half to second half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)]
// copy first half to first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy first byte of 1 element array to last position
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)]
// copy first two bytes of 2 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6, 7 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy last two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 5, 6 }, 1, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 2 element array to the middle of other array
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 3, 4 }, 0, 2,
new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
public void SpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
if (expected != null)
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
Assert.True(spanA.TryCopyTo(spanB));
Assert.Equal(expected, b);
Span<byte> spanExpected = new Span<byte>(expected);
Span<byte> spanBAll = new Span<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
Assert.False(spanA.TryCopyTo(spanB));
}
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)]
// copy first half to first half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)]
// copy second half to second half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)]
// copy first half to first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy first byte of 1 element array to last position
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)]
// copy first two bytes of 2 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6, 7 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy last two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 5, 6 }, 1, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 2 element array to the middle of other array
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 3, 4 }, 0, 2,
new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
// copy one byte from the beginning at the end of other array
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
(byte[])null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
public void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
if (expected != null)
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
Assert.True(spanA.TryCopyTo(spanB));
Assert.Equal(expected, b);
ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
Assert.False(spanA.TryCopyTo(spanB));
}
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A12_CityRoad (editable child object).<br/>
/// This is a generated base class of <see cref="A12_CityRoad"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A11_CityRoadColl"/> collection.
/// </remarks>
[Serializable]
public partial class A12_CityRoad : BusinessBase<A12_CityRoad>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
[NonSerialized]
internal int parent_City_ID = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="CityRoad_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CityRoad_IDProperty = RegisterProperty<int>(p => p.CityRoad_ID, "City Road ID");
/// <summary>
/// Gets the City Road ID.
/// </summary>
/// <value>The City Road ID.</value>
public int CityRoad_ID
{
get { return GetProperty(CityRoad_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CityRoad_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> CityRoad_NameProperty = RegisterProperty<string>(p => p.CityRoad_Name, "City Road Name");
/// <summary>
/// Gets or sets the City Road Name.
/// </summary>
/// <value>The City Road Name.</value>
public string CityRoad_Name
{
get { return GetProperty(CityRoad_NameProperty); }
set { SetProperty(CityRoad_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A12_CityRoad"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="A12_CityRoad"/> object.</returns>
internal static A12_CityRoad NewA12_CityRoad()
{
return DataPortal.CreateChild<A12_CityRoad>();
}
/// <summary>
/// Factory method. Loads a <see cref="A12_CityRoad"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A12_CityRoad"/> object.</returns>
internal static A12_CityRoad GetA12_CityRoad(SafeDataReader dr)
{
A12_CityRoad obj = new A12_CityRoad();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A12_CityRoad"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A12_CityRoad()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="A12_CityRoad"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(CityRoad_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="A12_CityRoad"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(CityRoad_IDProperty, dr.GetInt32("CityRoad_ID"));
LoadProperty(CityRoad_NameProperty, dr.GetString("CityRoad_Name"));
// parent properties
parent_City_ID = dr.GetInt32("Parent_City_ID");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="A12_CityRoad"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(A10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddA12_CityRoad", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_City_ID", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@CityRoad_ID", ReadProperty(CityRoad_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@CityRoad_Name", ReadProperty(CityRoad_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(CityRoad_IDProperty, (int) cmd.Parameters["@CityRoad_ID"].Value);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="A12_CityRoad"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateA12_CityRoad", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CityRoad_ID", ReadProperty(CityRoad_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@CityRoad_Name", ReadProperty(CityRoad_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="A12_CityRoad"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteA12_CityRoad", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CityRoad_ID", ReadProperty(CityRoad_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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 proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.RecommendationEngine.V1Beta1
{
/// <summary>Settings for <see cref="PredictionApiKeyRegistryClient"/> instances.</summary>
public sealed partial class PredictionApiKeyRegistrySettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="PredictionApiKeyRegistrySettings"/>.</summary>
/// <returns>A new instance of the default <see cref="PredictionApiKeyRegistrySettings"/>.</returns>
public static PredictionApiKeyRegistrySettings GetDefault() => new PredictionApiKeyRegistrySettings();
/// <summary>
/// Constructs a new <see cref="PredictionApiKeyRegistrySettings"/> object with default settings.
/// </summary>
public PredictionApiKeyRegistrySettings()
{
}
private PredictionApiKeyRegistrySettings(PredictionApiKeyRegistrySettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
CreatePredictionApiKeyRegistrationSettings = existing.CreatePredictionApiKeyRegistrationSettings;
ListPredictionApiKeyRegistrationsSettings = existing.ListPredictionApiKeyRegistrationsSettings;
DeletePredictionApiKeyRegistrationSettings = existing.DeletePredictionApiKeyRegistrationSettings;
OnCopy(existing);
}
partial void OnCopy(PredictionApiKeyRegistrySettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>PredictionApiKeyRegistryClient.CreatePredictionApiKeyRegistration</c> and
/// <c>PredictionApiKeyRegistryClient.CreatePredictionApiKeyRegistrationAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreatePredictionApiKeyRegistrationSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>PredictionApiKeyRegistryClient.ListPredictionApiKeyRegistrations</c> and
/// <c>PredictionApiKeyRegistryClient.ListPredictionApiKeyRegistrationsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListPredictionApiKeyRegistrationsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>PredictionApiKeyRegistryClient.DeletePredictionApiKeyRegistration</c> and
/// <c>PredictionApiKeyRegistryClient.DeletePredictionApiKeyRegistrationAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeletePredictionApiKeyRegistrationSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="PredictionApiKeyRegistrySettings"/> object.</returns>
public PredictionApiKeyRegistrySettings Clone() => new PredictionApiKeyRegistrySettings(this);
}
/// <summary>
/// Builder class for <see cref="PredictionApiKeyRegistryClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
public sealed partial class PredictionApiKeyRegistryClientBuilder : gaxgrpc::ClientBuilderBase<PredictionApiKeyRegistryClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public PredictionApiKeyRegistrySettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public PredictionApiKeyRegistryClientBuilder()
{
UseJwtAccessWithScopes = PredictionApiKeyRegistryClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref PredictionApiKeyRegistryClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<PredictionApiKeyRegistryClient> task);
/// <summary>Builds the resulting client.</summary>
public override PredictionApiKeyRegistryClient Build()
{
PredictionApiKeyRegistryClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<PredictionApiKeyRegistryClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<PredictionApiKeyRegistryClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private PredictionApiKeyRegistryClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return PredictionApiKeyRegistryClient.Create(callInvoker, Settings);
}
private async stt::Task<PredictionApiKeyRegistryClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return PredictionApiKeyRegistryClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => PredictionApiKeyRegistryClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => PredictionApiKeyRegistryClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => PredictionApiKeyRegistryClient.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>PredictionApiKeyRegistry client wrapper, for convenient use.</summary>
/// <remarks>
/// Service for registering API keys for use with the `predict` method. If you
/// use an API key to request predictions, you must first register the API key.
/// Otherwise, your prediction request is rejected. If you use OAuth to
/// authenticate your `predict` method call, you do not need to register an API
/// key. You can register up to 20 API keys per project.
/// </remarks>
public abstract partial class PredictionApiKeyRegistryClient
{
/// <summary>
/// The default endpoint for the PredictionApiKeyRegistry service, which is a host of
/// "recommendationengine.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "recommendationengine.googleapis.com:443";
/// <summary>The default PredictionApiKeyRegistry scopes.</summary>
/// <remarks>
/// The default PredictionApiKeyRegistry 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="PredictionApiKeyRegistryClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="PredictionApiKeyRegistryClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="PredictionApiKeyRegistryClient"/>.</returns>
public static stt::Task<PredictionApiKeyRegistryClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new PredictionApiKeyRegistryClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="PredictionApiKeyRegistryClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="PredictionApiKeyRegistryClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="PredictionApiKeyRegistryClient"/>.</returns>
public static PredictionApiKeyRegistryClient Create() => new PredictionApiKeyRegistryClientBuilder().Build();
/// <summary>
/// Creates a <see cref="PredictionApiKeyRegistryClient"/> 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="PredictionApiKeyRegistrySettings"/>.</param>
/// <returns>The created <see cref="PredictionApiKeyRegistryClient"/>.</returns>
internal static PredictionApiKeyRegistryClient Create(grpccore::CallInvoker callInvoker, PredictionApiKeyRegistrySettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
PredictionApiKeyRegistry.PredictionApiKeyRegistryClient grpcClient = new PredictionApiKeyRegistry.PredictionApiKeyRegistryClient(callInvoker);
return new PredictionApiKeyRegistryClientImpl(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 PredictionApiKeyRegistry client</summary>
public virtual PredictionApiKeyRegistry.PredictionApiKeyRegistryClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Register an API key for use with predict method.
/// </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 PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Register an API key for use with predict method.
/// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Register an API key for use with predict method.
/// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest request, st::CancellationToken cancellationToken) =>
CreatePredictionApiKeyRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Register an API key for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`.
/// </param>
/// <param name="predictionApiKeyRegistration">
/// Required. The prediction API key registration.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(string parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) =>
CreatePredictionApiKeyRegistration(new CreatePredictionApiKeyRegistrationRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)),
}, callSettings);
/// <summary>
/// Register an API key for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`.
/// </param>
/// <param name="predictionApiKeyRegistration">
/// Required. The prediction API key registration.
/// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(string parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) =>
CreatePredictionApiKeyRegistrationAsync(new CreatePredictionApiKeyRegistrationRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)),
}, callSettings);
/// <summary>
/// Register an API key for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`.
/// </param>
/// <param name="predictionApiKeyRegistration">
/// Required. The prediction API key registration.
/// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(string parent, PredictionApiKeyRegistration predictionApiKeyRegistration, st::CancellationToken cancellationToken) =>
CreatePredictionApiKeyRegistrationAsync(parent, predictionApiKeyRegistration, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Register an API key for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`.
/// </param>
/// <param name="predictionApiKeyRegistration">
/// Required. The prediction API key registration.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(EventStoreName parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) =>
CreatePredictionApiKeyRegistration(new CreatePredictionApiKeyRegistrationRequest
{
ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)),
}, callSettings);
/// <summary>
/// Register an API key for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`.
/// </param>
/// <param name="predictionApiKeyRegistration">
/// Required. The prediction API key registration.
/// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(EventStoreName parent, PredictionApiKeyRegistration predictionApiKeyRegistration, gaxgrpc::CallSettings callSettings = null) =>
CreatePredictionApiKeyRegistrationAsync(new CreatePredictionApiKeyRegistrationRequest
{
ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PredictionApiKeyRegistration = gax::GaxPreconditions.CheckNotNull(predictionApiKeyRegistration, nameof(predictionApiKeyRegistration)),
}, callSettings);
/// <summary>
/// Register an API key for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store`.
/// </param>
/// <param name="predictionApiKeyRegistration">
/// Required. The prediction API key registration.
/// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(EventStoreName parent, PredictionApiKeyRegistration predictionApiKeyRegistration, st::CancellationToken cancellationToken) =>
CreatePredictionApiKeyRegistrationAsync(parent, predictionApiKeyRegistration, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </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 pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public virtual gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </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 pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent placement resource name such as
/// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public virtual gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListPredictionApiKeyRegistrations(new ListPredictionApiKeyRegistrationsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent placement resource name such as
/// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListPredictionApiKeyRegistrationsAsync(new ListPredictionApiKeyRegistrationsRequest
{
Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent placement resource name such as
/// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public virtual gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(EventStoreName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListPredictionApiKeyRegistrations(new ListPredictionApiKeyRegistrationsRequest
{
ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </summary>
/// <param name="parent">
/// Required. The parent placement resource name such as
/// `projects/1234/locations/global/catalogs/default_catalog/eventStores/default_event_store`
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(EventStoreName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListPredictionApiKeyRegistrationsAsync(new ListPredictionApiKeyRegistrationsRequest
{
ParentAsEventStoreName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </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 void DeletePredictionApiKeyRegistration(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </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 DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </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 DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest request, st::CancellationToken cancellationToken) =>
DeletePredictionApiKeyRegistrationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </summary>
/// <param name="name">
/// Required. The API key to unregister including full resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&lt;YOUR_API_KEY&gt;`
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeletePredictionApiKeyRegistration(string name, gaxgrpc::CallSettings callSettings = null) =>
DeletePredictionApiKeyRegistration(new DeletePredictionApiKeyRegistrationRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </summary>
/// <param name="name">
/// Required. The API key to unregister including full resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&lt;YOUR_API_KEY&gt;`
/// </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 DeletePredictionApiKeyRegistrationAsync(string name, gaxgrpc::CallSettings callSettings = null) =>
DeletePredictionApiKeyRegistrationAsync(new DeletePredictionApiKeyRegistrationRequest
{
Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)),
}, callSettings);
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </summary>
/// <param name="name">
/// Required. The API key to unregister including full resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&lt;YOUR_API_KEY&gt;`
/// </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 DeletePredictionApiKeyRegistrationAsync(string name, st::CancellationToken cancellationToken) =>
DeletePredictionApiKeyRegistrationAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </summary>
/// <param name="name">
/// Required. The API key to unregister including full resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&lt;YOUR_API_KEY&gt;`
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeletePredictionApiKeyRegistration(PredictionApiKeyRegistrationName name, gaxgrpc::CallSettings callSettings = null) =>
DeletePredictionApiKeyRegistration(new DeletePredictionApiKeyRegistrationRequest
{
PredictionApiKeyRegistrationName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </summary>
/// <param name="name">
/// Required. The API key to unregister including full resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&lt;YOUR_API_KEY&gt;`
/// </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 DeletePredictionApiKeyRegistrationAsync(PredictionApiKeyRegistrationName name, gaxgrpc::CallSettings callSettings = null) =>
DeletePredictionApiKeyRegistrationAsync(new DeletePredictionApiKeyRegistrationRequest
{
PredictionApiKeyRegistrationName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)),
}, callSettings);
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </summary>
/// <param name="name">
/// Required. The API key to unregister including full resource path.
/// `projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations/&lt;YOUR_API_KEY&gt;`
/// </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 DeletePredictionApiKeyRegistrationAsync(PredictionApiKeyRegistrationName name, st::CancellationToken cancellationToken) =>
DeletePredictionApiKeyRegistrationAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>PredictionApiKeyRegistry client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service for registering API keys for use with the `predict` method. If you
/// use an API key to request predictions, you must first register the API key.
/// Otherwise, your prediction request is rejected. If you use OAuth to
/// authenticate your `predict` method call, you do not need to register an API
/// key. You can register up to 20 API keys per project.
/// </remarks>
public sealed partial class PredictionApiKeyRegistryClientImpl : PredictionApiKeyRegistryClient
{
private readonly gaxgrpc::ApiCall<CreatePredictionApiKeyRegistrationRequest, PredictionApiKeyRegistration> _callCreatePredictionApiKeyRegistration;
private readonly gaxgrpc::ApiCall<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse> _callListPredictionApiKeyRegistrations;
private readonly gaxgrpc::ApiCall<DeletePredictionApiKeyRegistrationRequest, wkt::Empty> _callDeletePredictionApiKeyRegistration;
/// <summary>
/// Constructs a client wrapper for the PredictionApiKeyRegistry service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="PredictionApiKeyRegistrySettings"/> used within this client.
/// </param>
public PredictionApiKeyRegistryClientImpl(PredictionApiKeyRegistry.PredictionApiKeyRegistryClient grpcClient, PredictionApiKeyRegistrySettings settings)
{
GrpcClient = grpcClient;
PredictionApiKeyRegistrySettings effectiveSettings = settings ?? PredictionApiKeyRegistrySettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callCreatePredictionApiKeyRegistration = clientHelper.BuildApiCall<CreatePredictionApiKeyRegistrationRequest, PredictionApiKeyRegistration>(grpcClient.CreatePredictionApiKeyRegistrationAsync, grpcClient.CreatePredictionApiKeyRegistration, effectiveSettings.CreatePredictionApiKeyRegistrationSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreatePredictionApiKeyRegistration);
Modify_CreatePredictionApiKeyRegistrationApiCall(ref _callCreatePredictionApiKeyRegistration);
_callListPredictionApiKeyRegistrations = clientHelper.BuildApiCall<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse>(grpcClient.ListPredictionApiKeyRegistrationsAsync, grpcClient.ListPredictionApiKeyRegistrations, effectiveSettings.ListPredictionApiKeyRegistrationsSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListPredictionApiKeyRegistrations);
Modify_ListPredictionApiKeyRegistrationsApiCall(ref _callListPredictionApiKeyRegistrations);
_callDeletePredictionApiKeyRegistration = clientHelper.BuildApiCall<DeletePredictionApiKeyRegistrationRequest, wkt::Empty>(grpcClient.DeletePredictionApiKeyRegistrationAsync, grpcClient.DeletePredictionApiKeyRegistration, effectiveSettings.DeletePredictionApiKeyRegistrationSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeletePredictionApiKeyRegistration);
Modify_DeletePredictionApiKeyRegistrationApiCall(ref _callDeletePredictionApiKeyRegistration);
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_CreatePredictionApiKeyRegistrationApiCall(ref gaxgrpc::ApiCall<CreatePredictionApiKeyRegistrationRequest, PredictionApiKeyRegistration> call);
partial void Modify_ListPredictionApiKeyRegistrationsApiCall(ref gaxgrpc::ApiCall<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse> call);
partial void Modify_DeletePredictionApiKeyRegistrationApiCall(ref gaxgrpc::ApiCall<DeletePredictionApiKeyRegistrationRequest, wkt::Empty> call);
partial void OnConstruction(PredictionApiKeyRegistry.PredictionApiKeyRegistryClient grpcClient, PredictionApiKeyRegistrySettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC PredictionApiKeyRegistry client</summary>
public override PredictionApiKeyRegistry.PredictionApiKeyRegistryClient GrpcClient { get; }
partial void Modify_CreatePredictionApiKeyRegistrationRequest(ref CreatePredictionApiKeyRegistrationRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListPredictionApiKeyRegistrationsRequest(ref ListPredictionApiKeyRegistrationsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeletePredictionApiKeyRegistrationRequest(ref DeletePredictionApiKeyRegistrationRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Register an API key for use with predict method.
/// </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 PredictionApiKeyRegistration CreatePredictionApiKeyRegistration(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreatePredictionApiKeyRegistrationRequest(ref request, ref callSettings);
return _callCreatePredictionApiKeyRegistration.Sync(request, callSettings);
}
/// <summary>
/// Register an API key for use with predict method.
/// </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<PredictionApiKeyRegistration> CreatePredictionApiKeyRegistrationAsync(CreatePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreatePredictionApiKeyRegistrationRequest(ref request, ref callSettings);
return _callCreatePredictionApiKeyRegistration.Async(request, callSettings);
}
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </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 pageable sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public override gax::PagedEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrations(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListPredictionApiKeyRegistrationsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration>(_callListPredictionApiKeyRegistrations, request, callSettings);
}
/// <summary>
/// List the registered apiKeys for use with predict method.
/// </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 pageable asynchronous sequence of <see cref="PredictionApiKeyRegistration"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration> ListPredictionApiKeyRegistrationsAsync(ListPredictionApiKeyRegistrationsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListPredictionApiKeyRegistrationsRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListPredictionApiKeyRegistrationsRequest, ListPredictionApiKeyRegistrationsResponse, PredictionApiKeyRegistration>(_callListPredictionApiKeyRegistrations, request, callSettings);
}
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </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 void DeletePredictionApiKeyRegistration(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeletePredictionApiKeyRegistrationRequest(ref request, ref callSettings);
_callDeletePredictionApiKeyRegistration.Sync(request, callSettings);
}
/// <summary>
/// Unregister an apiKey from using for predict method.
/// </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 DeletePredictionApiKeyRegistrationAsync(DeletePredictionApiKeyRegistrationRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeletePredictionApiKeyRegistrationRequest(ref request, ref callSettings);
return _callDeletePredictionApiKeyRegistration.Async(request, callSettings);
}
}
public partial class ListPredictionApiKeyRegistrationsRequest : gaxgrpc::IPageRequest
{
}
public partial class ListPredictionApiKeyRegistrationsResponse : gaxgrpc::IPageResponse<PredictionApiKeyRegistration>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<PredictionApiKeyRegistration> GetEnumerator() =>
PredictionApiKeyRegistrations.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// AcceptSocket property variables.
internal Socket _acceptSocket;
private Socket _connectSocket;
// Buffer,Offset,Count property variables.
internal byte[] _buffer;
internal int _count;
internal int _offset;
// BufferList property variables.
private IList<ArraySegment<byte>> _bufferList;
private List<ArraySegment<byte>> _bufferListInternal;
// BytesTransferred property variables.
private int _bytesTransferred;
// Completed event property variables.
private event EventHandler<SocketAsyncEventArgs> _completed;
private bool _completedChanged;
// DisconnectReuseSocket propery variables.
private bool _disconnectReuseSocket;
// LastOperation property variables.
private SocketAsyncOperation _completedOperation;
// ReceiveMessageFromPacketInfo property variables.
private IPPacketInformation _receiveMessageFromPacketInfo;
// RemoteEndPoint property variables.
private EndPoint _remoteEndPoint;
// SendPacketsSendSize property variable.
internal int _sendPacketsSendSize;
// SendPacketsElements property variables.
internal SendPacketsElement[] _sendPacketsElements;
// SendPacketsFlags property variable.
internal TransmitFileOptions _sendPacketsFlags;
// SocketError property variables.
private SocketError _socketError;
private Exception _connectByNameError;
// SocketFlags property variables.
internal SocketFlags _socketFlags;
// UserToken property variables.
private object _userToken;
// Internal buffer for AcceptEx when Buffer not supplied.
internal byte[] _acceptBuffer;
internal int _acceptAddressBufferCount;
// Internal SocketAddress buffer.
internal Internals.SocketAddress _socketAddress;
// Misc state variables.
private ExecutionContext _context;
private static readonly ContextCallback s_executionCallback = ExecutionCallback;
private Socket _currentSocket;
private bool _disposeCalled;
// Controls thread safety via Interlocked.
private const int Configuring = -1;
private const int Free = 0;
private const int InProgress = 1;
private const int Disposed = 2;
private int _operating;
private MultipleConnectAsync _multipleConnect;
public SocketAsyncEventArgs()
{
InitializeInternals();
}
public Socket AcceptSocket
{
get { return _acceptSocket; }
set { _acceptSocket = value; }
}
public Socket ConnectSocket
{
get { return _connectSocket; }
}
public byte[] Buffer
{
get { return _buffer; }
}
public Memory<byte> GetBuffer()
{
// TODO https://github.com/dotnet/corefx/issues/24429:
// Actually support Memory<byte> natively.
return _buffer != null ?
new Memory<byte>(_buffer, _offset, _count) :
Memory<byte>.Empty;
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
// SendPacketsFlags property.
public TransmitFileOptions SendPacketsFlags
{
get { return _sendPacketsFlags; }
set { _sendPacketsFlags = value; }
}
// NOTE: this property is mutually exclusive with Buffer.
// Setting this property with an existing non-null Buffer will throw.
public IList<ArraySegment<byte>> BufferList
{
get { return _bufferList; }
set
{
StartConfiguring();
try
{
if (value != null)
{
if (_buffer != null)
{
// Can't have both set
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(Buffer)));
}
// Copy the user-provided list into our internal buffer list,
// so that we are not affected by subsequent changes to the list.
// We reuse the existing list so that we can avoid reallocation when possible.
int bufferCount = value.Count;
if (_bufferListInternal == null)
{
_bufferListInternal = new List<ArraySegment<byte>>(bufferCount);
}
else
{
_bufferListInternal.Clear();
}
for (int i = 0; i < bufferCount; i++)
{
ArraySegment<byte> buffer = value[i];
RangeValidationHelpers.ValidateSegment(buffer);
_bufferListInternal.Add(buffer);
}
}
else
{
_bufferListInternal?.Clear();
}
_bufferList = value;
SetupMultipleBuffers();
}
finally
{
Complete();
}
}
}
public int BytesTransferred
{
get { return _bytesTransferred; }
}
public event EventHandler<SocketAsyncEventArgs> Completed
{
add
{
_completed += value;
_completedChanged = true;
}
remove
{
_completed -= value;
_completedChanged = true;
}
}
protected virtual void OnCompleted(SocketAsyncEventArgs e)
{
EventHandler<SocketAsyncEventArgs> handler = _completed;
if (handler != null)
{
handler(e._currentSocket, e);
}
}
// DisconnectResuseSocket property.
public bool DisconnectReuseSocket
{
get { return _disconnectReuseSocket; }
set { _disconnectReuseSocket = value; }
}
public SocketAsyncOperation LastOperation
{
get { return _completedOperation; }
}
public IPPacketInformation ReceiveMessageFromPacketInfo
{
get { return _receiveMessageFromPacketInfo; }
}
public EndPoint RemoteEndPoint
{
get { return _remoteEndPoint; }
set { _remoteEndPoint = value; }
}
public SendPacketsElement[] SendPacketsElements
{
get { return _sendPacketsElements; }
set
{
StartConfiguring();
try
{
_sendPacketsElements = value;
SetupSendPacketsElements();
}
finally
{
Complete();
}
}
}
public int SendPacketsSendSize
{
get { return _sendPacketsSendSize; }
set { _sendPacketsSendSize = value; }
}
public SocketError SocketError
{
get { return _socketError; }
set { _socketError = value; }
}
public Exception ConnectByNameError
{
get { return _connectByNameError; }
}
public SocketFlags SocketFlags
{
get { return _socketFlags; }
set { _socketFlags = value; }
}
public object UserToken
{
get { return _userToken; }
set { _userToken = value; }
}
public void SetBuffer(byte[] buffer, int offset, int count)
{
SetBufferInternal(buffer, offset, count);
}
public void SetBuffer(int offset, int count)
{
SetBufferInternal(_buffer, offset, count);
}
public void SetBuffer(Memory<byte> buffer)
{
if (!buffer.TryGetArray(out ArraySegment<byte> array))
{
// TODO https://github.com/dotnet/corefx/issues/24429:
// Actually support Memory<byte> natively.
throw new ArgumentException();
}
SetBuffer(array.Array, array.Offset, array.Count);
}
internal bool HasMultipleBuffers
{
get { return _bufferList != null; }
}
private void SetBufferInternal(byte[] buffer, int offset, int count)
{
StartConfiguring();
try
{
if (buffer == null)
{
// Clear out existing buffer.
_buffer = null;
_offset = 0;
_count = 0;
}
else
{
// Can't have both Buffer and BufferList.
if (_bufferList != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(BufferList)));
}
// Offset and count can't be negative and the
// combination must be in bounds of the array.
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException(nameof(count));
}
_buffer = buffer;
_offset = offset;
_count = count;
}
// Pin new or unpin old buffer if necessary.
SetupSingleBuffer();
}
finally
{
Complete();
}
}
internal void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
_socketError = socketError;
_connectByNameError = null;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
}
internal void SetResults(Exception exception, int bytesTransferred, SocketFlags flags)
{
_connectByNameError = exception;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
if (exception == null)
{
_socketError = SocketError.Success;
}
else
{
SocketException socketException = exception as SocketException;
if (socketException != null)
{
_socketError = socketException.SocketErrorCode;
}
else
{
_socketError = SocketError.SocketError;
}
}
}
private static void ExecutionCallback(object state)
{
var thisRef = (SocketAsyncEventArgs)state;
thisRef.OnCompleted(thisRef);
}
// Marks this object as no longer "in-use". Will also execute a Dispose deferred
// because I/O was in progress.
internal void Complete()
{
// Mark as not in-use.
_operating = Free;
// Check for deferred Dispose().
// The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress.
// The _disposeCalled variable is not managed in a thread-safe manner on purpose for performance.
if (_disposeCalled)
{
Dispose();
}
}
// Dispose call to implement IDisposable.
public void Dispose()
{
// Remember that Dispose was called.
_disposeCalled = true;
// Check if this object is in-use for an async socket operation.
if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free)
{
// Either already disposed or will be disposed when current operation completes.
return;
}
// OK to dispose now.
FreeInternals();
// Don't bother finalizing later.
GC.SuppressFinalize(this);
}
~SocketAsyncEventArgs()
{
if (!Environment.HasShutdownStarted)
{
FreeInternals();
}
}
// NOTE: Use a try/finally to make sure Complete is called when you're done
private void StartConfiguring()
{
int status = Interlocked.CompareExchange(ref _operating, Configuring, Free);
if (status != Free)
{
ThrowForNonFreeStatus(status);
}
}
private void ThrowForNonFreeStatus(int status)
{
Debug.Assert(status == InProgress || status == Configuring || status == Disposed, $"Unexpected status: {status}");
if (status == Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
else
{
throw new InvalidOperationException(SR.net_socketopinprogress);
}
}
// Prepares for a native async socket call.
// This method performs the tasks common to all socket operations.
internal void StartOperationCommon(Socket socket)
{
// Change status to "in-use".
int status = Interlocked.CompareExchange(ref _operating, InProgress, Free);
if (status != Free)
{
ThrowForNonFreeStatus(status);
}
// Prepare execution context for callback.
// If event delegates have changed or socket has changed
// then discard any existing context.
if (_completedChanged || socket != _currentSocket)
{
_completedChanged = false;
_currentSocket = socket;
_context = null;
}
// Capture execution context if none already.
if (_context == null)
{
_context = ExecutionContext.Capture();
}
}
internal void StartOperationAccept()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Accept;
// AcceptEx needs a single buffer that's the size of two native sockaddr buffers with 16
// extra bytes each. It can also take additional buffer space in front of those special
// sockaddr structures that can be filled in with initial data coming in on a connection.
_acceptAddressBufferCount = 2 * (Socket.GetAddressSize(_currentSocket._rightEndPoint) + 16);
// If our caller specified a buffer (willing to get received data with the Accept) then
// it needs to be large enough for the two special sockaddr buffers that AcceptEx requires.
// Throw if that buffer is not large enough.
bool userSuppliedBuffer = _buffer != null;
if (userSuppliedBuffer)
{
// Caller specified a buffer - see if it is large enough
if (_count < _acceptAddressBufferCount)
{
throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, nameof(Count)));
}
// Buffer is already pinned if necessary.
}
else
{
// Caller didn't specify a buffer so use an internal one.
// See if current internal one is big enough, otherwise create a new one.
if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount)
{
_acceptBuffer = new byte[_acceptAddressBufferCount];
}
}
InnerStartOperationAccept(userSuppliedBuffer);
}
internal void StartOperationConnect()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = null;
_connectSocket = null;
InnerStartOperationConnect();
}
internal void StartOperationWrapperConnect(MultipleConnectAsync args)
{
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = args;
_connectSocket = null;
}
internal void CancelConnectAsync()
{
if (_operating == InProgress && _completedOperation == SocketAsyncOperation.Connect)
{
if (_multipleConnect != null)
{
// If a multiple connect is in progress, abort it.
_multipleConnect.Cancel();
}
else
{
// Otherwise we're doing a normal ConnectAsync - cancel it by closing the socket.
// _currentSocket will only be null if _multipleConnect was set, so we don't have to check.
if (_currentSocket == null)
{
NetEventSource.Fail(this, "CurrentSocket and MultipleConnect both null!");
}
_currentSocket.Dispose();
}
}
}
internal void StartOperationDisconnect()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Disconnect;
InnerStartOperationDisconnect();
}
internal void StartOperationReceive()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Receive;
InnerStartOperationReceive();
}
internal void StartOperationReceiveFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveFrom;
InnerStartOperationReceiveFrom();
}
internal void StartOperationReceiveMessageFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveMessageFrom;
InnerStartOperationReceiveMessageFrom();
}
internal void StartOperationSend()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Send;
InnerStartOperationSend();
}
internal void StartOperationSendPackets()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendPackets;
InnerStartOperationSendPackets();
}
internal void StartOperationSendTo()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendTo;
InnerStartOperationSendTo();
}
internal void UpdatePerfCounters(int size, bool sendOp)
{
if (sendOp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesSent, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsSent);
}
}
else
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived);
}
}
}
internal void FinishOperationSyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
_currentSocket?.UpdateStatusAfterSocketError(socketError);
Complete();
}
internal void FinishConnectByNameSyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
_currentSocket?.UpdateStatusAfterSocketError(_socketError);
Complete();
}
internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
_currentSocket?.UpdateStatusAfterSocketError(socketError);
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishOperationAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
_currentSocket?.UpdateStatusAfterSocketError(_socketError);
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishWrapperConnectSuccess(Socket connectSocket, int bytesTransferred, SocketFlags flags)
{
SetResults(SocketError.Success, bytesTransferred, flags);
_currentSocket = connectSocket;
_connectSocket = connectSocket;
// Complete the operation and raise the event.
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
internal void FinishOperationSyncSuccess(int bytesTransferred, SocketFlags flags)
{
SetResults(SocketError.Success, bytesTransferred, flags);
if (NetEventSource.IsEnabled || Socket.s_perfCountersEnabled)
{
LogBytesTransferred(bytesTransferred, _completedOperation);
}
SocketError socketError = SocketError.Success;
switch (_completedOperation)
{
case SocketAsyncOperation.Accept:
// Get the endpoint.
Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);
socketError = FinishOperationAccept(remoteSocketAddress);
if (socketError == SocketError.Success)
{
_acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));
if (NetEventSource.IsEnabled) NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint);
}
else
{
SetResults(socketError, bytesTransferred, flags);
_acceptSocket = null;
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
break;
case SocketAsyncOperation.Connect:
socketError = FinishOperationConnect();
if (socketError == SocketError.Success)
{
if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint);
// Mark socket connected.
_currentSocket.SetToConnected();
_connectSocket = _currentSocket;
}
else
{
SetResults(socketError, bytesTransferred, flags);
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
break;
case SocketAsyncOperation.Disconnect:
_currentSocket.SetToDisconnected();
_currentSocket._remoteEndPoint = null;
break;
case SocketAsyncOperation.ReceiveFrom:
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
break;
case SocketAsyncOperation.ReceiveMessageFrom:
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
FinishOperationReceiveMessageFrom();
break;
case SocketAsyncOperation.SendPackets:
FinishOperationSendPackets();
break;
}
Complete();
}
private void LogBytesTransferred(int bytesTransferred, SocketAsyncOperation operation)
{
if (bytesTransferred > 0)
{
if (NetEventSource.IsEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
bool sendOp = false;
switch (operation)
{
case SocketAsyncOperation.Connect:
case SocketAsyncOperation.Send:
case SocketAsyncOperation.SendPackets:
case SocketAsyncOperation.SendTo:
sendOp = true;
break;
}
UpdatePerfCounters(bytesTransferred, sendOp);
}
}
}
internal void FinishOperationAsyncSuccess(int bytesTransferred, SocketFlags flags)
{
FinishOperationSyncSuccess(bytesTransferred, flags);
// Raise completion event.
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_context, s_executionCallback, this);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using Microsoft.VisualBasic.CompilerServices.Tests;
using Xunit;
namespace Microsoft.VisualBasic.Tests
{
public class StringsTests
{
static StringsTests()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
[Fact]
public void Asc_Char_ReturnsChar()
{
Assert.Equal('3', Strings.Asc('3'));
}
[Theory]
[InlineData("3", 51)]
[InlineData("345", 51)]
[InlineData("ABCD", 65)]
public void Asc_String_ReturnsExpected(string String, int expected)
{
Assert.Equal(expected, Strings.Asc(String));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Asc_NullOrEmpty_ThrowsArgumentException(string String)
{
AssertExtensions.Throws<ArgumentException>("String", null, () => Strings.Asc(String));
}
[Fact]
public void AscW_Char_ReturnsChar()
{
Assert.Equal('3', Strings.AscW('3'));
}
[Theory]
[InlineData("3", 51)]
[InlineData("345", 51)]
[InlineData("ABCD", 65)]
public void AscW_String_ReturnsExpected(string String, int expected)
{
Assert.Equal(expected, Strings.AscW(String));
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void AscW_NullOrEmpty_ThrowsArgumentException(string String)
{
AssertExtensions.Throws<ArgumentException>("String", null, () => Strings.AscW(String));
}
[Theory]
[InlineData(97)]
[InlineData(65)]
[InlineData(0)]
public void Chr_CharCodeInRange_ReturnsExpected(int charCode)
{
Assert.Equal(Convert.ToChar(charCode & 0XFFFF), Strings.Chr(charCode));
}
[Theory]
[InlineData(-1)]
[InlineData(256)]
public void Chr_CharCodeOutOfRange_ThrowsNotSupportedException(int charCode)
{
AssertExtensions.Throws<ArgumentException>(null, () => Strings.Chr(charCode));
}
[Theory]
[InlineData(-32769)]
[InlineData(65536)]
public void Chr_CharCodeOutOfRange_ThrowsArgumentException(int charCode)
{
AssertExtensions.Throws<ArgumentException>("CharCode", null, () => Strings.Chr(charCode));
}
[Theory]
[InlineData(97)]
[InlineData(65)]
[InlineData(65535)]
[InlineData(-32768)]
public void ChrW_CharCodeInRange_ReturnsExpected(int charCode)
{
Assert.Equal(Convert.ToChar(charCode & 0XFFFF), Strings.ChrW(charCode));
}
[Theory]
[InlineData(-32769)]
[InlineData(65536)]
public void ChrW_CharCodeOutOfRange_ThrowsArgumentException(int charCode)
{
AssertExtensions.Throws<ArgumentException>("CharCode", null, () => Strings.ChrW(charCode));
}
[Theory]
[InlineData(new string[] { }, null, null)]
[InlineData(new string[] { }, "", null)]
public void Filter_WhenNoMatchArgument_ReturnsNull(string[] source, string match, string[] expected)
{
Assert.Equal(expected, Strings.Filter(source, match));
}
[Theory]
[InlineData(new string[] { }, "a", new string[] { }, new string[] { })]
public void Filter_NoElements(string[] source, string match, string[] includeExpected, string[] excludeExpected)
{
Assert.Equal(includeExpected, Strings.Filter(source, match, Include: true));
Assert.Equal(excludeExpected, Strings.Filter(source, match, Include: false));
}
[Theory]
[InlineData(new string[] { }, "a", new string[] { }, new string[] { })]
[InlineData(new string[] { "a" }, "a", new string[] { "a" }, new string[] { })]
[InlineData(new string[] { "ab" }, "a", new string[] { "ab" }, new string[] { })]
[InlineData(new string[] { "ba" }, "a", new string[] { "ba" }, new string[] { })]
[InlineData(new string[] { "bab" }, "a", new string[] { "bab" }, new string[] { })]
[InlineData(new string[] { "b" }, "a", new string[] { }, new string[] { "b" })]
[InlineData(new string[] { "a" }, "ab", new string[] { }, new string[] { "a" })]
[InlineData(new string[] { "ab" }, "ab", new string[] { "ab" }, new string[] { })]
public void Filter_SingleElement(string[] source, string match, string[] includeExpected, string[] excludeExpected)
{
Assert.Equal(includeExpected, Strings.Filter(source, match, Include: true));
Assert.Equal(excludeExpected, Strings.Filter(source, match, Include: false));
}
[Theory]
[InlineData(new string[] { "A" }, "a", new string[] { }, new string[] { "A" })]
public void Filter_SingleElement_BinaryCompare(string[] source, string match, string[] includeExpected, string[] excludeExpected)
{
Assert.Equal(includeExpected, Strings.Filter(source, match, Include: true, Compare: CompareMethod.Binary));
Assert.Equal(excludeExpected, Strings.Filter(source, match, Include: false, Compare: CompareMethod.Binary));
}
[Theory]
[InlineData(new string[] { "A" }, "a", new string[] { "A" }, new string[] { })]
public void Filter_SingleElement_TextCompare(string[] source, string match, string[] includeExpected, string[] excludeExpected)
{
Assert.Equal(includeExpected, Strings.Filter(source, match, Include: true, Compare: CompareMethod.Text));
Assert.Equal(excludeExpected, Strings.Filter(source, match, Include: false, Compare: CompareMethod.Text));
}
[Theory]
[InlineData(new string[] { "a", "a" }, "a", new string[] { "a", "a" }, new string[] { })]
[InlineData(new string[] { "a", "b" }, "a", new string[] { "a" }, new string[] { "b" })]
[InlineData(new string[] { "b", "a" }, "a", new string[] { "a" }, new string[] { "b" })]
[InlineData(new string[] { "b", "b" }, "a", new string[] { }, new string[] { "b", "b" })]
public void Filter_MultipleElements(string[] source, string match, string[] includeExpected, string[] excludeExpected)
{
Assert.Equal(includeExpected, Strings.Filter(source, match, Include: true));
Assert.Equal(excludeExpected, Strings.Filter(source, match, Include: false));
}
[Fact]
public void Filter_Objects_WhenObjectCannotBeConvertedToString_ThrowsArgumentOutOfRangeException()
{
object[] source = new object[] { typeof(object) };
string match = "a";
AssertExtensions.Throws<ArgumentException>("Source", null, () => Strings.Filter(source, match));
}
[Theory]
[InlineData(new object[] { 42 }, "42", new string[] { "42" }, new string[] { })]
[InlineData(new object[] { true }, "True", new string[] { "True" }, new string[] { })]
public void Filter_Objects(object[] source, string match, string[] includeExpected, string[] excludeExpected)
{
Assert.Equal(includeExpected, Strings.Filter(source, match, Include: true));
Assert.Equal(excludeExpected, Strings.Filter(source, match, Include: false));
}
[Theory]
[MemberData(nameof(InStr_TestData_NullsAndEmpties))]
[MemberData(nameof(InStr_FromBegin_TestData))]
public void InStr_FromBegin(string string1, string string2, int expected)
{
Assert.Equal(expected, Strings.InStr(string1, string2));
Assert.Equal(expected, Strings.InStr(1, string1, string2));
}
[Theory]
[MemberData(nameof(InStr_TestData_NullsAndEmpties))]
[MemberData(nameof(InStr_FromWithin_TestData))]
public void InStr_FromWithin(string string1, string string2, int expected)
{
Assert.Equal(expected, Strings.InStr(2, string1, string2));
}
[Theory]
[InlineData("A", "a", 0)]
[InlineData("Aa", "a", 2)]
public void InStr_BinaryCompare(string string1, string string2, int expected)
{
Assert.Equal(expected, Strings.InStr(string1, string2, CompareMethod.Binary));
Assert.Equal(expected, Strings.InStr(1, string1, string2, CompareMethod.Binary));
}
[Theory]
[InlineData("A", "a", 1)]
[InlineData("Aa", "a", 1)]
public void InStr_TextCompare(string string1, string string2, int expected)
{
Assert.Equal(expected, Strings.InStr(string1, string2, CompareMethod.Text));
Assert.Equal(expected, Strings.InStr(1, string1, string2, CompareMethod.Text));
}
[Theory]
[InlineData(2)]
[InlineData(3)]
public void InStr_WhenStartGreatherThanLength_ReturnsZero(int start)
{
Assert.Equal(0, Strings.InStr(start, "a", "a"));
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void InStr_WhenStartZeroOrLess_ThrowsArgumentException(int start)
{
AssertExtensions.Throws<ArgumentException>("Start", null, () => Strings.InStr(start, "a", "a"));
}
[Theory]
[MemberData(nameof(InStr_TestData_NullsAndEmpties))]
[MemberData(nameof(InStrRev_FromEnd_TestData))]
public void InStrRev_FromEnd(string stringCheck, string stringMatch, int expected)
{
Assert.Equal(expected, Strings.InStrRev(stringCheck, stringMatch));
}
[Theory]
[MemberData(nameof(InStrRev_FromWithin_TestData))]
public void InStrRev_FromWithin(string stringCheck, string stringMatch, int start, int expected)
{
Assert.Equal(expected, Strings.InStrRev(stringCheck, stringMatch, start));
}
[Theory]
[InlineData("A", "a", 1, 0)]
[InlineData("aA", "a", 2, 1)]
public void InStrRev_BinaryCompare(string stringCheck, string stringMatch, int start, int expected)
{
Assert.Equal(expected, Strings.InStrRev(stringCheck, stringMatch, start, CompareMethod.Binary));
}
[Theory]
[InlineData("A", "a", 1, 1)]
[InlineData("aA", "a", 2, 2)]
public void InStrRev_TextCompare(string stringCheck, string stringMatch, int start, int expected)
{
Assert.Equal(expected, Strings.InStrRev(stringCheck, stringMatch, start, CompareMethod.Text));
}
[Fact]
public void InStrRev_WhenStartMinusOne_SearchesFromEnd()
{
Assert.Equal(2, Strings.InStrRev("aa", "a", -1));
}
[Theory]
[InlineData(2)]
[InlineData(3)]
public void InStrRev_WhenStartGreatherThanLength_ReturnsZero(int start)
{
Assert.Equal(0, Strings.InStrRev("a", "a", start));
}
[Theory]
[InlineData(0)]
[InlineData(-2)]
[InlineData(-3)]
public void InStrRev_WhenStartZeroOrMinusTwoOrLess_ThrowsArgumentException(int start)
{
AssertExtensions.Throws<ArgumentException>("Start", null, () => Strings.InStrRev("a", "a", start));
}
[Theory]
[InlineData("a", -1)]
public void Left_Invalid(string str, int length)
{
AssertExtensions.Throws<ArgumentException>("Length", null, () => Strings.Left(str, length));
}
[Theory]
[InlineData("", 0, "")]
[InlineData("", 1, "")]
[InlineData("abc", 0, "")]
[InlineData("abc", 2, "ab")]
[InlineData("abc", int.MaxValue, "abc")]
public void Left_Valid(string str, int length, string expected)
{
Assert.Equal(expected, Strings.Left(str, length));
}
[Theory]
[MemberData(nameof(Len_Object_Data))]
[MemberData(nameof(StructUtilsTestData.RecordsAndLength), MemberType = typeof(StructUtilsTestData))]
public void Len_Object(object o, int length)
{
Assert.Equal(length, Strings.Len(o));
}
public static TheoryData<object, int> Len_Object_Data() => new TheoryData<object, int>
{
{ null, 0 },
{ new bool(), 2 },
{ new sbyte(), 1 },
{ new byte(), 1 },
{ new short(), 2 },
{ new ushort(), 2 },
{ new uint(), 4 },
{ new int(), 4 },
{ new ulong(), 8 },
{ new decimal(), 16 },
{ new float(), 4 },
{ new double(), 8 },
{ new DateTime(), 8 },
{ new char(), 2 },
{ "", 0 },
{ "a", 1 },
{ "ab", 2 },
{ "ab\0", 3 },
};
[Theory]
[InlineData("a", -1)]
public void Right_Invalid(string str, int length)
{
AssertExtensions.Throws<ArgumentException>("Length", null, () => Strings.Right(str, length));
}
[Theory]
[InlineData("", 0, "")]
[InlineData("", 1, "")]
[InlineData("abc", 0, "")]
[InlineData("abc", 2, "bc")]
[InlineData("abc", int.MaxValue, "abc")]
public void Right_Valid(string str, int length, string expected)
{
Assert.Equal(expected, Strings.Right(str, length));
}
[Theory]
[InlineData("a", -1)]
public void Mid2_Invalid(string str, int start)
{
AssertExtensions.Throws<ArgumentException>("Start", null, () => Strings.Mid(str, start));
}
[Theory]
[InlineData("", 1, "")]
[InlineData(null, 1, null)]
[InlineData("abc", 1000, "")]
[InlineData("abcde", 2, "bcde")]
[InlineData("abc", 1, "abc")] // 1-based strings in VB
[InlineData("abcd", 2, "bcd")]
[InlineData("abcd", 3, "cd")]
public void Mid2_Valid(string str, int start, string expected)
{
Assert.Equal(expected, Strings.Mid(str, start));
}
[Theory]
[InlineData("a", 1, -1)]
[InlineData("a", -1, 1)]
public void Mid3_Invalid(string str, int start, int length)
{
AssertExtensions.Throws<ArgumentException>(start < 1 ? "Start" : "Length", null, () => Strings.Mid(str, start, length));
}
[Theory]
[InlineData("", 1, 0, "")]
[InlineData(null, 1, 1, "")]
[InlineData("abc", 1000, 1, "")]
[InlineData("abcde", 2, 1000, "bcde")]
[InlineData("abc", 1, 2, "ab")] // 1-based strings in VB
[InlineData("abcd", 2, 2, "bc")]
[InlineData("abcd", 2, 3, "bcd")]
public void Mid3_Valid(string str, int start, int length, string expected)
{
Assert.Equal(expected, Strings.Mid(str, start, length));
}
[Theory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData(" ", "")]
[InlineData(" abc ", "abc ")]
[InlineData("\u3000\nabc ", "\nabc ")]
[InlineData("\nabc ", "\nabc ")]
[InlineData("abc ", "abc ")]
[InlineData("abc", "abc")]
public void LTrim_Valid(string str, string expected)
{
// Trims only space and \u3000 specifically
Assert.Equal(expected, Strings.LTrim(str));
}
[Theory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData(" ", "")]
[InlineData(" abc ", " abc")]
[InlineData(" abc\n\u3000", " abc\n")]
[InlineData(" abc\n", " abc\n")]
[InlineData(" abc", " abc")]
[InlineData("abc", "abc")]
public void RTrim_Valid(string str, string expected)
{
// Trims only space and \u3000 specifically
Assert.Equal(expected, Strings.RTrim(str));
}
[Theory]
[InlineData(null, "")]
[InlineData("", "")]
[InlineData(" ", "")]
[InlineData(" abc ", "abc")]
[InlineData("abc\n\u3000", "abc\n")]
[InlineData("\u3000abc\n\u3000", "abc\n")]
[InlineData("abc\n", "abc\n")]
[InlineData("abc", "abc")]
public void Trim_Valid(string str, string expected)
{
// Trims only space and \u3000 specifically
Assert.Equal(expected, Strings.Trim(str));
}
public static TheoryData<string, string, int> InStr_TestData_NullsAndEmpties() => new TheoryData<string, string, int>
{
{null, null, 0 },
{null, "", 0 },
{"", null, 0 },
{"", "", 0 },
};
public static TheoryData<string, string, int> InStr_FromBegin_TestData() => new TheoryData<string, string, int>
{
{ null, "a", 0 },
{ "a", null, 1 },
{ "a", "a", 1 },
{ "aa", "a", 1 },
{ "ab", "a", 1 },
{ "ba", "a", 2 },
{ "b", "a", 0 },
{ "a", "ab", 0 },
{ "ab", "ab", 1 },
};
public static TheoryData<string, string, int> InStr_FromWithin_TestData() => new TheoryData<string, string, int>
{
{ null, "a", 0 },
{ "aa", null, 2 },
{ "aa", "a", 2 },
{ "aab", "a", 2 },
{ "aba", "a", 3 },
{ "ab", "a", 0 },
{ "aa", "ab", 0 },
{ "abab", "ab", 3 },
};
public static TheoryData<string, string, int> InStrRev_FromEnd_TestData() => new TheoryData<string, string, int>
{
{ null, "a", 0 },
{ "a", null, 1 },
{ "a", "a", 1 },
{ "aa", "a", 2 },
{ "ba", "a", 2 },
{ "ab", "a", 1 },
{ "b", "a", 0 },
{ "a", "ab", 0 },
{ "ab", "ab", 1 },
};
public static TheoryData<string, string, int,int> InStrRev_FromWithin_TestData() => new TheoryData<string, string, int, int>
{
{ null, null, 1, 0 },
{ null, "", 1, 0 },
{ "", null, 1, 0 },
{ "", "", 1, 0 },
{ null, "a", 1, 0 },
{ "aa", null, 1, 1 },
{ "aa", "a", 1, 1 },
{ "baa", "a", 2, 2 },
{ "aba", "a", 2, 1 },
{ "ba", "a", 1, 0 },
{ "aa", "ab", 1, 0 },
{ "abab", "ab", 3, 1 },
};
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.