context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#region Copyright (c) 2006-2008, Nate Zobrist
/*
* Copyright (c) 2006-2008, Nate Zobrist
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with
* the distribution.
* Neither the name of "Nate Zobrist" nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion Copyright (c) 2006-2008, Nate Zobrist
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Xml;
namespace Pinboard
{
public static class Connection
{
private static string _Username;
private static string _Password;
private static int _MaxRetries = Constants.MaxRetries;
private static int _TimeOut = Constants.DefaultTimeOut;
private static string _ApiBaseUrl;
private static DateTime lastConnectTime = DateTime.MinValue;
/// <summary>
/// Connect to the del.icio.us API, returning an <c>XmlDocument</c> of the response
/// </summary>
/// <param name="relativeUrl">Constant defined in <c>Pinboard.Constants.RelativeUrl</c></param>
/// <returns>XmlDocument containing data from the del.icio.us api call</returns>
internal static XmlDocument Connect (string relativeUrl)
{
System.Xml.XmlDocument xmlDoc;
try
{
xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml (GetRawXml (relativeUrl));
}
catch (XmlException)
{
throw new Exceptions.PinboardException ("The webserver did not return valid XML.");
}
return xmlDoc;
}
/// <summary>
/// Connect to the del.icio.us API, returning the raw xml response
/// </summary>
/// <param name="relativeUrl">Constant defined in <c>Pinboard.Constants.RelativeUrl</c></param>
/// <returns>string containing raw xml data from the del.icio.us api call</returns>
internal static string GetRawXml (string relativeUrl)
{
return GetRawXml (relativeUrl, 0);
}
/// <summary>
/// Connect to the del.icio.us API.
/// Per instructions on the api site, don't allow queries more than once per second.
/// </summary>
/// <param name="relativeUrl">Constant defined in <c>Pinboard.Constants.RelativeUrl</c></param>
/// <param name="callCount">Beginning at 0, this number should be incremented by one each time the method
/// is recursively called due to a Timeout error. The increased number will increase the forced delay
/// in contacting the del.icio.us servers.</param>
/// <returns>XmlDocument containing data from the del.icio.us api call</returns>
private static string GetRawXml (string relativeUrl, int callCount)
{
int millisecondsBetweenQueries = Constants.MinimumMillisecondsBetweenQueries +
(1000 * callCount * callCount);
string fullUrl = ApiBaseUrl + relativeUrl;
string rawXml;
TimeSpan span = System.DateTime.Now - lastConnectTime.AddMilliseconds (millisecondsBetweenQueries);
if (span.TotalMilliseconds < 0)
Thread.Sleep (Math.Abs ((int)span.TotalMilliseconds));
HttpWebResponse response = null;
StreamReader readStream = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (fullUrl);
request.Credentials = new System.Net.NetworkCredential (Username, Password);
request.Timeout = TimeOut;
request.AllowAutoRedirect = false;
request.UserAgent = Constants.UserAgentValue;
request.MaximumResponseHeadersLength = 4;
request.KeepAlive = false;
request.Pipelined = false;
response = (HttpWebResponse)request.GetResponse ();
Stream receiveStream = response.GetResponseStream ();
readStream = new StreamReader (receiveStream, Encoding.UTF8);
rawXml = readStream.ReadToEnd ();
lastConnectTime = System.DateTime.Now;
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError ||
e.Status == WebExceptionStatus.Timeout)
{
HttpWebResponse webResponse = e.Response as HttpWebResponse;
if (webResponse != null)
{
// del.icio.us servers seem to have less-than-ideal response times quite often.
// we try to compensate for those probelms, but eventually error out.
if (e.Status == WebExceptionStatus.Timeout ||
webResponse.StatusCode == HttpStatusCode.ServiceUnavailable /*503 we have been throttled*/||
(int)webResponse.StatusCode == 999 /*Unable to process request at this time*/)
{
if (callCount < MaxRetries) // don't loop endlessly here, eventually just error out
return GetRawXml (relativeUrl, callCount + 1);
else
throw new Exceptions.PinboardTimeoutException (String.Format ("The server is not responding.\t{0}", webResponse.StatusCode));
}
else if (webResponse.StatusCode == HttpStatusCode.Unauthorized /*401*/)
{
throw new Exceptions.PinboardNotAuthorizedException ("Invalid username/password combination");
}
else
{
throw new Exceptions.PinboardException (webResponse.StatusCode.ToString ());
}
}
}
throw new Exceptions.PinboardException (e.Status.ToString ());
}
catch (IOException e)
{
// Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
throw new Exceptions.PinboardTimeoutException (e.ToString ());
}
finally
{
if (response != null)
response.Close();
if (readStream != null)
readStream.Close();
}
return rawXml;
}
/// <summary>
/// Gets or sets the API base URL.
/// </summary>
/// <value>The API base URL.</value>
public static string ApiBaseUrl
{
get
{
if (_ApiBaseUrl == null || _ApiBaseUrl.Length == 0)
return Constants.ApiBaseUrl;
return _ApiBaseUrl;
}
set
{
_ApiBaseUrl = value;
// a bunch of stuff depeneds on this already having the trailing slash
if (!_ApiBaseUrl.EndsWith ("/"))
_ApiBaseUrl += "/";
}
}
/// <summary>
/// Gets or sets the username.
/// </summary>
/// <value>The username.</value>
public static string Username
{
get { return _Username; }
set
{
if (_Username == value)
return;
_Username = value;
}
}
/// <summary>
/// Gets or sets the password.
/// </summary>
/// <value>The password.</value>
public static string Password
{
get { return _Password; }
set
{
if (_Password == value)
return;
_Password = value;
}
}
/// <summary>
/// Gets or sets the max retries.
/// </summary>
/// <value>The max retries.</value>
public static int MaxRetries
{
get { return _MaxRetries; }
set { _MaxRetries = (value < 0) ? 0 : value; }
}
/// <summary>
/// Gets or sets the time out.
/// </summary>
/// <value>The time out.</value>
public static int TimeOut
{
get { return _TimeOut; }
set { _TimeOut = (value < 0) ? Constants.DefaultTimeOut : value; }
}
/// <summary>
/// Gets the time of the last update to the del.icio.us account
/// </summary>
/// <returns>Returns a DateTime representing the last update time or DateTime.MinValue if there was an error</returns>
public static DateTime LastUpdated ()
{
DateTime lastUpdated = DateTime.MinValue;
System.Xml.XmlDocument xmlDoc = Connection.Connect (Constants.RelativeUrl.PostsUpdate);
if (xmlDoc == null)
return DateTime.MinValue;
XmlElement xmlElement = xmlDoc[ Constants.XmlTag.Update ];
if (xmlElement != null)
{
string time = xmlElement.GetAttribute (Constants.XmlAttribute.Time);
try
{
lastUpdated = DateTime.Parse (time, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
Debug.Fail (e.ToString ());
}
}
return lastUpdated;
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using OpenADK.Library;
using log4net;
namespace OpenADK.Web
{
/// <summary>
/// Summary description for AdkSocketBinding.
/// </summary>
public class AdkSocketBinding
{
//
private const int DEFAULT_MAX_CONNECTIONS = 50;
// The amount of time to keep connections open in seconds
private const int KEEP_ALIVE_TIME = 180;
private Timer fCleanupTimer;
private IPAddress fIPAddress;
private int fPort = 0;
private bool fIsRunning;
private bool fIsShuttingDown;
private IAcceptSocket fAcceptSocket;
///<summary>A vector of AdkSocketConnection objects </summary>
private ArrayList fSocketConnections;
private int fMaxClientConnections = 50;
private int fRawBufferSize = 2048;
private Boolean fDisposed;
private ILog fLog;
/// <summary> Constructor </summary>
public AdkSocketBinding( IAcceptSocket socket )
{
fAcceptSocket = socket;
fSocketConnections = new ArrayList();
TimeSpan cleanupInterval = TimeSpan.FromSeconds( (int) (KEEP_ALIVE_TIME/3) );
fCleanupTimer =
new Timer
( new TimerCallback( Cleanup ), cleanupInterval, cleanupInterval,
cleanupInterval );
}
/// <summary> Constructor </summary>
public AdkSocketBinding( IAcceptSocket socket,
ILog log )
: this( socket )
{
fLog = log;
}
//********************************************************************
/// <summary> Dispose function to shutdown the AdkSocketConnection </summary>
public void Dispose()
{
if ( !fDisposed )
{
try
{
fDisposed = true;
Stop();
}
catch
{
}
}
}
/// <summary>
/// Closes any idle socket connections
/// </summary>
public void Cleanup( object timeInterval )
{
try
{
fCleanupTimer.Change( Timeout.Infinite, Timeout.Infinite );
lock ( fSocketConnections.SyncRoot )
{
for ( int i = fSocketConnections.Count - 1; i > -1; i-- )
{
AdkSocketConnection connection = (AdkSocketConnection) fSocketConnections[i];
if ( connection.IdleTime.TotalSeconds > KEEP_ALIVE_TIME )
{
connection.Dispose(); // will automatically remove itself
}
}
}
}
finally
{
TimeSpan timerInterval = (TimeSpan) timeInterval;
fCleanupTimer.Change( timerInterval, timerInterval );
}
}
protected virtual void OnMaxConnectionsReached( IConnectedSocket connectedSocket )
{
}
protected virtual void OnError( Exception ex )
{
Error( ex.Message, null, ex );
}
//********************************************************************
/// <summary> Function to start the SocketServer </summary>
public void Start()
{
if ( fIPAddress == null || fPort == 0 )
{
// TODO:
throw new Exception( "Unable to start Socket server with specified values" );
}
// Is the Socket already listening?
if ( !fIsRunning )
{
fIsShuttingDown = false;
// Init the array of AdkSocketConnection references
fSocketConnections = new ArrayList( fMaxClientConnections );
IPEndPoint ipEndpoint = new IPEndPoint( fIPAddress, fPort );
AsyncCallback handler = new AsyncCallback( AcceptNewConnection );
// Call the derived class to begin accepting connections
fAcceptSocket.Bind( ipEndpoint );
fAcceptSocket.BeginAccept( handler, null );
Debug( "AdkSocketServer Started. Listening on port : {0}", new object[] {fPort} );
fIsRunning = true;
}
}
//********************************************************************
/// <summary> Function to stop the SocketServer.It can be restarted with Start </summary>
public void Stop()
{
if ( fIsRunning )
{
fIsShuttingDown = true;
fIsRunning = false;
// Dispose of all of the socket connections
for ( int i = fSocketConnections.Count - 1; i > -1; i -- )
{
try
{
((AdkSocketConnection) fSocketConnections[i]).Dispose();
// Automatically removes itself from the list
}
catch ( Exception ex )
{
Error( ex.Message, null, ex );
}
}
fAcceptSocket.Close();
}
}
public void Debug( string message,
object[] mergeValues )
{
if ( fLog != null && fLog.IsDebugEnabled )
{
fLog.Debug( string.Format( message, mergeValues ) );
}
}
public void Error( string message,
object[] mergeValues,
Exception ex )
{
if ( fLog != null && fLog.IsErrorEnabled )
{
fLog.Error( string.Format( message, mergeValues ), ex );
}
}
#region Public Methods
/// <summary> Function to remove a socket from the list of sockets </summary>
/// <param name="connection">The index of the socket to remove </param>
public void RemoveSocket( AdkSocketConnection connection )
{
lock ( fSocketConnections.SyncRoot )
{
try
{
fSocketConnections.Remove( connection );
}
catch
{
}
}
}
/// <summary>
/// The port this server is listening on
/// </summary>
public int Port
{
get { return fPort; }
set
{
if ( CanSetValues() )
{
fPort = value;
}
}
}
public IPAddress HostAddress
{
get { return fIPAddress; }
set
{
if ( CanSetValues() )
{
fIPAddress = value;
}
}
}
public bool IsStarted
{
get { return fIsRunning; }
}
public int ConnectionCount
{
get { return fSocketConnections.Count; }
}
/// <summary>
/// The size of memory that will be reserved for receiving data by this listener
/// </summary>
public int RawBufferSize
{
get { return fRawBufferSize; }
set { fRawBufferSize = value; }
}
///<summary>Maximum number of client connections that will be accepted by this listener </summary>
public int MaxClientConnections
{
get { return fMaxClientConnections; }
set
{
if ( value < 1 )
{
fMaxClientConnections = DEFAULT_MAX_CONNECTIONS;
}
else
{
fMaxClientConnections = value;
}
}
}
public event AdkSocketMessageHandler SocketAccepted;
public event AdkSocketMessageHandler DataReceived;
public event AdkSocketMessageHandler SocketClosed;
public event AdkSocketErrorHandler SocketError;
#endregion
#region Private Methods
/// <summary> Function to process and accept socket connection requests </summary>
private void AcceptNewConnection( IAsyncResult ar )
{
if ( fIsShuttingDown )
{
return;
}
IConnectedSocket clientSocket = null;
try
{
// Call the derived class's accept handler
clientSocket = fAcceptSocket.EndAccept( ar );
if ( !clientSocket.Connected )
{
return;
}
lock ( fSocketConnections.SyncRoot )
{
try
{
// If we have room to accept this connection
if ( fSocketConnections.Count <= MaxClientConnections )
{
// Create a AdkSocketConnection object
AdkSocketConnection adkSocket = new AdkSocketConnection
(
this, clientSocket, RawBufferSize,
DataReceived,
SocketClosed,
SocketError
);
// Call the Accept Handler
fSocketConnections.Add( adkSocket );
if ( SocketAccepted != null )
{
try
{
SocketAccepted( adkSocket );
}
catch
{
}
}
}
else
{
OnMaxConnectionsReached( clientSocket );
// Close the socket connection
clientSocket.Shutdown( SocketShutdown.Both );
clientSocket.Close();
}
}
catch ( SocketException e )
{
// Did we stop the TCPListener
if ( e.ErrorCode == 10004 )
{
// The connection is being shut down, ignore the error
}
else
{
OnError( e );
// Close the socket down if it exists
if ( clientSocket != null && clientSocket.Connected )
{
clientSocket.Shutdown( SocketShutdown.Both );
clientSocket.Close();
}
}
}
catch ( Exception ex )
{
OnError( ex );
// Close the socket down if it exists
if ( clientSocket != null && clientSocket.Connected )
{
clientSocket.Shutdown( SocketShutdown.Both );
clientSocket.Close();
}
}
}
}
catch ( SocketException e )
{
// Did we stop the TCPListener
if ( e.ErrorCode == 10004 )
{
// We're done
return;
}
else
{
OnError( e );
// Close the socket down if it exists
if ( clientSocket != null && clientSocket.Connected )
{
clientSocket.Shutdown( SocketShutdown.Both );
clientSocket.Close();
}
}
}
finally
{
if ( fIsRunning )
{
fAcceptSocket.BeginAccept( new AsyncCallback( AcceptNewConnection ), null );
}
}
}
private bool CanSetValues()
{
lock ( fSocketConnections.SyncRoot )
{
if ( fIsRunning )
{
throw new AdkException
( "Cannot switch connection properties while server is running", null );
}
else
{
return true;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Rendering;
namespace GLTF
{
public class GLTFLoader
{
public enum MaterialType
{
PbrMetallicRoughness,
PbrSpecularGlossiness,
CommonConstant,
CommonPhong,
CommonBlinn,
CommonLambert
}
private struct MaterialCacheKey
{
public Material Material;
public bool UseVertexColors;
}
public bool Multithreaded = true;
public int MaximumLod = 300;
public UnityEngine.Material ColorMaterial;
public UnityEngine.Material NoColorMaterial;
private readonly byte[] _gltfData;
private GLTFRoot _root;
private GameObject _lastLoadedScene;
private AsyncAction asyncAction;
private readonly Transform _sceneParent;
private readonly Dictionary<Buffer, byte[]> _bufferCache = new Dictionary<Buffer, byte[]>();
private readonly Dictionary<MaterialCacheKey, UnityEngine.Material> _materialCache = new Dictionary<MaterialCacheKey, UnityEngine.Material>();
private readonly Dictionary<Image, Texture2D> _imageCache = new Dictionary<Image, Texture2D>();
private Dictionary<Mesh, GameObject> _meshCache = new Dictionary<Mesh, GameObject>();
private readonly Dictionary<MeshPrimitive, MeshPrimitiveAttributes> _attributesCache = new Dictionary<MeshPrimitive, MeshPrimitiveAttributes>();
private readonly Dictionary<MaterialType, Shader> _shaderCache = new Dictionary<MaterialType, Shader>();
public GLTFLoader(byte[] gltfData, Transform parent = null)
{
_gltfData = gltfData;
_sceneParent = parent;
asyncAction = new AsyncAction();
}
public GameObject LastLoadedScene
{
get
{
return _lastLoadedScene;
}
}
public void SetShaderForMaterialType(MaterialType type, Shader shader)
{
_shaderCache.Add(type, shader);
}
public IEnumerator Load(int sceneIndex = -1)
{
if (_root == null)
{
if (Multithreaded)
{
yield return asyncAction.RunOnWorkerThread(() => ParseGLTF(_gltfData));
}
else
{
ParseGLTF(_gltfData);
}
}
Scene scene;
if (sceneIndex >= 0 && sceneIndex < _root.Scenes.Count)
{
scene = _root.Scenes[sceneIndex];
}
else
{
scene = _root.GetDefaultScene();
}
if (scene == null)
{
throw new Exception("No default scene in gltf file.");
}
if (_lastLoadedScene == null)
{
if (_root.Buffers != null)
{
foreach (var buffer in _root.Buffers)
{
yield return LoadBuffer(buffer);
}
}
if (_root.Images != null)
{
foreach (var image in _root.Images)
{
yield return LoadImage(image);
}
}
if (Multithreaded)
{
yield return asyncAction.RunOnWorkerThread(() => BuildMeshAttributes());
}
else
{
BuildMeshAttributes();
}
}
else
{
_meshCache = new Dictionary<Mesh, GameObject>();
}
var sceneObj = CreateScene(scene);
if (_sceneParent != null)
{
sceneObj.transform.SetParent(_sceneParent, false);
}
_lastLoadedScene = sceneObj;
}
private void ParseGLTF(byte[] gltfData)
{
byte[] glbBuffer;
_root = GLTFParser.ParseBinary(gltfData, out glbBuffer);
if (glbBuffer != null)
{
_bufferCache[_root.Buffers[0]] = glbBuffer;
}
}
private void BuildMeshAttributes()
{
foreach (var mesh in _root.Meshes)
{
foreach (var primitive in mesh.Primitives)
{
var attributes = primitive.BuildMeshAttributes(_bufferCache);
_attributesCache[primitive] = attributes;
}
}
}
private GameObject CreateScene(Scene scene)
{
var sceneObj = new GameObject(scene.Name ?? "GLTFScene");
foreach (var node in scene.Nodes)
{
var nodeObj = CreateNode(node.Value);
nodeObj.transform.SetParent(sceneObj.transform, false);
}
return sceneObj;
}
private GameObject CreateNode(Node node)
{
var nodeObj = new GameObject(node.Name ?? "GLTFNode");
Vector3 position;
Quaternion rotation;
Vector3 scale;
node.GetUnityTRSProperties(out position, out rotation, out scale);
nodeObj.transform.localPosition = position;
nodeObj.transform.localRotation = rotation;
nodeObj.transform.localScale = scale;
// TODO: Add support for skin/morph targets
if (node.Mesh != null)
{
var meshObj = FindOrCreateMeshObject(node.Mesh.Value);
meshObj.transform.SetParent(nodeObj.transform, false);
}
/* TODO: implement camera (probably a flag to disable for VR as well)
if (camera != null)
{
GameObject cameraObj = camera.Value.Create();
cameraObj.transform.parent = nodeObj.transform;
}
*/
if (node.Children != null)
{
foreach (var child in node.Children)
{
var childObj = CreateNode(child.Value);
childObj.transform.SetParent(nodeObj.transform, false);
}
}
return nodeObj;
}
private GameObject FindOrCreateMeshObject(Mesh mesh)
{
GameObject meshObj;
if (_meshCache.TryGetValue(mesh, out meshObj))
{
return GameObject.Instantiate(meshObj);
}
meshObj = CreateMeshObject(mesh);
_meshCache.Add(mesh, meshObj);
return meshObj;
}
private GameObject CreateMeshObject(Mesh mesh)
{
var meshName = mesh.Name ?? "GLTFMesh";
var meshObj = new GameObject(meshName);
foreach (var primitive in mesh.Primitives)
{
var primitiveObj = CreateMeshPrimitive(primitive);
primitiveObj.transform.SetParent(meshObj.transform, false);
}
return meshObj;
}
private GameObject CreateMeshPrimitive(MeshPrimitive primitive)
{
var primitiveObj = new GameObject("Primitive");
var meshFilter = primitiveObj.AddComponent<MeshFilter>();
var attributes = _attributesCache[primitive];
var mesh = new UnityEngine.Mesh
{
vertices = attributes.Vertices,
normals = attributes.Normals,
uv = attributes.Uv,
uv2 = attributes.Uv2,
uv3 = attributes.Uv3,
uv4 = attributes.Uv4,
colors = attributes.Colors,
triangles = attributes.Triangles,
tangents = attributes.Tangents
};
meshFilter.mesh = mesh;
var meshRenderer = primitiveObj.AddComponent<MeshRenderer>();
UnityEngine.Material material = null;
if (primitive.Material != null)
{
var materialCacheKey = new MaterialCacheKey
{
Material = primitive.Material.Value,
UseVertexColors = attributes.Colors != null
};
try
{
material = FindOrCreateMaterial(materialCacheKey);
}
catch (Exception e)
{
Debug.LogException(e);
Debug.LogWarningFormat("Failed to create material from {0}, using default", materialCacheKey.Material.Name);
}
}
if (material == null)
{
var materialCacheKey = new MaterialCacheKey
{
Material = new Material(),
UseVertexColors = attributes.Colors != null
};
material = FindOrCreateMaterial(materialCacheKey);
}
meshRenderer.material = material;
return primitiveObj;
}
private UnityEngine.Material FindOrCreateMaterial(MaterialCacheKey materialKey)
{
UnityEngine.Material material;
if (_materialCache.TryGetValue(materialKey, out material))
{
return material;
}
material = CreateMaterial(materialKey.Material, materialKey.UseVertexColors);
_materialCache.Add(materialKey, material);
return material;
}
private UnityEngine.Material CreateMaterial(Material def, bool useVertexColors)
{
UnityEngine.Material material = new UnityEngine.Material(useVertexColors ? ColorMaterial : NoColorMaterial);
material.shader.maximumLOD = MaximumLod;
if (def.AlphaMode == AlphaMode.MASK)
{
material.SetOverrideTag("RenderType", "TransparentCutout");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.EnableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
}
else if (def.AlphaMode == AlphaMode.BLEND)
{
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
}
else
{
material.SetOverrideTag("RenderType", "Opaque");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
}
if (def.DoubleSided)
{
material.SetInt("_Cull", (int)CullMode.Off);
}
else
{
material.SetInt("_Cull", (int)CullMode.Back);
}
if (useVertexColors)
{
material.EnableKeyword("VERTEX_COLOR_ON");
}
if (def.PbrMetallicRoughness != null)
{
var pbr = def.PbrMetallicRoughness;
material.SetColor("_Color", pbr.BaseColorFactor);
if (pbr.BaseColorTexture != null)
{
var texture = pbr.BaseColorTexture.Index.Value;
material.SetTexture("_MainTex", _imageCache[texture.Source.Value]);
}
material.SetFloat("_Metallic", (float)pbr.MetallicFactor);
if (pbr.MetallicRoughnessTexture != null)
{
var texture = pbr.MetallicRoughnessTexture.Index.Value;
material.SetTexture("_MetallicRoughnessMap", _imageCache[texture.Source.Value]);
}
material.SetFloat("_Roughness", (float)pbr.RoughnessFactor);
}
if (def.CommonConstant != null)
{
material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor);
if (def.CommonConstant.LightmapTexture != null)
{
material.EnableKeyword("LIGHTMAP_ON");
var texture = def.CommonConstant.LightmapTexture.Index.Value;
material.SetTexture("_LightMap", _imageCache[texture.Source.Value]);
material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord);
}
material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor);
}
if (def.NormalTexture != null)
{
var texture = def.NormalTexture.Index.Value;
material.EnableKeyword("_NORMALMAP");
material.SetTexture("_BumpMap", _imageCache[texture.Source.Value]);
material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
}
else
{
material.SetTexture("_BumpMap", null);
material.DisableKeyword("_NORMALMAP");
}
if (def.OcclusionTexture != null)
{
var texture = def.OcclusionTexture.Index;
material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);
if (def.PbrMetallicRoughness != null
&& def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id)
{
material.EnableKeyword("OCC_METAL_ROUGH_ON");
}
else
{
material.SetTexture("_OcclusionMap", _imageCache[texture.Value.Source.Value]);
}
}
if (def.EmissiveTexture != null)
{
var texture = def.EmissiveTexture.Index.Value;
material.EnableKeyword("_EMISSION");
material.EnableKeyword("EMISSION_MAP_ON");
material.SetTexture("_EmissionMap", _imageCache[texture.Source.Value]);
material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);
}
material.SetColor("_EmissionColor", def.EmissiveFactor);
return material;
}
private const string Base64StringInitializer = "^data:[a-z-]+/[a-z-]+;base64,";
/// <summary>
/// Get the absolute path to a gltf uri reference.
/// </summary>
/// <param name="relativePath">The relative path stored in the uri.</param>
/// <returns></returns>
private string AbsolutePath(string relativePath)
{
var uri = new Uri(relativePath);
var partialPath = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length - 1].Length);
return partialPath + relativePath;
}
private IEnumerator LoadImage(Image image)
{
Texture2D texture;
if (image.Uri != null)
{
var uri = image.Uri;
Regex regex = new Regex(Base64StringInitializer);
Match match = regex.Match(uri);
if (match.Success)
{
var base64Data = uri.Substring(match.Length);
var textureData = Convert.FromBase64String(base64Data);
texture = new Texture2D(0, 0);
texture.LoadImage(textureData);
}
else
{
var www = UnityWebRequest.Get(AbsolutePath(uri));
www.downloadHandler = new DownloadHandlerTexture();
yield return www.SendWebRequest();
// HACK to enable mipmaps :(
var tempTexture = DownloadHandlerTexture.GetContent(www);
if (tempTexture != null)
{
texture = new Texture2D(tempTexture.width, tempTexture.height, tempTexture.format, true);
texture.SetPixels(tempTexture.GetPixels());
texture.Apply(true);
}
else
{
Debug.LogFormat("{0} {1}", www.responseCode, www.url);
texture = new Texture2D(16, 16);
}
}
}
else
{
texture = new Texture2D(0, 0);
var bufferView = image.BufferView.Value;
var buffer = bufferView.Buffer.Value;
var bufferData = _bufferCache[buffer];
var data = new byte[bufferView.ByteLength];
System.Buffer.BlockCopy(bufferData, bufferView.ByteOffset, data, 0, data.Length);
texture.LoadImage(data);
}
_imageCache[image] = texture;
}
/// <summary>
/// Load the remote URI data into a byte array.
/// </summary>
private IEnumerator LoadBuffer(Buffer buffer)
{
if (buffer.Uri != null)
{
byte[] bufferData;
var uri = buffer.Uri;
Regex regex = new Regex(Base64StringInitializer);
Match match = regex.Match(uri);
if (match.Success)
{
var base64Data = uri.Substring(match.Length);
bufferData = Convert.FromBase64String(base64Data);
}
else
{
var www = UnityWebRequest.Get(AbsolutePath(uri));
yield return www.SendWebRequest();
bufferData = www.downloadHandler.data;
}
_bufferCache[buffer] = bufferData;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InlineTemporary), Shared]
internal partial class InlineTemporaryCodeRefactoringProvider : CodeRefactoringProvider
{
internal static readonly SyntaxAnnotation DefinitionAnnotation = new SyntaxAnnotation();
internal static readonly SyntaxAnnotation ReferenceAnnotation = new SyntaxAnnotation();
internal static readonly SyntaxAnnotation InitializerAnnotation = new SyntaxAnnotation();
internal static readonly SyntaxAnnotation ExpressionToInlineAnnotation = new SyntaxAnnotation();
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var root = await document.GetCSharpSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var token = root.FindToken(textSpan.Start);
if (!token.Span.Contains(textSpan))
{
return;
}
var node = token.Parent;
if (!node.IsKind(SyntaxKind.VariableDeclarator) ||
!node.IsParentKind(SyntaxKind.VariableDeclaration) ||
!node.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement))
{
return;
}
var variableDeclarator = (VariableDeclaratorSyntax)node;
var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
var localDeclarationStatement = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
if (variableDeclarator.Identifier != token ||
variableDeclarator.Initializer == null ||
variableDeclarator.Initializer.Value.IsMissing ||
variableDeclarator.Initializer.Value.IsKind(SyntaxKind.StackAllocArrayCreationExpression))
{
return;
}
if (localDeclarationStatement.ContainsDiagnostics)
{
return;
}
var references = await GetReferencesAsync(document, variableDeclarator, cancellationToken).ConfigureAwait(false);
if (!references.Any())
{
return;
}
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.InlineTemporaryVariable,
(c) => this.InlineTemporaryAsync(document, variableDeclarator, c)));
}
private async Task<IEnumerable<ReferenceLocation>> GetReferencesAsync(
Document document,
VariableDeclaratorSyntax variableDeclarator,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var local = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
if (local != null)
{
var findReferencesResult = await SymbolFinder.FindReferencesAsync(local, document.Project.Solution, cancellationToken).ConfigureAwait(false);
var locations = findReferencesResult.Single(r => r.Definition == local).Locations;
if (!locations.Any(loc => semanticModel.SyntaxTree.OverlapsHiddenPosition(loc.Location.SourceSpan, cancellationToken)))
{
return locations;
}
}
return SpecializedCollections.EmptyEnumerable<ReferenceLocation>();
}
private static bool HasConflict(IdentifierNameSyntax identifier, VariableDeclaratorSyntax variableDeclarator)
{
// TODO: Check for more conflict types.
if (identifier.SpanStart < variableDeclarator.SpanStart)
{
return true;
}
var identifierNode = identifier
.Ancestors()
.TakeWhile(n => n.Kind() == SyntaxKind.ParenthesizedExpression || n.Kind() == SyntaxKind.CastExpression)
.LastOrDefault();
if (identifierNode == null)
{
identifierNode = identifier;
}
if (identifierNode.IsParentKind(SyntaxKind.Argument))
{
var argument = (ArgumentSyntax)identifierNode.Parent;
if (argument.RefOrOutKeyword.Kind() != SyntaxKind.None)
{
return true;
}
}
else if (identifierNode.Parent.IsKind(
SyntaxKind.PreDecrementExpression,
SyntaxKind.PreIncrementExpression,
SyntaxKind.PostDecrementExpression,
SyntaxKind.PostIncrementExpression,
SyntaxKind.AddressOfExpression))
{
return true;
}
else if (identifierNode.Parent is AssignmentExpressionSyntax)
{
var binaryExpression = (AssignmentExpressionSyntax)identifierNode.Parent;
if (binaryExpression.Left == identifierNode)
{
return true;
}
}
return false;
}
private static SyntaxAnnotation CreateConflictAnnotation()
{
return ConflictAnnotation.Create(CSharpFeaturesResources.ConflictsDetected);
}
private async Task<Document> InlineTemporaryAsync(Document document, VariableDeclaratorSyntax declarator, CancellationToken cancellationToken)
{
var workspace = document.Project.Solution.Workspace;
// Annotate the variable declarator so that we can get back to it later.
var updatedDocument = await document.ReplaceNodeAsync(declarator, declarator.WithAdditionalAnnotations(DefinitionAnnotation), cancellationToken).ConfigureAwait(false);
var semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
// Create the expression that we're actually going to inline.
var expressionToInline = await CreateExpressionToInlineAsync(variableDeclarator, updatedDocument, cancellationToken).ConfigureAwait(false);
// Collect the identifier names for each reference.
var local = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
var symbolRefs = await SymbolFinder.FindReferencesAsync(local, updatedDocument.Project.Solution, cancellationToken).ConfigureAwait(false);
var references = symbolRefs.Single(r => r.Definition == local).Locations;
var syntaxRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
// Collect the topmost parenting expression for each reference.
var nonConflictingIdentifierNodes = references
.Select(loc => (IdentifierNameSyntax)syntaxRoot.FindToken(loc.Location.SourceSpan.Start).Parent)
.Where(ident => !HasConflict(ident, variableDeclarator));
// Add referenceAnnotions to identifier nodes being replaced.
updatedDocument = await updatedDocument.ReplaceNodesAsync(
nonConflictingIdentifierNodes,
(o, n) => n.WithAdditionalAnnotations(ReferenceAnnotation),
cancellationToken).ConfigureAwait(false);
semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
// Get the annotated reference nodes.
nonConflictingIdentifierNodes = await FindReferenceAnnotatedNodesAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
var topmostParentingExpressions = nonConflictingIdentifierNodes
.Select(ident => GetTopMostParentingExpression(ident))
.Distinct();
var originalInitializerSymbolInfo = semanticModel.GetSymbolInfo(variableDeclarator.Initializer.Value, cancellationToken);
// Make each topmost parenting statement or Equals Clause Expressions semantically explicit.
updatedDocument = await updatedDocument.ReplaceNodesAsync(topmostParentingExpressions, (o, n) => Simplifier.Expand(n, semanticModel, workspace, cancellationToken: cancellationToken), cancellationToken).ConfigureAwait(false);
semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var semanticModelBeforeInline = semanticModel;
variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
var scope = GetScope(variableDeclarator);
var newScope = ReferenceRewriter.Visit(semanticModel, scope, variableDeclarator, expressionToInline, cancellationToken);
updatedDocument = await updatedDocument.ReplaceNodeAsync(scope, newScope, cancellationToken).ConfigureAwait(false);
semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
variableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
newScope = GetScope(variableDeclarator);
var conflicts = newScope.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind);
var declaratorConflicts = variableDeclarator.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind);
// Note that we only remove the local declaration if there weren't any conflicts,
// unless those conflicts are inside the local declaration.
if (conflicts.Count() == declaratorConflicts.Count())
{
// Certain semantic conflicts can be detected only after the reference rewriter has inlined the expression
var newDocument = await DetectSemanticConflicts(updatedDocument,
semanticModel,
semanticModelBeforeInline,
originalInitializerSymbolInfo,
cancellationToken).ConfigureAwait(false);
if (updatedDocument == newDocument)
{
// No semantic conflicts, we can remove the definition.
updatedDocument = await updatedDocument.ReplaceNodeAsync(newScope, RemoveDeclaratorFromScope(variableDeclarator, newScope), cancellationToken).ConfigureAwait(false);
}
else
{
// There were some semantic conflicts, don't remove the definition.
updatedDocument = newDocument;
}
}
return updatedDocument;
}
private static async Task<VariableDeclaratorSyntax> FindDeclaratorAsync(Document document, CancellationToken cancellationToken)
{
return await FindNodeWithAnnotationAsync<VariableDeclaratorSyntax>(document, DefinitionAnnotation, cancellationToken).ConfigureAwait(false);
}
private static async Task<ExpressionSyntax> FindInitializerAsync(Document document, CancellationToken cancellationToken)
{
return await FindNodeWithAnnotationAsync<ExpressionSyntax>(document, InitializerAnnotation, cancellationToken).ConfigureAwait(false);
}
private static async Task<T> FindNodeWithAnnotationAsync<T>(Document document, SyntaxAnnotation annotation, CancellationToken cancellationToken)
where T : SyntaxNode
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return root
.GetAnnotatedNodesAndTokens(annotation)
.Single()
.AsNode() as T;
}
private static async Task<IEnumerable<IdentifierNameSyntax>> FindReferenceAnnotatedNodesAsync(Document document, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
return FindReferenceAnnotatedNodes(root);
}
private static IEnumerable<IdentifierNameSyntax> FindReferenceAnnotatedNodes(SyntaxNode root)
{
var annotatedNodesAndTokens = root.GetAnnotatedNodesAndTokens(ReferenceAnnotation);
foreach (var nodeOrToken in annotatedNodesAndTokens)
{
if (nodeOrToken.IsNode && nodeOrToken.AsNode().IsKind(SyntaxKind.IdentifierName))
{
yield return (IdentifierNameSyntax)nodeOrToken.AsNode();
}
}
}
private SyntaxNode GetScope(VariableDeclaratorSyntax variableDeclarator)
{
var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
var scope = localDeclaration.Parent;
while (scope.IsKind(SyntaxKind.LabeledStatement))
{
scope = scope.Parent;
}
var parentExpressions = scope.AncestorsAndSelf().OfType<ExpressionSyntax>();
if (parentExpressions.Any())
{
scope = parentExpressions.LastOrDefault().Parent;
}
return scope;
}
private VariableDeclaratorSyntax FindDeclarator(SyntaxNode node)
{
var annotatedNodesOrTokens = node.GetAnnotatedNodesAndTokens(DefinitionAnnotation).ToList();
Contract.Requires(annotatedNodesOrTokens.Count == 1, "Only a single variable declarator should have been annotated.");
return (VariableDeclaratorSyntax)annotatedNodesOrTokens.First().AsNode();
}
private SyntaxTriviaList GetTriviaToPreserve(SyntaxTriviaList syntaxTriviaList)
{
return ShouldPreserve(syntaxTriviaList) ? syntaxTriviaList : default(SyntaxTriviaList);
}
private static bool ShouldPreserve(SyntaxTriviaList trivia)
{
return trivia.Any(
t => t.Kind() == SyntaxKind.SingleLineCommentTrivia ||
t.Kind() == SyntaxKind.MultiLineCommentTrivia ||
t.IsDirective);
}
private SyntaxNode RemoveDeclaratorFromVariableList(VariableDeclaratorSyntax variableDeclarator, VariableDeclarationSyntax variableDeclaration)
{
Debug.Assert(variableDeclaration.Variables.Count > 1);
Debug.Assert(variableDeclaration.Variables.Contains(variableDeclarator));
var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
var scope = GetScope(variableDeclarator);
var newLocalDeclaration = localDeclaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepNoTrivia)
.WithAdditionalAnnotations(Formatter.Annotation);
return scope.ReplaceNode(localDeclaration, newLocalDeclaration);
}
private SyntaxNode RemoveDeclaratorFromScope(VariableDeclaratorSyntax variableDeclarator, SyntaxNode scope)
{
var variableDeclaration = (VariableDeclarationSyntax)variableDeclarator.Parent;
// If there is more than one variable declarator, remove this one from the variable declaration.
if (variableDeclaration.Variables.Count > 1)
{
return RemoveDeclaratorFromVariableList(variableDeclarator, variableDeclaration);
}
var localDeclaration = (LocalDeclarationStatementSyntax)variableDeclaration.Parent;
// There's only one variable declarator, so we'll remove the local declaration
// statement entirely. This means that we'll concatenate the leading and trailing
// trivia of this declaration and move it to the next statement.
var leadingTrivia = localDeclaration
.GetLeadingTrivia()
.Reverse()
.SkipWhile(t => t.MatchesKind(SyntaxKind.WhitespaceTrivia))
.Reverse()
.ToSyntaxTriviaList();
var trailingTrivia = localDeclaration
.GetTrailingTrivia()
.SkipWhile(t => t.MatchesKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia))
.ToSyntaxTriviaList();
var newLeadingTrivia = leadingTrivia.Concat(trailingTrivia);
var nextToken = localDeclaration.GetLastToken().GetNextTokenOrEndOfFile();
var newNextToken = nextToken.WithPrependedLeadingTrivia(newLeadingTrivia)
.WithAdditionalAnnotations(Formatter.Annotation);
var newScope = scope.ReplaceToken(nextToken, newNextToken);
var newLocalDeclaration = (LocalDeclarationStatementSyntax)FindDeclarator(newScope).Parent.Parent;
// If the local is parented by a label statement, we can't remove this statement. Instead,
// we'll replace the local declaration with an empty expression statement.
if (newLocalDeclaration.IsParentKind(SyntaxKind.LabeledStatement))
{
var labeledStatement = (LabeledStatementSyntax)newLocalDeclaration.Parent;
var newLabeledStatement = labeledStatement.ReplaceNode(newLocalDeclaration, SyntaxFactory.ParseStatement(""));
return newScope.ReplaceNode(labeledStatement, newLabeledStatement);
}
return newScope.RemoveNode(newLocalDeclaration, SyntaxRemoveOptions.KeepNoTrivia);
}
private ExpressionSyntax SkipRedundantExteriorParentheses(ExpressionSyntax expression)
{
while (expression.IsKind(SyntaxKind.ParenthesizedExpression))
{
var parenthesized = (ParenthesizedExpressionSyntax)expression;
if (parenthesized.Expression == null ||
parenthesized.Expression.IsMissing)
{
break;
}
if (parenthesized.Expression.IsKind(SyntaxKind.ParenthesizedExpression) ||
parenthesized.Expression.IsKind(SyntaxKind.IdentifierName))
{
expression = parenthesized.Expression;
}
else
{
break;
}
}
return expression;
}
private async Task<ExpressionSyntax> CreateExpressionToInlineAsync(
VariableDeclaratorSyntax variableDeclarator,
Document document,
CancellationToken cancellationToken)
{
var updatedDocument = document;
var expression = SkipRedundantExteriorParentheses(variableDeclarator.Initializer.Value);
var semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
var newExpression = InitializerRewriter.Visit(expression, localSymbol, semanticModel);
// If this is an array initializer, we need to transform it into an array creation
// expression for inlining.
if (newExpression.Kind() == SyntaxKind.ArrayInitializerExpression)
{
var arrayType = (ArrayTypeSyntax)localSymbol.Type.GenerateTypeSyntax();
var arrayInitializer = (InitializerExpressionSyntax)newExpression;
// Add any non-whitespace trailing trivia from the equals clause to the type.
var equalsToken = variableDeclarator.Initializer.EqualsToken;
if (equalsToken.HasTrailingTrivia)
{
var trailingTrivia = equalsToken.TrailingTrivia.SkipInitialWhitespace();
if (trailingTrivia.Any())
{
arrayType = arrayType.WithTrailingTrivia(trailingTrivia);
}
}
newExpression = SyntaxFactory.ArrayCreationExpression(arrayType, arrayInitializer);
}
newExpression = newExpression.WithAdditionalAnnotations(InitializerAnnotation);
updatedDocument = await updatedDocument.ReplaceNodeAsync(variableDeclarator.Initializer.Value, newExpression, cancellationToken).ConfigureAwait(false);
semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
newExpression = await FindInitializerAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
var newVariableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(newVariableDeclarator, cancellationToken);
bool wasCastAdded;
var explicitCastExpression = newExpression.CastIfPossible(localSymbol.Type, newVariableDeclarator.SpanStart, semanticModel, out wasCastAdded);
if (wasCastAdded)
{
updatedDocument = await updatedDocument.ReplaceNodeAsync(newExpression, explicitCastExpression, cancellationToken).ConfigureAwait(false);
semanticModel = await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
newVariableDeclarator = await FindDeclaratorAsync(updatedDocument, cancellationToken).ConfigureAwait(false);
}
// Now that the variable declarator is normalized, make its initializer
// value semantically explicit.
newExpression = await Simplifier.ExpandAsync(newVariableDeclarator.Initializer.Value, updatedDocument, cancellationToken: cancellationToken).ConfigureAwait(false);
return newExpression.WithAdditionalAnnotations(ExpressionToInlineAnnotation);
}
private static SyntaxNode GetTopMostParentingExpression(ExpressionSyntax expression)
{
return expression.AncestorsAndSelf().OfType<ExpressionSyntax>().Last();
}
private static async Task<Document> DetectSemanticConflicts(
Document inlinedDocument,
SemanticModel newSemanticModelForInlinedDocument,
SemanticModel semanticModelBeforeInline,
SymbolInfo originalInitializerSymbolInfo,
CancellationToken cancellationToken)
{
// In this method we detect if inlining the expression introduced the following semantic change:
// The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
// If any semantic changes were introduced by inlining, we update the document with conflict annotations.
// Otherwise we return the given inlined document without any changes.
var syntaxRootBeforeInline = await semanticModelBeforeInline.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
// Get all the identifier nodes which were replaced with inlined expression.
var originalIdentifierNodes = FindReferenceAnnotatedNodes(syntaxRootBeforeInline);
if (originalIdentifierNodes.IsEmpty())
{
// No conflicts
return inlinedDocument;
}
// Get all the inlined expression nodes.
var syntaxRootAfterInline = await inlinedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var inlinedExprNodes = syntaxRootAfterInline.GetAnnotatedNodesAndTokens(ExpressionToInlineAnnotation);
Debug.Assert(originalIdentifierNodes.Count() == inlinedExprNodes.Count());
Dictionary<SyntaxNode, SyntaxNode> replacementNodesWithChangedSemantics = null;
using (var originalNodesEnum = originalIdentifierNodes.GetEnumerator())
{
using (var inlinedNodesOrTokensEnum = inlinedExprNodes.GetEnumerator())
{
while (originalNodesEnum.MoveNext())
{
inlinedNodesOrTokensEnum.MoveNext();
var originalNode = originalNodesEnum.Current;
// expressionToInline is Parenthesized prior to replacement, so get the parenting parenthesized expression.
var inlinedNode = (ExpressionSyntax)inlinedNodesOrTokensEnum.Current.Parent;
Debug.Assert(inlinedNode.IsKind(SyntaxKind.ParenthesizedExpression));
// inlinedNode is the expanded form of the actual initializer expression in the original document.
// We have annotated the inner initializer with a special syntax annotation "InitializerAnnotation".
// Get this annotated node and compute the symbol info for this node in the inlined document.
var innerInitializerInInlineNodeorToken = inlinedNode.GetAnnotatedNodesAndTokens(InitializerAnnotation).First();
ExpressionSyntax innerInitializerInInlineNode = (ExpressionSyntax)(innerInitializerInInlineNodeorToken.IsNode ?
innerInitializerInInlineNodeorToken.AsNode() :
innerInitializerInInlineNodeorToken.AsToken().Parent);
var newInializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(innerInitializerInInlineNode, cancellationToken);
// Verification: The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
if (!SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInializerSymbolInfo, performEquivalenceCheck: true))
{
newInializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(inlinedNode, cancellationToken);
if (!SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInializerSymbolInfo, performEquivalenceCheck: true))
{
if (replacementNodesWithChangedSemantics == null)
{
replacementNodesWithChangedSemantics = new Dictionary<SyntaxNode, SyntaxNode>();
}
replacementNodesWithChangedSemantics.Add(inlinedNode, originalNode);
}
}
}
}
}
if (replacementNodesWithChangedSemantics == null)
{
// No conflicts.
return inlinedDocument;
}
// Replace the conflicting inlined nodes with the original nodes annotated with conflict annotation.
Func<SyntaxNode, SyntaxNode, SyntaxNode> conflictAnnotationAdder =
(SyntaxNode oldNode, SyntaxNode newNode) =>
newNode.WithAdditionalAnnotations(ConflictAnnotation.Create(CSharpFeaturesResources.ConflictsDetected));
return await inlinedDocument.ReplaceNodesAsync(replacementNodesWithChangedSemantics.Keys, conflictAnnotationAdder, cancellationToken).ConfigureAwait(false);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument)
{
}
}
}
}
| |
using System;
using System.Xml.Linq;
namespace WixSharp
{
//http://www.davidwhitney.co.uk/content/blog/index.php/2009/02/11/installing-certificates-using-wix-windows-installer-xml-voltive/
//http://stackoverflow.com/questions/860996/wix-and-certificates-in-iis
/// <summary>
/// This class defines website certificate attributes. It is a close equivalent of Certificate WiX element.
/// </summary>
public class Certificate : WixEntity
{
#region constructors
/// <summary>
/// Creates an instance of Certificate
/// </summary>
public Certificate()
{
}
/// <summary>
/// Creates an instance of Certificate where the certificate is a binary resource
/// </summary>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="binaryKey">The binary key.</param>
/// <exception cref="ArgumentNullException">
/// name;name is a null reference or empty
/// or
/// binaryKey;binaryKey is a null reference or empty
/// </exception>
public Certificate(string name, StoreLocation storeLocation, StoreName storeName, string binaryKey)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name", "name is a null reference or empty");
if (string.IsNullOrEmpty(binaryKey)) throw new ArgumentNullException("binaryKey", "binaryKey is a null reference or empty");
base.Name = name;
Name = name;
BinaryKey = binaryKey;
StoreLocation = storeLocation;
StoreName = storeName;
}
/// <summary>
/// Creates an instance of Certificate where the certificate is a binary resource
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="binaryKey">The binary key.</param>
public Certificate(Id id, string name, StoreLocation storeLocation, StoreName storeName, string binaryKey)
: this(name, storeLocation, storeName, binaryKey)
{
Id = id;
}
/// <summary>
/// Creates an instance of Certificate where the certificate is a binary resource
/// </summary>
/// <param name="feature">The feature.</param>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="binaryKey">The binary key.</param>
public Certificate(Feature feature, string name, StoreLocation storeLocation, StoreName storeName, string binaryKey)
: this(name, storeLocation, storeName, binaryKey)
{
Feature = feature;
}
/// <summary>
/// Creates an instance of Certificate where the certificate is a binary resource
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="feature">The feature.</param>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="binaryKey">The binary key.</param>
public Certificate(Id id, Feature feature, string name, StoreLocation storeLocation, StoreName storeName, string binaryKey)
: this(name, storeLocation, storeName, binaryKey)
{
Id = id;
Feature = feature;
}
/// <summary>
/// Creates an instance of Certificate where the certificate is requested or exists at the specified path
/// </summary>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="certificatePath">The certificate path.</param>
/// <param name="authorityRequest">if set to <c>true</c> [authority request].</param>
/// <exception cref="ArgumentNullException">name;name is a null reference or empty
/// or
/// certificatePath;certificatePath is a null reference or empty</exception>
public Certificate(string name, StoreLocation storeLocation, StoreName storeName, string certificatePath, bool authorityRequest)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name", "name is a null reference or empty");
if (string.IsNullOrEmpty(certificatePath)) throw new ArgumentNullException("certificatePath", "certificatePath is a null reference or empty");
base.Name = name;
Name = name;
CertificatePath = certificatePath;
Request = authorityRequest;
StoreLocation = storeLocation;
StoreName = storeName;
}
/// <summary>
/// Creates an instance of Certificate where the certificate is requested or exists at the specified path
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="certificatePath">The certificate path.</param>
/// <param name="request">if set to <c>true</c> [request].</param>
public Certificate(Id id, string name, StoreLocation storeLocation, StoreName storeName, string certificatePath, bool request)
: this(name, storeLocation, storeName, certificatePath, request)
{
Id = id;
}
/// <summary>
/// Creates an instance of Certificate where the certificate is requested or exists at the specified path
/// </summary>
/// <param name="feature">The feature.</param>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="certificatePath">The certificate path.</param>
/// <param name="request">if set to <c>true</c> [request].</param>
public Certificate(Feature feature, string name, StoreLocation storeLocation, StoreName storeName, string certificatePath, bool request)
: this(name, storeLocation, storeName, certificatePath, request)
{
Feature = feature;
}
/// <summary>
/// Creates an instance of Certificate where the certificate is requested or exists at the specified path
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="feature">The feature.</param>
/// <param name="name">The name.</param>
/// <param name="storeLocation">The store location.</param>
/// <param name="storeName">Name of the store.</param>
/// <param name="certificatePath">The certificate path.</param>
/// <param name="request">if set to <c>true</c> [request].</param>
public Certificate(Id id, Feature feature, string name, StoreLocation storeLocation, StoreName storeName, string certificatePath, bool request)
: this(name, storeLocation, storeName, certificatePath, request)
{
Id = id;
Feature = feature;
}
#endregion constructors
#region attributes
/// <summary>
/// The Id of a Binary instance that is the certificate to be installed
/// </summary>
public string BinaryKey;
/// <summary>
/// If the Request attribute is <c>false</c> then this attribute is the path to the certificate file outside of the package.
/// If the Request attribute is <c>true</c> then this attribute is the certificate authority to request the certificate from.
/// </summary>
public string CertificatePath;
/// <summary>
/// The name of the certificate being installed
/// </summary>
public new string Name;
/// <summary>
/// Flag to indicate if the certificate should be overwritten.
/// </summary>
public bool? Overwrite;
/// <summary>
/// This attribute controls whether the CertificatePath attribute is a path to a certificate file (Request=<c>false</c>) or
/// the certificate authority to request the certificate from (Request=<c>true</c>).
/// </summary>
public bool? Request;
/// <summary>
/// If the Binary stream or path to the file outside of the package is a password protected PFX file, the password for that PFX must be specified here.
/// </summary>
public string PFXPassword;
/// <summary>
/// Sets the certificate StoreLocation.
/// </summary>
public StoreLocation StoreLocation;
/// <summary>
/// Sets the certificate StoreName.
/// </summary>
public StoreName StoreName;
#endregion attributes
/// <summary>
/// Emits WiX XML.
/// </summary>
/// <returns></returns>
public XContainer[] ToXml()
{
var element = new XElement(WixExtension.IIs.ToXNamespace() + "Certificate");
element.SetAttribute("Id", Id)
.SetAttribute("BinaryKey", BinaryKey)
.SetAttribute("CertificatePath", CertificatePath)
.SetAttribute("Name", Name)
.SetAttribute("Overwrite", Overwrite)
.SetAttribute("PFXPassword", PFXPassword)
.SetAttribute("Request", Request)
.SetAttribute("StoreLocation", Enum.GetName(typeof(StoreLocation), StoreLocation))
.SetAttribute("StoreName", Enum.GetName(typeof(StoreName), StoreName));
return new[] { element };
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Configuration;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
namespace PCSComProduct.Items.DS
{
public class ITM_DeliveryPolicyDS
{
public ITM_DeliveryPolicyDS()
{
}
private const string THIS = "PCSComProduct.Items.DS.DS.ITM_DeliveryPolicyDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to ITM_DeliveryPolicy
/// </Description>
/// <Inputs>
/// ITM_DeliveryPolicyVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, January 19, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS =null;
try
{
ITM_DeliveryPolicyVO objObject = (ITM_DeliveryPolicyVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql= "INSERT INTO ITM_DeliveryPolicy("
+ ITM_DeliveryPolicyTable.CODE_FLD + ","
+ ITM_DeliveryPolicyTable.DESCRIPTION_FLD + ","
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD + ")"
+ "VALUES(?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeliveryPolicyTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[ITM_DeliveryPolicyTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeliveryPolicyTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[ITM_DeliveryPolicyTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD].Value = objObject.DeliveryPolicyDays;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from ITM_DeliveryPolicy
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql= "DELETE " + ITM_DeliveryPolicyTable.TABLE_NAME + " WHERE " + "DeliveryPolicyID" + "=" + pintID.ToString();
OleDbConnection oconPCS=null;
OleDbCommand ocmdPCS =null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from ITM_DeliveryPolicy
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// ITM_DeliveryPolicyVO
/// </Outputs>
/// <Returns>
/// ITM_DeliveryPolicyVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, January 19, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD + ","
+ ITM_DeliveryPolicyTable.CODE_FLD + ","
+ ITM_DeliveryPolicyTable.DESCRIPTION_FLD + ","
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD
+ " FROM " + ITM_DeliveryPolicyTable.TABLE_NAME
+" WHERE " + ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
ITM_DeliveryPolicyVO objObject = new ITM_DeliveryPolicyVO();
while (odrPCS.Read())
{
objObject.DeliveryPolicyID = int.Parse(odrPCS[ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD].ToString().Trim());
objObject.Code = odrPCS[ITM_DeliveryPolicyTable.CODE_FLD].ToString().Trim();
objObject.Description = odrPCS[ITM_DeliveryPolicyTable.DESCRIPTION_FLD].ToString().Trim();
objObject.DeliveryPolicyDays = Decimal.Parse(odrPCS[ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD].ToString().Trim());
}
return objObject;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to ITM_DeliveryPolicy
/// </Description>
/// <Inputs>
/// ITM_DeliveryPolicyVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
ITM_DeliveryPolicyVO objObject = (ITM_DeliveryPolicyVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql= "UPDATE ITM_DeliveryPolicy SET "
+ ITM_DeliveryPolicyTable.CODE_FLD + "= ?" + ","
+ ITM_DeliveryPolicyTable.DESCRIPTION_FLD + "= ?" + ","
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD + "= ?"
+" WHERE " + ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeliveryPolicyTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[ITM_DeliveryPolicyTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeliveryPolicyTable.DESCRIPTION_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[ITM_DeliveryPolicyTable.DESCRIPTION_FLD].Value = objObject.Description;
ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD].Value = objObject.DeliveryPolicyDays;
ocmdPCS.Parameters.Add(new OleDbParameter(ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD].Value = objObject.DeliveryPolicyID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from ITM_DeliveryPolicy
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, January 19, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS =null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD + ","
+ ITM_DeliveryPolicyTable.CODE_FLD + ","
+ ITM_DeliveryPolicyTable.DESCRIPTION_FLD + ","
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD
+ " FROM " + ITM_DeliveryPolicyTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS,ITM_DeliveryPolicyTable.TABLE_NAME);
return dstPCS;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Wednesday, January 19, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS =null;
OleDbCommandBuilder odcbPCS ;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql= "SELECT "
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYID_FLD + ","
+ ITM_DeliveryPolicyTable.CODE_FLD + ","
+ ITM_DeliveryPolicyTable.DESCRIPTION_FLD + ","
+ ITM_DeliveryPolicyTable.DELIVERYPOLICYDAYS_FLD
+ " FROM " + ITM_DeliveryPolicyTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData,ITM_DeliveryPolicyTable.TABLE_NAME);
}
catch(OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
}
catch(InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A certificate that can be installed on compute nodes and can be used to authenticate operations on a node.
/// </summary>
public partial class Certificate : ITransportObjectProvider<Models.CertificateAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<Common.CertificateFormat?> CertificateFormatProperty;
public readonly PropertyAccessor<string> DataProperty;
public readonly PropertyAccessor<DeleteCertificateError> DeleteCertificateErrorProperty;
public readonly PropertyAccessor<string> PasswordProperty;
public readonly PropertyAccessor<Common.CertificateState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<string> PublicDataProperty;
public readonly PropertyAccessor<Common.CertificateState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<string> ThumbprintProperty;
public readonly PropertyAccessor<string> ThumbprintAlgorithmProperty;
public readonly PropertyAccessor<string> UrlProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.CertificateFormatProperty = this.CreatePropertyAccessor<Common.CertificateFormat?>(nameof(CertificateFormat), BindingAccess.Read | BindingAccess.Write);
this.DataProperty = this.CreatePropertyAccessor<string>(nameof(Data), BindingAccess.Read | BindingAccess.Write);
this.DeleteCertificateErrorProperty = this.CreatePropertyAccessor<DeleteCertificateError>(nameof(DeleteCertificateError), BindingAccess.None);
this.PasswordProperty = this.CreatePropertyAccessor<string>(nameof(Password), BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.CertificateState?>(nameof(PreviousState), BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None);
this.PublicDataProperty = this.CreatePropertyAccessor<string>(nameof(PublicData), BindingAccess.None);
this.StateProperty = this.CreatePropertyAccessor<Common.CertificateState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.ThumbprintProperty = this.CreatePropertyAccessor<string>(nameof(Thumbprint), BindingAccess.Read | BindingAccess.Write);
this.ThumbprintAlgorithmProperty = this.CreatePropertyAccessor<string>(nameof(ThumbprintAlgorithm), BindingAccess.Read | BindingAccess.Write);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
}
public PropertyContainer(Models.Certificate protocolObject) : base(BindingState.Bound)
{
this.CertificateFormatProperty = this.CreatePropertyAccessor<Common.CertificateFormat?>(
nameof(CertificateFormat),
BindingAccess.None);
this.DataProperty = this.CreatePropertyAccessor<string>(
nameof(Data),
BindingAccess.None);
this.DeleteCertificateErrorProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DeleteCertificateError, o => new DeleteCertificateError(o).Freeze()),
nameof(DeleteCertificateError),
BindingAccess.Read);
this.PasswordProperty = this.CreatePropertyAccessor<string>(
nameof(Password),
BindingAccess.None);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.CertificateState, Common.CertificateState>(protocolObject.PreviousState),
nameof(PreviousState),
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
nameof(PreviousStateTransitionTime),
BindingAccess.Read);
this.PublicDataProperty = this.CreatePropertyAccessor(
protocolObject.PublicData,
nameof(PublicData),
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.CertificateState, Common.CertificateState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.ThumbprintProperty = this.CreatePropertyAccessor(
protocolObject.Thumbprint,
nameof(Thumbprint),
BindingAccess.Read);
this.ThumbprintAlgorithmProperty = this.CreatePropertyAccessor(
protocolObject.ThumbprintAlgorithm,
nameof(ThumbprintAlgorithm),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Certificate"/> class.
/// </summary>
/// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param>
/// <param name='baseBehaviors'>The base behaviors to use.</param>
/// <param name='data'>The base64-encoded raw certificate data (contents of the .pfx or .cer file or data from which the <see cref="Certificate"/>
/// was created).</param>
/// <param name='thumbprint'>The thumbprint of the certificate. This is a sequence of up to 40 hex digits.</param>
/// <param name='thumbprintAlgorithm'>The algorithm used to derive the thumbprint.</param>
/// <param name='certificateFormat'>The format of the certificate data.</param>
/// <param name='password'>The password to access the certificate private key.</param>
internal Certificate(
BatchClient parentBatchClient,
IEnumerable<BatchClientBehavior> baseBehaviors,
string data,
string thumbprint,
string thumbprintAlgorithm,
Common.CertificateFormat? certificateFormat = default(Common.CertificateFormat?),
string password = default(string))
{
this.propertyContainer = new PropertyContainer();
this.parentBatchClient = parentBatchClient;
this.Data = data;
this.Thumbprint = thumbprint;
this.ThumbprintAlgorithm = thumbprintAlgorithm;
this.CertificateFormat = certificateFormat;
this.Password = password;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
}
internal Certificate(
BatchClient parentBatchClient,
Models.Certificate protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="Certificate"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region Certificate
/// <summary>
/// Gets the format of the certificate data.
/// </summary>
public Common.CertificateFormat? CertificateFormat
{
get { return this.propertyContainer.CertificateFormatProperty.Value; }
private set { this.propertyContainer.CertificateFormatProperty.Value = value; }
}
/// <summary>
/// Gets the base64-encoded raw certificate data (contents of the .pfx or .cer file or data from which the <see cref="Certificate"/>
/// was created).
/// </summary>
/// <remarks>
/// <para>This property is set when creating a new <see cref="Certificate"/>. It is not defined for certificates
/// retrieved from the Batch service.</para> <para>The maximum size is 10 KB.</para>
/// </remarks>
public string Data
{
get { return this.propertyContainer.DataProperty.Value; }
private set { this.propertyContainer.DataProperty.Value = value; }
}
/// <summary>
/// Gets the error that occurred on the last attempt to delete this certificate.
/// </summary>
/// <remarks>
/// This property is null unless the certificate is in the <see cref="Common.CertificateState.DeleteFailed"/> state.
/// </remarks>
public DeleteCertificateError DeleteCertificateError
{
get { return this.propertyContainer.DeleteCertificateErrorProperty.Value; }
}
/// <summary>
/// Gets the password to access the certificate private key.
/// </summary>
/// <remarks>
/// This property is set when creating a new <see cref="Certificate"/> from .pfx format data (see <see cref="CertificateOperations.CreateCertificateFromPfx(byte[],
/// string)"/> and <see cref="CertificateOperations.CreateCertificateFromPfx(string, string)"/>). It is not defined for
/// certificates retrieved from the Batch service.
/// </remarks>
public string Password
{
get { return this.propertyContainer.PasswordProperty.Value; }
private set { this.propertyContainer.PasswordProperty.Value = value; }
}
/// <summary>
/// Gets the previous state of the certificate.
/// </summary>
/// <remarks>
/// If the certificate is in its initial <see cref="Common.CertificateState.Active"/> state, the PreviousState property
/// is not defined.
/// </remarks>
public Common.CertificateState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the certificate entered its previous state.
/// </summary>
/// <remarks>
/// If the certificate is in its initial <see cref="Common.CertificateState.Active"/> state, the PreviousStateTransitionTime
/// property is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the public part of the certificate as a string containing base-64 encoded .cer format data.
/// </summary>
public string PublicData
{
get { return this.propertyContainer.PublicDataProperty.Value; }
}
/// <summary>
/// Gets the current state of the certificate.
/// </summary>
public Common.CertificateState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the certificate entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the thumbprint of the certificate. This is a sequence of up to 40 hex digits.
/// </summary>
public string Thumbprint
{
get { return this.propertyContainer.ThumbprintProperty.Value; }
private set { this.propertyContainer.ThumbprintProperty.Value = value; }
}
/// <summary>
/// Gets the algorithm used to derive the thumbprint.
/// </summary>
public string ThumbprintAlgorithm
{
get { return this.propertyContainer.ThumbprintAlgorithmProperty.Value; }
private set { this.propertyContainer.ThumbprintAlgorithmProperty.Value = value; }
}
/// <summary>
/// Gets the URL of the certificate.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
#endregion // Certificate
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.CertificateAddParameter ITransportObjectProvider<Models.CertificateAddParameter>.GetTransportObject()
{
Models.CertificateAddParameter result = new Models.CertificateAddParameter()
{
CertificateFormat = UtilitiesInternal.MapNullableEnum<Common.CertificateFormat, Models.CertificateFormat>(this.CertificateFormat),
Data = this.Data,
Password = this.Password,
Thumbprint = this.Thumbprint,
ThumbprintAlgorithm = this.ThumbprintAlgorithm,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
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 YesNoWebApp.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;
}
}
}
| |
#region License
//-----------------------------------------------------------------------
// <copyright>
// The MIT License (MIT)
//
// Copyright (c) 2014 Kirk S Woll
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
//-----------------------------------------------------------------------
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;
using Nito.AsyncEx;
using WootzJs.Compiler.JsAst;
namespace WootzJs.Compiler
{
public class Compiler
{
public static bool RemoveUnusedSymbols;
private string mscorlib;
private string[] defines;
public Compiler(string mscorlib, string[] defines)
{
this.mscorlib = mscorlib;
this.defines = defines;
}
public static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Please provide two arguments:");
Console.WriteLine("1. The fully qualified path to your .csproj file.");
Console.WriteLine("2. The relative path to your project's output folder.");
Console.WriteLine();
Console.WriteLine("For example:");
Console.WriteLine(@"WootzJs.Compiler.exe c:\dev\MyProject\MyProject.csproj bin\");
return;
}
var projectOrSolutionFile = args[0];
var outputFolder = args[1];
var namedArguments = args.Skip(2).Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1]);
var mscorlib = namedArguments.Get("mscorlib");
var performanceFile = namedArguments.Get("performanceFile");
var define = namedArguments.Get("define");
var defines = define == null ? new string[0] : define.Split(',');
if (performanceFile != null)
{
Profiler.Output = new StreamWriter(performanceFile);
}
var fileInfo = new FileInfo(projectOrSolutionFile);
var fileFolder = fileInfo.Directory.FullName;
AsyncContext.Run(async () =>
{
try
{
if (fileInfo.Extension.Equals(".sln", StringComparison.InvariantCultureIgnoreCase))
{
var result = await Profiler.Time("Total Time", async () => await new Compiler(mscorlib, defines).CompileSolution(projectOrSolutionFile));
var output = result.Item1;
var solution = result.Item2;
var solutionName = fileInfo.Name.Substring(0, fileInfo.Name.Length - ".sln".Length);
File.WriteAllText(fileFolder + "\\" + outputFolder + solutionName + ".js", output);
}
else
{
var result = await Profiler.Time("Total Time", async () => await new Compiler(mscorlib, defines).CompileProject(projectOrSolutionFile));
var output = result.Item1;
var project = result.Item2;
var projectName = project.AssemblyName;
File.WriteAllText(fileFolder + "\\" + outputFolder + projectName + ".js", output);
}
}
catch (Exception e)
{
Console.WriteLine($"MSBUILD : error : WootzJs: {e.Message}");
Console.WriteLine(e);
Console.ReadLine();
Environment.Exit(1);
}
});
}
public async Task<Tuple<string, Solution>> CompileSolution(string solutionFile)
{
// var solution = await Profiler.Time("Loading Project", async () => await MSBuildWorkspace.Create().OpenSolutionAsync(solutionFile));
var jsCompilationUnit = new JsCompilationUnit { UseStrict = true };
// Since we have all the types required by the solution, we can keep track of which symbols are used and which
// are not. This of course means depending on reflection where you don't reference the actual symbol in code
// will result in unexpected behavior.
RemoveUnusedSymbols = true;
var projectFiles = FileUtils.GetProjectFiles(solutionFile);
var workspace = MSBuildWorkspace.Create();
var solution = await Profiler.Time("Loading Solution", async () =>
{
string mscorlib = this.mscorlib;
if (mscorlib == null)
{
mscorlib = projectFiles.Select(x => FileUtils.GetWootzJsTargetFile(x)).First();
}
Solution result = workspace.CurrentSolution;
if (mscorlib != null)
{
var mscorlibProject = await workspace.OpenProjectAsync(mscorlib);
// result = result.AddProject(mscorlibProject.Id, mscorlibProject.Name, mscorlibProject.AssemblyName, mscorlibProject.Language);
foreach (var projectFile in projectFiles)
{
var project = result.Projects.SingleOrDefault(x => x.FilePath.Equals(projectFile, StringComparison.InvariantCultureIgnoreCase));
if (project == null)
project = await workspace.OpenProjectAsync(projectFile);
// result = result.AddProject(project.Id, project.Name, project.AssemblyName, project.Language);
// project = result.GetProject(project.Id);
project = project.AddProjectReference(new ProjectReference(mscorlibProject.Id));
project = project.RemoveMetadataReference(project.MetadataReferences.Single(x => x.Display.Contains("mscorlib.dll")));
result = project.Solution;
}
}
else
{
result = await workspace.OpenSolutionAsync(solutionFile);
}
return result;
});
var projectCompilers = SortProjectsByDependencies(solution).Select(x => new ProjectCompiler(x, jsCompilationUnit, defines)).ToArray();
foreach (var compiler in projectCompilers)
{
await compiler.Compile();
}
// Write out the compiled Javascript file to the target location.
var renderer = new JsRenderer();
Profiler.Time("Rendering javascript", () => jsCompilationUnit.Accept(renderer));
// solution.Projects
return Tuple.Create(renderer.Output, solution);
}
private IEnumerable<Project> SortProjectsByDependencies(Solution solution)
{
var projects = solution.Projects.Select((x, i) => new { Index = i, Project = x }).ToList();
var prepend = projects.Take(0).ToHashSet();
do
{
if (prepend.Any())
projects = prepend.Concat(projects.Except(prepend)).Select((x, i) => new { Index = i, x.Project }).ToList();
prepend.Clear();
var mscorlib = projects.Single(x => x.Project.AssemblyName == "mscorlib");
foreach (var item in projects)
{
var referencedProjects = item.Project.ProjectReferences.Where(x => solution.ProjectIds.Contains(x.ProjectId)).Select(x => projects.Single(y => y.Project.Id == x.ProjectId)).ToList();
if (item.Project.Id != mscorlib.Project.Id)
referencedProjects.Add(mscorlib);
foreach (var referencedProject in referencedProjects)
{
if (referencedProject.Index > item.Index)
{
prepend.Add(referencedProject);
}
}
}
} while (prepend.Any());
return projects.Select(x => x.Project).ToArray();
}
public async Task<Tuple<string, Project>> CompileProject(string projectFile)
{
var projectFileInfo = new FileInfo(projectFile);
var projectFolder = projectFileInfo.Directory.FullName;
// These two lines are just a weird hack because you get no files back from compilation.SyntaxTrees
// if the user file isn't modified. Not sure why that's happening.
// var projectUserFile = projectFolder + "\\" + projectFileInfo.Name + ".user";
// if (File.Exists(projectUserFile))
// File.SetLastWriteTime(projectUserFile, DateTime.Now);
var jsCompilationUnit = new JsCompilationUnit { UseStrict = true };
var workspace = MSBuildWorkspace.Create();
var project = await Profiler.Time("Loading Project", async () =>
{
string mscorlib = this.mscorlib;
if (mscorlib == null)
{
mscorlib = FileUtils.GetWootzJsTargetFile(projectFile);
}
Project result;
if (mscorlib != null)
{
var mscorlibProject = await workspace.OpenProjectAsync(mscorlib);
result = await workspace.OpenProjectAsync(projectFile);
result = result.AddProjectReference(new ProjectReference(mscorlibProject.Id));
result = result.RemoveMetadataReference(result.MetadataReferences.Single(x => x.Display.Contains("mscorlib.dll")));
}
else
{
result = await workspace.OpenProjectAsync(projectFile);
}
return result;
});
var projectCompiler = new ProjectCompiler(project, jsCompilationUnit, defines);
await projectCompiler.Compile();
// Write out the compiled Javascript file to the target location.
var renderer = new JsRenderer();
// renderer.Builder.IsCompacting = true;
Profiler.Time("Rendering javascript", () => jsCompilationUnit.Accept(renderer));
return Tuple.Create(renderer.Output, project);
}
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using GameLibrary.Dependencies.Physics.Collision;
using GameLibrary.Dependencies.Physics.Collision.Shapes;
using GameLibrary.Dependencies.Physics.Common;
using GameLibrary.Dependencies.Physics.Dynamics.Contacts;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace GameLibrary.Dependencies.Physics.Dynamics
{
[Flags]
public enum Category
{
None = 0,
All = int.MaxValue,
Cat1 = 1,
Cat2 = 2,
Cat3 = 4,
Cat4 = 8,
Cat5 = 16,
Cat6 = 32,
Cat7 = 64,
Cat8 = 128,
Cat9 = 256,
Cat10 = 512,
Cat11 = 1024,
Cat12 = 2048,
Cat13 = 4096,
Cat14 = 8192,
Cat15 = 16384,
Cat16 = 32768,
Cat17 = 65536,
Cat18 = 131072,
Cat19 = 262144,
Cat20 = 524288,
Cat21 = 1048576,
Cat22 = 2097152,
Cat23 = 4194304,
Cat24 = 8388608,
Cat25 = 16777216,
Cat26 = 33554432,
Cat27 = 67108864,
Cat28 = 134217728,
Cat29 = 268435456,
Cat30 = 536870912,
Cat31 = 1073741824
}
/// <summary>
/// This proxy is used internally to connect fixtures to the broad-phase.
/// </summary>
public struct FixtureProxy
{
public AABB AABB;
public int ChildIndex;
public Fixture Fixture;
public int ProxyId;
}
/// <summary>
/// A fixture is used to attach a Shape to a body for collision detection. A fixture
/// inherits its transform from its parent. Fixtures hold additional non-geometric data
/// such as friction, collision filters, etc.
/// Fixtures are created via Body.CreateFixture.
/// Warning: You cannot reuse fixtures.
/// </summary>
public class Fixture : IDisposable
{
private static int _fixtureIdCounter;
/// <summary>
/// Fires after two shapes has collided and are solved. This gives you a chance to get the impact force.
/// </summary>
public AfterCollisionEventHandler AfterCollision;
/// <summary>
/// Fires when two fixtures are close to each other.
/// Due to how the broadphase works, this can be quite inaccurate as shapes are approximated using AABBs.
/// </summary>
public BeforeCollisionEventHandler BeforeCollision;
/// <summary>
/// Fires when two shapes collide and a contact is created between them.
/// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnCollisionEventHandler OnCollision;
/// <summary>
/// Fires when two shapes separate and a contact is removed between them.
/// Note that the first fixture argument is always the fixture that the delegate is subscribed to.
/// </summary>
public OnSeparationEventHandler OnSeparation;
public FixtureProxy[] Proxies;
public int ProxyCount;
internal Category _collidesWith;
internal Category _collisionCategories;
internal short _collisionGroup;
internal Dictionary<int, bool> _collisionIgnores;
private float _friction;
private float _restitution;
internal Fixture()
{
}
public Fixture(PhysicsBody body, Shape shape)
: this(body, shape, null)
{
}
public Fixture(PhysicsBody body, Shape shape, object userData)
{
if (Settings.UseFPECollisionCategories)
_collisionCategories = Category.All;
else
_collisionCategories = Category.Cat1;
_collidesWith = Category.All;
_collisionGroup = 0;
//Fixture defaults
Friction = 0.2f;
Restitution = 0;
IsSensor = false;
Body = body;
UserData = userData;
if (Settings.ConserveMemory)
Shape = shape;
else
Shape = shape.Clone();
RegisterFixture();
}
/// <summary>
/// Defaults to 0
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Collision groups allow a certain group of objects to never collide (negative)
/// or always collide (positive). Zero means no collision group. Non-zero group
/// filtering always wins against the mask bits.
///
/// If Settings.UseFPECollisionCategories is set to true:
/// If 2 fixtures are in the same collision group, they will not collide.
/// </summary>
public short CollisionGroup
{
set
{
if (_collisionGroup == value)
return;
_collisionGroup = value;
Refilter();
}
get { return _collisionGroup; }
}
/// <summary>
/// Defaults to Category.All
///
/// The collision mask bits. This states the categories that this
/// fixture would accept for collision.
/// Use Settings.UseFPECollisionCategories to change the behavior.
/// </summary>
public Category CollidesWith
{
get { return _collidesWith; }
set
{
if (_collidesWith == value)
return;
_collidesWith = value;
Refilter();
}
}
/// <summary>
/// The collision categories this fixture is a part of.
///
/// If Settings.UseFPECollisionCategories is set to false:
/// Defaults to Category.Cat1
///
/// If Settings.UseFPECollisionCategories is set to true:
/// Defaults to Category.All
/// </summary>
public Category CollisionCategories
{
get { return _collisionCategories; }
set
{
if (_collisionCategories == value)
return;
_collisionCategories = value;
Refilter();
}
}
/// <summary>
/// Get the type of the child Shape. You can use this to down cast to the concrete Shape.
/// </summary>
/// <value>The type of the shape.</value>
public ShapeType ShapeType
{
get { return Shape.ShapeType; }
}
/// <summary>
/// Get the child Shape. You can modify the child Shape, however you should not change the
/// number of vertices because this will crash some collision caching mechanisms.
/// </summary>
/// <value>The shape.</value>
public Shape Shape { get; internal set; }
/// <summary>
/// Gets or sets a value indicating whether this fixture is a sensor.
/// </summary>
/// <value><c>true</c> if this instance is a sensor; otherwise, <c>false</c>.</value>
public bool IsSensor { get; set; }
/// <summary>
/// Get the parent body of this fixture. This is null if the fixture is not attached.
/// </summary>
/// <value>The body.</value>
public PhysicsBody Body { get; internal set; }
/// <summary>
/// Set the user data. Use this to store your application specific data.
/// </summary>
/// <value>The user data.</value>
public object UserData { get; set; }
/// <summary>
/// Get or set the coefficient of friction.
/// </summary>
/// <value>The friction.</value>
public float Friction
{
get { return _friction; }
set
{
Debug.Assert(!float.IsNaN(value));
_friction = value;
}
}
/// <summary>
/// Get or set the coefficient of restitution.
/// </summary>
/// <value>The restitution.</value>
public float Restitution
{
get { return _restitution; }
set
{
Debug.Assert(!float.IsNaN(value));
_restitution = value;
}
}
/// <summary>
/// Gets a unique ID for this fixture.
/// </summary>
/// <value>The fixture id.</value>
public int FixtureId { get; private set; }
#region IDisposable Members
public bool IsDisposed { get; set; }
public void Dispose()
{
if (!IsDisposed)
{
Body.DestroyFixture(this);
IsDisposed = true;
GC.SuppressFinalize(this);
}
}
#endregion IDisposable Members
/// <summary>
/// Restores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void RestoreCollisionWith(Fixture fixture)
{
if (_collisionIgnores == null)
return;
if (_collisionIgnores.ContainsKey(fixture.FixtureId))
{
_collisionIgnores[fixture.FixtureId] = false;
Refilter();
}
}
/// <summary>
/// Ignores collisions between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
public void IgnoreCollisionWith(Fixture fixture)
{
if (_collisionIgnores == null)
_collisionIgnores = new Dictionary<int, bool>();
if (_collisionIgnores.ContainsKey(fixture.FixtureId))
_collisionIgnores[fixture.FixtureId] = true;
else
_collisionIgnores.Add(fixture.FixtureId, true);
Refilter();
}
/// <summary>
/// Determines whether collisions are ignored between this fixture and the provided fixture.
/// </summary>
/// <param name="fixture">The fixture.</param>
/// <returns>
/// <c>true</c> if the fixture is ignored; otherwise, <c>false</c>.
/// </returns>
public bool IsFixtureIgnored(Fixture fixture)
{
if (_collisionIgnores == null)
return false;
if (_collisionIgnores.ContainsKey(fixture.FixtureId))
return _collisionIgnores[fixture.FixtureId];
return false;
}
/// <summary>
/// Contacts are persistant and will keep being persistant unless they are
/// flagged for filtering.
/// This methods flags all contacts associated with the body for filtering.
/// </summary>
internal void Refilter()
{
// Flag associated contacts for filtering.
ContactEdge edge = Body.ContactList;
while (edge != null)
{
Contact contact = edge.Contact;
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
if (fixtureA == this || fixtureB == this)
{
contact.FlagForFiltering();
}
edge = edge.Next;
}
PhysicsWorld world = Body.World;
if (world == null)
{
return;
}
// Touch each proxy so that new pairs may be created
IBroadPhase broadPhase = world.ContactManager.BroadPhase;
for (int i = 0; i < ProxyCount; ++i)
{
broadPhase.TouchProxy(Proxies[i].ProxyId);
}
}
private void RegisterFixture()
{
// Reserve proxy space
Proxies = new FixtureProxy[Shape.ChildCount];
ProxyCount = 0;
FixtureId = _fixtureIdCounter++;
if ((Body.Flags & BodyFlags.Enabled) == BodyFlags.Enabled)
{
IBroadPhase broadPhase = Body.World.ContactManager.BroadPhase;
CreateProxies(broadPhase, ref Body.Xf);
}
Body.FixtureList.Add(this);
// Adjust mass properties if needed.
if (Shape._density > 0.0f)
{
Body.ResetMassData();
}
// Let the world know we have a new fixture. This will cause new contacts
// to be created at the beginning of the next time step.
Body.World.Flags |= WorldFlags.NewFixture;
if (Body.World.FixtureAdded != null)
{
Body.World.FixtureAdded(this);
}
}
/// <summary>
/// Test a point for containment in this fixture.
/// </summary>
/// <param name="point">A point in world coordinates.</param>
/// <returns></returns>
public bool TestPoint(ref Vector2 point)
{
return Shape.TestPoint(ref Body.Xf, ref point);
}
/// <summary>
/// Cast a ray against this Shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="childIndex">Index of the child.</param>
/// <returns></returns>
public bool RayCast(out RayCastOutput output, ref RayCastInput input, int childIndex)
{
return Shape.RayCast(out output, ref input, ref Body.Xf, childIndex);
}
/// <summary>
/// Get the fixture's AABB. This AABB may be enlarge and/or stale.
/// If you need a more accurate AABB, compute it using the Shape and
/// the body transform.
/// </summary>
/// <param name="aabb">The aabb.</param>
/// <param name="childIndex">Index of the child.</param>
public void GetAABB(out AABB aabb, int childIndex)
{
Debug.Assert(0 <= childIndex && childIndex < ProxyCount);
aabb = Proxies[childIndex].AABB;
}
public Fixture Clone(PhysicsBody body)
{
Fixture fixture = new Fixture();
fixture.Body = body;
if (Settings.ConserveMemory)
fixture.Shape = Shape;
else
fixture.Shape = Shape.Clone();
fixture.UserData = UserData;
fixture.Restitution = Restitution;
fixture.Friction = Friction;
fixture.IsSensor = IsSensor;
fixture._collisionGroup = CollisionGroup;
fixture._collisionCategories = CollisionCategories;
fixture._collidesWith = CollidesWith;
if (_collisionIgnores != null)
{
fixture._collisionIgnores = new Dictionary<int, bool>();
foreach (KeyValuePair<int, bool> pair in _collisionIgnores)
{
fixture._collisionIgnores.Add(pair.Key, pair.Value);
}
}
fixture.RegisterFixture();
return fixture;
}
public Fixture DeepClone()
{
Fixture fix = Clone(Body.Clone());
return fix;
}
internal void Destroy()
{
// The proxies must be destroyed before calling this.
Debug.Assert(ProxyCount == 0);
// Free the proxy array.
Proxies = null;
Shape = null;
BeforeCollision = null;
OnCollision = null;
OnSeparation = null;
AfterCollision = null;
if (Body.World.FixtureRemoved != null)
{
Body.World.FixtureRemoved(this);
}
Body.World.FixtureAdded = null;
Body.World.FixtureRemoved = null;
OnSeparation = null;
OnCollision = null;
}
// These support body activation/deactivation.
internal void CreateProxies(IBroadPhase broadPhase, ref Transform xf)
{
Debug.Assert(ProxyCount == 0);
// Create proxies in the broad-phase.
ProxyCount = Shape.ChildCount;
for (int i = 0; i < ProxyCount; ++i)
{
FixtureProxy proxy = new FixtureProxy();
Shape.ComputeAABB(out proxy.AABB, ref xf, i);
proxy.Fixture = this;
proxy.ChildIndex = i;
proxy.ProxyId = broadPhase.AddProxy(ref proxy);
Proxies[i] = proxy;
}
}
internal void DestroyProxies(IBroadPhase broadPhase)
{
// Destroy proxies in the broad-phase.
for (int i = 0; i < ProxyCount; ++i)
{
broadPhase.RemoveProxy(Proxies[i].ProxyId);
Proxies[i].ProxyId = -1;
}
ProxyCount = 0;
}
internal void Synchronize(IBroadPhase broadPhase, ref Transform transform1, ref Transform transform2)
{
if (ProxyCount == 0)
{
return;
}
for (int i = 0; i < ProxyCount; ++i)
{
FixtureProxy proxy = Proxies[i];
// Compute an AABB that covers the swept Shape (may miss some rotation effect).
AABB aabb1, aabb2;
Shape.ComputeAABB(out aabb1, ref transform1, proxy.ChildIndex);
Shape.ComputeAABB(out aabb2, ref transform2, proxy.ChildIndex);
proxy.AABB.Combine(ref aabb1, ref aabb2);
Vector2 displacement = transform2.Position - transform1.Position;
broadPhase.MoveProxy(proxy.ProxyId, ref proxy.AABB, displacement);
}
}
internal bool CompareTo(Fixture fixture)
{
return (
CollidesWith == fixture.CollidesWith &&
CollisionCategories == fixture.CollisionCategories &&
CollisionGroup == fixture.CollisionGroup &&
Friction == fixture.Friction &&
IsSensor == fixture.IsSensor &&
Restitution == fixture.Restitution &&
Shape.CompareTo(fixture.Shape) &&
UserData == fixture.UserData);
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Drawing;
using Gallio.Common.IO;
using Gallio.Common.Xml;
using Gallio.Icarus.Controllers;
using Gallio.Icarus.Controls;
using Gallio.Icarus.Tests.Utilities;
using Gallio.Model;
using Gallio.Runner;
using Gallio.Runtime.Logging;
using Gallio.UI.Common.Policies;
using Gallio.UI.Events;
using MbUnit.Framework;
using Rhino.Mocks;
namespace Gallio.Icarus.Tests.Controllers
{
[Category("Controllers"), TestsOn(typeof(OptionsController))]
internal class OptionsControllerTest
{
private IEventAggregator eventAggregator;
private OptionsController optionsController;
private IFileSystem fileSystem;
private IXmlSerializer xmlSerializer;
private IUnhandledExceptionPolicy unhandledExceptionPolicy;
[SetUp]
public void SetUp()
{
fileSystem = MockRepository.GenerateStub<IFileSystem>();
xmlSerializer = MockRepository.GenerateStub<IXmlSerializer>();
unhandledExceptionPolicy = MockRepository.GenerateStub<IUnhandledExceptionPolicy>();
eventAggregator = MockRepository.GenerateStub<IEventAggregator>();
optionsController = new OptionsController(fileSystem, xmlSerializer, unhandledExceptionPolicy, eventAggregator);
}
private void SetUpOptionsController(Settings settings)
{
fileSystem.Stub(fs => fs.FileExists(Arg<string>.Is.Anything)).Return(true);
xmlSerializer.Stub(xs => xs.LoadFromXml<Settings>(Arg<string>.Is.Anything)).Return(settings);
optionsController.Load();
}
[Test]
public void RestorePreviousSettings_Test()
{
SetUpOptionsController(new Settings());
Assert.IsTrue(optionsController.RestorePreviousSettings);
optionsController.RestorePreviousSettings = false;
Assert.IsFalse(optionsController.RestorePreviousSettings);
}
[SyncTest]
public void TestRunnerFactory_Test()
{
SetUpOptionsController(new Settings());
bool propChangedFlag = false;
optionsController.TestRunnerFactory.PropertyChanged += (s, e) =>
{
propChangedFlag = true;
};
Assert.AreEqual(StandardTestRunnerFactoryNames.IsolatedProcess, optionsController.TestRunnerFactory.Value);
optionsController.TestRunnerFactory.Value = StandardTestRunnerFactoryNames.Local;
Assert.IsTrue(propChangedFlag);
Assert.AreEqual(StandardTestRunnerFactoryNames.Local, optionsController.TestRunnerFactory.Value);
}
[Test]
public void AlwaysReloadFiles_Test()
{
SetUpOptionsController(new Settings());
Assert.IsFalse(optionsController.AlwaysReloadFiles);
optionsController.AlwaysReloadFiles = true;
Assert.IsTrue(optionsController.AlwaysReloadFiles);
}
[Test]
public void ShowProgressDialogs_Test()
{
SetUpOptionsController(new Settings());
Assert.IsTrue(optionsController.ShowProgressDialogs);
optionsController.ShowProgressDialogs = false;
Assert.IsFalse(optionsController.ShowProgressDialogs);
}
[Test]
public void TestStatusBarStyle_Test()
{
SetUpOptionsController(new Settings());
Assert.AreEqual(TestStatusBarStyles.Integration, optionsController.TestStatusBarStyle);
optionsController.TestStatusBarStyle = TestStatusBarStyles.UnitTest;
Assert.AreEqual(TestStatusBarStyles.UnitTest, optionsController.TestStatusBarStyle);
}
[Test]
public void FailedColor_Test()
{
SetUpOptionsController(new Settings());
Assert.AreEqual(Color.Red.ToArgb(), optionsController.FailedColor.ToArgb());
optionsController.FailedColor = Color.Black;
Assert.AreEqual(Color.Black.ToArgb(), optionsController.FailedColor.ToArgb());
}
[Test]
public void PassedColor_Test()
{
SetUpOptionsController(new Settings());
Assert.AreEqual(Color.Green.ToArgb(), optionsController.PassedColor.ToArgb());
optionsController.PassedColor = Color.Black;
Assert.AreEqual(Color.Black.ToArgb(), optionsController.PassedColor.ToArgb());
}
[Test]
public void InconclusiveColor_Test()
{
SetUpOptionsController(new Settings());
Assert.AreEqual(Color.Gold.ToArgb(), optionsController.InconclusiveColor.ToArgb());
optionsController.InconclusiveColor = Color.Black;
Assert.AreEqual(Color.Black.ToArgb(), optionsController.InconclusiveColor.ToArgb());
}
[Test]
public void SkippedColor_Test()
{
SetUpOptionsController(new Settings());
Assert.AreEqual(Color.SlateGray.ToArgb(), optionsController.SkippedColor.ToArgb());
optionsController.SkippedColor = Color.Black;
Assert.AreEqual(Color.Black.ToArgb(), optionsController.SkippedColor.ToArgb());
}
[Test]
public void SelectedTreeViewCategories_Test()
{
SetUpOptionsController(new Settings());
Assert.Count(5, optionsController.SelectedTreeViewCategories.Value);
}
[Test]
public void UnselectedTreeViewCategories_Test()
{
SetUpOptionsController(new Settings());
Assert.AreEqual(typeof(MetadataKeys).GetFields().Length - 4,
optionsController.UnselectedTreeViewCategories.Value.Count);
}
[Test]
public void Cancel_should_reload_options()
{
SetUpOptionsController(new Settings());
optionsController.Cancel();
xmlSerializer.AssertWasCalled(xs => xs.LoadFromXml<Settings>(Arg<string>.Is.Anything),
o => o.Repeat.Twice());
}
[Test]
public void Save_should_save_settings_as_xml()
{
fileSystem.Stub(fs => fs.DirectoryExists(Arg<string>.Is.Anything)).Return(true);
optionsController.Save();
xmlSerializer.AssertWasCalled(xs => xs.SaveToXml(Arg<Settings>.Is.Anything,
Arg<string>.Is.Anything));
}
[Test]
public void Save_should_create_directory_if_it_does_not_exist()
{
fileSystem.Stub(fs => fs.DirectoryExists(Arg<string>.Is.Anything)).Return(false);
optionsController.Save();
fileSystem.AssertWasCalled(fs => fs.CreateDirectory(Arg<string>.Is.Anything));
}
[Test]
public void GenerateReportAfterTestRun_Test()
{
SetUpOptionsController(new Settings());
Assert.IsTrue(optionsController.GenerateReportAfterTestRun);
optionsController.GenerateReportAfterTestRun = false;
Assert.IsFalse(optionsController.GenerateReportAfterTestRun);
}
[Test]
public void Location_Test()
{
SetUpOptionsController(new Settings());
var p = new Point(0, 0);
optionsController.Location = p;
Assert.AreEqual(p, optionsController.Location);
}
[Test]
public void RecentProjects_Test()
{
var settings = new Settings();
settings.RecentProjects.AddRange(new[] { "one", "two" });
SetUpOptionsController(settings);
Assert.AreEqual(settings.RecentProjects.Count, optionsController.RecentProjects.Count);
Assert.AreElementsEqual(settings.RecentProjects, optionsController.RecentProjects.Items);
}
[Test]
public void RunTestsAfterReload_Test()
{
SetUpOptionsController(new Settings());
Assert.IsFalse(optionsController.RunTestsAfterReload);
optionsController.RunTestsAfterReload = true;
Assert.IsTrue(optionsController.RunTestsAfterReload);
}
[Test]
public void Size_Test()
{
SetUpOptionsController(new Settings());
var size = new Size(0, 0);
optionsController.Size = size;
Assert.AreEqual(size, optionsController.Size);
}
[Test]
public void UpdateDelay_Test()
{
SetUpOptionsController(new Settings());
Assert.AreEqual(1000, optionsController.UpdateDelay);
}
[Test]
public void AnnotationShowErrors_Test()
{
SetUpOptionsController(new Settings());
optionsController.AnnotationsShowErrors = false;
Assert.AreEqual(false, optionsController.AnnotationsShowErrors);
}
[Test]
public void AnnotationShowInfos_Test()
{
SetUpOptionsController(new Settings());
optionsController.AnnotationsShowInfos = false;
Assert.AreEqual(false, optionsController.AnnotationsShowInfos);
}
[Test]
public void AnnotationShowWarnings_Test()
{
SetUpOptionsController(new Settings());
optionsController.AnnotationsShowWarnings = false;
Assert.AreEqual(false, optionsController.AnnotationsShowWarnings);
}
[Test]
public void MinLogSeverity_should_return_value_from_settings()
{
var settings = new Settings { MinLogSeverity = LogSeverity.Error };
SetUpOptionsController(settings);
Assert.AreEqual(LogSeverity.Error, optionsController.MinLogSeverity);
optionsController.MinLogSeverity = LogSeverity.Debug;
Assert.AreEqual(LogSeverity.Debug, optionsController.MinLogSeverity);
}
[Test]
public void RecursiveExecutionLog_Test()
{
SetUpOptionsController(new Settings());
Assert.IsTrue(optionsController.RecursiveExecutionLog);
optionsController.RecursiveExecutionLog = false;
Assert.IsFalse(optionsController.RecursiveExecutionLog);
}
[Test]
public void AutoSave_Test()
{
SetUpOptionsController(new Settings());
Assert.IsFalse(optionsController.AutoSaveProject);
optionsController.AutoSaveProject = true;
Assert.IsTrue(optionsController.AutoSaveProject);
}
}
}
| |
using System;
using System.Collections;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.IO {
// ABOUT:
// Helps with path normalization; support allocating on the stack or heap
//
// PathHelper can't stackalloc the array for obvious reasons; you must pass
// in an array of chars allocated on the stack.
//
// USAGE:
// Suppose you need to represent a char array of length len. Then this is the
// suggested way to instantiate PathHelper:
// ***************************************************************************
// PathHelper pathHelper;
// if (charArrayLength less than stack alloc threshold == Path.MaxPath)
// char* arrayPtr = stackalloc char[Path.MaxPath];
// pathHelper = new PathHelper(arrayPtr);
// else
// pathHelper = new PathHelper(capacity, maxPath);
// ***************************************************************************
//
// note in the StringBuilder ctor:
// - maxPath may be greater than Path.MaxPath (for isolated storage)
// - capacity may be greater than maxPath. This is even used for non-isolated
// storage scenarios where we want to temporarily allow strings greater
// than Path.MaxPath if they can be normalized down to Path.MaxPath. This
// can happen if the path contains escape characters "..".
//
unsafe internal class PathHelper { // should not be serialized
// maximum size, max be greater than max path if contains escape sequence
private int m_capacity;
// current length (next character position)
private int m_length;
// max path, may be less than capacity
private int m_maxPath;
// ptr to stack alloc'd array of chars
[SecurityCritical]
private char* m_arrayPtr;
// StringBuilder
private StringBuilder m_sb;
// whether to operate on stack alloc'd or heap alloc'd array
private bool useStackAlloc;
// Whether to skip calls to Win32Native.GetLongPathName becasue we tried before and failed:
private bool doNotTryExpandShortFileName;
// Instantiates a PathHelper with a stack alloc'd array of chars
[System.Security.SecurityCritical]
internal PathHelper(char* charArrayPtr, int length) {
Contract.Requires(charArrayPtr != null);
// force callers to be aware of this
Contract.Requires(length == Path.MaxPath);
this.m_arrayPtr = charArrayPtr;
this.m_capacity = length;
this.m_maxPath = Path.MaxPath;
useStackAlloc = true;
doNotTryExpandShortFileName = false;
}
// Instantiates a PathHelper with a heap alloc'd array of ints. Will create a StringBuilder
internal PathHelper(int capacity, int maxPath) {
this.m_sb = new StringBuilder(capacity);
this.m_capacity = capacity;
this.m_maxPath = maxPath;
doNotTryExpandShortFileName = false;
}
internal int Length {
get {
if (useStackAlloc) {
return m_length;
}
else {
return m_sb.Length;
}
}
set {
if (useStackAlloc) {
m_length = value;
}
else {
m_sb.Length = value;
}
}
}
internal int Capacity {
get {
return m_capacity;
}
}
internal char this[int index] {
[System.Security.SecurityCritical]
get {
Contract.Requires(index >= 0 && index < Length);
if (useStackAlloc) {
return m_arrayPtr[index];
}
else {
return m_sb[index];
}
}
[System.Security.SecurityCritical]
set {
Contract.Requires(index >= 0 && index < Length);
if (useStackAlloc) {
m_arrayPtr[index] = value;
}
else {
m_sb[index] = value;
}
}
}
[System.Security.SecurityCritical]
internal unsafe void Append(char value) {
if (Length + 1 >= m_capacity)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
if (useStackAlloc) {
m_arrayPtr[Length] = value;
m_length++;
}
else {
m_sb.Append(value);
}
}
[System.Security.SecurityCritical]
internal unsafe int GetFullPathName() {
if (useStackAlloc) {
char* finalBuffer = stackalloc char[Path.MaxPath + 1];
int result = Win32Native.GetFullPathName(m_arrayPtr, Path.MaxPath + 1, finalBuffer, IntPtr.Zero);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (result > Path.MaxPath) {
char* tempBuffer = stackalloc char[result];
finalBuffer = tempBuffer;
result = Win32Native.GetFullPathName(m_arrayPtr, result, finalBuffer, IntPtr.Zero);
}
// Full path is genuinely long
if (result >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
Contract.Assert(result < Path.MaxPath, "did we accidently remove a PathTooLongException check?");
if (result == 0 && m_arrayPtr[0] != '\0') {
__Error.WinIOError();
}
else if (result < Path.MaxPath) {
// Null terminate explicitly (may be only needed for some cases such as empty strings)
// GetFullPathName return length doesn't account for null terminating char...
finalBuffer[result] = '\0'; // Safe to write directly as result is < Path.MaxPath
}
// We have expanded the paths and GetLongPathName may or may not behave differently from before.
// We need to call it again to see:
doNotTryExpandShortFileName = false;
String.wstrcpy(m_arrayPtr, finalBuffer, result);
// Doesn't account for null terminating char. Think of this as the last
// valid index into the buffer but not the length of the buffer
Length = result;
return result;
}
else {
StringBuilder finalBuffer = new StringBuilder(m_capacity + 1);
int result = Win32Native.GetFullPathName(m_sb.ToString(), m_capacity + 1, finalBuffer, IntPtr.Zero);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (result > m_maxPath) {
finalBuffer.Length = result;
result = Win32Native.GetFullPathName(m_sb.ToString(), result, finalBuffer, IntPtr.Zero);
}
// Fullpath is genuinely long
if (result >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
Contract.Assert(result < m_maxPath, "did we accidentally remove a PathTooLongException check?");
if (result == 0 && m_sb[0] != '\0') {
if (Length >= m_maxPath) {
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
__Error.WinIOError();
}
// We have expanded the paths and GetLongPathName may or may not behave differently from before.
// We need to call it again to see:
doNotTryExpandShortFileName = false;
m_sb = finalBuffer;
return result;
}
}
[System.Security.SecurityCritical]
internal unsafe bool TryExpandShortFileName() {
if (doNotTryExpandShortFileName)
return false;
if (useStackAlloc) {
NullTerminate();
char* buffer = UnsafeGetArrayPtr();
char* shortFileNameBuffer = stackalloc char[Path.MaxPath + 1];
int r = Win32Native.GetLongPathName(buffer, shortFileNameBuffer, Path.MaxPath);
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (r >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
if (r == 0) {
// Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
// path like \\.\PHYSICALDEVICE0 - some device driver doesn't
// support GetLongPathName on that string. This behavior is
// by design, according to the Core File Services team.
// We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
// intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
// We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
int lastErr = Marshal.GetLastWin32Error();
if (lastErr == Win32Native.ERROR_FILE_NOT_FOUND || lastErr == Win32Native.ERROR_PATH_NOT_FOUND)
doNotTryExpandShortFileName = true;
return false;
}
// Safe to copy as we have already done Path.MaxPath bound checking
String.wstrcpy(buffer, shortFileNameBuffer, r);
Length = r;
// We should explicitly null terminate as in some cases the long version of the path
// might actually be shorter than what we started with because of Win32's normalization
// Safe to write directly as bufferLength is guaranteed to be < Path.MaxPath
NullTerminate();
return true;
}
else {
StringBuilder sb = GetStringBuilder();
String origName = sb.ToString();
String tempName = origName;
bool addedPrefix = false;
if (tempName.Length > Path.MaxPath) {
tempName = Path.AddLongPathPrefix(tempName);
addedPrefix = true;
}
sb.Capacity = m_capacity;
sb.Length = 0;
int r = Win32Native.GetLongPathName(tempName, sb, m_capacity);
if (r == 0) {
// Note: GetLongPathName will return ERROR_INVALID_FUNCTION on a
// path like \\.\PHYSICALDEVICE0 - some device driver doesn't
// support GetLongPathName on that string. This behavior is
// by design, according to the Core File Services team.
// We also get ERROR_NOT_ENOUGH_QUOTA in SQL_CLR_STRESS runs
// intermittently on paths like D:\DOCUME~1\user\LOCALS~1\Temp\
// We do not need to call GetLongPathName if we know it will fail becasue the path does not exist:
int lastErr = Marshal.GetLastWin32Error();
if (Win32Native.ERROR_FILE_NOT_FOUND == lastErr || Win32Native.ERROR_PATH_NOT_FOUND == lastErr)
doNotTryExpandShortFileName = true;
sb.Length = 0;
sb.Append(origName);
return false;
}
if (addedPrefix)
r -= 4;
// If success, the return buffer length does not account for the terminating null character.
// If in-sufficient buffer, the return buffer length does account for the path + the terminating null character.
// If failure, the return buffer length is zero
if (r >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
sb = Path.RemoveLongPathPrefix(sb);
Length = sb.Length;
return true;
}
}
[System.Security.SecurityCritical]
internal unsafe void Fixup(int lenSavedName, int lastSlash) {
if (useStackAlloc) {
char* savedName = stackalloc char[lenSavedName];
String.wstrcpy(savedName, m_arrayPtr + lastSlash + 1, lenSavedName);
Length = lastSlash;
NullTerminate();
doNotTryExpandShortFileName = false;
bool r = TryExpandShortFileName();
// Clean up changes made to the newBuffer.
Append(Path.DirectorySeparatorChar);
if (Length + lenSavedName >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
String.wstrcpy(m_arrayPtr + Length, savedName, lenSavedName);
Length = Length + lenSavedName;
}
else {
String savedName = m_sb.ToString(lastSlash + 1, lenSavedName);
Length = lastSlash;
doNotTryExpandShortFileName = false;
bool r = TryExpandShortFileName();
// Clean up changes made to the newBuffer.
Append(Path.DirectorySeparatorChar);
if (Length + lenSavedName >= m_maxPath)
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
m_sb.Append(savedName);
}
}
[System.Security.SecurityCritical]
internal unsafe bool OrdinalStartsWith(String compareTo, bool ignoreCase) {
if (Length < compareTo.Length)
return false;
if (useStackAlloc) {
NullTerminate();
if (ignoreCase) {
String s = new String(m_arrayPtr, 0, compareTo.Length);
return compareTo.Equals(s, StringComparison.OrdinalIgnoreCase);
}
else {
for (int i = 0; i < compareTo.Length; i++) {
if (m_arrayPtr[i] != compareTo[i]) {
return false;
}
}
return true;
}
}
else {
if (ignoreCase) {
return m_sb.ToString().StartsWith(compareTo, StringComparison.OrdinalIgnoreCase);
}
else {
return m_sb.ToString().StartsWith(compareTo, StringComparison.Ordinal);
}
}
}
[System.Security.SecuritySafeCritical]
public override String ToString() {
if (useStackAlloc) {
return new String(m_arrayPtr, 0, Length);
}
else {
return m_sb.ToString();
}
}
[System.Security.SecurityCritical]
private unsafe char* UnsafeGetArrayPtr() {
Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
return m_arrayPtr;
}
private StringBuilder GetStringBuilder() {
Contract.Requires(!useStackAlloc, "This should never be called for PathHelpers that wrap a stackalloc'd buffer");
return m_sb;
}
[System.Security.SecurityCritical]
private unsafe void NullTerminate() {
Contract.Requires(useStackAlloc, "This should never be called for PathHelpers wrapping a StringBuilder");
m_arrayPtr[m_length] = '\0';
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Microsoft.Zelig.Test
{
public class ArraysOtherTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize( )
{
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
result |= Assert.CheckFailed( Othersystemarrays_conversion_01_Test( ) );
result |= Assert.CheckFailed( Othersystemarrays_conversion_02_Test( ) );
result |= Assert.CheckFailed( Othersystemarrays_nullvalue_01_Test( ) );
result |= Assert.CheckFailed( Othercovariance_exception_01_Test( ) );
result |= Assert.CheckFailed( Othercovariance_exception_02_Test( ) );
result |= Assert.CheckFailed( Othercovariance_explicit_01_Test( ) );
result |= Assert.CheckFailed( Othercovariance_explicit_02_Test( ) );
result |= Assert.CheckFailed( Othercovariance_explicit_03_Test( ) );
result |= Assert.CheckFailed( Othercovariance_explicit_04_Test( ) );
result |= Assert.CheckFailed( Othercovariance_implicit_01_Test( ) );
result |= Assert.CheckFailed( Othercovariance_implicit_02_Test( ) );
result |= Assert.CheckFailed( Othercovariance_implicit_03_Test( ) );
result |= Assert.CheckFailed( Othercovariance_implicit_04_Test( ) );
result |= Assert.CheckFailed( Othercovariance_implicit_05_Test( ) );
return result;
}
//Other Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Other
//systemarrays_conversion_01,systemarrays_conversion_02,systemarrays_nullvalue_01,covariance_exception_01,covariance_exception_02,covariance_explicit_01,covariance_explicit_02,covariance_explicit_03,covariance_explicit_04,covariance_implicit_01,covariance_implicit_02,covariance_implicit_03,covariance_implicit_04,covariance_implicit_05
//Test Case Calls
[TestMethod]
public TestResult Othersystemarrays_conversion_01_Test()
{
Log.Comment("System.Array Type - Conversions ");
Log.Comment("Verify that an implicit reference conversion from T[D] to System.Array exists");
if (Other_TestClass_systemarrays_conversion_01.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othersystemarrays_conversion_02_Test()
{
Log.Comment("System.Array Type - Conversions ");
Log.Comment("Verify that an explicit reference conversion from System.Array to T[D] exists");
if (Other_TestClass_systemarrays_conversion_02.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othersystemarrays_nullvalue_01_Test()
{
Log.Comment("System.Array Type - Null Values");
Log.Comment("Verify that a System.Array array can be set to null");
if (Other_TestClass_systemarrays_nullvalue_01.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_exception_01_Test()
{
if (Other_TestClass_covariance_exception_01.testMethod())
{
return TestResult.Pass;
}
return TestResult.KnownFailure;
}
[TestMethod]
public TestResult Othercovariance_exception_02_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify an System.Exception is thrown when incompatible types are assigned to array elements");
if (Other_TestClass_covariance_exception_02.testMethod())
{
return TestResult.Pass;
}
return TestResult.KnownFailure;
}
[TestMethod]
public TestResult Othercovariance_explicit_01_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from object to any reference-type (class)");
if (Other_TestClass_covariance_explicit_01.testMethod())
{
return TestResult.Pass;
}
return TestResult.KnownFailure;
}
[TestMethod]
public TestResult Othercovariance_explicit_02_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any reference-type (interface) to object");
if (Other_TestClass_covariance_explicit_02.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_explicit_03_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any class-type S to any class-type T, provided S is base class of T");
if (Other_TestClass_covariance_explicit_03.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_explicit_04_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any interface-type S to any interface-type T, provided S is not derived from T");
if (Other_TestClass_covariance_explicit_04.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_implicit_01_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any reference-type (class) to object");
if (Other_TestClass_covariance_implicit_01.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_implicit_02_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any reference-type (interface) to object");
if (Other_TestClass_covariance_implicit_02.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_implicit_03_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any class-type S to any class-type T, provided S is derived from T");
if (Other_TestClass_covariance_implicit_03.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_implicit_04_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any class-type S to any interface-type T, provided S implements T");
if (Other_TestClass_covariance_implicit_04.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Othercovariance_implicit_05_Test()
{
Log.Comment("Array Covariance");
Log.Comment("Verify covariance from any interface-type S to any interface-type T, provided S is derived from T");
if (Other_TestClass_covariance_implicit_05.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult BinarySearch_Test()
{
Log.Comment("Array.BinarySearch");
var objects = new MyClass[6];
for (int i = 0; i < 6; i++)
{
objects[i] = new MyClass(i + 1);
}
int y = Array.BinarySearch(objects, new MyClass(5), null);
if (y == 4)
{
return TestResult.Pass;
}
else
{
Log.Comment("BinarySearch returns " + y.ToString());
return TestResult.Fail;
}
}
class MyClass : IComparable
{
int m_int;
public MyClass(int i)
{
m_int = i;
}
public int Value { get { return m_int; } }
public int CompareTo(object obj)
{
var target = obj as MyClass;
if (target == null)
{
throw new ArgumentException( );
}
return m_int - target.m_int;
}
}
//Compiled Test Cases
class Other_TestClass_systemarrays_conversion_01
{
public static int Main_old()
{
int result = 32;
MyClass[] a = new MyClass[] { new MyClass(5), new MyClass(6), new MyClass(7) };
System.Array SystemArray;
int[] StaticArray = new int[] { 10, 20, 30, 40 };
// There exists an implicit reference conversion for this
SystemArray = StaticArray;
if (result == a[2].Value)
{
return 1;
}
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class Other_TestClass_systemarrays_conversion_02
{
public static int Main_old()
{
System.Array SystemArray;
int[] StaticArray = new int[] { 10, 20, 30, 40 };
int[] StaticArray2 = new int[] { 1, 2, 3, 4 };
SystemArray = StaticArray;
StaticArray2 = (int[])SystemArray;
int result = 0;
for (int x = 0; x < 4; x++)
{
if (StaticArray[x] != (x + 1) * 10)
{
result = 1;
}
}
return result;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class Other_TestClass_systemarrays_nullvalue_01
{
public static int Main_old()
{
System.Array SystemArray;
SystemArray = null;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class Other_TestClass_covariance_exception_01
{
static void Fill(object[] array, int index, int count, object value)
{
for (int i = index; i < index + count; i++)
array[i] = value;
}
public static int Main_old( )
{
string[] strings = new string[100];
Fill( strings, 0, 100, "Undefined" );
Fill( strings, 0, 10, null );
try
{
Fill( strings, 90, 10, 0 );
}
catch(System.Exception)
{
return 0;
}
return 1;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class Queue
{
int next;
int prev;
}
class Other_TestClass_covariance_exception_02
{
public static int Main_old()
{
string[] stringArr = new string[10];
object[] objectArr = stringArr;
objectArr[0] = "hello";
try
{
objectArr[1] = new Queue();
}
catch (System.Exception)
{
return 0;
}
return 1;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class Other_TestClass_covariance_explicit_01_Imp
{
public int x;
}
class Other_TestClass_covariance_explicit_01
{
public static int Main_old()
{
Other_TestClass_covariance_explicit_01_Imp[] mc = new Other_TestClass_covariance_explicit_01_Imp[10];
for (int x=0; x < 10; x++)
{
mc[x] = new Other_TestClass_covariance_explicit_01_Imp( );
mc[x].x = x;
}
object[] o = new Other_TestClass_covariance_explicit_01_Imp[10];
mc = (Other_TestClass_covariance_explicit_01_Imp[])o;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
interface Other_TestClass_covariance_explicit_02_Inter
{
int testmethod( );
}
class Other_TestClass_covariance_explicit_02_Imp : Other_TestClass_covariance_explicit_02_Inter
{
public int testmethod()
{
Log.Comment("Other_TestClass_covariance_explicit_02_Imp::testmethod()");
return 0;
}
}
class Other_TestClass_covariance_explicit_02
{
public static int Main_old()
{
Other_TestClass_covariance_explicit_02_Inter[] inst = new Other_TestClass_covariance_explicit_02_Inter[10];
for (int x = 0; x < 10; x++)
{
inst[x] = new Other_TestClass_covariance_explicit_02_Imp( );
}
object[] o = new Other_TestClass_covariance_explicit_02_Imp[10];
inst = (Other_TestClass_covariance_explicit_02_Imp[])o;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class ClassS
{
public int x;
}
class ClassT : ClassS
{
public int y;
}
class Other_TestClass_covariance_explicit_03
{
public static int Main_old()
{
ClassS[] cs = new ClassT[10];
ClassT[] ct = new ClassT[10];
for (int x = 0; x < 10; x++)
{
cs[x] = new ClassT( );
ct[x] = new ClassT( );
}
ct = (ClassT[])cs;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
interface InterfaceS
{
int Other_TestClass_covariance_explicit_04MethodS( );
}
interface InterfaceT : InterfaceS
{
int Other_TestClass_covariance_explicit_04MethodT( );
}
class Other_TestClass_covariance_explicit_04_Imp : InterfaceS, InterfaceT
{
public int x;
public int Other_TestClass_covariance_explicit_04MethodS()
{
return 0;
}
public int Other_TestClass_covariance_explicit_04MethodT()
{
return 0;
}
}
class Other_TestClass_covariance_explicit_04
{
public static int Main_old()
{
InterfaceS[] ifs = new InterfaceT[10];
InterfaceT[] ift = new InterfaceT[10];
Other_TestClass_covariance_explicit_04_Imp mc = new Other_TestClass_covariance_explicit_04_Imp( );
for (int x = 0; x < 10; x++)
{
ifs[x] = new Other_TestClass_covariance_explicit_04_Imp( );
ift[x] = new Other_TestClass_covariance_explicit_04_Imp( );
}
ift = (InterfaceT[])ifs;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class Other_TestClass_covariance_implicit_01_Imp
{
public int x;
}
class Other_TestClass_covariance_implicit_01
{
public static int Main_old()
{
Other_TestClass_covariance_implicit_01_Imp[] mc = new Other_TestClass_covariance_implicit_01_Imp[10];
for (int x = 0; x < 10; x++)
{
mc[x] = new Other_TestClass_covariance_implicit_01_Imp( );
Log.Comment(x.ToString());
mc[x].x = x;
}
object[] o = new object[10];
o = mc;
for (int x = 0; x < 10; x++)
{
Log.Comment(((Other_TestClass_covariance_implicit_01_Imp)o[x]).x.ToString());
}
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
interface Other_TestClass_covariance_implicit_02_Inter
{
int testmethod( );
}
class Other_TestClass_covariance_implicit_02_Imp : Other_TestClass_covariance_implicit_02_Inter
{
public int testmethod()
{
Log.Comment("Other_TestClass_covariance_implicit_02_Imp::testmethod()");
return 0;
}
}
class Other_TestClass_covariance_implicit_02
{
public static int Main_old()
{
Other_TestClass_covariance_implicit_02_Inter[] inst = new Other_TestClass_covariance_implicit_02_Inter[10];
for (int x = 0; x < 10; x++)
{
inst[x] = new Other_TestClass_covariance_implicit_02_Imp( );
}
object[] o = new object[10];
o = inst;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
class Other_TestClass_covariance_implicit_03_T
{
public int x;
}
class Other_TestClass_covariance_implicit_03_S : Other_TestClass_covariance_implicit_03_T
{
public int y;
}
class Other_TestClass_covariance_implicit_03
{
public static int Main_old()
{
Other_TestClass_covariance_implicit_03_S[] cs = new Other_TestClass_covariance_implicit_03_S[10];
Other_TestClass_covariance_implicit_03_T[] ct = new Other_TestClass_covariance_implicit_03_T[10];
for (int x = 0; x < 10; x++)
{
cs[x] = new Other_TestClass_covariance_implicit_03_S( );
ct[x] = new Other_TestClass_covariance_implicit_03_T( );
}
ct = cs;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
interface Other_TestClass_covariance_implicit_04_IT
{
int Other_TestClass_covariance_implicit_04Method( );
}
class Other_TestClass_covariance_implicit_04_ImpS : Other_TestClass_covariance_implicit_04_IT
{
public int x;
public int Other_TestClass_covariance_implicit_04Method()
{
return 0;
}
}
class Other_TestClass_covariance_implicit_04
{
public static int Main_old()
{
Other_TestClass_covariance_implicit_04_IT[] it = new Other_TestClass_covariance_implicit_04_IT[10];
Other_TestClass_covariance_implicit_04_ImpS[] cs = new Other_TestClass_covariance_implicit_04_ImpS[10];
for (int x = 0; x < 10; x++)
{
it[x] = new Other_TestClass_covariance_implicit_04_ImpS( );
cs[x] = new Other_TestClass_covariance_implicit_04_ImpS( );
}
it = cs;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
interface Other_TestClass_covariance_implicit_05_IT
{
int Other_TestClass_covariance_implicit_05MethodT( );
}
interface Other_TestClass_covariance_implicit_05_IS : Other_TestClass_covariance_implicit_05_IT
{
int Other_TestClass_covariance_implicit_05MethodS( );
}
class Other_TestClass_covariance_implicit_05_ImpT : Other_TestClass_covariance_implicit_05_IT
{
public int x;
public int Other_TestClass_covariance_implicit_05MethodT()
{
return 0;
}
}
class Other_TestClass_covariance_implicit_05_ImpS : Other_TestClass_covariance_implicit_05_IS
{
public int x;
public int Other_TestClass_covariance_implicit_05MethodS()
{
return 0;
}
public int Other_TestClass_covariance_implicit_05MethodT()
{
return 0;
}
}
class Other_TestClass_covariance_implicit_05
{
public static int Main_old()
{
Other_TestClass_covariance_implicit_05_IS[] ifs = new Other_TestClass_covariance_implicit_05_IS[10];
Other_TestClass_covariance_implicit_05_IT[] ift = new Other_TestClass_covariance_implicit_05_IT[10];
Other_TestClass_covariance_implicit_05_ImpS cs = new Other_TestClass_covariance_implicit_05_ImpS( );
Other_TestClass_covariance_implicit_05_ImpT ct = new Other_TestClass_covariance_implicit_05_ImpT( );
for (int x = 0; x < 10; x++)
{
ifs[x] = new Other_TestClass_covariance_implicit_05_ImpS( );
ift[x] = new Other_TestClass_covariance_implicit_05_ImpT( );
}
ift = ifs;
return 0;
}
public static bool testMethod()
{
return (Main_old() == 0);
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// BufferBlock.cs
//
//
// A propagator block that provides support for unbounded and bounded FIFO buffers.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using System.Threading.Tasks.Dataflow.Internal;
using System.Diagnostics.CodeAnalysis;
namespace System.Threading.Tasks.Dataflow
{
/// <summary>Provides a buffer for storing data.</summary>
/// <typeparam name="T">Specifies the type of the data buffered by this dataflow block.</typeparam>
[DebuggerDisplay("{DebuggerDisplayContent,nq}")]
[DebuggerTypeProxy(typeof(BufferBlock<>.DebugView))]
public sealed class BufferBlock<T> : IPropagatorBlock<T, T>, IReceivableSourceBlock<T>, IDebuggerDisplay
{
/// <summary>The core logic for the buffer block.</summary>
private readonly SourceCore<T> _source;
/// <summary>The bounding state for when in bounding mode; null if not bounding.</summary>
private readonly BoundingStateWithPostponedAndTask<T> _boundingState;
/// <summary>Whether all future messages should be declined on the target.</summary>
private bool _targetDecliningPermanently;
/// <summary>A task has reserved the right to run the target's completion routine.</summary>
private bool _targetCompletionReserved;
/// <summary>Gets the lock object used to synchronize incoming requests.</summary>
private object IncomingLock { get { return _source; } }
/// <summary>Initializes the <see cref="BufferBlock{T}"/>.</summary>
public BufferBlock() :
this(DataflowBlockOptions.Default)
{ }
/// <summary>Initializes the <see cref="BufferBlock{T}"/> with the specified <see cref="DataflowBlockOptions"/>.</summary>
/// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BufferBlock{T}"/>.</param>
/// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception>
public BufferBlock(DataflowBlockOptions dataflowBlockOptions)
{
if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions));
Contract.EndContractBlock();
// Ensure we have options that can't be changed by the caller
dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone();
// Initialize bounding state if necessary
Action<ISourceBlock<T>, int> onItemsRemoved = null;
if (dataflowBlockOptions.BoundedCapacity > 0)
{
onItemsRemoved = (owningSource, count) => ((BufferBlock<T>)owningSource).OnItemsRemoved(count);
_boundingState = new BoundingStateWithPostponedAndTask<T>(dataflowBlockOptions.BoundedCapacity);
}
// Initialize the source state
_source = new SourceCore<T>(this, dataflowBlockOptions,
owningSource => ((BufferBlock<T>)owningSource).Complete(),
onItemsRemoved);
// It is possible that the source half may fault on its own, e.g. due to a task scheduler exception.
// In those cases we need to fault the target half to drop its buffered messages and to release its
// reservations. This should not create an infinite loop, because all our implementations are designed
// to handle multiple completion requests and to carry over only one.
_source.Completion.ContinueWith((completed, state) =>
{
var thisBlock = ((BufferBlock<T>)state) as IDataflowBlock;
Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion.");
thisBlock.Fault(completed.Exception);
}, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default);
// Handle async cancellation requests by declining on the target
Common.WireCancellationToComplete(
dataflowBlockOptions.CancellationToken, _source.Completion, owningSource => ((BufferBlock<T>)owningSource).Complete(), this);
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.DataflowBlockCreated(this, dataflowBlockOptions);
}
#endif
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' />
DataflowMessageStatus ITargetBlock<T>.OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept)
{
// Validate arguments
if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader));
if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept));
Contract.EndContractBlock();
lock (IncomingLock)
{
// If we've already stopped accepting messages, decline permanently
if (_targetDecliningPermanently)
{
CompleteTargetIfPossible();
return DataflowMessageStatus.DecliningPermanently;
}
// We can directly accept the message if:
// 1) we are not bounding, OR
// 2) we are bounding AND there is room available AND there are no postponed messages AND we are not currently processing.
// (If there were any postponed messages, we would need to postpone so that ordering would be maintained.)
// (We should also postpone if we are currently processing, because there may be a race between consuming postponed messages and
// accepting new ones directly into the queue.)
if (_boundingState == null
||
(_boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count == 0 && _boundingState.TaskForInputProcessing == null))
{
// Consume the message from the source if necessary
if (consumeToAccept)
{
Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true.");
bool consumed;
messageValue = source.ConsumeMessage(messageHeader, this, out consumed);
if (!consumed) return DataflowMessageStatus.NotAvailable;
}
// Once consumed, pass it to the source
_source.AddMessage(messageValue);
if (_boundingState != null) _boundingState.CurrentCount++;
return DataflowMessageStatus.Accepted;
}
// Otherwise, we try to postpone if a source was provided
else if (source != null)
{
Debug.Assert(_boundingState != null && _boundingState.PostponedMessages != null,
"PostponedMessages must have been initialized during construction in bounding mode.");
_boundingState.PostponedMessages.Push(source, messageHeader);
return DataflowMessageStatus.Postponed;
}
// We can't do anything else about this message
return DataflowMessageStatus.Declined;
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' />
public void Complete() { CompleteCore(exception: null, storeExceptionEvenIfAlreadyCompleting: false); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' />
void IDataflowBlock.Fault(Exception exception)
{
if (exception == null) throw new ArgumentNullException(nameof(exception));
Contract.EndContractBlock();
CompleteCore(exception, storeExceptionEvenIfAlreadyCompleting: false);
}
private void CompleteCore(Exception exception, bool storeExceptionEvenIfAlreadyCompleting, bool revertProcessingState = false)
{
Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState,
"Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true.");
Contract.EndContractBlock();
lock (IncomingLock)
{
// Faulting from outside is allowed until we start declining permanently.
// Faulting from inside is allowed at any time.
if (exception != null && (!_targetDecliningPermanently || storeExceptionEvenIfAlreadyCompleting))
{
_source.AddException(exception);
}
// Revert the dirty processing state if requested
if (revertProcessingState)
{
Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null,
"The processing state must be dirty when revertProcessingState==true.");
_boundingState.TaskForInputProcessing = null;
}
// Trigger completion
_targetDecliningPermanently = true;
CompleteTargetIfPossible();
}
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' />
public IDisposable LinkTo(ITargetBlock<T> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' />
public Boolean TryReceive(Predicate<T> filter, out T item) { return _source.TryReceive(filter, out item); }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' />
public Boolean TryReceiveAll(out IList<T> items) { return _source.TryReceiveAll(out items); }
/// <summary>Gets the number of items currently stored in the buffer.</summary>
public Int32 Count { get { return _source.OutputCount; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' />
public Task Completion { get { return _source.Completion; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' />
T ISourceBlock<T>.ConsumeMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target, out Boolean messageConsumed)
{
return _source.ConsumeMessage(messageHeader, target, out messageConsumed);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' />
bool ISourceBlock<T>.ReserveMessage(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
return _source.ReserveMessage(messageHeader, target);
}
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' />
void ISourceBlock<T>.ReleaseReservation(DataflowMessageHeader messageHeader, ITargetBlock<T> target)
{
_source.ReleaseReservation(messageHeader, target);
}
/// <summary>Notifies the block that one or more items was removed from the queue.</summary>
/// <param name="numItemsRemoved">The number of items removed.</param>
private void OnItemsRemoved(int numItemsRemoved)
{
Debug.Assert(numItemsRemoved > 0, "A positive number of items to remove is required.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
// If we're bounding, we need to know when an item is removed so that we
// can update the count that's mirroring the actual count in the source's queue,
// and potentially kick off processing to start consuming postponed messages.
if (_boundingState != null)
{
lock (IncomingLock)
{
// Decrement the count, which mirrors the count in the source half
Debug.Assert(_boundingState.CurrentCount - numItemsRemoved >= 0,
"It should be impossible to have a negative number of items.");
_boundingState.CurrentCount -= numItemsRemoved;
ConsumeAsyncIfNecessary();
CompleteTargetIfPossible();
}
}
}
/// <summary>Called when postponed messages may need to be consumed.</summary>
/// <param name="isReplacementReplica">Whether this call is the continuation of a previous message loop.</param>
internal void ConsumeAsyncIfNecessary(bool isReplacementReplica = false)
{
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
Debug.Assert(_boundingState != null, "Must be in bounded mode.");
if (!_targetDecliningPermanently &&
_boundingState.TaskForInputProcessing == null &&
_boundingState.PostponedMessages.Count > 0 &&
_boundingState.CountIsLessThanBound)
{
// Create task and store into _taskForInputProcessing prior to scheduling the task
// so that _taskForInputProcessing will be visibly set in the task loop.
_boundingState.TaskForInputProcessing =
new Task(state => ((BufferBlock<T>)state).ConsumeMessagesLoopCore(), this,
Common.GetCreationOptionsForTask(isReplacementReplica));
#if FEATURE_TRACING
DataflowEtwProvider etwLog = DataflowEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TaskLaunchedForMessageHandling(
this, _boundingState.TaskForInputProcessing, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages,
_boundingState.PostponedMessages.Count);
}
#endif
// Start the task handling scheduling exceptions
Exception exception = Common.StartTaskSafe(_boundingState.TaskForInputProcessing, _source.DataflowBlockOptions.TaskScheduler);
if (exception != null)
{
// Get out from under currently held locks. CompleteCore re-acquires the locks it needs.
Task.Factory.StartNew(exc => CompleteCore(exception: (Exception)exc, storeExceptionEvenIfAlreadyCompleting: true, revertProcessingState: true),
exception, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
}
}
/// <summary>Task body used to consume postponed messages.</summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ConsumeMessagesLoopCore()
{
Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null,
"May only be called in bounded mode and when a task is in flight.");
Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId,
"This must only be called from the in-flight processing task.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
try
{
int maxMessagesPerTask = _source.DataflowBlockOptions.ActualMaxMessagesPerTask;
for (int i = 0;
i < maxMessagesPerTask && ConsumeAndStoreOneMessageIfAvailable();
i++)
;
}
catch (Exception exc)
{
// Prevent the creation of new processing tasks
CompleteCore(exc, storeExceptionEvenIfAlreadyCompleting: true);
}
finally
{
lock (IncomingLock)
{
// We're no longer processing, so null out the processing task
_boundingState.TaskForInputProcessing = null;
// However, we may have given up early because we hit our own configured
// processing limits rather than because we ran out of work to do. If that's
// the case, make sure we spin up another task to keep going.
ConsumeAsyncIfNecessary(isReplacementReplica: true);
// If, however, we stopped because we ran out of work to do and we
// know we'll never get more, then complete.
CompleteTargetIfPossible();
}
}
}
/// <summary>
/// Retrieves one postponed message if there's room and if we can consume a postponed message.
/// Stores any consumed message into the source half.
/// </summary>
/// <returns>true if a message could be consumed and stored; otherwise, false.</returns>
/// <remarks>This must only be called from the asynchronous processing loop.</remarks>
private bool ConsumeAndStoreOneMessageIfAvailable()
{
Debug.Assert(_boundingState != null && _boundingState.TaskForInputProcessing != null,
"May only be called in bounded mode and when a task is in flight.");
Debug.Assert(_boundingState.TaskForInputProcessing.Id == Task.CurrentId,
"This must only be called from the in-flight processing task.");
Common.ContractAssertMonitorStatus(IncomingLock, held: false);
// Loop through the postponed messages until we get one.
while (true)
{
// Get the next item to retrieve. If there are no more, bail.
KeyValuePair<ISourceBlock<T>, DataflowMessageHeader> sourceAndMessage;
lock (IncomingLock)
{
if (_targetDecliningPermanently) return false;
if (!_boundingState.CountIsLessThanBound) return false;
if (!_boundingState.PostponedMessages.TryPop(out sourceAndMessage)) return false;
// Optimistically assume we're going to get the item. This avoids taking the lock
// again if we're right. If we're wrong, we decrement it later under lock.
_boundingState.CurrentCount++;
}
// Consume the item
bool consumed = false;
try
{
T consumedValue = sourceAndMessage.Key.ConsumeMessage(sourceAndMessage.Value, this, out consumed);
if (consumed)
{
_source.AddMessage(consumedValue);
return true;
}
}
finally
{
// We didn't get the item, so decrement the count to counteract our optimistic assumption.
if (!consumed)
{
lock (IncomingLock) _boundingState.CurrentCount--;
}
}
}
}
/// <summary>Completes the target, notifying the source, once all completion conditions are met.</summary>
private void CompleteTargetIfPossible()
{
Common.ContractAssertMonitorStatus(IncomingLock, held: true);
if (_targetDecliningPermanently &&
!_targetCompletionReserved &&
(_boundingState == null || _boundingState.TaskForInputProcessing == null))
{
_targetCompletionReserved = true;
// If we're in bounding mode and we have any postponed messages, we need to clear them,
// which means calling back to the source, which means we need to escape the incoming lock.
if (_boundingState != null && _boundingState.PostponedMessages.Count > 0)
{
Task.Factory.StartNew(state =>
{
var thisBufferBlock = (BufferBlock<T>)state;
// Release any postponed messages
List<Exception> exceptions = null;
if (thisBufferBlock._boundingState != null)
{
// Note: No locks should be held at this point
Common.ReleaseAllPostponedMessages(thisBufferBlock,
thisBufferBlock._boundingState.PostponedMessages,
ref exceptions);
}
if (exceptions != null)
{
// It is important to migrate these exceptions to the source part of the owning batch,
// because that is the completion task that is publically exposed.
thisBufferBlock._source.AddExceptions(exceptions);
}
thisBufferBlock._source.Complete();
}, this, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default);
}
// Otherwise, we can just decline the source directly.
else
{
_source.Complete();
}
}
}
/// <summary>Gets the number of messages in the buffer. This must only be used from the debugger as it avoids taking necessary locks.</summary>
private int CountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } }
/// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' />
public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); }
/// <summary>The data to display in the debugger display attribute.</summary>
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
private object DebuggerDisplayContent
{
get
{
return string.Format("{0}, Count={1}",
Common.GetNameForDebugger(this, _source.DataflowBlockOptions),
CountForDebugger);
}
}
/// <summary>Gets the data to display in the debugger display attribute for this instance.</summary>
object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } }
/// <summary>Provides a debugger type proxy for the BufferBlock.</summary>
private sealed class DebugView
{
/// <summary>The buffer block.</summary>
private readonly BufferBlock<T> _bufferBlock;
/// <summary>The buffer's source half.</summary>
private readonly SourceCore<T>.DebuggingInformation _sourceDebuggingInformation;
/// <summary>Initializes the debug view.</summary>
/// <param name="bufferBlock">The BufferBlock being viewed.</param>
public DebugView(BufferBlock<T> bufferBlock)
{
Debug.Assert(bufferBlock != null, "Need a block with which to construct the debug view.");
_bufferBlock = bufferBlock;
_sourceDebuggingInformation = bufferBlock._source.GetDebuggingInformation();
}
/// <summary>Gets the collection of postponed message headers.</summary>
public QueuedMap<ISourceBlock<T>, DataflowMessageHeader> PostponedMessages
{
get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.PostponedMessages : null; }
}
/// <summary>Gets the messages in the buffer.</summary>
public IEnumerable<T> Queue { get { return _sourceDebuggingInformation.OutputQueue; } }
/// <summary>The task used to process messages.</summary>
public Task TaskForInputProcessing { get { return _bufferBlock._boundingState != null ? _bufferBlock._boundingState.TaskForInputProcessing : null; } }
/// <summary>Gets the task being used for output processing.</summary>
public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } }
/// <summary>Gets the DataflowBlockOptions used to configure this block.</summary>
public DataflowBlockOptions DataflowBlockOptions { get { return _sourceDebuggingInformation.DataflowBlockOptions; } }
/// <summary>Gets whether the block is declining further messages.</summary>
public bool IsDecliningPermanently { get { return _bufferBlock._targetDecliningPermanently; } }
/// <summary>Gets whether the block is completed.</summary>
public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } }
/// <summary>Gets the block's Id.</summary>
public int Id { get { return Common.GetBlockId(_bufferBlock); } }
/// <summary>Gets the set of all targets linked from this block.</summary>
public TargetRegistry<T> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } }
/// <summary>Gets the set of all targets linked from this block.</summary>
public ITargetBlock<T> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } }
}
}
}
| |
// 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 ExtendToVector256Double()
{
var test = new GenericUnaryOpTest__ExtendToVector256Double();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class GenericUnaryOpTest__ExtendToVector256Double
{
private struct TestStruct
{
public Vector128<Double> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(GenericUnaryOpTest__ExtendToVector256Double testClass)
{
var result = Avx.ExtendToVector256<Double>(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double);
private static Double[] _data = new Double[Op1ElementCount];
private static Vector128<Double> _clsVar;
private Vector128<Double> _fld;
private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable;
static GenericUnaryOpTest__ExtendToVector256Double()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public GenericUnaryOpTest__ExtendToVector256Double()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.ExtendToVector256<Double>(
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.ExtendToVector256<Double>(
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.ExtendToVector256<Double>(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(Double) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(Double) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(Double) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.ExtendToVector256<Double>(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Double>>(_dataTable.inArrayPtr);
var result = Avx.ExtendToVector256<Double>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Double*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<Double>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<Double>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new GenericUnaryOpTest__ExtendToVector256Double();
var result = Avx.ExtendToVector256<Double>(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.ExtendToVector256<Double>(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.ExtendToVector256(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Double[] inArray = new Double[Op1ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "")
{
if (firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < (RetElementCount / 2)) ? firstOp[i] : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtendToVector256)}<Double>(Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2007 Jonathan Mark Porter. http://physics2d.googlepages.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
#region Axiom LGPL License
/*
Since enough of this code is Axioms here is thier License
Axiom Game Engine LibrarY
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained Within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, Which can be found at http://ogre.sourceforge.net.
ManY thanks to the OGRE team for maintaining such a high qualitY project.
The math library included in this project, in addition to being a derivative of
the Works of Ogre, also include derivative Work of the free portion of the
Wild Magic mathematics source code that is distributed With the excellent
book Game Engine Design.
http://www.wild-magic.com/
This library is free softWare; You can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free SoftWare Foundation; either
version 2.1 of the License, or (at Your option) anY later version.
This library is distributed in the hope that it Will be useful,
but WITHOUT ANY WARRANTY; Without even the implied Warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along With this library; if not, Write to the Free SoftWare
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using AdvanceMath.Design;
namespace AdvanceMath
{
/// <summary>
/// Summary description for Quaternion.
/// </summary>
[StructLayout(LayoutKind.Sequential), Serializable]
[AdvBrowsableOrder("W,X,Y,Z")]
[System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<Quaternion>))]
public struct Quaternion
{
#region static fields
/// <summary>
/// An Identity Quaternion.
/// </summary>
public static readonly Quaternion Identity = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
/// <summary>
/// A Quaternion With all elements set to 0.0f;
/// </summary>
public static readonly Quaternion Zero = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);
private static readonly int[] next = new int[3] { 1, 2, 0 };
#endregion
#region Static methods
public static Quaternion Slerp(Scalar time, Quaternion quatA, Quaternion quatB)
{
return Slerp(time, quatA, quatB, false);
}
/// <summary>
///
/// </summary>
/// <param name="time"></param>
/// <param name="quatA"></param>
/// <param name="quatB"></param>
/// <param name="useShortestPath"></param>
/// <returns></returns>
public static Quaternion Slerp(Scalar time, Quaternion quatA, Quaternion quatB, bool useShortestPath)
{
Scalar cos = quatA.Dot(quatB);
Scalar angle = MathHelper.Acos(cos);
if (MathHelper.Abs(angle) < MathHelper.EPSILON)
{
return quatA;
}
Scalar sin = MathHelper.Sin(angle);
Scalar inverseSin = 1.0f / sin;
Scalar coeff0 = MathHelper.Sin((1.0f - time) * angle) * inverseSin;
Scalar coeff1 = MathHelper.Sin(time * angle) * inverseSin;
Quaternion returnvalue;
if (cos < 0.0f && useShortestPath)
{
coeff0 = -coeff0;
// taking the complement requires renormalisation
Quaternion t = coeff0 * quatA + coeff1 * quatB;
t.Normalize();
returnvalue = t;
}
else
{
returnvalue = (coeff0 * quatA + coeff1 * quatB);
}
return returnvalue;
}
/// <summary>
/// Creates a Quaternion from a supplied angle and aXis.
/// </summary>
/// <param name="angle">Value of an angle in radians.</param>
/// <param name="aXis">ArbitrarY aXis vector.</param>
/// <returns></returns>
public static Quaternion FromAngleAxis(Scalar angle, Vector3D aXis)
{
Quaternion quat = new Quaternion();
Scalar halfAngle = 0.5f * angle;
Scalar sin = MathHelper.Sin(halfAngle);
quat.W = MathHelper.Cos(halfAngle);
quat.X = sin * aXis.X;
quat.Y = sin * aXis.Y;
quat.Z = sin * aXis.Z;
return quat;
}
public static Quaternion Squad(Scalar t, Quaternion p, Quaternion a, Quaternion b, Quaternion q)
{
return Squad(t, p, a, b, q, false);
}
/// <summary>
/// Performs spherical quadratic interpolation.
/// </summary>
/// <param name="t"></param>
/// <param name="p"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="q"></param>
/// <returns></returns>
public static Quaternion Squad(Scalar t, Quaternion p, Quaternion a, Quaternion b, Quaternion q, bool useShortestPath)
{
Scalar slerpT = 2.0f * t * (1.0f - t);
// use spherical linear interpolation
Quaternion slerpP = Slerp(t, p, q, useShortestPath);
Quaternion slerpQ = Slerp(t, a, b);
// run another Slerp on the returnvalues of the first 2, and return the returnvalues
return Slerp(slerpT, slerpP, slerpQ);
}
#endregion
#region fields
[AdvBrowsable ]
[XmlAttribute ]
public Scalar X;
[AdvBrowsable]
[XmlAttribute]
public Scalar Y;
[AdvBrowsable]
[XmlAttribute]
public Scalar Z;
[AdvBrowsable]
[XmlAttribute]
public Scalar W;
#endregion
#region Constructors
// public Quaternion()
// {
// this.W = 1.0f;
// }
/// <summary>
/// Creates a new Quaternion.
/// </summary>
[InstanceConstructor("W,X,Y,Z")]
public Quaternion(Scalar W, Scalar X, Scalar Y, Scalar Z)
{
this.W = W;
this.X = X;
this.Y = Y;
this.Z = Z;
}
#endregion
#region Properties
/// <summary>
/// Squared 'length' of this quaternion.
/// </summary>
public Scalar Norm
{
get
{
return X * X + Y * Y + Z * Z + W * W;
}
}
/// <summary>
/// Local X-aXis portion of this rotation.
/// </summary>
public Vector3D XAxis
{
get
{
Scalar fTX = 2.0f * X;
Scalar fTY = 2.0f * Y;
Scalar fTZ = 2.0f * Z;
Scalar fTWY = fTY * W;
Scalar fTWZ = fTZ * W;
Scalar fTXY = fTY * X;
Scalar fTXZ = fTZ * X;
Scalar fTYY = fTY * Y;
Scalar fTZZ = fTZ * Z;
Vector3D result;
result.X = 1.0f - (fTYY + fTZZ);
result.Y = fTXY + fTWZ;
result.Z = fTXZ - fTWY;
return result;
//return new Vector3D(1.0f - (fTYY + fTZZ), fTXY + fTWZ, fTXZ - fTWY);
}
}
/// <summary>
/// Local Y-aXis portion of this rotation.
/// </summary>
public Vector3D YAxis
{
get
{
Scalar fTX = 2.0f * X;
Scalar fTY = 2.0f * Y;
Scalar fTZ = 2.0f * Z;
Scalar fTWX = fTX * W;
Scalar fTWZ = fTZ * W;
Scalar fTXX = fTX * X;
Scalar fTXY = fTY * X;
Scalar fTYZ = fTZ * Y;
Scalar fTZZ = fTZ * Z;
Vector3D result;
result.X = fTXY - fTWZ;
result.Y = 1.0f - (fTXX + fTZZ);
result.Z = fTYZ + fTWX;
return result;
//return new Vector3D(fTXY - fTWZ, 1.0f - (fTXX + fTZZ), fTYZ + fTWX);
}
}
/// <summary>
/// Local Z-aXis portion of this rotation.
/// </summary>
public Vector3D ZAxis
{
get
{
Scalar fTX = 2.0f * X;
Scalar fTY = 2.0f * Y;
Scalar fTZ = 2.0f * Z;
Scalar fTWX = fTX * W;
Scalar fTWY = fTY * W;
Scalar fTXX = fTX * X;
Scalar fTXZ = fTZ * X;
Scalar fTYY = fTY * Y;
Scalar fTYZ = fTZ * Y;
Vector3D result;
result.X = fTXZ + fTWY;
result.Y = fTYZ - fTWX;
result.Z = 1.0f - (fTXX + fTYY);
return result;
//return new Vector3D(fTXZ + fTWY, fTYZ - fTWX, 1.0f - (fTXX + fTYY));
}
}
[XmlIgnore, SoapIgnore]
public Scalar PitchInDegrees { get { return MathHelper.RadiansToDegrees(Pitch); } set { Pitch = MathHelper.DegreesToRadians(value); } }
[XmlIgnore, SoapIgnore]
public Scalar YawInDegrees { get { return MathHelper.RadiansToDegrees(Yaw); } set { Yaw = MathHelper.DegreesToRadians(value); } }
[XmlIgnore, SoapIgnore]
public Scalar RollInDegrees { get { return MathHelper.RadiansToDegrees(Roll); } set { Roll = MathHelper.DegreesToRadians(value); } }
[XmlIgnore, SoapIgnore]
public Scalar Pitch
{
set
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
FromEulerAngles(value, Yaw, roll);
}
get
{
Scalar test = X * Y + Z * W;
if (Math.Abs(test) > 0.499f) // singularitY at north and south pole
return 0f;
return MathHelper.Atan2(2 * X * W - 2 * Y * Z, 1 - 2 * X * X - 2 * Z * Z);
}
}
[XmlIgnore, SoapIgnore]
public Scalar Yaw
{
set
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
FromEulerAngles(pitch, value, roll);
}
get
{
Scalar test = X * Y + Z * W;
if (Math.Abs(test) > 0.499f) // singularitY at north and south pole
return Math.Sign(test) * 2 * MathHelper.Atan2(X, W);
return MathHelper.Atan2(2 * Y * W - 2 * X * Z, 1 - 2 * Y * Y - 2 * Z * Z);
}
}
[XmlIgnore, SoapIgnore]
public Scalar Roll
{
set
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
FromEulerAngles(pitch, Yaw, value);
}
get
{
Scalar test = X * Y + Z * W;
if (Math.Abs(test) > 0.499f) // singularitY at north and south pole
return Math.Sign(test) * MathHelper.PI / 2;
return MathHelper.Asin(2 * test);
}
}
#endregion
#region Public methods
#region Euler Angles
public Vector3D ToEulerAnglesInDegrees()
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
return new Vector3D(MathHelper.RadiansToDegrees(pitch), MathHelper.RadiansToDegrees(Yaw), MathHelper.RadiansToDegrees(roll));
}
public Vector3D ToEulerAngles()
{
Scalar pitch, Yaw, roll;
ToEulerAngles(out pitch, out Yaw, out roll);
return new Vector3D(pitch, Yaw, roll);
}
public void ToEulerAnglesInDegrees(out Scalar pitch, out Scalar Yaw, out Scalar roll)
{
ToEulerAngles(out pitch, out Yaw, out roll);
pitch = MathHelper.RadiansToDegrees(pitch);
Yaw = MathHelper.RadiansToDegrees(Yaw);
roll = MathHelper.RadiansToDegrees(roll);
}
public void ToEulerAngles(out Scalar pitch, out Scalar Yaw, out Scalar roll)
{
Scalar halfPi = (Scalar)Math.PI / 2;
Scalar test = X * Y + Z * W;
if (test > 0.499f)
{ // singularitY at north pole
Yaw = 2 * MathHelper.Atan2(X, W);
roll = halfPi;
pitch = 0;
}
else if (test < -0.499f)
{ // singularitY at south pole
Yaw = -2 * MathHelper.Atan2(X, W);
roll = -halfPi;
pitch = 0;
}
else
{
Scalar sqX = X * X;
Scalar sqY = Y * Y;
Scalar sqZ = Z * Z;
Yaw = MathHelper.Atan2(2 * Y * W - 2 * X * Z, 1 - 2 * sqY - 2 * sqZ);
roll = MathHelper.Asin(2 * test);
pitch = MathHelper.Atan2(2 * X * W - 2 * Y * Z, 1 - 2 * sqX - 2 * sqZ);
}
if (pitch <= Scalar.Epsilon)
pitch = 0f;
if (Yaw <= Scalar.Epsilon)
Yaw = 0f;
if (roll <= Scalar.Epsilon)
roll = 0f;
}
public static Quaternion FromEulerAnglesInDegrees(Scalar pitch, Scalar Yaw, Scalar roll)
{
return FromEulerAngles(MathHelper.DegreesToRadians(pitch), MathHelper.DegreesToRadians(Yaw), MathHelper.DegreesToRadians(roll));
}
/// <summary>
/// Combines the euler angles in the order Yaw, pitch, roll to create a rotation quaternion
/// </summary>
/// <param name="pitch"></param>
/// <param name="Yaw"></param>
/// <param name="roll"></param>
/// <returns></returns>
public static Quaternion FromEulerAngles(Scalar pitch, Scalar Yaw, Scalar roll)
{
return Quaternion.FromAngleAxis(Yaw, Vector3D.YAxis)
* Quaternion.FromAngleAxis(pitch, Vector3D.XAxis)
* Quaternion.FromAngleAxis(roll, Vector3D.ZAxis);
/*TODO: Debug
//Equation from http://WWW.euclideanspace.com/maths/geometrY/rotations/conversions/eulerToQuaternion/indeX.htm
//heading
Scalar c1 = (Scalar)Math.Cos(Yaw/2);
Scalar s1 = (Scalar)Math.Sin(Yaw/2);
//attitude
Scalar c2 = (Scalar)Math.Cos(roll/2);
Scalar s2 = (Scalar)Math.Sin(roll/2);
//bank
Scalar c3 = (Scalar)Math.Cos(pitch/2);
Scalar s3 = (Scalar)Math.Sin(pitch/2);
Scalar c1c2 = c1*c2;
Scalar s1s2 = s1*s2;
Scalar W =c1c2*c3 - s1s2*s3;
Scalar X =c1c2*s3 + s1s2*c3;
Scalar Y =s1*c2*c3 + c1*s2*s3;
Scalar Z =c1*s2*c3 - s1*c2*s3;
return new Quaternion(W,X,Y,Z);*/
}
#endregion
/// <summary>
/// Performs a Dot Product operation on 2 Quaternions.
/// </summary>
/// <param name="quat"></param>
/// <returns></returns>
public Scalar Dot(Quaternion quat)
{
return this.W * quat.W + this.X * quat.X + this.Y * quat.Y + this.Z * quat.Z;
}
/// <summary>
/// Normalizes elements of this quaterion to the range [0,1].
/// </summary>
public void Normalize()
{
Scalar factor = 1.0f / MathHelper.Sqrt(this.Norm);
W = W * factor;
X = X * factor;
Y = Y * factor;
Z = Z * factor;
}
/// <summary>
///
/// </summary>
/// <param name="angle"></param>
/// <param name="aXis"></param>
/// <returns></returns>
public void ToAngleAxis(ref Scalar angle, ref Vector3D aXis)
{
// The quaternion representing the rotation is
// q = cos(A/2)+sin(A/2)*(X*i+Y*j+Z*k)
Scalar sqrLength = X * X + Y * Y + Z * Z;
if (sqrLength > 0.0f)
{
angle = 2.0f * MathHelper.Acos(W);
Scalar invLength = MathHelper.InvSqrt(sqrLength);
aXis.X = X * invLength;
aXis.Y = Y * invLength;
aXis.Z = Z * invLength;
}
else
{
angle = 0.0f;
aXis.X = 1.0f;
aXis.Y = 0.0f;
aXis.Z = 0.0f;
}
}
/// <summary>
/// Gets a 3X3 rotation matriX from this Quaternion.
/// </summary>
/// <returns></returns>
public Matrix3x3 ToRotationMatrix()
{
Matrix3x3 rotation = new Matrix3x3();
Scalar tX = 2.0f * this.X;
Scalar tY = 2.0f * this.Y;
Scalar tZ = 2.0f * this.Z;
Scalar tWX = tX * this.W;
Scalar tWY = tY * this.W;
Scalar tWZ = tZ * this.W;
Scalar tXX = tX * this.X;
Scalar tXY = tY * this.X;
Scalar tXZ = tZ * this.X;
Scalar tYY = tY * this.Y;
Scalar tYZ = tZ * this.Y;
Scalar tZZ = tZ * this.Z;
rotation.m00 = 1.0f - (tYY + tZZ);
rotation.m01 = tXY - tWZ;
rotation.m02 = tXZ + tWY;
rotation.m10 = tXY + tWZ;
rotation.m11 = 1.0f - (tXX + tZZ);
rotation.m12 = tYZ - tWX;
rotation.m20 = tXZ - tWY;
rotation.m21 = tYZ + tWX;
rotation.m22 = 1.0f - (tXX + tYY);
return rotation;
}
/// <summary>
/// Computes the inverse of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Inverse()
{
Scalar norm = this.W * this.W + this.X * this.X + this.Y * this.Y + this.Z * this.Z;
if (norm > 0.0f)
{
Scalar inverseNorm = 1.0f / norm;
return new Quaternion(this.W * inverseNorm, -this.X * inverseNorm, -this.Y * inverseNorm, -this.Z * inverseNorm);
}
else
{
// return an invalid returnvalue to flag the error
return Quaternion.Zero;
}
}
/// <summary>
///
/// </summary>
/// <param name="XAxis"></param>
/// <param name="YAxis"></param>
/// <param name="ZAxis"></param>
public void ToAxis(out Vector3D XAxis, out Vector3D YAxis, out Vector3D ZAxis)
{
XAxis = new Vector3D();
YAxis = new Vector3D();
ZAxis = new Vector3D();
Matrix3x3 rotation = this.ToRotationMatrix();
XAxis.X = rotation.m00;
XAxis.Y = rotation.m10;
XAxis.Z = rotation.m20;
YAxis.X = rotation.m01;
YAxis.Y = rotation.m11;
YAxis.Z = rotation.m21;
ZAxis.X = rotation.m02;
ZAxis.Y = rotation.m12;
ZAxis.Z = rotation.m22;
}
/// <summary>
///
/// </summary>
/// <param name="XAxis"></param>
/// <param name="YAxis"></param>
/// <param name="ZAxis"></param>
public void FromAxis(Vector3D XAxis, Vector3D YAxis, Vector3D ZAxis)
{
Matrix3x3 rotation = new Matrix3x3();
rotation.m00 = XAxis.X;
rotation.m10 = XAxis.Y;
rotation.m20 = XAxis.Z;
rotation.m01 = YAxis.X;
rotation.m11 = YAxis.Y;
rotation.m21 = YAxis.Z;
rotation.m02 = ZAxis.X;
rotation.m12 = ZAxis.Y;
rotation.m22 = ZAxis.Z;
// set this quaternions values from the rotation matriX built
FromRotationMatrix(rotation);
}
/// <summary>
///
/// </summary>
/// <param name="matriX"></param>
public void FromRotationMatrix(Matrix3x3 matriX)
{
// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
Scalar trace = matriX.m00 + matriX.m11 + matriX.m22;
Scalar root = 0.0f;
if (trace > 0.0f)
{
// |this.W| > 1/2, maY as Well choose this.W > 1/2
root = MathHelper.Sqrt(trace + 1.0f); // 2W
this.W = 0.5f * root;
root = 0.5f / root; // 1/(4W)
this.X = (matriX.m21 - matriX.m12) * root;
this.Y = (matriX.m02 - matriX.m20) * root;
this.Z = (matriX.m10 - matriX.m01) * root;
}
else
{
// |this.W| <= 1/2
int i = 0;
if (matriX.m11 > matriX.m00)
i = 1;
if (matriX.m22 > matriX[i, i])
i = 2;
int j = next[i];
int k = next[j];
root = MathHelper.Sqrt(matriX[i, i] - matriX[j, j] - matriX[k, k] + 1.0f);
unsafe
{
fixed (Scalar* apkQuat = &this.X)
{
apkQuat[i] = 0.5f * root;
root = 0.5f / root;
this.W = (matriX[k, j] - matriX[j, k]) * root;
apkQuat[j] = (matriX[j, i] + matriX[i, j]) * root;
apkQuat[k] = (matriX[k, i] + matriX[i, k]) * root;
}
}
}
}
/// <summary>
/// Calculates the logarithm of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Log()
{
// BLACKBOX: Learn this
// If q = cos(A)+sin(A)*(X*i+Y*j+Z*k) Where (X,Y,Z) is unit length, then
// log(q) = A*(X*i+Y*j+Z*k). If sin(A) is near Zero, use log(q) =
// sin(A)*(X*i+Y*j+Z*k) since sin(A)/A has limit 1.
// start off With a Zero quat
Quaternion returnvalue = Quaternion.Zero;
if (MathHelper.Abs(W) < 1.0f)
{
Scalar angle = MathHelper.Acos(W);
Scalar sin = MathHelper.Sin(angle);
if (MathHelper.Abs(sin) >= MathHelper.EPSILON)
{
Scalar coeff = angle / sin;
returnvalue.X = coeff * X;
returnvalue.Y = coeff * Y;
returnvalue.Z = coeff * Z;
}
else
{
returnvalue.X = X;
returnvalue.Y = Y;
returnvalue.Z = Z;
}
}
return returnvalue;
}
/// <summary>
/// Calculates the Exponent of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Exp()
{
// If q = A*(X*i+Y*j+Z*k) Where (X,Y,Z) is unit length, then
// eXp(q) = cos(A)+sin(A)*(X*i+Y*j+Z*k). If sin(A) is near Zero,
// use eXp(q) = cos(A)+A*(X*i+Y*j+Z*k) since A/sin(A) has limit 1.
Scalar angle = MathHelper.Sqrt(X * X + Y * Y + Z * Z);
Scalar sin = MathHelper.Sin(angle);
// start off With a Zero quat
Quaternion returnvalue = Quaternion.Zero;
returnvalue.W = MathHelper.Cos(angle);
if (MathHelper.Abs(sin) >= MathHelper.EPSILON)
{
Scalar coeff = sin / angle;
returnvalue.X = coeff * X;
returnvalue.Y = coeff * Y;
returnvalue.Z = coeff * Z;
}
else
{
returnvalue.X = X;
returnvalue.Y = Y;
returnvalue.Z = Z;
}
return returnvalue;
}
#endregion
#region Object overloads
/// <summary>
/// Overrides the Object.ToString() method to provide a teXt representation of
/// a Quaternion.
/// </summary>
/// <returns>A string representation of a Quaternion.</returns>
public override string ToString()
{
return string.Format("Quaternion({0}, {1}, {2}, {3})", this.X, this.Y, this.Z, this.W);
}
[ParseMethod]
public static Quaternion Parse(string text)
{
string[] vals = text.Replace("Quaternion", "").Trim(' ', '(', '[', '<', ')', ']', '>').Split(',');
if (vals.Length != 4)
{
throw new FormatException(string.Format("Cannot parse the text '{0}' because it does not have 4 parts separated by commas in the form (x,y,z,w) with optional parenthesis.", text));
}
else
{
try
{
Quaternion returnvalue;
returnvalue.X = Scalar.Parse(vals[0].Trim());
returnvalue.Y = Scalar.Parse(vals[1].Trim());
returnvalue.Z = Scalar.Parse(vals[2].Trim());
returnvalue.W = Scalar.Parse(vals[3].Trim());
return returnvalue;
}
catch (Exception ex)
{
throw new FormatException("The parts of the vectors must be decimal numbers", ex);
}
}
}
public override int GetHashCode()
{
return (int)X ^ (int)Y ^ (int)Z ^ (int)W;
}
public override bool Equals(object obj)
{
return obj is Quaternion && (Quaternion)obj == this;
}
#endregion
#region operator overloads
public static Quaternion Multiply(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W * right.W - left.X * right.X - left.Y * right.Y - left.Z * right.Z;
result.X = left.W * right.X + left.X * right.W + left.Y * right.Z - left.Z * right.Y;
result.Y = left.W * right.Y + left.Y * right.W + left.Z * right.X - left.X * right.Z;
result.Z = left.W * right.Z + left.Z * right.W + left.X * right.Y - left.Y * right.X;
return result;
}
public static void Multiply(ref Quaternion left,ref Quaternion right,out Quaternion result)
{
Scalar W = left.W * right.W - left.X * right.X - left.Y * right.Y - left.Z * right.Z;
Scalar X = left.W * right.X + left.X * right.W + left.Y * right.Z - left.Z * right.Y;
Scalar Y = left.W * right.Y + left.Y * right.W + left.Z * right.X - left.X * right.Z;
result.Z = left.W * right.Z + left.Z * right.W + left.X * right.Y - left.Y * right.X;
result.W = W;
result.X = X;
result.Y = Y;
}
public static Quaternion Multiply(Quaternion left, Scalar scalar)
{
Quaternion result;
result.W = left.W * scalar;
result.X = left.X * scalar;
result.Y = left.Y * scalar;
result.Z = left.Z * scalar;
return result;
}
public static void Multiply(ref Quaternion left,ref Scalar scalar, out Quaternion result)
{
result.W = left.W * scalar;
result.X = left.X * scalar;
result.Y = left.Y * scalar;
result.Z = left.Z * scalar;
}
public static Quaternion Add(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W + right.W;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
return result;
}
public static void Add(ref Quaternion left,ref Quaternion right, out Quaternion result)
{
result.W = left.W + right.W;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
}
public static Quaternion Subtract(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W - right.W;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
return result;
}
public static void Subtract(ref Quaternion left,ref Quaternion right, out Quaternion result)
{
result.W = left.W - right.W;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
}
public static Quaternion Negate(Quaternion value)
{
Quaternion result;
result.W = -value.W;
result.X = -value.X;
result.Y = -value.Y;
result.Z = -value.Z;
return result;
}
[CLSCompliant(false)]
public static void Negate(ref Quaternion value)
{
Negate(ref value, out value);
}
public static void Negate(ref Quaternion value, out Quaternion result)
{
result.W = -value.W;
result.X = -value.X;
result.Y = -value.Y;
result.Z = -value.Z;
}
public static Quaternion operator *(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W * right.W - left.X * right.X - left.Y * right.Y - left.Z * right.Z;
result.X = left.W * right.X + left.X * right.W + left.Y * right.Z - left.Z * right.Y;
result.Y = left.W * right.Y + left.Y * right.W + left.Z * right.X - left.X * right.Z;
result.Z = left.W * right.Z + left.Z * right.W + left.X * right.Y - left.Y * right.X;
return result;
}
public static Quaternion operator *(Scalar scalar, Quaternion right)
{
Quaternion result;
result.W = scalar * right.W;
result.X = scalar * right.X;
result.Y = scalar * right.Y;
result.Z = scalar * right.Z;
return result;
}
public static Quaternion operator *(Quaternion left, Scalar scalar)
{
Quaternion result;
result.W = left.W * scalar;
result.X = left.X * scalar;
result.Y = left.Y * scalar;
result.Z = left.Z * scalar;
return result;
}
public static Quaternion operator +(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W + right.W;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
return result;
}
public static Quaternion operator -(Quaternion left, Quaternion right)
{
Quaternion result;
result.W = left.W - right.W;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
return result;
}
public static Quaternion operator -(Quaternion value)
{
Quaternion result;
result.W = -value.W;
result.X = -value.X;
result.Y = -value.Y;
result.Z = -value.Z;
return result;
}
public static bool operator ==(Quaternion left, Quaternion right)
{
return
left.W == right.W &&
left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z;
}
public static bool operator !=(Quaternion left, Quaternion right)
{
return !(left == right);
}
#endregion
}
}
| |
#region Licensed
// Copyright 2010 John Sheehan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using NUnit.Framework;
using RestSharp.Deserializers;
using RestSharp.Tests.SampleClasses.Lastfm;
namespace RestSharp.Tests
{
[TestFixture]
public class NamespacedXmlTests
{
private const string GUID_STRING = "AC1FC4BC-087A-4242-B8EE-C53EBE9887A5";
[Test]
public void Can_Deserialize_Elements_With_Namespace()
{
var doc = CreateElementsXml();
var response = new RestResponse { Content = doc };
var d = new XmlDeserializer { Namespace = "http://restsharp.org" };
var p = d.Deserialize<PersonForXml>(response);
Assert.AreEqual("John Sheehan", p.Name);
Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate);
Assert.AreEqual(28, p.Age);
Assert.AreEqual(long.MaxValue, p.BigNumber);
Assert.AreEqual(99.9999m, p.Percent);
Assert.AreEqual(false, p.IsCool);
Assert.AreEqual(new Guid(GUID_STRING), p.UniqueId);
Assert.AreEqual(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url);
Assert.AreEqual(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath);
Assert.NotNull(p.Friends);
Assert.AreEqual(10, p.Friends.Count);
Assert.NotNull(p.BestFriend);
Assert.AreEqual("The Fonz", p.BestFriend.Name);
Assert.AreEqual(1952, p.BestFriend.Since);
}
[Test]
public void Can_Deserialize_Elements_With_Namespace_Autodetect_Namespace()
{
var doc = CreateElementsXml();
var response = new RestResponse { Content = doc };
var d = new XmlDeserializer();
var p = d.Deserialize<PersonForXml>(response);
Assert.AreEqual("John Sheehan", p.Name);
Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate);
Assert.AreEqual(28, p.Age);
Assert.AreEqual(long.MaxValue, p.BigNumber);
Assert.AreEqual(99.9999m, p.Percent);
Assert.AreEqual(false, p.IsCool);
Assert.AreEqual(new Guid(GUID_STRING), p.UniqueId);
Assert.AreEqual(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url);
Assert.AreEqual(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath);
Assert.NotNull(p.Friends);
Assert.AreEqual(10, p.Friends.Count);
Assert.NotNull(p.BestFriend);
Assert.AreEqual("The Fonz", p.BestFriend.Name);
Assert.AreEqual(1952, p.BestFriend.Since);
}
[Test]
public void Can_Deserialize_Attributes_With_Namespace()
{
var doc = CreateAttributesXml();
var response = new RestResponse { Content = doc };
var d = new XmlDeserializer { Namespace = "http://restsharp.org" };
var p = d.Deserialize<PersonForXml>(response);
Assert.AreEqual("John Sheehan", p.Name);
Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate);
Assert.AreEqual(28, p.Age);
Assert.AreEqual(long.MaxValue, p.BigNumber);
Assert.AreEqual(99.9999m, p.Percent);
Assert.AreEqual(false, p.IsCool);
Assert.AreEqual(new Guid(GUID_STRING), p.UniqueId);
Assert.AreEqual(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url);
Assert.AreEqual(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath);
Assert.NotNull(p.BestFriend);
Assert.AreEqual("The Fonz", p.BestFriend.Name);
Assert.AreEqual(1952, p.BestFriend.Since);
}
[Test]
public void Ignore_Protected_Property_That_Exists_In_Data()
{
var doc = CreateElementsXml();
var response = new RestResponse { Content = doc };
var d = new XmlDeserializer { Namespace = "http://restsharp.org" };
var p = d.Deserialize<PersonForXml>(response);
Assert.Null(p.IgnoreProxy);
}
[Test]
public void Ignore_ReadOnly_Property_That_Exists_In_Data()
{
var doc = CreateElementsXml();
var response = new RestResponse { Content = doc };
var d = new XmlDeserializer { Namespace = "http://restsharp.org" };
var p = d.Deserialize<PersonForXml>(response);
Assert.Null(p.ReadOnlyProxy);
}
[Test]
public void Can_Deserialize_Names_With_Underscores_With_Namespace()
{
var doc = CreateUnderscoresXml();
var response = new RestResponse { Content = doc };
var d = new XmlDeserializer { Namespace = "http://restsharp.org" };
var p = d.Deserialize<PersonForXml>(response);
Assert.AreEqual("John Sheehan", p.Name);
Assert.AreEqual(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate);
Assert.AreEqual(28, p.Age);
Assert.AreEqual(long.MaxValue, p.BigNumber);
Assert.AreEqual(99.9999m, p.Percent);
Assert.AreEqual(false, p.IsCool);
Assert.AreEqual(new Guid(GUID_STRING), p.UniqueId);
Assert.AreEqual(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url);
Assert.AreEqual(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath);
Assert.NotNull(p.Friends);
Assert.AreEqual(10, p.Friends.Count);
Assert.NotNull(p.BestFriend);
Assert.AreEqual("The Fonz", p.BestFriend.Name);
Assert.AreEqual(1952, p.BestFriend.Since);
Assert.NotNull(p.Foes);
Assert.AreEqual(5, p.Foes.Count);
Assert.AreEqual("Yankees", p.Foes.Team);
}
[Test]
public void Can_Deserialize_List_Of_Primitives_With_Namespace()
{
var doc = CreateListOfPrimitivesXml();
var response = new RestResponse { Content = doc };
var d = new XmlDeserializer { Namespace = "http://restsharp.org" };
var a = d.Deserialize<List<artist>>(response);
Assert.AreEqual(2, a.Count);
Assert.AreEqual("first", a[0].Value);
Assert.AreEqual("second", a[1].Value);
}
private static string CreateListOfPrimitivesXml()
{
var doc = new XDocument();
var ns = XNamespace.Get("http://restsharp.org");
var root = new XElement(ns + "artists");
root.Add(new XElement(ns + "artist", "first"));
root.Add(new XElement(ns + "artist", "second"));
doc.Add(root);
return doc.ToString();
}
private static string CreateUnderscoresXml()
{
var doc = new XDocument();
var ns = XNamespace.Get("http://restsharp.org");
var root = new XElement(ns + "Person");
root.Add(new XElement(ns + "Name", "John Sheehan"));
root.Add(new XElement(ns + "Start_Date", new DateTime(2009, 9, 25, 0, 6, 1)));
root.Add(new XAttribute(ns + "Age", 28));
root.Add(new XElement(ns + "Percent", 99.9999m));
root.Add(new XElement(ns + "Big_Number", long.MaxValue));
root.Add(new XAttribute(ns + "Is_Cool", false));
root.Add(new XElement(ns + "Ignore", "dummy"));
root.Add(new XAttribute(ns + "Read_Only", "dummy"));
root.Add(new XAttribute(ns + "Unique_Id", new Guid(GUID_STRING)));
root.Add(new XElement(ns + "Url", "http://example.com"));
root.Add(new XElement(ns + "Url_Path", "/foo/bar"));
root.Add(new XElement(ns + "Best_Friend",
new XElement(ns + "Name", "The Fonz"),
new XAttribute(ns + "Since", 1952)));
var friends = new XElement(ns + "Friends");
for (int i = 0; i < 10; i++)
{
friends.Add(new XElement(ns + "Friend",
new XElement(ns + "Name", "Friend" + i),
new XAttribute(ns + "Since", DateTime.Now.Year - i)));
}
root.Add(friends);
var foes = new XElement(ns + "Foes");
foes.Add(new XAttribute(ns + "Team", "Yankees"));
for (int i = 0; i < 5; i++)
{
foes.Add(new XElement(ns + "Foe", new XElement(ns + "Nickname", "Foe" + i)));
}
root.Add(foes);
doc.Add(root);
return doc.ToString();
}
private static string CreateElementsXml()
{
var doc = new XDocument();
var ns = XNamespace.Get("http://restsharp.org");
var root = new XElement(ns + "Person");
root.Add(new XElement(ns + "Name", "John Sheehan"));
root.Add(new XElement(ns + "StartDate", new DateTime(2009, 9, 25, 0, 6, 1)));
root.Add(new XElement(ns + "Age", 28));
root.Add(new XElement(ns + "Percent", 99.9999m));
root.Add(new XElement(ns + "BigNumber", long.MaxValue));
root.Add(new XElement(ns + "IsCool", false));
root.Add(new XElement(ns + "Ignore", "dummy"));
root.Add(new XElement(ns + "ReadOnly", "dummy"));
root.Add(new XElement(ns + "UniqueId", new Guid(GUID_STRING)));
root.Add(new XElement(ns + "Url", "http://example.com"));
root.Add(new XElement(ns + "UrlPath", "/foo/bar"));
root.Add(new XElement(ns + "BestFriend",
new XElement(ns + "Name", "The Fonz"),
new XElement(ns + "Since", 1952)));
var friends = new XElement(ns + "Friends");
for (int i = 0; i < 10; i++)
{
friends.Add(new XElement(ns + "Friend",
new XElement(ns + "Name", "Friend" + i),
new XElement(ns + "Since", DateTime.Now.Year - i)));
}
root.Add(friends);
root.Add(new XElement(ns + "FavoriteBand",
new XElement(ns + "Name", "Goldfinger")));
doc.Add(root);
return doc.ToString();
}
private static string CreateAttributesXml()
{
var doc = new XDocument();
var ns = XNamespace.Get("http://restsharp.org");
var root = new XElement(ns + "Person");
root.Add(new XAttribute(ns + "Name", "John Sheehan"));
root.Add(new XAttribute(ns + "StartDate", new DateTime(2009, 9, 25, 0, 6, 1)));
root.Add(new XAttribute(ns + "Age", 28));
root.Add(new XAttribute(ns + "Percent", 99.9999m));
root.Add(new XAttribute(ns + "BigNumber", long.MaxValue));
root.Add(new XAttribute(ns + "IsCool", false));
root.Add(new XAttribute(ns + "Ignore", "dummy"));
root.Add(new XAttribute(ns + "ReadOnly", "dummy"));
root.Add(new XAttribute(ns + "UniqueId", new Guid(GUID_STRING)));
root.Add(new XAttribute(ns + "Url", "http://example.com"));
root.Add(new XAttribute(ns + "UrlPath", "/foo/bar"));
root.Add(new XElement(ns + "BestFriend",
new XAttribute(ns + "Name", "The Fonz"),
new XAttribute(ns + "Since", 1952)));
doc.Add(root);
return doc.ToString();
}
}
}
| |
using UnityEngine;
using System.Collections;
public class Demo : MonoBehaviour
{
public float USER_LOG_IN_X;
public float USER_LOG_IN_Y;
public float USER_LOG_IN_WIDTH;
public float USER_LOG_IN_HEIGHT;
public float PIN_INPUT_X;
public float PIN_INPUT_Y;
public float PIN_INPUT_WIDTH;
public float PIN_INPUT_HEIGHT;
public float PIN_ENTER_X;
public float PIN_ENTER_Y;
public float PIN_ENTER_WIDTH;
public float PIN_ENTER_HEIGHT;
public float TWEET_INPUT_X;
public float TWEET_INPUT_Y;
public float TWEET_INPUT_WIDTH;
public float TWEET_INPUT_HEIGHT;
public float POST_TWEET_X;
public float POST_TWEET_Y;
public float POST_TWEET_WIDTH;
public float POST_TWEET_HEIGHT;
// You need to register your game or application in Twitter to get cosumer key and secret.
// Go to this page for registration: http://dev.twitter.com/apps/new
public string CONSUMER_KEY;
public string CONSUMER_SECRET;
// You need to save access token and secret for later use.
// You can keep using them whenever you need to access the user's Twitter account.
// They will be always valid until the user revokes the access to your application.
const string PLAYER_PREFS_TWITTER_USER_ID = "TwitterUserID";
const string PLAYER_PREFS_TWITTER_USER_SCREEN_NAME = "TwitterUserScreenName";
const string PLAYER_PREFS_TWITTER_USER_TOKEN = "TwitterUserToken";
const string PLAYER_PREFS_TWITTER_USER_TOKEN_SECRET = "TwitterUserTokenSecret";
Twitter.RequestTokenResponse m_RequestTokenResponse;
Twitter.AccessTokenResponse m_AccessTokenResponse;
string m_PIN = "Please enter your PIN here.";
string m_Tweet = "Please enter your tweet here.";
// Use this for initialization
void Start()
{
LoadTwitterUserInfo();
}
// Update is called once per frame
void Update()
{
}
// GUI
void OnGUI()
{
// LogIn/Register Button
Rect rect = new Rect(Screen.width * USER_LOG_IN_X,
Screen.height * USER_LOG_IN_Y,
Screen.width * USER_LOG_IN_WIDTH,
Screen.height * USER_LOG_IN_HEIGHT);
if (string.IsNullOrEmpty(CONSUMER_KEY) || string.IsNullOrEmpty(CONSUMER_SECRET))
{
string text = "You need to register your game or application first.\n Click this button, register and fill CONSUMER_KEY and CONSUMER_SECRET of Demo game object.";
if (GUI.Button(rect, text))
{
Application.OpenURL("http://dev.twitter.com/apps/new");
}
}
else
{
string text = string.Empty;
if (!string.IsNullOrEmpty(m_AccessTokenResponse.ScreenName))
{
text = m_AccessTokenResponse.ScreenName + "\nClick to register with a different Twitter account";
}
else
{
text = "You need to register your game or application first.";
}
if (GUI.Button(rect, text))
{
StartCoroutine(Twitter.API.GetRequestToken(CONSUMER_KEY, CONSUMER_SECRET,
new Twitter.RequestTokenCallback(this.OnRequestTokenCallback)));
}
}
// PIN Input
rect.x = Screen.width * PIN_INPUT_X;
rect.y = Screen.height * PIN_INPUT_Y;
rect.width = Screen.width * PIN_INPUT_WIDTH;
rect.height = Screen.height * PIN_INPUT_HEIGHT;
m_PIN = GUI.TextField(rect, m_PIN);
// PIN Enter Button
rect.x = Screen.width * PIN_ENTER_X;
rect.y = Screen.height * PIN_ENTER_Y;
rect.width = Screen.width * PIN_ENTER_WIDTH;
rect.height = Screen.height * PIN_ENTER_HEIGHT;
if (GUI.Button(rect, "Enter PIN"))
{
StartCoroutine(Twitter.API.GetAccessToken(CONSUMER_KEY, CONSUMER_SECRET, m_RequestTokenResponse.Token, m_PIN,
new Twitter.AccessTokenCallback(this.OnAccessTokenCallback)));
}
// Tweet Input
rect.x = Screen.width * TWEET_INPUT_X;
rect.y = Screen.height * TWEET_INPUT_Y;
rect.width = Screen.width * TWEET_INPUT_WIDTH;
rect.height = Screen.height * TWEET_INPUT_HEIGHT;
m_Tweet = GUI.TextField(rect, m_Tweet);
// Post Tweet Button
rect.x = Screen.width * POST_TWEET_X;
rect.y = Screen.height * POST_TWEET_Y;
rect.width = Screen.width * POST_TWEET_WIDTH;
rect.height = Screen.height * POST_TWEET_HEIGHT;
if (GUI.Button(rect, "Post Tweet"))
{
StartCoroutine(Twitter.API.PostTweet(m_Tweet, CONSUMER_KEY, CONSUMER_SECRET, m_AccessTokenResponse,
new Twitter.PostTweetCallback(this.OnPostTweet)));
}
}
void LoadTwitterUserInfo()
{
m_AccessTokenResponse = new Twitter.AccessTokenResponse();
m_AccessTokenResponse.UserId = PlayerPrefs.GetString(PLAYER_PREFS_TWITTER_USER_ID);
m_AccessTokenResponse.ScreenName = PlayerPrefs.GetString(PLAYER_PREFS_TWITTER_USER_SCREEN_NAME);
m_AccessTokenResponse.Token = PlayerPrefs.GetString(PLAYER_PREFS_TWITTER_USER_TOKEN);
m_AccessTokenResponse.TokenSecret = PlayerPrefs.GetString(PLAYER_PREFS_TWITTER_USER_TOKEN_SECRET);
if (!string.IsNullOrEmpty(m_AccessTokenResponse.Token) &&
!string.IsNullOrEmpty(m_AccessTokenResponse.ScreenName) &&
!string.IsNullOrEmpty(m_AccessTokenResponse.Token) &&
!string.IsNullOrEmpty(m_AccessTokenResponse.TokenSecret))
{
string log = "LoadTwitterUserInfo - succeeded";
log += "\n UserId : " + m_AccessTokenResponse.UserId;
log += "\n ScreenName : " + m_AccessTokenResponse.ScreenName;
log += "\n Token : " + m_AccessTokenResponse.Token;
log += "\n TokenSecret : " + m_AccessTokenResponse.TokenSecret;
print(log);
}
}
void OnRequestTokenCallback(bool success, Twitter.RequestTokenResponse response)
{
if (success)
{
string log = "OnRequestTokenCallback - succeeded";
log += "\n Token : " + response.Token;
log += "\n TokenSecret : " + response.TokenSecret;
print(log);
m_RequestTokenResponse = response;
Twitter.API.OpenAuthorizationPage(response.Token);
}
else
{
print("OnRequestTokenCallback - failed.");
}
}
void OnAccessTokenCallback(bool success, Twitter.AccessTokenResponse response)
{
if (success)
{
string log = "OnAccessTokenCallback - succeeded";
log += "\n UserId : " + response.UserId;
log += "\n ScreenName : " + response.ScreenName;
log += "\n Token : " + response.Token;
log += "\n TokenSecret : " + response.TokenSecret;
print(log);
m_AccessTokenResponse = response;
PlayerPrefs.SetString(PLAYER_PREFS_TWITTER_USER_ID, response.UserId);
PlayerPrefs.SetString(PLAYER_PREFS_TWITTER_USER_SCREEN_NAME, response.ScreenName);
PlayerPrefs.SetString(PLAYER_PREFS_TWITTER_USER_TOKEN, response.Token);
PlayerPrefs.SetString(PLAYER_PREFS_TWITTER_USER_TOKEN_SECRET, response.TokenSecret);
}
else
{
print("OnAccessTokenCallback - failed.");
}
}
void OnPostTweet(bool success)
{
print("OnPostTweet - " + (success ? "succedded." : "failed."));
}
}
| |
// <copyright file="StringExtensions.InvariantCulture.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System.Globalization;
namespace IX.StandardExtensions.Globalization;
/// <summary>
/// Extensions to strings to help with globalization.
/// </summary>
public static partial class StringExtensions
{
#region Methods
#region Static methods
/// <summary>
/// Compares the source string with a selected value in a case-sensitive manner using the comparison rules of the
/// invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// The comparison of the two strings, with 0 meaning equality.
/// </returns>
public static int InvariantCultureCompareTo(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.Compare(
source,
value,
CompareOptions.None);
/// <summary>
/// Compares the source string with a selected value in a case-insensitive manner using the comparison rules of the
/// invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// The comparison of the two strings, with 0 meaning equality.
/// </returns>
public static int InvariantCultureCompareToInsensitive(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.Compare(
source,
value,
CompareOptions.IgnoreCase);
/// <summary>
/// Determines whether a source string contains the specified value string in a case-sensitive manner using the
/// comparison rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string contains the specified value string; otherwise,
/// <see langword="false" />.
/// </returns>
public static bool InvariantCultureContains(
this string source,
string value) =>
source.InvariantCultureIndexOf(value) >= 0;
/// <summary>
/// Determines whether a source string contains the specified value string in a case-insensitive manner using the
/// comparison rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string contains the specified value string; otherwise,
/// <see langword="false" />.
/// </returns>
public static bool InvariantCultureContainsInsensitive(
this string source,
string value) =>
source.InvariantCultureIndexOfInsensitive(value) >= 0;
/// <summary>
/// Checks whether or not the source string ends with a selected value in a case-sensitive manner using the comparison
/// rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />.
/// </returns>
public static bool InvariantCultureEndsWith(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.IsSuffix(
source,
value,
CompareOptions.None);
/// <summary>
/// Checks whether or not the source string ends with a selected value in a case-insensitive manner using the
/// comparison rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />.
/// </returns>
public static bool InvariantCultureEndsWithInsensitive(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.IsSuffix(
source,
value,
CompareOptions.IgnoreCase);
/// <summary>
/// Equates the source string with a selected value in a case-sensitive manner using the comparison rules of the
/// invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />.
/// </returns>
public static bool InvariantCultureEquals(
this string source,
string value) =>
source.InvariantCultureCompareTo(value) == 0;
/// <summary>
/// Equates the source string with a selected value in a case-insensitive manner using the comparison rules of the
/// invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />.
/// </returns>
public static bool InvariantCultureEqualsInsensitive(
this string source,
string value) =>
source.InvariantCultureCompareToInsensitive(value) == 0;
/// <summary>
/// Finds the index of the specified value string in a source string in a case-sensitive manner using the comparison
/// rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// The index where the string is found, otherwise -1.
/// </returns>
public static int InvariantCultureIndexOf(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.IndexOf(
source,
value,
CompareOptions.None);
/// <summary>
/// Finds the index of the specified value string in a source string in a case-sensitive manner using the comparison
/// rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <param name="startIndex">The index in the source string to start searching at.</param>
/// <returns>The index where the string is found, otherwise -1.</returns>
public static int InvariantCultureIndexOf(
this string source,
string value,
int startIndex) =>
CultureInfo.InvariantCulture.CompareInfo.IndexOf(
source,
value,
startIndex,
CompareOptions.None);
/// <summary>
/// Finds the index of the specified value string in a source string in a case-sensitive manner using the comparison
/// rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <param name="startIndex">The index in the source string to start searching at.</param>
/// <param name="count">The number of characters to search.</param>
/// <returns>The index where the string is found, otherwise -1.</returns>
public static int InvariantCultureIndexOf(
this string source,
string value,
int startIndex,
int count) =>
CultureInfo.InvariantCulture.CompareInfo.IndexOf(
source,
value,
startIndex,
count,
CompareOptions.None);
/// <summary>
/// Finds the index of the specified value string in a source string in a case-insensitive manner using the comparison
/// rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// The index where the string is found, otherwise -1.
/// </returns>
public static int InvariantCultureIndexOfInsensitive(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.IndexOf(
source,
value,
CompareOptions.IgnoreCase);
/// <summary>
/// Finds the index of the specified value string in a source string in a case-insensitive manner using the comparison
/// rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <param name="startIndex">The index in the source string to start searching at.</param>
/// <returns>The index where the string is found, otherwise -1.</returns>
public static int InvariantCultureIndexOfInsensitive(
this string source,
string value,
int startIndex) =>
CultureInfo.InvariantCulture.CompareInfo.IndexOf(
source,
value,
startIndex,
CompareOptions.IgnoreCase);
/// <summary>
/// Finds the index of the specified value string in a source string in a case-insensitive manner using the comparison
/// rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <param name="startIndex">The index in the source string to start searching at.</param>
/// <param name="count">The number of characters to search.</param>
/// <returns>The index where the string is found, otherwise -1.</returns>
public static int InvariantCultureIndexOfInsensitive(
this string source,
string value,
int startIndex,
int count) =>
CultureInfo.InvariantCulture.CompareInfo.IndexOf(
source,
value,
startIndex,
count,
CompareOptions.IgnoreCase);
/// <summary>
/// Checks whether or not the source string starts with a selected value in a case-sensitive manner using the
/// comparison rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />.
/// </returns>
public static bool InvariantCultureStartsWith(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.IsPrefix(
source,
value,
CompareOptions.None);
/// <summary>
/// Checks whether or not the source string starts with a selected value in a case-insensitive manner using the
/// comparison rules of the invariant culture.
/// </summary>
/// <param name="source">The source to search in.</param>
/// <param name="value">The string value to do the evaluation.</param>
/// <returns>
/// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />.
/// </returns>
public static bool InvariantCultureStartsWithInsensitive(
this string source,
string value) =>
CultureInfo.InvariantCulture.CompareInfo.IsPrefix(
source,
value,
CompareOptions.IgnoreCase);
#endregion
#endregion
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Webrtc {
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']"
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid", DoNotGenerateAcw=true)]
public partial class VideoCapturerAndroid : global::Org.Webrtc.VideoCapturer, global::Android.Hardware.Camera.IPreviewCallback {
// Metadata.xml XPath interface reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoCapturerAndroid.CameraErrorHandler']"
[Register ("org/webrtc/VideoCapturerAndroid$CameraErrorHandler", "", "Org.Webrtc.VideoCapturerAndroid/ICameraErrorHandlerInvoker")]
public partial interface ICameraErrorHandler : IJavaObject {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoCapturerAndroid.CameraErrorHandler']/method[@name='onCameraError' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("onCameraError", "(Ljava/lang/String;)V", "GetOnCameraError_Ljava_lang_String_Handler:Org.Webrtc.VideoCapturerAndroid/ICameraErrorHandlerInvoker, WebRTCBindings")]
void OnCameraError (string p0);
}
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$CameraErrorHandler", DoNotGenerateAcw=true)]
internal class ICameraErrorHandlerInvoker : global::Java.Lang.Object, ICameraErrorHandler {
static IntPtr java_class_ref = JNIEnv.FindClass ("org/webrtc/VideoCapturerAndroid$CameraErrorHandler");
IntPtr class_ref;
public static ICameraErrorHandler GetObject (IntPtr handle, JniHandleOwnership transfer)
{
return global::Java.Lang.Object.GetObject<ICameraErrorHandler> (handle, transfer);
}
static IntPtr Validate (IntPtr handle)
{
if (!JNIEnv.IsInstanceOf (handle, java_class_ref))
throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.",
JNIEnv.GetClassNameFromInstance (handle), "org.webrtc.VideoCapturerAndroid.CameraErrorHandler"));
return handle;
}
protected override void Dispose (bool disposing)
{
if (this.class_ref != IntPtr.Zero)
JNIEnv.DeleteGlobalRef (this.class_ref);
this.class_ref = IntPtr.Zero;
base.Dispose (disposing);
}
public ICameraErrorHandlerInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer)
{
IntPtr local_ref = JNIEnv.GetObjectClass (Handle);
this.class_ref = JNIEnv.NewGlobalRef (local_ref);
JNIEnv.DeleteLocalRef (local_ref);
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (ICameraErrorHandlerInvoker); }
}
static Delegate cb_onCameraError_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetOnCameraError_Ljava_lang_String_Handler ()
{
if (cb_onCameraError_Ljava_lang_String_ == null)
cb_onCameraError_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_OnCameraError_Ljava_lang_String_);
return cb_onCameraError_Ljava_lang_String_;
}
static void n_OnCameraError_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Webrtc.VideoCapturerAndroid.ICameraErrorHandler __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.ICameraErrorHandler> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.OnCameraError (p0);
}
#pragma warning restore 0169
IntPtr id_onCameraError_Ljava_lang_String_;
public unsafe void OnCameraError (string p0)
{
if (id_onCameraError_Ljava_lang_String_ == IntPtr.Zero)
id_onCameraError_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "onCameraError", "(Ljava/lang/String;)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_p0);
JNIEnv.CallVoidMethod (Handle, id_onCameraError_Ljava_lang_String_, __args);
JNIEnv.DeleteLocalRef (native_p0);
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CameraThread']"
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$CameraThread", DoNotGenerateAcw=true)]
public partial class CameraThread : global::Java.Lang.Thread {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/VideoCapturerAndroid$CameraThread", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (CameraThread); }
}
protected CameraThread (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Lorg_webrtc_VideoCapturerAndroid_Ljava_util_concurrent_Exchanger_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CameraThread']/constructor[@name='VideoCapturerAndroid.CameraThread' and count(parameter)=2 and parameter[1][@type='org.webrtc.VideoCapturerAndroid'] and parameter[2][@type='java.util.concurrent.Exchanger<android.os.Handler>']]"
[Register (".ctor", "(Lorg/webrtc/VideoCapturerAndroid;Ljava/util/concurrent/Exchanger;)V", "")]
public unsafe CameraThread (global::Org.Webrtc.VideoCapturerAndroid __self, global::Java.Util.Concurrent.Exchanger p0)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (__self);
__args [1] = new JValue (p0);
if (GetType () != typeof (CameraThread)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(L" + global::Android.Runtime.JNIEnv.GetJniName (GetType ().DeclaringType) + ";Ljava/util/concurrent/Exchanger;)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(L" + global::Android.Runtime.JNIEnv.GetJniName (GetType ().DeclaringType) + ";Ljava/util/concurrent/Exchanger;)V", __args);
return;
}
if (id_ctor_Lorg_webrtc_VideoCapturerAndroid_Ljava_util_concurrent_Exchanger_ == IntPtr.Zero)
id_ctor_Lorg_webrtc_VideoCapturerAndroid_Ljava_util_concurrent_Exchanger_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/webrtc/VideoCapturerAndroid;Ljava/util/concurrent/Exchanger;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_webrtc_VideoCapturerAndroid_Ljava_util_concurrent_Exchanger_, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_webrtc_VideoCapturerAndroid_Ljava_util_concurrent_Exchanger_, __args);
} finally {
}
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']"
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$CaptureFormat", DoNotGenerateAcw=true)]
public partial class CaptureFormat : global::Java.Lang.Object {
static IntPtr height_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/field[@name='height']"
[Register ("height")]
public int Height {
get {
if (height_jfieldId == IntPtr.Zero)
height_jfieldId = JNIEnv.GetFieldID (class_ref, "height", "I");
return JNIEnv.GetIntField (Handle, height_jfieldId);
}
set {
if (height_jfieldId == IntPtr.Zero)
height_jfieldId = JNIEnv.GetFieldID (class_ref, "height", "I");
try {
JNIEnv.SetField (Handle, height_jfieldId, value);
} finally {
}
}
}
static IntPtr imageFormat_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/field[@name='imageFormat']"
[Register ("imageFormat")]
public int ImageFormat {
get {
if (imageFormat_jfieldId == IntPtr.Zero)
imageFormat_jfieldId = JNIEnv.GetFieldID (class_ref, "imageFormat", "I");
return JNIEnv.GetIntField (Handle, imageFormat_jfieldId);
}
set {
if (imageFormat_jfieldId == IntPtr.Zero)
imageFormat_jfieldId = JNIEnv.GetFieldID (class_ref, "imageFormat", "I");
try {
JNIEnv.SetField (Handle, imageFormat_jfieldId, value);
} finally {
}
}
}
static IntPtr maxFramerate_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/field[@name='maxFramerate']"
[Register ("maxFramerate")]
public int MaxFramerate {
get {
if (maxFramerate_jfieldId == IntPtr.Zero)
maxFramerate_jfieldId = JNIEnv.GetFieldID (class_ref, "maxFramerate", "I");
return JNIEnv.GetIntField (Handle, maxFramerate_jfieldId);
}
set {
if (maxFramerate_jfieldId == IntPtr.Zero)
maxFramerate_jfieldId = JNIEnv.GetFieldID (class_ref, "maxFramerate", "I");
try {
JNIEnv.SetField (Handle, maxFramerate_jfieldId, value);
} finally {
}
}
}
static IntPtr minFramerate_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/field[@name='minFramerate']"
[Register ("minFramerate")]
public int MinFramerate {
get {
if (minFramerate_jfieldId == IntPtr.Zero)
minFramerate_jfieldId = JNIEnv.GetFieldID (class_ref, "minFramerate", "I");
return JNIEnv.GetIntField (Handle, minFramerate_jfieldId);
}
set {
if (minFramerate_jfieldId == IntPtr.Zero)
minFramerate_jfieldId = JNIEnv.GetFieldID (class_ref, "minFramerate", "I");
try {
JNIEnv.SetField (Handle, minFramerate_jfieldId, value);
} finally {
}
}
}
static IntPtr width_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/field[@name='width']"
[Register ("width")]
public int Width {
get {
if (width_jfieldId == IntPtr.Zero)
width_jfieldId = JNIEnv.GetFieldID (class_ref, "width", "I");
return JNIEnv.GetIntField (Handle, width_jfieldId);
}
set {
if (width_jfieldId == IntPtr.Zero)
width_jfieldId = JNIEnv.GetFieldID (class_ref, "width", "I");
try {
JNIEnv.SetField (Handle, width_jfieldId, value);
} finally {
}
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/VideoCapturerAndroid$CaptureFormat", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (CaptureFormat); }
}
protected CaptureFormat (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_IIII;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/constructor[@name='VideoCapturerAndroid.CaptureFormat' and count(parameter)=4 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int'] and parameter[4][@type='int']]"
[Register (".ctor", "(IIII)V", "")]
public unsafe CaptureFormat (int p0, int p1, int p2, int p3)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
try {
JValue* __args = stackalloc JValue [4];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
__args [3] = new JValue (p3);
if (GetType () != typeof (CaptureFormat)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(IIII)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(IIII)V", __args);
return;
}
if (id_ctor_IIII == IntPtr.Zero)
id_ctor_IIII = JNIEnv.GetMethodID (class_ref, "<init>", "(IIII)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_IIII, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_IIII, __args);
} finally {
}
}
static Delegate cb_frameSize;
#pragma warning disable 0169
static Delegate GetFrameSizeHandler ()
{
if (cb_frameSize == null)
cb_frameSize = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_FrameSize);
return cb_frameSize;
}
static int n_FrameSize (IntPtr jnienv, IntPtr native__this)
{
global::Org.Webrtc.VideoCapturerAndroid.CaptureFormat __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.CaptureFormat> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.FrameSize ();
}
#pragma warning restore 0169
static IntPtr id_frameSize;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/method[@name='frameSize' and count(parameter)=0]"
[Register ("frameSize", "()I", "GetFrameSizeHandler")]
public virtual unsafe int FrameSize ()
{
if (id_frameSize == IntPtr.Zero)
id_frameSize = JNIEnv.GetMethodID (class_ref, "frameSize", "()I");
try {
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_frameSize);
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "frameSize", "()I"));
} finally {
}
}
static IntPtr id_frameSize_III;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.CaptureFormat']/method[@name='frameSize' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int']]"
[Register ("frameSize", "(III)I", "")]
public static unsafe int FrameSize (int p0, int p1, int p2)
{
if (id_frameSize_III == IntPtr.Zero)
id_frameSize_III = JNIEnv.GetStaticMethodID (class_ref, "frameSize", "(III)I");
try {
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
return JNIEnv.CallStaticIntMethod (class_ref, id_frameSize_III, __args);
} finally {
}
}
}
// Metadata.xml XPath interface reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoCapturerAndroid.CapturerObserver']"
[Register ("org/webrtc/VideoCapturerAndroid$CapturerObserver", "", "Org.Webrtc.VideoCapturerAndroid/ICapturerObserverInvoker")]
public partial interface ICapturerObserver : IJavaObject {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoCapturerAndroid.CapturerObserver']/method[@name='OnCapturerStarted' and count(parameter)=1 and parameter[1][@type='boolean']]"
[Register ("OnCapturerStarted", "(Z)V", "GetOnCapturerStarted_ZHandler:Org.Webrtc.VideoCapturerAndroid/ICapturerObserverInvoker, WebRTCBindings")]
void OnCapturerStarted (bool p0);
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoCapturerAndroid.CapturerObserver']/method[@name='OnFrameCaptured' and count(parameter)=6 and parameter[1][@type='byte[]'] and parameter[2][@type='int'] and parameter[3][@type='int'] and parameter[4][@type='int'] and parameter[5][@type='int'] and parameter[6][@type='long']]"
[Register ("OnFrameCaptured", "([BIIIIJ)V", "GetOnFrameCaptured_arrayBIIIIJHandler:Org.Webrtc.VideoCapturerAndroid/ICapturerObserverInvoker, WebRTCBindings")]
void OnFrameCaptured (byte[] p0, int p1, int p2, int p3, int p4, long p5);
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/interface[@name='VideoCapturerAndroid.CapturerObserver']/method[@name='OnOutputFormatRequest' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int']]"
[Register ("OnOutputFormatRequest", "(III)V", "GetOnOutputFormatRequest_IIIHandler:Org.Webrtc.VideoCapturerAndroid/ICapturerObserverInvoker, WebRTCBindings")]
void OnOutputFormatRequest (int p0, int p1, int p2);
}
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$CapturerObserver", DoNotGenerateAcw=true)]
internal class ICapturerObserverInvoker : global::Java.Lang.Object, ICapturerObserver {
static IntPtr java_class_ref = JNIEnv.FindClass ("org/webrtc/VideoCapturerAndroid$CapturerObserver");
IntPtr class_ref;
public static ICapturerObserver GetObject (IntPtr handle, JniHandleOwnership transfer)
{
return global::Java.Lang.Object.GetObject<ICapturerObserver> (handle, transfer);
}
static IntPtr Validate (IntPtr handle)
{
if (!JNIEnv.IsInstanceOf (handle, java_class_ref))
throw new InvalidCastException (string.Format ("Unable to convert instance of type '{0}' to type '{1}'.",
JNIEnv.GetClassNameFromInstance (handle), "org.webrtc.VideoCapturerAndroid.CapturerObserver"));
return handle;
}
protected override void Dispose (bool disposing)
{
if (this.class_ref != IntPtr.Zero)
JNIEnv.DeleteGlobalRef (this.class_ref);
this.class_ref = IntPtr.Zero;
base.Dispose (disposing);
}
public ICapturerObserverInvoker (IntPtr handle, JniHandleOwnership transfer) : base (Validate (handle), transfer)
{
IntPtr local_ref = JNIEnv.GetObjectClass (Handle);
this.class_ref = JNIEnv.NewGlobalRef (local_ref);
JNIEnv.DeleteLocalRef (local_ref);
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (ICapturerObserverInvoker); }
}
static Delegate cb_OnCapturerStarted_Z;
#pragma warning disable 0169
static Delegate GetOnCapturerStarted_ZHandler ()
{
if (cb_OnCapturerStarted_Z == null)
cb_OnCapturerStarted_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_OnCapturerStarted_Z);
return cb_OnCapturerStarted_Z;
}
static void n_OnCapturerStarted_Z (IntPtr jnienv, IntPtr native__this, bool p0)
{
global::Org.Webrtc.VideoCapturerAndroid.ICapturerObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.ICapturerObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnCapturerStarted (p0);
}
#pragma warning restore 0169
IntPtr id_OnCapturerStarted_Z;
public unsafe void OnCapturerStarted (bool p0)
{
if (id_OnCapturerStarted_Z == IntPtr.Zero)
id_OnCapturerStarted_Z = JNIEnv.GetMethodID (class_ref, "OnCapturerStarted", "(Z)V");
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
JNIEnv.CallVoidMethod (Handle, id_OnCapturerStarted_Z, __args);
}
static Delegate cb_OnFrameCaptured_arrayBIIIIJ;
#pragma warning disable 0169
static Delegate GetOnFrameCaptured_arrayBIIIIJHandler ()
{
if (cb_OnFrameCaptured_arrayBIIIIJ == null)
cb_OnFrameCaptured_arrayBIIIIJ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, int, int, int, int, long>) n_OnFrameCaptured_arrayBIIIIJ);
return cb_OnFrameCaptured_arrayBIIIIJ;
}
static void n_OnFrameCaptured_arrayBIIIIJ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, int p1, int p2, int p3, int p4, long p5)
{
global::Org.Webrtc.VideoCapturerAndroid.ICapturerObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.ICapturerObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
byte[] p0 = (byte[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (byte));
__this.OnFrameCaptured (p0, p1, p2, p3, p4, p5);
if (p0 != null)
JNIEnv.CopyArray (p0, native_p0);
}
#pragma warning restore 0169
IntPtr id_OnFrameCaptured_arrayBIIIIJ;
public unsafe void OnFrameCaptured (byte[] p0, int p1, int p2, int p3, int p4, long p5)
{
if (id_OnFrameCaptured_arrayBIIIIJ == IntPtr.Zero)
id_OnFrameCaptured_arrayBIIIIJ = JNIEnv.GetMethodID (class_ref, "OnFrameCaptured", "([BIIIIJ)V");
IntPtr native_p0 = JNIEnv.NewArray (p0);
JValue* __args = stackalloc JValue [6];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
__args [3] = new JValue (p3);
__args [4] = new JValue (p4);
__args [5] = new JValue (p5);
JNIEnv.CallVoidMethod (Handle, id_OnFrameCaptured_arrayBIIIIJ, __args);
if (p0 != null) {
JNIEnv.CopyArray (native_p0, p0);
JNIEnv.DeleteLocalRef (native_p0);
}
}
static Delegate cb_OnOutputFormatRequest_III;
#pragma warning disable 0169
static Delegate GetOnOutputFormatRequest_IIIHandler ()
{
if (cb_OnOutputFormatRequest_III == null)
cb_OnOutputFormatRequest_III = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int, int>) n_OnOutputFormatRequest_III);
return cb_OnOutputFormatRequest_III;
}
static void n_OnOutputFormatRequest_III (IntPtr jnienv, IntPtr native__this, int p0, int p1, int p2)
{
global::Org.Webrtc.VideoCapturerAndroid.ICapturerObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.ICapturerObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnOutputFormatRequest (p0, p1, p2);
}
#pragma warning restore 0169
IntPtr id_OnOutputFormatRequest_III;
public unsafe void OnOutputFormatRequest (int p0, int p1, int p2)
{
if (id_OnOutputFormatRequest_III == IntPtr.Zero)
id_OnOutputFormatRequest_III = JNIEnv.GetMethodID (class_ref, "OnOutputFormatRequest", "(III)V");
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
JNIEnv.CallVoidMethod (Handle, id_OnOutputFormatRequest_III, __args);
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.ClosestComparator']"
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$ClosestComparator", DoNotGenerateAcw=true)]
public abstract partial class ClosestComparator : global::Java.Lang.Object, global::Java.Util.IComparator {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/VideoCapturerAndroid$ClosestComparator", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (ClosestComparator); }
}
protected ClosestComparator (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static Delegate cb_compare_Ljava_lang_Object_Ljava_lang_Object_;
#pragma warning disable 0169
static Delegate GetCompare_Ljava_lang_Object_Ljava_lang_Object_Handler ()
{
if (cb_compare_Ljava_lang_Object_Ljava_lang_Object_ == null)
cb_compare_Ljava_lang_Object_Ljava_lang_Object_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, int>) n_Compare_Ljava_lang_Object_Ljava_lang_Object_);
return cb_compare_Ljava_lang_Object_Ljava_lang_Object_;
}
static int n_Compare_Ljava_lang_Object_Ljava_lang_Object_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Org.Webrtc.VideoCapturerAndroid.ClosestComparator __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.ClosestComparator> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Object p0 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p0, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.Object p1 = global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (native_p1, JniHandleOwnership.DoNotTransfer);
int __ret = __this.Compare (p0, p1);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_compare_Ljava_lang_Object_Ljava_lang_Object_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.ClosestComparator']/method[@name='compare' and count(parameter)=2 and parameter[1][@type='T'] and parameter[2][@type='T']]"
[Register ("compare", "(Ljava/lang/Object;Ljava/lang/Object;)I", "GetCompare_Ljava_lang_Object_Ljava_lang_Object_Handler")]
public virtual unsafe int Compare (global::Java.Lang.Object p0, global::Java.Lang.Object p1)
{
if (id_compare_Ljava_lang_Object_Ljava_lang_Object_ == IntPtr.Zero)
id_compare_Ljava_lang_Object_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "compare", "(Ljava/lang/Object;Ljava/lang/Object;)I");
IntPtr native_p0 = JNIEnv.ToLocalJniHandle (p0);
IntPtr native_p1 = JNIEnv.ToLocalJniHandle (p1);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (native_p1);
int __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallIntMethod (Handle, id_compare_Ljava_lang_Object_Ljava_lang_Object_, __args);
else
__ret = JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "compare", "(Ljava/lang/Object;Ljava/lang/Object;)I"), __args);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
JNIEnv.DeleteLocalRef (native_p1);
}
}
}
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$ClosestComparator", DoNotGenerateAcw=true)]
internal partial class ClosestComparatorInvoker : ClosestComparator {
public ClosestComparatorInvoker (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) {}
protected override global::System.Type ThresholdType {
get { return typeof (ClosestComparatorInvoker); }
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.FramePool']"
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$FramePool", DoNotGenerateAcw=true)]
public partial class FramePool : global::Java.Lang.Object {
protected FramePool (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.NativeObserver']"
[global::Android.Runtime.Register ("org/webrtc/VideoCapturerAndroid$NativeObserver", DoNotGenerateAcw=true)]
public partial class NativeObserver : global::Java.Lang.Object, global::Org.Webrtc.VideoCapturerAndroid.ICapturerObserver {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/VideoCapturerAndroid$NativeObserver", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (NativeObserver); }
}
protected NativeObserver (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_J;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.NativeObserver']/constructor[@name='VideoCapturerAndroid.NativeObserver' and count(parameter)=1 and parameter[1][@type='long']]"
[Register (".ctor", "(J)V", "")]
public unsafe NativeObserver (long p0)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
if (GetType () != typeof (NativeObserver)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(J)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(J)V", __args);
return;
}
if (id_ctor_J == IntPtr.Zero)
id_ctor_J = JNIEnv.GetMethodID (class_ref, "<init>", "(J)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_J, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_J, __args);
} finally {
}
}
static Delegate cb_OnCapturerStarted_Z;
#pragma warning disable 0169
static Delegate GetOnCapturerStarted_ZHandler ()
{
if (cb_OnCapturerStarted_Z == null)
cb_OnCapturerStarted_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_OnCapturerStarted_Z);
return cb_OnCapturerStarted_Z;
}
static void n_OnCapturerStarted_Z (IntPtr jnienv, IntPtr native__this, bool p0)
{
global::Org.Webrtc.VideoCapturerAndroid.NativeObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.NativeObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnCapturerStarted (p0);
}
#pragma warning restore 0169
static IntPtr id_OnCapturerStarted_Z;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.NativeObserver']/method[@name='OnCapturerStarted' and count(parameter)=1 and parameter[1][@type='boolean']]"
[Register ("OnCapturerStarted", "(Z)V", "GetOnCapturerStarted_ZHandler")]
public virtual unsafe void OnCapturerStarted (bool p0)
{
if (id_OnCapturerStarted_Z == IntPtr.Zero)
id_OnCapturerStarted_Z = JNIEnv.GetMethodID (class_ref, "OnCapturerStarted", "(Z)V");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_OnCapturerStarted_Z, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "OnCapturerStarted", "(Z)V"), __args);
} finally {
}
}
static Delegate cb_OnFrameCaptured_arrayBIIIIJ;
#pragma warning disable 0169
static Delegate GetOnFrameCaptured_arrayBIIIIJHandler ()
{
if (cb_OnFrameCaptured_arrayBIIIIJ == null)
cb_OnFrameCaptured_arrayBIIIIJ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, int, int, int, int, long>) n_OnFrameCaptured_arrayBIIIIJ);
return cb_OnFrameCaptured_arrayBIIIIJ;
}
static void n_OnFrameCaptured_arrayBIIIIJ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, int p1, int p2, int p3, int p4, long p5)
{
global::Org.Webrtc.VideoCapturerAndroid.NativeObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.NativeObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
byte[] p0 = (byte[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (byte));
__this.OnFrameCaptured (p0, p1, p2, p3, p4, p5);
if (p0 != null)
JNIEnv.CopyArray (p0, native_p0);
}
#pragma warning restore 0169
static IntPtr id_OnFrameCaptured_arrayBIIIIJ;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.NativeObserver']/method[@name='OnFrameCaptured' and count(parameter)=6 and parameter[1][@type='byte[]'] and parameter[2][@type='int'] and parameter[3][@type='int'] and parameter[4][@type='int'] and parameter[5][@type='int'] and parameter[6][@type='long']]"
[Register ("OnFrameCaptured", "([BIIIIJ)V", "GetOnFrameCaptured_arrayBIIIIJHandler")]
public virtual unsafe void OnFrameCaptured (byte[] p0, int p1, int p2, int p3, int p4, long p5)
{
if (id_OnFrameCaptured_arrayBIIIIJ == IntPtr.Zero)
id_OnFrameCaptured_arrayBIIIIJ = JNIEnv.GetMethodID (class_ref, "OnFrameCaptured", "([BIIIIJ)V");
IntPtr native_p0 = JNIEnv.NewArray (p0);
try {
JValue* __args = stackalloc JValue [6];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
__args [3] = new JValue (p3);
__args [4] = new JValue (p4);
__args [5] = new JValue (p5);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_OnFrameCaptured_arrayBIIIIJ, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "OnFrameCaptured", "([BIIIIJ)V"), __args);
} finally {
if (p0 != null) {
JNIEnv.CopyArray (native_p0, p0);
JNIEnv.DeleteLocalRef (native_p0);
}
}
}
static Delegate cb_OnOutputFormatRequest_III;
#pragma warning disable 0169
static Delegate GetOnOutputFormatRequest_IIIHandler ()
{
if (cb_OnOutputFormatRequest_III == null)
cb_OnOutputFormatRequest_III = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int, int>) n_OnOutputFormatRequest_III);
return cb_OnOutputFormatRequest_III;
}
static void n_OnOutputFormatRequest_III (IntPtr jnienv, IntPtr native__this, int p0, int p1, int p2)
{
global::Org.Webrtc.VideoCapturerAndroid.NativeObserver __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid.NativeObserver> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnOutputFormatRequest (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_OnOutputFormatRequest_III;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid.NativeObserver']/method[@name='OnOutputFormatRequest' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int']]"
[Register ("OnOutputFormatRequest", "(III)V", "GetOnOutputFormatRequest_IIIHandler")]
public virtual unsafe void OnOutputFormatRequest (int p0, int p1, int p2)
{
if (id_OnOutputFormatRequest_III == IntPtr.Zero)
id_OnOutputFormatRequest_III = JNIEnv.GetMethodID (class_ref, "OnOutputFormatRequest", "(III)V");
try {
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_OnOutputFormatRequest_III, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "OnOutputFormatRequest", "(III)V"), __args);
} finally {
}
}
}
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/VideoCapturerAndroid", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (VideoCapturerAndroid); }
}
protected VideoCapturerAndroid (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_getDeviceCount;
public static unsafe int DeviceCount {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='getDeviceCount' and count(parameter)=0]"
[Register ("getDeviceCount", "()I", "GetGetDeviceCountHandler")]
get {
if (id_getDeviceCount == IntPtr.Zero)
id_getDeviceCount = JNIEnv.GetStaticMethodID (class_ref, "getDeviceCount", "()I");
try {
return JNIEnv.CallStaticIntMethod (class_ref, id_getDeviceCount);
} finally {
}
}
}
static IntPtr id_getNameOfBackFacingDevice;
public static unsafe string NameOfBackFacingDevice {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='getNameOfBackFacingDevice' and count(parameter)=0]"
[Register ("getNameOfBackFacingDevice", "()Ljava/lang/String;", "GetGetNameOfBackFacingDeviceHandler")]
get {
if (id_getNameOfBackFacingDevice == IntPtr.Zero)
id_getNameOfBackFacingDevice = JNIEnv.GetStaticMethodID (class_ref, "getNameOfBackFacingDevice", "()Ljava/lang/String;");
try {
return JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_getNameOfBackFacingDevice), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
static IntPtr id_getNameOfFrontFacingDevice;
public static unsafe string NameOfFrontFacingDevice {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='getNameOfFrontFacingDevice' and count(parameter)=0]"
[Register ("getNameOfFrontFacingDevice", "()Ljava/lang/String;", "GetGetNameOfFrontFacingDeviceHandler")]
get {
if (id_getNameOfFrontFacingDevice == IntPtr.Zero)
id_getNameOfFrontFacingDevice = JNIEnv.GetStaticMethodID (class_ref, "getNameOfFrontFacingDevice", "()Ljava/lang/String;");
try {
return JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_getNameOfFrontFacingDevice), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
static Delegate cb_getSupportedFormats;
#pragma warning disable 0169
static Delegate GetGetSupportedFormatsHandler ()
{
if (cb_getSupportedFormats == null)
cb_getSupportedFormats = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetSupportedFormats);
return cb_getSupportedFormats;
}
static IntPtr n_GetSupportedFormats (IntPtr jnienv, IntPtr native__this)
{
global::Org.Webrtc.VideoCapturerAndroid __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return global::Android.Runtime.JavaList<global::Org.Webrtc.VideoCapturerAndroid.CaptureFormat>.ToLocalJniHandle (__this.SupportedFormats);
}
#pragma warning restore 0169
static IntPtr id_getSupportedFormats;
public virtual unsafe global::System.Collections.Generic.IList<global::Org.Webrtc.VideoCapturerAndroid.CaptureFormat> SupportedFormats {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='getSupportedFormats' and count(parameter)=0]"
[Register ("getSupportedFormats", "()Ljava/util/List;", "GetGetSupportedFormatsHandler")]
get {
if (id_getSupportedFormats == IntPtr.Zero)
id_getSupportedFormats = JNIEnv.GetMethodID (class_ref, "getSupportedFormats", "()Ljava/util/List;");
try {
if (GetType () == ThresholdType)
return global::Android.Runtime.JavaList<global::Org.Webrtc.VideoCapturerAndroid.CaptureFormat>.FromJniHandle (JNIEnv.CallObjectMethod (Handle, id_getSupportedFormats), JniHandleOwnership.TransferLocalRef);
else
return global::Android.Runtime.JavaList<global::Org.Webrtc.VideoCapturerAndroid.CaptureFormat>.FromJniHandle (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getSupportedFormats", "()Ljava/util/List;")), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
}
static Delegate cb_changeCaptureFormat_III;
#pragma warning disable 0169
static Delegate GetChangeCaptureFormat_IIIHandler ()
{
if (cb_changeCaptureFormat_III == null)
cb_changeCaptureFormat_III = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int, int>) n_ChangeCaptureFormat_III);
return cb_changeCaptureFormat_III;
}
static void n_ChangeCaptureFormat_III (IntPtr jnienv, IntPtr native__this, int p0, int p1, int p2)
{
global::Org.Webrtc.VideoCapturerAndroid __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.ChangeCaptureFormat (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_changeCaptureFormat_III;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='changeCaptureFormat' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int']]"
[Register ("changeCaptureFormat", "(III)V", "GetChangeCaptureFormat_IIIHandler")]
public virtual unsafe void ChangeCaptureFormat (int p0, int p1, int p2)
{
if (id_changeCaptureFormat_III == IntPtr.Zero)
id_changeCaptureFormat_III = JNIEnv.GetMethodID (class_ref, "changeCaptureFormat", "(III)V");
try {
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_changeCaptureFormat_III, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "changeCaptureFormat", "(III)V"), __args);
} finally {
}
}
static IntPtr id_create_Ljava_lang_String_Lorg_webrtc_VideoCapturerAndroid_CameraErrorHandler_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='create' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='org.webrtc.VideoCapturerAndroid.CameraErrorHandler']]"
[Register ("create", "(Ljava/lang/String;Lorg/webrtc/VideoCapturerAndroid$CameraErrorHandler;)Lorg/webrtc/VideoCapturerAndroid;", "")]
public static unsafe global::Org.Webrtc.VideoCapturerAndroid Create (string p0, global::Org.Webrtc.VideoCapturerAndroid.ICameraErrorHandler p1)
{
if (id_create_Ljava_lang_String_Lorg_webrtc_VideoCapturerAndroid_CameraErrorHandler_ == IntPtr.Zero)
id_create_Ljava_lang_String_Lorg_webrtc_VideoCapturerAndroid_CameraErrorHandler_ = JNIEnv.GetStaticMethodID (class_ref, "create", "(Ljava/lang/String;Lorg/webrtc/VideoCapturerAndroid$CameraErrorHandler;)Lorg/webrtc/VideoCapturerAndroid;");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
global::Org.Webrtc.VideoCapturerAndroid __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid> (JNIEnv.CallStaticObjectMethod (class_ref, id_create_Ljava_lang_String_Lorg_webrtc_VideoCapturerAndroid_CameraErrorHandler_, __args), JniHandleOwnership.TransferLocalRef);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
static IntPtr id_getDeviceName_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='getDeviceName' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getDeviceName", "(I)Ljava/lang/String;", "")]
public static unsafe string GetDeviceName (int p0)
{
if (id_getDeviceName_I == IntPtr.Zero)
id_getDeviceName_I = JNIEnv.GetStaticMethodID (class_ref, "getDeviceName", "(I)Ljava/lang/String;");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
return JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_getDeviceName_I, __args), JniHandleOwnership.TransferLocalRef);
} finally {
}
}
static IntPtr id_getDeviceNames;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='getDeviceNames' and count(parameter)=0]"
[Register ("getDeviceNames", "()[Ljava/lang/String;", "")]
public static unsafe string[] GetDeviceNames ()
{
if (id_getDeviceNames == IntPtr.Zero)
id_getDeviceNames = JNIEnv.GetStaticMethodID (class_ref, "getDeviceNames", "()[Ljava/lang/String;");
try {
return (string[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_getDeviceNames), JniHandleOwnership.TransferLocalRef, typeof (string));
} finally {
}
}
static Delegate cb_onOutputFormatRequest_III;
#pragma warning disable 0169
static Delegate GetOnOutputFormatRequest_IIIHandler ()
{
if (cb_onOutputFormatRequest_III == null)
cb_onOutputFormatRequest_III = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, int, int>) n_OnOutputFormatRequest_III);
return cb_onOutputFormatRequest_III;
}
static void n_OnOutputFormatRequest_III (IntPtr jnienv, IntPtr native__this, int p0, int p1, int p2)
{
global::Org.Webrtc.VideoCapturerAndroid __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.OnOutputFormatRequest (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_onOutputFormatRequest_III;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='onOutputFormatRequest' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='int'] and parameter[3][@type='int']]"
[Register ("onOutputFormatRequest", "(III)V", "GetOnOutputFormatRequest_IIIHandler")]
public virtual unsafe void OnOutputFormatRequest (int p0, int p1, int p2)
{
if (id_onOutputFormatRequest_III == IntPtr.Zero)
id_onOutputFormatRequest_III = JNIEnv.GetMethodID (class_ref, "onOutputFormatRequest", "(III)V");
try {
JValue* __args = stackalloc JValue [3];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onOutputFormatRequest_III, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onOutputFormatRequest", "(III)V"), __args);
} finally {
}
}
static Delegate cb_onPreviewFrame_arrayBLandroid_hardware_Camera_;
#pragma warning disable 0169
static Delegate GetOnPreviewFrame_arrayBLandroid_hardware_Camera_Handler ()
{
if (cb_onPreviewFrame_arrayBLandroid_hardware_Camera_ == null)
cb_onPreviewFrame_arrayBLandroid_hardware_Camera_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_OnPreviewFrame_arrayBLandroid_hardware_Camera_);
return cb_onPreviewFrame_arrayBLandroid_hardware_Camera_;
}
static void n_OnPreviewFrame_arrayBLandroid_hardware_Camera_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1)
{
global::Org.Webrtc.VideoCapturerAndroid __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
byte[] p0 = (byte[]) JNIEnv.GetArray (native_p0, JniHandleOwnership.DoNotTransfer, typeof (byte));
global::Android.Hardware.Camera p1 = global::Java.Lang.Object.GetObject<global::Android.Hardware.Camera> (native_p1, JniHandleOwnership.DoNotTransfer);
__this.OnPreviewFrame (p0, p1);
if (p0 != null)
JNIEnv.CopyArray (p0, native_p0);
}
#pragma warning restore 0169
static IntPtr id_onPreviewFrame_arrayBLandroid_hardware_Camera_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='onPreviewFrame' and count(parameter)=2 and parameter[1][@type='byte[]'] and parameter[2][@type='android.hardware.Camera']]"
[Register ("onPreviewFrame", "([BLandroid/hardware/Camera;)V", "GetOnPreviewFrame_arrayBLandroid_hardware_Camera_Handler")]
public virtual unsafe void OnPreviewFrame (byte[] p0, global::Android.Hardware.Camera p1)
{
if (id_onPreviewFrame_arrayBLandroid_hardware_Camera_ == IntPtr.Zero)
id_onPreviewFrame_arrayBLandroid_hardware_Camera_ = JNIEnv.GetMethodID (class_ref, "onPreviewFrame", "([BLandroid/hardware/Camera;)V");
IntPtr native_p0 = JNIEnv.NewArray (p0);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_onPreviewFrame_arrayBLandroid_hardware_Camera_, __args);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "onPreviewFrame", "([BLandroid/hardware/Camera;)V"), __args);
} finally {
if (p0 != null) {
JNIEnv.CopyArray (native_p0, p0);
JNIEnv.DeleteLocalRef (native_p0);
}
}
}
static Delegate cb_switchCamera_Ljava_lang_Runnable_;
#pragma warning disable 0169
static Delegate GetSwitchCamera_Ljava_lang_Runnable_Handler ()
{
if (cb_switchCamera_Ljava_lang_Runnable_ == null)
cb_switchCamera_Ljava_lang_Runnable_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_SwitchCamera_Ljava_lang_Runnable_);
return cb_switchCamera_Ljava_lang_Runnable_;
}
static bool n_SwitchCamera_Ljava_lang_Runnable_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Webrtc.VideoCapturerAndroid __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.VideoCapturerAndroid> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Java.Lang.IRunnable p0 = (global::Java.Lang.IRunnable)global::Java.Lang.Object.GetObject<global::Java.Lang.IRunnable> (native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.SwitchCamera (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_switchCamera_Ljava_lang_Runnable_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='VideoCapturerAndroid']/method[@name='switchCamera' and count(parameter)=1 and parameter[1][@type='java.lang.Runnable']]"
[Register ("switchCamera", "(Ljava/lang/Runnable;)Z", "GetSwitchCamera_Ljava_lang_Runnable_Handler")]
public virtual unsafe bool SwitchCamera (global::Java.Lang.IRunnable p0)
{
if (id_switchCamera_Ljava_lang_Runnable_ == IntPtr.Zero)
id_switchCamera_Ljava_lang_Runnable_ = JNIEnv.GetMethodID (class_ref, "switchCamera", "(Ljava/lang/Runnable;)Z");
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (p0);
bool __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallBooleanMethod (Handle, id_switchCamera_Ljava_lang_Runnable_, __args);
else
__ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "switchCamera", "(Ljava/lang/Runnable;)Z"), __args);
return __ret;
} finally {
}
}
}
}
| |
// Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
using AppBrix.Events.Async.Services;
using AppBrix.Events.Async.Tests.Mocks;
using AppBrix.Events.Contracts;
using AppBrix.Tests;
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Xunit;
namespace AppBrix.Events.Async.Tests;
public sealed class AsyncEventHubTests : TestsBase
{
#region Setup and cleanup
public AsyncEventHubTests() : base(TestUtils.CreateTestApp<AsyncEventsModule>()) => this.app.Start();
#endregion
#region Tests
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestEvent()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var called = 0;
hub.Subscribe<EventMock>(e =>
{
e.Should().BeSameAs(args, "the passed arguments should be the same as provided");
called++;
});
hub.Raise(args);
this.app.Stop();
called.Should().Be(1, "event handler should be called exactly once");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestEventChild()
{
var hub = this.GetAsyncEventHub();
var args = new EventMockChild(10);
var called = 0;
hub.Subscribe<EventMock>(e =>
{
e.Should().BeSameAs(args, "the passed arguments should be the same as provided");
called++;
});
hub.Raise(args);
this.app.Stop();
called.Should().Be(1, "event handler should be called exactly once");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestEventInterface()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var called = 0;
hub.Subscribe<IEvent>(e =>
{
e.Should().BeSameAs(args, "the passed arguments should be the same as provided");
called++;
});
hub.Raise(args);
this.app.Stop();
called.Should().Be(1, "event handler should be called exactly once");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestNoSubscription()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
hub.Raise(args);
this.app.Stop();
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestParentAndChildSubscription()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var called = 0;
Action<EventMock> handler = _ => called++;
hub.Subscribe(handler);
hub.Subscribe<EventMockChild>(handler);
hub.Raise(args);
this.app.Stop();
called.Should().Be(1, "event handler should be called exactly once");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestDoubleSubscription()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var called = 0;
Action<IEvent> handler = _ => called++;
hub.Subscribe(handler);
hub.Subscribe(handler);
hub.Raise(args);
this.app.Stop();
called.Should().Be(2, "event handler should be called exactly twice");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestDoubleRaise()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var called = 0;
Action<IEvent> handler = _ => called++;
hub.Subscribe(handler);
hub.Raise(args);
hub.Raise(args);
this.app.Stop();
called.Should().Be(2, "event handler should be called exactly twice after the second raise");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestUnsubscribe()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var called = 0;
Action<EventMock> handler = _ => called++;
hub.Subscribe(handler);
hub.Unsubscribe(handler);
hub.Raise(args);
this.app.Stop();
called.Should().Be(0, "event handler should not be called after the unsubscription");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestUninitialize()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var called = 0;
Action<EventMock> handler = _ => called++;
hub.Subscribe(handler);
hub.Raise(args);
this.app.Stop();
called.Should().Be(1, "event handler should be called exactly once after the first raise");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestNullArgumentSubscribe()
{
var hub = this.GetAsyncEventHub();
Action action = () => hub.Subscribe<IEvent>(null);
action.Should().Throw<ArgumentNullException>();
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestNullArgumentUnsubscribe()
{
var hub = this.GetAsyncEventHub();
Action action = () => hub.Unsubscribe<IEvent>(null);
action.Should().Throw<ArgumentNullException>();
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestNullArgumentRaise()
{
var hub = this.GetAsyncEventHub();
Action action = () => hub.Raise(null);
action.Should().Throw<ArgumentNullException>();
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestHandlerUnsubscribingItself()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var beforeHandlerCalled = 0;
var unsubscribingHandlerCalled = 0;
var afterHandlerCalled = 0;
hub.Subscribe<IEvent>(_ => beforeHandlerCalled++);
Action<IEvent> unsubscribingHandler = null;
unsubscribingHandler = _ => { unsubscribingHandlerCalled++; hub.Unsubscribe(unsubscribingHandler); };
hub.Subscribe(unsubscribingHandler);
hub.Subscribe<IEvent>(_ => afterHandlerCalled++);
hub.Raise(args);
hub.Raise(args);
this.app.Stop();
beforeHandlerCalled.Should().Be(2, "before event handler should be called exactly twice");
unsubscribingHandlerCalled.Should().Be(1, "unsubscribing event handler should not be called after the second raise since it has unsubscribed itself during the first");
afterHandlerCalled.Should().Be(2, "after event handler should be called exactly twice");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestHandlerThrowingException()
{
var hub = this.GetAsyncEventHub();
var args = new EventMock(10);
var beforeHandlerCalled = 0;
var throwingHandlerCalled = 0;
var afterHandlerCalled = 0;
hub.Subscribe<IEvent>(_ => beforeHandlerCalled++);
hub.Subscribe<IEvent>(_ =>
{
throwingHandlerCalled++;
throw new InvalidOperationException("Exception during handler");
});
hub.Subscribe<IEvent>(_ => afterHandlerCalled++);
hub.Raise(args);
hub.Raise(args);
this.app.Stop();
beforeHandlerCalled.Should().Be(2, "before event handler should be called exactly twice");
throwingHandlerCalled.Should().Be(2, "throwing event handler should be called exactly twice");
afterHandlerCalled.Should().Be(2, "after event handler should be called exactly twice");
}
[Fact, Trait(TestCategories.Category, TestCategories.Functional)]
public void TestThreadManagement()
{
var initialThreads = Process.GetCurrentProcess().Threads.Count;
var hub = this.GetAsyncEventHub();
Process.GetCurrentProcess().Threads.Count.Should().Be(initialThreads, "no threads should be created when getting the async event hub");
hub.Subscribe<IEvent>(_ => { });
Process.GetCurrentProcess().Threads.Count.Should().Be(initialThreads, "no thread should be created when subscribing to a new event");
hub.Subscribe<IEvent>(_ => { });
Process.GetCurrentProcess().Threads.Count.Should().Be(initialThreads, "no threads should be created when subscribing to an event with subscribers");
hub.Subscribe<EventMock>(_ => { });
Process.GetCurrentProcess().Threads.Count.Should().Be(initialThreads, "no thread should be created when subscribing to a second new event");
this.app.Stop();
Process.GetCurrentProcess().Threads.Count.Should().Be(initialThreads, "threads should be disposed of on uninitialization");
}
[Fact, Trait(TestCategories.Category, TestCategories.Performance)]
public void TestPerformanceEventsSubscribe() => TestUtils.TestPerformance(this.TestPerformanceEventsSubscribeInternal);
[Fact, Trait(TestCategories.Category, TestCategories.Performance)]
public void TestPerformanceEventsUnsubscribe() => TestUtils.TestPerformance(this.TestPerformanceEventsUnsubscribeInternal);
[Fact, Trait(TestCategories.Category, TestCategories.Performance)]
public void TestPerformanceEventsRaise() => TestUtils.TestPerformance(this.TestPerformanceEventsRaiseInternal);
#endregion
#region Private methods
private IAsyncEventHub GetAsyncEventHub() => this.app.GetAsyncEventHub();
private void TestPerformanceEventsSubscribeInternal()
{
var hub = this.GetAsyncEventHub();
var calledCount = 100000;
var handlers = new List<Action<EventMockChild>>(calledCount);
for (var i = 0; i < calledCount; i++)
{
var j = i;
handlers.Add(_ => j++);
}
for (var i = 0; i < handlers.Count; i++)
{
hub.Subscribe(handlers[i]);
}
this.app.Reinitialize();
}
private void TestPerformanceEventsUnsubscribeInternal()
{
var hub = this.GetAsyncEventHub();
var calledCount = 60000;
var handlers = new List<Action<EventMockChild>>(calledCount);
for (var i = 0; i < calledCount; i++)
{
var j = i;
handlers.Add(_ => j++);
}
for (var i = 0; i < handlers.Count; i++)
{
hub.Subscribe(handlers[i]);
}
for (var i = handlers.Count - 1; i >= 0; i--)
{
hub.Unsubscribe(handlers[i]);
}
this.app.Reinitialize();
}
private void TestPerformanceEventsRaiseInternal()
{
var hub = this.GetAsyncEventHub();
var args = new EventMockChild(10);
var childCalled = 0;
var interfaceCalled = 0;
hub.Subscribe<EventMockChild>(_ => childCalled++);
hub.Subscribe<IEvent>(_ => interfaceCalled++);
var calledCount = 15000;
for (var i = 0; i < calledCount; i++)
{
hub.Raise(args);
}
this.app.Stop();
childCalled.Should().Be(calledCount, "The child should be called exactly {0} times", calledCount);
interfaceCalled.Should().Be(calledCount, "The interface should be called exactly {0} times", calledCount);
this.app.Start();
}
#endregion
}
| |
using System;
using System.Linq;
using System.IO;
using System.Net;
using System.Net.FtpClient;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using BigDataPipeline.Interfaces;
namespace FileListenerPlugin
{
public class FTPTransfer : IFileTransfer
{
FtpClient client;
static string[] serviceSchemes = new[] { "ftp", "ftps", "fptes" };
/// <summary>
/// Gets the URI scheme names that this intance can handle.
/// </summary>
public IEnumerable<string> GetSchemeNames ()
{
return serviceSchemes;
}
public FileServiceConnectionInfo ParseConnectionUri (string connectionUri, IEnumerable<KeyValuePair<string, string>> extraOptions)
{
var info = new FileServiceConnectionInfo (connectionUri, extraOptions);
// parse host
if (info.Port <= 0)
{
if (info.Location == "ftp")
info.Port = 21;
else if (info.Location == "ftps")
info.Port = 990;
else if (info.Location == "ftpes")
info.Port = 21;
}
return info;
}
public FileServiceConnectionInfo Details { get; private set; }
public bool Status { get; private set; }
public string LastError { get; private set; }
private void _setStatus (Exception message)
{
string msg = null;
if (message != null && message.Message != null)
{
msg = message.Message;
if (message.InnerException != null && message.InnerException.Message != null)
msg += "; " + message.InnerException.Message;
}
_setStatus (false, msg);
}
private void _setStatus (bool status, string message = null)
{
Status = status;
LastError = message;
}
public bool Open (FileServiceConnectionInfo details)
{
Details = details;
if (Details.RetryCount <= 0)
Details.RetryCount = 1;
return Open ();
}
private bool Open ()
{
if (IsOpened ())
return true;
var lastMode = Details.Location;
// try to apply some fixes
if (Details.Port <= 0)
Details.Port = Details.Location == "ftps" ? 990 : 21;
// check for empty login/password
if (String.IsNullOrEmpty (Details.Login) && String.IsNullOrEmpty (Details.Password))
{
Details.Login = Details.Get ("ftpLogin", Details.Login);
Details.Password = Details.Get ("ftpPassword", Details.Password);
}
// Default, use the EPSV command for data channels. Other
// options are Passive (PASV), ExtenedActive (EPRT) and
// Active (PORT). EPSV should work for most people against
// a properly configured server and firewall.
var list = new List<Tuple<string, FtpDataConnectionType>> ()
{
Tuple.Create ("ftp", FtpDataConnectionType.AutoPassive),
Tuple.Create ("ftp", FtpDataConnectionType.AutoActive),
Tuple.Create ("ftps", FtpDataConnectionType.AutoPassive),
Tuple.Create ("ftps", FtpDataConnectionType.AutoActive),
Tuple.Create ("ftp", FtpDataConnectionType.AutoPassive),
Tuple.Create ("ftpes", FtpDataConnectionType.AutoActive)
};
list = list.OrderBy (i => i.Item1 == lastMode ? 1 : 2).ToList ();
int retries = Details.RetryCount < 2 ? 2 : Details.RetryCount;
for (var i = 0; i < retries; i++)
{
var mode = list[i];
try
{
client = new FtpClient ();
client.DataConnectionType = mode.Item2;
client.Host = Details.Host;
client.Port = Details.Port;
client.Credentials = new NetworkCredential (Details.Login, Details.Password);
client.ValidateCertificate += new FtpSslValidation (OnValidateCertificate);
client.SocketKeepAlive = true;
client.ReadTimeout = 40000;
client.EncryptionMode = mode.Item1 == "ftp" ? FtpEncryptionMode.None : mode.Item1 == "ftps" ? FtpEncryptionMode.Implicit : FtpEncryptionMode.Explicit;
client.Connect ();
// go to dir
if (!String.IsNullOrEmpty (Details.BasePath))
{
//CreateDirectory (Details.BasePath);
client.SetWorkingDirectory (Details.BasePath);
}
_setStatus (true);
}
catch (Exception ex)
{
_setStatus (ex);
Close ();
}
if (client != null)
break;
System.Threading.Thread.Sleep (Details.RetryWaitMs);
}
return IsOpened ();
}
static void OnValidateCertificate (FtpClient control, FtpSslValidationEventArgs e)
{
if (e.PolicyErrors != System.Net.Security.SslPolicyErrors.None)
{
// invalid cert, do you want to accept it?
e.Accept = true;
}
}
private void CreateDirectory (string folder)
{
if (String.IsNullOrEmpty (folder))
return;
folder = PreparePath (folder);
if (!client.DirectoryExists (folder.TrimEnd ('/') + '/'))
{
var folders = folder.Trim ('/').Split ('/');
var current = "/";
foreach (var f in folders)
{
current += f.TrimEnd ('/') + '/';
if (!client.DirectoryExists (current))
{
client.CreateDirectory (current);
}
}
}
}
private string PreparePath (string folder)
{
if (String.IsNullOrEmpty (folder))
folder = "/";
folder = folder.Replace ('\\', '/');
if (!folder.StartsWith ("/"))
folder = "/" + folder;
return folder;
}
public bool IsOpened ()
{
return client != null;
}
public void Dispose ()
{
Close ();
}
private void Close ()
{
if (client != null)
{
try
{
using (var ptr = client)
{
client = null;
ptr.ValidateCertificate -= new FtpSslValidation (OnValidateCertificate);
if (ptr.IsConnected)
ptr.Disconnect ();
}
}
catch (Exception ex)
{
_setStatus (ex);
}
}
client = null;
}
private IEnumerable<FtpListItem> _listFiles (string folder, System.Text.RegularExpressions.Regex pattern, bool recursive)
{
_setStatus (true);
if (!Open ())
yield break;
folder = PreparePath (folder);
foreach (var f in client.GetListing (folder))
if (f.Type == FtpFileSystemObjectType.Directory && recursive && f.FullName.StartsWith (folder) && !f.FullName.EndsWith ("."))
foreach (var n in _listFiles (f.FullName, pattern, recursive))
yield return n;
else if (f.Type == FtpFileSystemObjectType.File)
if (pattern == null || pattern.IsMatch (f.FullName))
yield return f;
}
public IEnumerable<FileTransferInfo> ListFiles ()
{
return ListFiles (Details.BasePath, Details.FullPath.TrimStart ('/'), !Details.SearchTopDirectoryOnly);
}
public IEnumerable<FileTransferInfo> ListFiles (string folder, bool recursive)
{
return ListFiles (folder, null, recursive);
}
public IEnumerable<FileTransferInfo> ListFiles (string folder, string fileMask, bool recursive)
{
var pattern = String.IsNullOrEmpty (fileMask) ? null : new System.Text.RegularExpressions.Regex (FileTransferHelpers.WildcardToRegex (fileMask), System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);
return _listFiles (folder, pattern, recursive).Select (i => new FileTransferInfo (i.FullName, i.Size, i.Created, i.Modified));
}
public StreamTransferInfo GetFileStream (string file)
{
_setStatus (true);
// download files
return new StreamTransferInfo
{
FileName = file,
FileStream = client.OpenRead (file)
};
}
public IEnumerable<StreamTransferInfo> GetFileStreams (string folder, string fileMask, bool recursive)
{
var pattern = String.IsNullOrEmpty (fileMask) ? null : new System.Text.RegularExpressions.Regex (FileTransferHelpers.WildcardToRegex (fileMask), System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);
// get files
List<FtpListItem> files = null;
for (int i = 0; i < Details.RetryCount; i++)
{
// try to open
if (!Open ())
continue;
try
{
// get all files to download, but limit to 2MM
files = _listFiles (folder, pattern, recursive).Take (2000000).ToList ();
_setStatus (true);
break;
}
catch (Exception ex)
{
_setStatus (ex);
// disconnect on error
Close ();
// delay in case of network error
System.Threading.Thread.Sleep (Details.RetryWaitMs);
}
}
// sanity check
if (files == null)
yield break;
_setStatus (true);
// download files
foreach (var f in files)
{
StreamTransferInfo file = null;
try
{
file = new StreamTransferInfo
{
FileName = f.FullName,
FileStream = client.OpenRead (f.FullName)
};
}
catch (Exception ex)
{
LastError = ex.Message;
// skip file
}
if (file != null)
yield return file;
}
}
public IEnumerable<StreamTransferInfo> GetFileStreams ()
{
if (Details.HasWildCardSearch)
return GetFileStreams (Details.BasePath, Details.FullPath.TrimStart ('/'), !Details.SearchTopDirectoryOnly);
else
return new StreamTransferInfo[] { GetFileStream (Details.FullPath) };
}
public FileTransferInfo GetFile (string file, string outputDirectory, bool deleteOnSuccess)
{
outputDirectory = outputDirectory.Replace ('\\', '/');
if (!outputDirectory.EndsWith ("/"))
outputDirectory += "/";
FileTransferHelpers.CreateDirectory (outputDirectory);
// download files
var f = GetFileStream (file);
string newFile = System.IO.Path.Combine (outputDirectory, System.IO.Path.GetFileName (f.FileName));
FileTransferHelpers.DeleteFile (newFile);
try
{
using (var output = new FileStream (newFile, FileMode.Create, FileAccess.Write, FileShare.Delete, FileServiceConnectionInfo.DefaultWriteBufferSize))
{
f.FileStream.CopyTo (output, FileServiceConnectionInfo.DefaultWriteBufferSize >> 2);
}
// check if we must remove file
if (deleteOnSuccess)
{
FileTransferHelpers.DeleteFile (f.FileName);
}
_setStatus (true);
}
catch (Exception ex)
{
_setStatus (ex);
FileTransferHelpers.DeleteFile (newFile);
newFile = null;
}
finally
{
f.FileStream.Close ();
}
// check if file was downloaded
if (newFile != null)
{
var info = new System.IO.FileInfo (newFile);
if (info.Exists)
return new FileTransferInfo (newFile, info.Length, info.CreationTime, info.LastWriteTime);
}
return null;
}
public string GetFileAsText (string file)
{
using (var reader = new StreamReader (GetFileStream (file).FileStream, FileTransferHelpers.TryGetEncoding (Details.Get ("encoding", "ISO-8859-1")), true))
return reader.ReadToEnd ();
}
public IEnumerable<FileTransferInfo> GetFiles (string folder, string fileMask, bool recursive, string outputDirectory, bool deleteOnSuccess)
{
outputDirectory = outputDirectory.Replace ('\\', '/');
if (!outputDirectory.EndsWith ("/"))
outputDirectory += "/";
FileTransferHelpers.CreateDirectory (outputDirectory);
// download files
foreach (var f in GetFileStreams (folder, fileMask, recursive))
{
string newFile = null;
// download file
try
{
newFile = System.IO.Path.Combine (outputDirectory, System.IO.Path.GetFileName (f.FileName));
FileTransferHelpers.DeleteFile (newFile);
using (var file = new FileStream (newFile, FileMode.Create, FileAccess.Write, FileShare.Delete, FileServiceConnectionInfo.DefaultWriteBufferSize))
{
f.FileStream.CopyTo (file, FileServiceConnectionInfo.DefaultWriteBufferSize >> 2);
}
f.FileStream.Close ();
f.FileStream = null;
// check if we must remove file
if (deleteOnSuccess && System.IO.File.Exists (newFile))
{
client.DeleteFile (f.FileName);
}
_setStatus (true);
break;
}
catch (Exception ex)
{
_setStatus (ex);
Close ();
FileTransferHelpers.DeleteFile (newFile);
newFile = null;
// delay in case of network error
System.Threading.Thread.Sleep (Details.RetryWaitMs);
// try to reopen
Open ();
}
finally
{
if (f.FileStream != null)
f.FileStream.Close ();
}
// check if file was downloaded
if (newFile != null)
{
var info = new System.IO.FileInfo (newFile);
if (info.Exists)
yield return new FileTransferInfo (newFile, info.Length, info.CreationTime, info.LastWriteTime);
}
}
}
public IEnumerable<FileTransferInfo> GetFiles (string outputDirectory, bool deleteOnSuccess)
{
if (Details.HasWildCardSearch)
return GetFiles (Details.BasePath, Details.SearchPattern, !Details.SearchTopDirectoryOnly, outputDirectory, deleteOnSuccess);
else
return new FileTransferInfo[] { GetFile (Details.FullPath, outputDirectory, deleteOnSuccess) };
}
public bool RemoveFiles (IEnumerable<string> files)
{
var enumerator = files.GetEnumerator ();
string file = null;
for (int i = 0; i < Details.RetryCount; i++)
{
// try to open
if (!Open ())
continue;
try
{
if (file == null)
{
enumerator.MoveNext ();
}
do
{
file = PreparePath (enumerator.Current);
client.DeleteFile (file);
}
while (enumerator.MoveNext ());
_setStatus (true);
break;
}
catch (Exception ex)
{
_setStatus (ex);
// disconnect on error
Close ();
// delay in case of network error
System.Threading.Thread.Sleep (Details.RetryWaitMs);
}
}
return Status;
}
public bool RemoveFile (string file)
{
_setStatus (false);
for (int i = 0; i < Details.RetryCount; i++)
{
// try to open
if (!Open ())
continue;
try
{
file = PreparePath (file);
client.DeleteFile (file);
_setStatus (true);
}
catch (Exception ex)
{
_setStatus (ex);
// disconnect on error
Close ();
// delay in case of network error
System.Threading.Thread.Sleep (Details.RetryWaitMs);
}
}
return Status;
}
public bool SendFile (string localFilename)
{
return SendFile (localFilename, System.IO.Path.Combine (Details.BasePath, System.IO.Path.GetFileName (localFilename)));
}
public bool SendFile (string localFilename, string destFilename)
{
using (var file = new FileStream (localFilename, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read, FileServiceConnectionInfo.DefaultReadBufferSize))
{
return SendFile (file, destFilename, false);
}
}
public bool SendFile (Stream localFile, string destFullPath, bool closeInputStream)
{
// try to upload file
for (int i = 0; i < Details.RetryCount; i++)
{
// try to open
if (!Open ())
return false;
try
{
// check folder existance
CreateDirectory (PreparePath (FileTransferHelpers.SplitByLastPathPart (destFullPath).Item1));
// upload
using (Stream ostream = client.OpenWrite (PreparePath (destFullPath)))
{
using (var file = localFile)
{
file.CopyTo (ostream, FileServiceConnectionInfo.DefaultWriteBufferSize >> 2);
}
}
_setStatus (true);
return true;
}
catch (Exception ex)
{
_setStatus (ex);
// disconnect on error
Close ();
}
finally
{
if (closeInputStream)
localFile.Close();
}
}
return false;
}
public bool MoveFile (string localFilename, string destFilename)
{
_setStatus (false, "Operation not supported");
return Status;
}
public Stream OpenWrite ()
{
return OpenWrite (Details.FullPath);
}
public Stream OpenWrite (string destFullPath)
{
// check folder existance
CreateDirectory (PreparePath (FileTransferHelpers.SplitByLastPathPart (destFullPath).Item1));
// upload
return client.OpenWrite (PreparePath (destFullPath));
}
}
}
| |
//#define TEST
//#define DEBUG
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ICSimulator
{
public class Network
{
// dimensions
public int X, Y;
// every node has a router and a processor; not every processor is an application proc
public Router[] routers;
public Node[] nodes;
public List<Link> links;
public Workload workload;
public Golden golden;
public NodeMapping mapping;
public CmpCache cache;
public RingRouter[] ringRouter;
public RingRouter[] connector;
// finish mode
public enum FinishMode { app, insn, synth, cycle, barrier };
FinishMode m_finish;
ulong m_finishCount;
public FinishMode finishMode { get { return m_finish; } }
public double _cycle_netutil; // HACK -- controllers can use this.
public ulong _cycle_insns; // HACK -- controllers can use this.
public Network(int dimX, int dimY)
{
X = dimX;
Y = dimY;
}
public void setup()
{
routers = new Router[Config.N * (1 + ((Config.RingRouter) ? Config.nrConnections : 0))];
nodes = new Node[Config.N];
links = new List<Link>();
cache = new CmpCache();
ringRouter = new RingRouter[Config.N * (1 + Config.nrConnections)];
/*if(Config.disjointRings)
{
bool ignoreCase = true;
if (String.Compare(Config.disjointConnection, "mesh", ignoreCase) == 0)
connector = new RingRouter[Config.N]; // Fix later
else if (String.Compare(Config.disjointConnection, "torus", ignoreCase) == 0)
connector = new RingRouter[Config.N];
else if (String.Compare(Config.disjointConnection, "ring", ignoreCase) == 0)
connector = new RingRouter[Config.N]; // Fix later
}*/
ParseFinish(Config.finish);
workload = new Workload(Config.traceFilenames);
mapping = new NodeMapping_AllCPU_SharedCache();
// create routers and nodes
for (int n = 0; n < Config.N; n++)
{
Coord c = new Coord(n);
nodes[n] = new Node(mapping, c);
if (!Config.RingRouter)
{
routers[n] = MakeRouter(c);
nodes[n].setRouter(routers[n]);
routers[n].setNode(nodes[n]);
}
}
/*if (Config.disjointRings)
for (int n = 0; n < 8; n++)
{
connectors[n] = MakeConnector(n);
}
*/
// create the Golden manager
golden = new Golden();
if (Config.RouterEvaluation)
return;
/*
* Ring width = node width of each ring
* Ring height = node height of each ring
* NrConnections = number of connections routers per node
*
*/
if (Config.RingRouter)
{
int nrPlaceholdersPerNetwork = Config.nrPlaceholders / 2;
int nrNodesPerRing = (Config.ringWidth * 2 + Config.ringHeight * 2 - 4);
int nrConnectPerRing = nrNodesPerRing * Config.nrConnections;
int nrItemInRing = nrConnectPerRing + nrNodesPerRing;
#if DEBUG
Console.WriteLine("NrNodesPerRing = {0}, NrConectPerRing = {1}, NrItemInRing = {2}", nrNodesPerRing, nrConnectPerRing, nrItemInRing);
#endif
int prevID = -1;
// TODO: Check edge conditions of for loops. Currently only using for 2x2 ring.
bool clockwise = false;
for (int y = 0; y < Config.network_nrY / Config.ringHeight; y++) {
for (int x = 0; x < Config.network_nrX / Config.ringWidth; x++) {
if (Config.alternateDir)
{
clockwise = !clockwise;
}
else
{
clockwise = true;
}
prevID = -1;
for (int z = 0; z < nrItemInRing; z++)
{
int ringID = RingCoord.getIDfromXYZ(x, y, z);
int nodeID = RingCoord.getIDfromRingID(ringID);
RingCoord rc = new RingCoord(ringID);
#if DEBUG
Console.WriteLine("ringID = {0}, nodeID = {1}, prevID = {2}", ringID, nodeID, prevID);
#endif
ringRouter[ringID] = makeNodeRouter(rc);
ringRouter[ringID].clockwise = clockwise;
routers[nodeID] = ringRouter[ringID];
nodes[nodeID].setRouter(ringRouter[ringID]);
ringRouter[ringID].setNode(nodes[nodeID]);
// Link them up if its not the first node in the loop
if (prevID != -1)
{
Link prev = new Link(Config.router.linkLatency - 1);
links.Add(prev);
#if DEBUG
Console.WriteLine("Connecting prev{0} & current{1} with link {2}", prevID, ringID, prev);
#endif
if (clockwise)
{
ringRouter[prevID].linkOut[Simulator.DIR_CW] = prev;
ringRouter[ringID].linkIn[Simulator.DIR_CCW] = prev;
}
else
{
ringRouter[prevID].linkIn[Simulator.DIR_CW] = prev;
ringRouter[ringID].linkOut[Simulator.DIR_CCW] = prev;
}
}
prevID = ringID;
// Connection routers
for (int i = 0; i < Config.nrConnections; i++)
{
z++;
int connectID = RingCoord.getIDfromXYZ(x, y, z);
int connect2ID = RingCoord.getIDfromRingID(connectID);
RingCoord connectRC = new RingCoord(connectID);
ringRouter[connectID] = makeConnection(connectRC);
ringRouter[connectID].clockwise = clockwise;
routers[connect2ID] = ringRouter[connectID];
Link prev_link = new Link(Config.router.linkLatency - 1);
links.Add(prev_link);
#if DEBUG
Console.WriteLine("Connecting prev{0} & connect{1} with link {2}", prevID, connectID, prev_link);
#endif
if (clockwise)
{
ringRouter[prevID].linkOut[Simulator.DIR_CW] = prev_link;
ringRouter[connectID].linkIn[Simulator.DIR_CCW] = prev_link;
}
else
{
ringRouter[prevID].linkIn[Simulator.DIR_CW] = prev_link;
ringRouter[connectID].linkOut[Simulator.DIR_CCW] = prev_link;
}
prevID = connectID;
}
}
// Finish ring
int startID = RingCoord.getIDfromXYZ(x, y, 0);
Link finish_link = new Link(Config.router.linkLatency - 1);
links.Add(finish_link);
#if DEBUG
Console.WriteLine("Finishing connecting prev{0} & start{1} with link {2}", prevID, startID, finish_link);
#endif
if (clockwise)
{
ringRouter[prevID].linkOut[Simulator.DIR_CW] = finish_link;
ringRouter[startID].linkIn[Simulator.DIR_CCW] = finish_link;
}
else
{
ringRouter[prevID].linkIn[Simulator.DIR_CW] = finish_link;
ringRouter[startID].linkOut[Simulator.DIR_CCW] = finish_link;
}
}
}
if (Config.nrConnections > 1)
throw new Exception("Check the rest of the code before you continue making more connections");
#if DEBUG
Console.WriteLine("Starting connections....");
#endif
int connectionDir, oppDir;
int oppX;
int oppY;
int oppZ;
int currentID, oppID;
for (int y = 0; y < Config.network_nrY / Config.ringHeight; y++) {
for (int x = 0; x < Config.network_nrX / Config.ringWidth; x++) {
for (int z = 0; z < nrItemInRing; z++) {
for (int i = 0; i < Config.nrConnections; i++) {
//TODO: reconfigure for more than a 4x4 network and/or more connections
z++;
connectionDir = -1;
oppDir = -1;
currentID = -1;
oppID = -1;
oppX = x;
oppY = y;
oppZ = z + 4;
if(oppZ > nrItemInRing)
oppZ -= nrItemInRing;
currentID = RingCoord.getIDfromXYZ(x, y, z);
#if DEBUG
Console.WriteLine("Current Coord ({0},{1},{2})", x, y, z);
#endif
int switchNum = (z - 1) / 2;
switch (switchNum)
{
case 0: connectionDir = Simulator.DIR_UP;
oppDir = Simulator.DIR_DOWN;
oppY = y - 1;
#if DEBUG
Console.WriteLine("0");
#endif
if (oppY < 0)
{
oppY = Config.network_nrY / Config.ringHeight - 1;
// ensure no duplication by handling a link at the lexicographically
// first router
if (oppX < x || (oppX == x && oppY < y)) continue;
if (!Config.torus)
{
//Lower the link latency because this router is not being used
oppID = RingCoord.getIDfromXYZ(oppX, oppY, oppZ);
int nextZ = ((z + 1) > nrItemInRing - 1) ? 0 : z+1;
int prevZ = ((z - 1) < 0) ? nrItemInRing - 1 : z-1;
int nextID = RingCoord.getIDfromXYZ(x, y, nextZ);
int previousID = RingCoord.getIDfromXYZ(x, y, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, currentID {4}, previousID {5}", oppX, oppY, oppZ, nextID, currentID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[currentID].linkIn[Simulator.DIR_CCW] = ringRouter[currentID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[currentID].linkIn[Simulator.DIR_CW] = ringRouter[currentID].linkOut[Simulator.DIR_CCW];
}
nextZ = ((oppZ + 1) > nrItemInRing - 1) ? 0 : oppZ+1;
prevZ = ((oppZ - 1) < 0) ? nrItemInRing - 1 : oppZ-1;
nextID = RingCoord.getIDfromXYZ(oppX, oppY, nextZ);
previousID = RingCoord.getIDfromXYZ(oppX, oppY, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, oppID {4}, previousID {5}", oppX, oppY, oppZ, nextID, oppID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[oppID].linkIn[Simulator.DIR_CCW] = ringRouter[oppID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[oppID].linkIn[Simulator.DIR_CW] = ringRouter[oppID].linkOut[Simulator.DIR_CCW];
}
ringRouter[currentID] = null;
ringRouter[oppID] = null;
continue;
}
}
break;
case 1: connectionDir = Simulator.DIR_RIGHT;
oppDir = Simulator.DIR_LEFT;
oppX = x + 1;
#if DEBUG
Console.WriteLine("1");
#endif
if (oppX >= Config.network_nrX / Config.ringWidth)
{
oppX = 0;
// ensure no duplication by handling a link at the lexicographically
// first router
if (oppX < x || (oppX == x && oppY < y)) continue;
if (!Config.torus)
{
//Lower the link latency because this router is not being used
oppID = RingCoord.getIDfromXYZ(oppX, oppY, oppZ);
int nextZ = ((z + 1) > nrItemInRing - 1) ? 0 : z+1;
int prevZ = ((z - 1) < 0) ? nrItemInRing - 1 : z-1;
int nextID = RingCoord.getIDfromXYZ(x, y, nextZ);
int previousID = RingCoord.getIDfromXYZ(x, y, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, currentID {4}, previousID {5}", oppX, oppY, oppZ, nextID, currentID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[currentID].linkIn[Simulator.DIR_CCW] = ringRouter[currentID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[currentID].linkIn[Simulator.DIR_CW] = ringRouter[currentID].linkOut[Simulator.DIR_CCW];
}
nextZ = ((oppZ + 1) > nrItemInRing - 1) ? 0 : oppZ+1;
prevZ = ((oppZ - 1) < 0) ? nrItemInRing - 1 : oppZ-1;
nextID = RingCoord.getIDfromXYZ(oppX, oppY, nextZ);
previousID = RingCoord.getIDfromXYZ(oppX, oppY, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, oppID {4}, previousID {5}", oppX, oppY, oppZ, nextID, oppID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[oppID].linkIn[Simulator.DIR_CCW] = ringRouter[oppID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[oppID].linkIn[Simulator.DIR_CW] = ringRouter[oppID].linkOut[Simulator.DIR_CCW];
}
ringRouter[currentID] = null;
ringRouter[oppID] = null;
continue;
}
}
break;
case 2: connectionDir = Simulator.DIR_DOWN;
oppDir = Simulator.DIR_UP;
oppY = y + 1;
#if DEBUG
Console.WriteLine("2");
#endif
if (oppY >= Config.network_nrY / Config.ringHeight)
{
oppY = 0;
// ensure no duplication by handling a link at the lexicographically
// first router
if (oppX < x || (oppX == x && oppY < y)) continue;
if (!Config.torus)
{
//Lower the link latency because this router is not being used
oppID = RingCoord.getIDfromXYZ(oppX, oppY, oppZ);
int nextZ = ((z + 1) > nrItemInRing - 1) ? 0 : z+1;
int prevZ = ((z - 1) < 0) ? nrItemInRing - 1 : z-1;
int nextID = RingCoord.getIDfromXYZ(x, y, nextZ);
int previousID = RingCoord.getIDfromXYZ(x, y, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, currentID {4}, previousID {5}", oppX, oppY, oppZ, nextID, currentID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[currentID].linkIn[Simulator.DIR_CCW] = ringRouter[currentID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[currentID].linkIn[Simulator.DIR_CW] = ringRouter[currentID].linkOut[Simulator.DIR_CCW];
}
nextZ = ((oppZ + 1) > nrItemInRing - 1) ? 0 : oppZ+1;
prevZ = ((oppZ - 1) < 0) ? nrItemInRing - 1 : oppZ-1;
nextID = RingCoord.getIDfromXYZ(oppX, oppY, nextZ);
previousID = RingCoord.getIDfromXYZ(oppX, oppY, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, oppID {4}, previousID {5}", oppX, oppY, oppZ, nextID, oppID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[oppID].linkIn[Simulator.DIR_CCW] = ringRouter[oppID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[oppID].linkIn[Simulator.DIR_CW] = ringRouter[oppID].linkOut[Simulator.DIR_CCW];
}
ringRouter[currentID] = null;
ringRouter[oppID] = null;
continue;
}
}
break;
case 3: connectionDir = Simulator.DIR_LEFT;
#if DEBUG
Console.WriteLine("3");
#endif
oppDir = Simulator.DIR_RIGHT;
oppX = x - 1;
if (oppX < 0)
{
oppX = Config.network_nrX / Config.ringWidth - 1;
// ensure no duplication by handling a link at the lexicographically
// first router
if (oppX < x || (oppX == x && oppY < y)) continue;
if (!Config.torus)
{
//Lower the link latency because this router is not being used
oppID = RingCoord.getIDfromXYZ(oppX, oppY, oppZ);
int nextZ = ((z + 1) > nrItemInRing - 1) ? 0 : z+1;
int prevZ = ((z - 1) < 0) ? nrItemInRing - 1 : z-1;
int nextID = RingCoord.getIDfromXYZ(x, y, nextZ);
int previousID = RingCoord.getIDfromXYZ(x, y, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, currentID {4}, previousID {5}", oppX, oppY, oppZ, nextID, currentID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[currentID].linkIn[Simulator.DIR_CCW] = ringRouter[currentID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[currentID].linkIn[Simulator.DIR_CW] = ringRouter[currentID].linkOut[Simulator.DIR_CCW];
}
nextZ = ((oppZ + 1) > nrItemInRing - 1) ? 0 : oppZ+1;
prevZ = ((oppZ - 1) < 0) ? nrItemInRing - 1 : oppZ-1;
nextID = RingCoord.getIDfromXYZ(oppX, oppY, nextZ);
previousID = RingCoord.getIDfromXYZ(oppX, oppY, prevZ);
#if DEBUG
Console.WriteLine("opp({0},{1},{2})\tnextID {3}, oppID {4}, previousID {5}", oppX, oppY, oppZ, nextID, oppID, previousID);
#endif
if (ringRouter[nextID].clockwise) {
ringRouter[nextID].linkIn[Simulator.DIR_CCW] = ringRouter[previousID].linkOut[Simulator.DIR_CW];
ringRouter[oppID].linkIn[Simulator.DIR_CCW] = ringRouter[oppID].linkOut[Simulator.DIR_CW];
}
else {
ringRouter[previousID].linkIn[Simulator.DIR_CW] = ringRouter[nextID].linkOut[Simulator.DIR_CCW];
ringRouter[oppID].linkIn[Simulator.DIR_CW] = ringRouter[oppID].linkOut[Simulator.DIR_CCW];
}
ringRouter[currentID] = null;
ringRouter[oppID] = null;
continue;
}
}
break;
default: throw new Exception("Ring too big for current system");
}
oppID = RingCoord.getIDfromXYZ(oppX, oppY, oppZ);
// ensure no duplication by handling a link at the lexicographically
// first router
if (oppX < x || (oppX == x && oppY < y)) continue;
#if DEBUG
Console.WriteLine("Creating normal link\topp({0},{1},{2})\toppID {3} dir {4} : oppdir {5}", oppX, oppY, oppZ, oppID, connectionDir, oppDir);
#endif
Link linkA = new Link(Config.router.linkLatency - 1);
Link linkB = new Link(Config.router.linkLatency - 1);
links.Add(linkA);
links.Add(linkB);
#if DEBUG
Console.WriteLine("-------------------------------------------current{0} opp{1}", currentID, oppID);
#endif
((Connector)ringRouter[currentID]).connectionDirection = connectionDir;
((Connector)ringRouter[oppID]).connectionDirection = oppDir;
ringRouter[currentID].linkOut[connectionDir] = linkA;
ringRouter[oppID].linkIn[oppDir] = linkA;
ringRouter[currentID].linkIn[connectionDir] = linkB;
ringRouter[oppID].linkOut[oppDir] = linkB;
if (nrPlaceholdersPerNetwork > 0) {
((Connector)ringRouter[currentID]).injectPlaceholder = 2;
nrPlaceholdersPerNetwork--;
}
}
}
}
}
#if DEBUG
//Verification
for (int y = 0; y < Config.network_nrY / Config.ringHeight; y++) {
for (int x = 0; x < Config.network_nrX / Config.ringWidth; x++) {
Console.WriteLine("");
for (int z = 0; z < nrItemInRing; z++) {
int tempID = RingCoord.getIDfromXYZ(x, y, z);
if (ringRouter[tempID] == null) continue;
if(z % 2 == 0) Console.WriteLine("Node with clockwise = {0}", ringRouter[tempID].clockwise);
if(z % 2 == 1) Console.WriteLine("Connector with direction {0}", ((Connector)ringRouter[tempID]).connectionDirection);
if (ringRouter[tempID].clockwise) {
for (int dir = 5; dir >= 0; dir--) {
if(ringRouter[tempID].linkIn[dir] != null)
Console.WriteLine("{0} | ID:{1}, \tLinkIn Direction {2}, \tLink: {3}\t|", ringRouter[tempID], tempID, dir, ringRouter[tempID].linkIn[dir]);
}
for (int dir = 0; dir < 6; dir++) {
if(ringRouter[tempID].linkOut[dir] != null)
Console.WriteLine("{0} | ID:{1}, \tLinkOut Direction {2}, \tLink: {3}\t|", ringRouter[tempID], tempID, dir, ringRouter[tempID].linkOut[dir]);
}
}
else {
for (int dir = 5; dir >= 0; dir--) {
if(ringRouter[tempID].linkOut[dir] != null)
Console.WriteLine("{0} | ID:{1}, \tLinkOut Direction {2}, \tLink: {3}\t|", ringRouter[tempID], tempID, dir, ringRouter[tempID].linkOut[dir]);
}
for (int dir = 0; dir < 6; dir++) {
if(ringRouter[tempID].linkIn[dir] != null)
Console.WriteLine("{0} | ID:{1}, \tLinkIn Direction {2}, \tLink: {3}\t|", ringRouter[tempID], tempID, dir, ringRouter[tempID].linkIn[dir]);
}
}
}
}
}
#endif
return;
}
/*
if (Config.DisjointRings)
{
if (Config.SeperateConnect)
{
if (Config.network_nrX != Config.network_nrY)
throw new Exception("Only works with square networks");
// Designed for ringSize of 2
// And square network
// TODO: work on different dimensions
int ringLength = Config.ringSize;
int netXLength = Config.network_nrX;
int netYLength = Config.network_nrY;
int numRings = (netYLength / ringLength) * (netXLength / ringLength);
int numRingNodes = (ringLength * ringLength);
int dirOut = 1;
int dirIn = 0;
int dirInject = 2;
int dirEject = 3;
Link A_B = new Link(Config.router.linkLatency - 1);
Link B_Z1A = new Link(Config.router.linkLatency - 1);
Link Z1A_C = new Link(Config.router.linkLatency - 1);
Link C_Z4B = new Link(Config.router.linkLatency - 1);
Link Z4B_D = new Link(Config.router.linkLatency - 1);
Link D_A = new Link(Config.router.linkLatency - 1);
Link E_F = new Link(Config.router.linkLatency - 1);
Link F_G = new Link(Config.router.linkLatency - 1);
Link G_Z2A = new Link(Config.router.linkLatency - 1);
Link Z2A_H = new Link(Config.router.linkLatency - 1);
Link H_Z1B = new Link(Config.router.linkLatency - 1);
Link Z1B_E = new Link(Config.router.linkLatency - 1);
Link M_Z2B = new Link(Config.router.linkLatency - 1);
Link Z2B_N = new Link(Config.router.linkLatency - 1);
Link N_O = new Link(Config.router.linkLatency - 1);
Link O_P = new Link(Config.router.linkLatency - 1);
Link P_Z3A = new Link(Config.router.linkLatency - 1);
Link Z3A_M = new Link(Config.router.linkLatency - 1);
Link I_Z4A = new Link(Config.router.linkLatency - 1);
Link Z4A_J = new Link(Config.router.linkLatency - 1);
Link J_Z3B = new Link(Config.router.linkLatency - 1);
Link Z3B_K = new Link(Config.router.linkLatency - 1);
Link K_L = new Link(Config.router.linkLatency - 1);
Link L_I = new Link(Config.router.linkLatency - 1);
Link A_B1 = new Link(Config.router.linkLatency - 1);
Link B_A1 = new Link(Config.router.linkLatency - 1);
Link A_B2 = new Link(Config.router.linkLatency - 1);
Link B_A2 = new Link(Config.router.linkLatency - 1);
Link A_B3 = new Link(Config.router.linkLatency - 1);
Link B_A3 = new Link(Config.router.linkLatency - 1);
Link A_B4 = new Link(Config.router.linkLatency - 1);
Link B_A4 = new Link(Config.router.linkLatency - 1);
links.Add(A_B);
links.Add(B_Z1A);
links.Add(Z1A_C);
links.Add(C_Z4B);
links.Add(Z4B_D);
links.Add(D_A);
links.Add(E_F);
links.Add(F_G);
links.Add(G_Z2A);
links.Add(Z2A_H);
links.Add(H_Z1B);
links.Add(Z1B_E);
links.Add(M_Z2B);
links.Add(Z2B_N);
links.Add(N_O);
links.Add(O_P);
links.Add(P_Z3A);
links.Add(Z3A_M);
links.Add(I_Z4A);
links.Add(Z4A_J);
links.Add(J_Z3B);
links.Add(Z3B_K);
links.Add(K_L);
links.Add(L_I);
links.Add(A_B1);
links.Add(B_A1);
links.Add(A_B2);
links.Add(B_A2);
links.Add(A_B3);
links.Add(B_A3);
links.Add(A_B4);
links.Add(B_A4);
int A = Coord.getIDfromXY(0, 0);
int B = Coord.getIDfromXY(1, 0);
int C = Coord.getIDfromXY(1, 1);
int D = Coord.getIDfromXY(0, 1);
int E = Coord.getIDfromXY(2, 0);
int F = Coord.getIDfromXY(3, 0);
int G = Coord.getIDfromXY(3, 1);
int H = Coord.getIDfromXY(2, 1);
int I = Coord.getIDfromXY(0, 2);
int J = Coord.getIDfromXY(1, 2);
int K = Coord.getIDfromXY(1, 3);
int L = Coord.getIDfromXY(0, 3);
int M = Coord.getIDfromXY(2, 2);
int N = Coord.getIDfromXY(3, 2);
int O = Coord.getIDfromXY(3, 3);
int P = Coord.getIDfromXY(2, 3);
int Z1A = 0;
int Z1B = 1;
int Z2A = 2;
int Z2B = 3;
int Z3A = 4;
int Z3B = 5;
int Z4A = 6;
int Z4B = 7;
routers[A].linkIn[dirIn] = D_A;
routers[A].linkOut[dirOut] = A_B;
routers[A].neigh[dirIn] = routers[D];
routers[A].neigh[dirOut] = routers[B];
routers[A].neighbors = 2;
routers[B].linkIn[dirIn] = A_B;
routers[B].linkOut[dirOut] = B_Z1A;
routers[B].neigh[dirIn] = routers[A];
routers[B].neigh[dirOut] = connectors[Z1A];
routers[B].neighbors = 2;
routers[C].linkIn[dirIn] = Z1A_C;
routers[C].linkOut[dirOut] = C_Z4B;
routers[C].neigh[dirIn] = connectors[Z1A];
routers[C].neigh[dirOut] = connectors[Z4B];
routers[C].neighbors = 2;
routers[D].linkIn[dirIn] = Z4B_D;
routers[D].linkOut[dirOut] = D_A;
routers[D].neigh[dirIn] = connectors[Z4B];
routers[D].neigh[dirOut] = routers[A];
routers[D].neighbors = 2;
if (Config.sameDir)
{
routers[E].linkIn[dirIn] = Z1B_E;
routers[E].linkOut[dirOut] = E_F;
routers[E].neigh[dirIn] = connectors[Z1B];
routers[E].neigh[dirOut] = routers[F];
routers[E].neighbors = 2;
routers[F].linkIn[dirIn] = E_F;
routers[F].linkOut[dirOut] = F_G;
routers[F].neigh[dirIn] = routers[E];
routers[F].neigh[dirOut] = routers[G];
routers[F].neighbors = 2;
routers[G].linkIn[dirIn] = F_G;
routers[G].linkOut[dirOut] = G_Z2A;
routers[G].neigh[dirIn] = routers[F];
routers[G].neigh[dirOut] = connectors[Z2A];
routers[G].neighbors = 2;
routers[H].linkIn[dirIn] = Z2A_H;
routers[H].linkOut[dirOut] = H_Z1B;
routers[H].neigh[dirIn] = connectors[Z2A];
routers[H].neigh[dirOut] = connectors[Z1B];
routers[H].neighbors = 2;
routers[I].linkIn[dirIn] = L_I;
routers[I].linkOut[dirOut] = I_Z4A;
routers[I].neigh[dirIn] = routers[L];
routers[I].neigh[dirOut] = connectors[Z4A];
routers[I].neighbors = 2;
routers[J].linkIn[dirIn] = Z4A_J;
routers[J].linkOut[dirOut] = J_Z3B;
routers[J].neigh[dirIn] = connectors[Z4A];
routers[J].neigh[dirOut] = connectors[Z3B];
routers[J].neighbors = 2;
routers[K].linkIn[dirIn] = Z3B_K;
routers[K].linkOut[dirOut] = K_L;
routers[K].neigh[dirIn] = connectors[Z3B];
routers[K].neigh[dirOut] = routers[L];
routers[K].neighbors = 2;
routers[L].linkIn[dirIn] = K_L;
routers[L].linkOut[dirOut] = L_I;
routers[L].neigh[dirIn] = routers[K];
routers[L].neigh[dirOut] = routers[I];
routers[L].neighbors = 2;
}
else
{
routers[E].linkIn[dirIn] = E_F;
routers[E].linkOut[dirOut] = Z1B_E;
routers[E].neigh[dirIn] = routers[F];
routers[E].neigh[dirOut] = connectors[Z1B];
routers[E].neighbors = 2;
routers[F].linkIn[dirIn] = F_G;
routers[F].linkOut[dirOut] = E_F;
routers[F].neigh[dirIn] = routers[G];
routers[F].neigh[dirOut] = routers[E];
routers[F].neighbors = 2;
routers[G].linkIn[dirIn] = G_Z2A;
routers[G].linkOut[dirOut] = F_G;
routers[G].neigh[dirIn] = connectors[Z2A];
routers[G].neigh[dirOut] = routers[F];
routers[G].neighbors = 2;
routers[H].linkIn[dirIn] = H_Z1B;
routers[H].linkOut[dirOut] = Z2A_H;
routers[H].neigh[dirIn] = connectors[Z1B];
routers[H].neigh[dirOut] = connectors[Z2A];
routers[H].neighbors = 2;
routers[I].linkIn[dirIn] = I_Z4A;
routers[I].linkOut[dirOut] = L_I;
routers[I].neigh[dirIn] = connectors[Z4A];
routers[I].neigh[dirOut] = routers[L];
routers[I].neighbors = 2;
routers[J].linkIn[dirIn] = J_Z3B;
routers[J].linkOut[dirOut] = Z4A_J;
routers[J].neigh[dirIn] = connectors[Z3B];
routers[J].neigh[dirOut] = connectors[Z4A];
routers[J].neighbors = 2;
routers[K].linkIn[dirIn] = K_L;
routers[K].linkOut[dirOut] = Z3B_K;
routers[K].neigh[dirIn] = routers[L];
routers[K].neigh[dirOut] = connectors[Z3B];
routers[K].neighbors = 2;
routers[L].linkIn[dirIn] = L_I;
routers[L].linkOut[dirOut] = K_L;
routers[L].neigh[dirIn] = routers[I];
routers[L].neigh[dirOut] = routers[K];
routers[L].neighbors = 2;
}
routers[M].linkIn[dirIn] = Z3A_M;
routers[M].linkOut[dirOut] = M_Z2B;
routers[M].neigh[dirIn] = connectors[Z3A];
routers[M].neigh[dirOut] = connectors[Z2B];
routers[M].neighbors = 2;
routers[N].linkIn[dirIn] = Z2B_N;
routers[N].linkOut[dirOut] = N_O;
routers[N].neigh[dirIn] = connectors[Z2B];
routers[N].neigh[dirOut] = routers[O];
routers[N].neighbors = 2;
routers[O].linkIn[dirIn] = N_O;
routers[O].linkOut[dirOut] = O_P;
routers[O].neigh[dirIn] = routers[N];
routers[O].neigh[dirOut] = routers[P];
routers[O].neighbors = 2;
routers[P].linkIn[dirIn] = O_P;
routers[P].linkOut[dirOut] = P_Z3A;
routers[P].neigh[dirIn] = routers[O];
routers[P].neigh[dirOut] = connectors[Z3A];
routers[P].neighbors = 2;
// Connectors
connectors[Z1A].linkIn[dirIn] = B_Z1A;
connectors[Z1A].linkOut[dirOut] = Z1A_C;
connectors[Z1A].neigh[dirIn] = routers[B];
connectors[Z1A].neigh[dirOut] = routers[C];
connectors[Z1A].neighbors += 2;
connectors[Z2B].linkIn[dirIn] = M_Z2B;
connectors[Z2B].linkOut[dirOut] = Z2B_N;
connectors[Z2B].neigh[dirIn] = routers[M];
connectors[Z2B].neigh[dirOut] = routers[N];
connectors[Z2B].neighbors += 2;
connectors[Z3A].linkIn[dirIn] = P_Z3A;
connectors[Z3A].linkOut[dirOut] = Z3A_M;
connectors[Z3A].neigh[dirIn] = routers[P];
connectors[Z3A].neigh[dirOut] = routers[M];
connectors[Z3A].neighbors += 2;
connectors[Z4B].linkIn[dirIn] = C_Z4B;
connectors[Z4B].linkOut[dirOut] = Z4B_D;
connectors[Z4B].neigh[dirIn] = routers[C];
connectors[Z4B].neigh[dirOut] = routers[D];
connectors[Z4B].neighbors += 2;
if (Config.sameDir)
{
connectors[Z1B].linkIn[dirIn] = H_Z1B;
connectors[Z1B].linkOut[dirOut] = Z1B_E;
connectors[Z1B].neigh[dirIn] = routers[H];
connectors[Z1B].neigh[dirOut] = routers[E];
connectors[Z1B].neighbors += 2;
connectors[Z2A].linkIn[dirIn] = G_Z2A;
connectors[Z2A].linkOut[dirOut] = Z2A_H;
connectors[Z2A].neigh[dirIn] = routers[G];
connectors[Z2A].neigh[dirOut] = routers[H];
connectors[Z2A].neighbors += 2;
connectors[Z4A].linkIn[dirIn] = I_Z4A;
connectors[Z4A].linkOut[dirOut] = Z4A_J;
connectors[Z4A].neigh[dirIn] = routers[I];
connectors[Z4A].neigh[dirOut] = routers[J];
connectors[Z4A].neighbors += 2;
connectors[Z3B].linkIn[dirIn] = J_Z3B;
connectors[Z3B].linkOut[dirOut] = Z3B_K;
connectors[Z3B].neigh[dirIn] = routers[J];
connectors[Z3B].neigh[dirOut] = routers[K];
connectors[Z3B].neighbors += 2;
}
else
{
connectors[Z1B].linkIn[dirIn] = Z1B_E;
connectors[Z1B].linkOut[dirOut] = H_Z1B;
connectors[Z1B].neigh[dirIn] = routers[E];
connectors[Z1B].neigh[dirOut] = routers[H];
connectors[Z1B].neighbors += 2;
connectors[Z2A].linkIn[dirIn] = Z2A_H;
connectors[Z2A].linkOut[dirOut] = G_Z2A;
connectors[Z2A].neigh[dirIn] = routers[H];
connectors[Z2A].neigh[dirOut] = routers[G];
connectors[Z2A].neighbors += 2;
connectors[Z4A].linkIn[dirIn] = Z4A_J;
connectors[Z4A].linkOut[dirOut] = I_Z4A;
connectors[Z4A].neigh[dirIn] = routers[J];
connectors[Z4A].neigh[dirOut] = routers[I];
connectors[Z4A].neighbors += 2;
connectors[Z3B].linkIn[dirIn] = Z3B_K;
connectors[Z3B].linkOut[dirOut] = J_Z3B;
connectors[Z3B].neigh[dirIn] = routers[K];
connectors[Z3B].neigh[dirOut] = routers[J];
connectors[Z3B].neighbors += 2;
}
connectors[Z1A].linkIn[dirInject] = B_A1;
connectors[Z1A].linkOut[dirEject] = A_B1;
connectors[Z1A].neigh[dirIn] = connectors[Z1B];
connectors[Z1A].neigh[dirOut] = connectors[Z1B];
connectors[Z1A].neighbors += 2;
connectors[Z1B].linkIn[dirInject] = A_B1;
connectors[Z1B].linkOut[dirEject] = B_A1;
connectors[Z1B].neigh[dirIn] = connectors[Z1A];
connectors[Z1B].neigh[dirOut] = connectors[Z1A];
connectors[Z1B].neighbors += 2;
connectors[Z2A].linkIn[dirInject] = B_A2;
connectors[Z2A].linkOut[dirEject] = A_B2;
connectors[Z2A].neigh[dirIn] = connectors[Z2B];
connectors[Z2A].neigh[dirOut] = connectors[Z2B];
connectors[Z2A].neighbors += 2;
connectors[Z2B].linkIn[dirInject] = A_B2;
connectors[Z2B].linkOut[dirEject] = B_A2;
connectors[Z2B].neigh[dirIn] = connectors[Z2A];
connectors[Z2B].neigh[dirOut] = connectors[Z2A];
connectors[Z2B].neighbors += 2;
connectors[Z3A].linkIn[dirInject] = B_A3;
connectors[Z3A].linkOut[dirEject] = A_B3;
connectors[Z3A].neigh[dirIn] = connectors[Z3B];
connectors[Z3A].neigh[dirOut] = connectors[Z3B];
connectors[Z3A].neighbors += 2;
connectors[Z3B].linkIn[dirInject] = A_B3;
connectors[Z3B].linkOut[dirEject] = B_A3;
connectors[Z3B].neigh[dirIn] = connectors[Z3A];
connectors[Z3B].neigh[dirOut] = connectors[Z3A];
connectors[Z3B].neighbors += 2;
connectors[Z4A].linkIn[dirInject] = B_A4;
connectors[Z4A].linkOut[dirEject] = A_B4;
connectors[Z4A].neigh[dirIn] = connectors[Z4B];
connectors[Z4A].neigh[dirOut] = connectors[Z4B];
connectors[Z4A].neighbors += 2;
connectors[Z4B].linkIn[dirInject] = A_B4;
connectors[Z4B].linkOut[dirEject] = B_A4;
connectors[Z4B].neigh[dirIn] = connectors[Z4A];
connectors[Z4B].neigh[dirOut] = connectors[Z4A];
connectors[Z4B].neighbors += 2;
return;
}
}
/*
if (Config.StreetRings)
{
// connect the network with Links
for (int n = 0; n < Config.N; n++)
{
int x, y;
Coord.getXYfromID(n, out x, out y);
// inter-router links
for (int dir = 0; dir < 2; dir++)
{
int oppDir = (dir + 2) % 4; // direction from neighbor's perspective
// determine neighbor's coordinates
int x_, y_;
switch (x % 2)
{
case 0:
switch (dir)
{
case 0: x_ = x; y_ = y + 1; break;
case 1: x_ = x; y_ = y - 1; break;
default: continue;
}
break;
case 1:
switch (dir)
{
case 0: x_ = x; y_ = y - 1; break;
case 1: x_ = x; y_ = y + 1; break;
default: continue;
}
break;
}
// ensure no duplication by handling a link at the lexicographically
// first router
if (x_ < x || (x_ == x && y_ < y)) continue;
// Link param is *extra* latency (over the standard 1 cycle)
Link dirA = new Link(Config.router.linkLatency - 1);
Link dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
// link 'em up
routers[Coord.getIDfromXY(x, y)].linkOut[dir] = dirA;
routers[Coord.getIDfromXY(x_, y_)].linkIn[oppDir] = dirA;
routers[Coord.getIDfromXY(x, y)].linkIn[dir] = dirB;
routers[Coord.getIDfromXY(x_, y_)].linkOut[oppDir] = dirB;
routers[Coord.getIDfromXY(x, y)].neighbors++;
routers[Coord.getIDfromXY(x_, y_)].neighbors++;
routers[Coord.getIDfromXY(x, y)].neigh[dir] = routers[Coord.getIDfromXY(x_, y_)];
routers[Coord.getIDfromXY(x_, y_)].neigh[oppDir] = routers[Coord.getIDfromXY(x, y)];
}
}
}
*/
// connect the network with Links
for (int n = 0; n < Config.N; n++)
{
int x, y;
Coord.getXYfromID(n, out x, out y);
int ID = n;
// inter-router links
for (int dir = 0; dir < 4; dir++)
{
int oppDir = (dir + 2) % 4; // direction from neighbor's perspective
// determine neighbor's coordinates
int x_, y_;
switch (dir)
{
case Simulator.DIR_UP: x_ = x; y_ = y + 1; break;
case Simulator.DIR_DOWN: x_ = x; y_ = y - 1; break;
case Simulator.DIR_RIGHT: x_ = x + 1; y_ = y; break;
case Simulator.DIR_LEFT: x_ = x - 1; y_ = y; break;
default: continue;
}
// If we are a torus, we manipulate x_ and y_
if(Config.torus)
{
if(x_ < 0)
x_ += X;
else if(x_ >= X)
x_ -= X;
if(y_ < 0)
y_ += Y;
else if(y_ >= Y)
y_ -= Y;
}
// mesh, not torus: detect edge
else if (x_ < 0 || x_ >= X || y_ < 0 || y_ >= Y)
{
if (Config.edge_loop)
{
Link edgeL = new Link(Config.router.linkLatency - 1);
links.Add(edgeL);
routers[ID].linkOut[dir] = edgeL;
routers[ID].linkIn[dir] = edgeL;
routers[ID].neighbors++;
routers[ID].neigh[dir] =
routers[ID];
}
continue;
}
// ensure no duplication by handling a link at the lexicographically
// first router
if (x_ < x || (x_ == x && y_ < y)) continue;
// Link param is *extra* latency (over the standard 1 cycle)
Link dirA = new Link(Config.router.linkLatency - 1);
Link dirB = new Link(Config.router.linkLatency - 1);
links.Add(dirA);
links.Add(dirB);
int oppID = Coord.getIDfromXY(x_, y_);
// link 'em up
routers[ID].linkOut[dir] = dirA;
routers[oppID].linkIn[oppDir] = dirA;
routers[ID].linkIn[dir] = dirB;
routers[oppID].linkOut[oppDir] = dirB;
routers[ID].neighbors++;
routers[oppID].neighbors++;
routers[ID].neigh[dir] = routers[oppID];
routers[oppID].neigh[oppDir] = routers[ID];
if (Config.router.algorithm == RouterAlgorithm.DR_SCARAB)
{
for (int wireNr = 0; wireNr < Config.nack_nr; wireNr++)
{
Link nackA = new Link(Config.nack_linkLatency - 1);
Link nackB = new Link(Config.nack_linkLatency - 1);
links.Add(nackA);
links.Add(nackB);
((Router_SCARAB)routers[Coord.getIDfromXY(x, y)]).nackOut[dir * Config.nack_nr + wireNr] = nackA;
((Router_SCARAB)routers[Coord.getIDfromXY(x_, y_)]).nackIn[oppDir * Config.nack_nr + wireNr] = nackA;
((Router_SCARAB)routers[Coord.getIDfromXY(x, y)]).nackIn[dir * Config.nack_nr + wireNr] = nackB;
((Router_SCARAB)routers[Coord.getIDfromXY(x_, y_)]).nackOut[oppDir * Config.nack_nr + wireNr] = nackB;
}
}
}
}
if (Config.torus)
for (int i = 0; i < Config.N; i++)
if (routers[i].neighbors < 4)
throw new Exception("torus construction not successful!");
}
public void doStep()
{
doStats();
// step the golden controller
golden.doStep();
// step the nodes
for (int n = 0; n < Config.N; n++)
nodes[n].doStep();
if (Config.RingRouter)
{
for(int n = 0; n < Config.N * (1 + Config.nrConnections); n++)
if(ringRouter[n] != null)
ringRouter[n].doStep();
}
else
{
// step the network sim: first, routers
for (int n = 0; n < Config.N; n++)
routers[n].doStep();
}
// now, step each link
foreach (Link l in links)
l.doStep();
}
void doStats()
{
int used_links = 0;
foreach (Link l in links)
if (l.Out != null)
used_links++;
this._cycle_netutil = (double)used_links / links.Count;
Simulator.stats.netutil.Add((double)used_links / links.Count);
this._cycle_insns = 0; // CPUs increment this each cycle -- we want a per-cycle sum
}
public bool isFinished()
{
switch (m_finish)
{
case FinishMode.app:
int count = 0;
for (int i = 0; i < Config.N; i++)
if (nodes[i].Finished) count++;
return count == Config.N;
case FinishMode.cycle:
return Simulator.CurrentRound >= m_finishCount;
case FinishMode.barrier:
return Simulator.CurrentBarrier >= (ulong)Config.barrier;
}
throw new Exception("unknown finish mode");
}
public bool isLivelocked()
{
for (int i = 0; i < Config.N; i++)
if (nodes[i].Livelocked) return true;
return false;
}
void ParseFinish(string finish)
{
// finish is "app", "insn <n>", "synth <n>", or "barrier <n>"
string[] parts = finish.Split(' ', '=');
if (parts[0] == "app")
m_finish = FinishMode.app;
else if (parts[0] == "cycle")
m_finish = FinishMode.cycle;
else if (parts[0] == "barrier")
m_finish = FinishMode.barrier;
else
throw new Exception("unknown finish mode");
if (m_finish == FinishMode.app || m_finish == FinishMode.barrier)
m_finishCount = 0;
else
m_finishCount = UInt64.Parse(parts[1]);
}
public void close()
{
for (int n = 0; n < Config.N; n++)
routers[n].close();
}
public void visitFlits(Flit.Visitor fv)
{
foreach (Link l in links)
l.visitFlits(fv);
foreach (Router r in routers)
r.visitFlits(fv);
foreach (Node n in nodes)
n.visitFlits(fv);
}
public delegate Flit FlitInjector();
public int injectFlits(int count, FlitInjector fi)
{
int i = 0;
for (; i < count; i++)
{
bool found = false;
foreach (Router r in routers)
if (r.canInjectFlit(null))
{
r.InjectFlit(fi());
found = true;
break;
}
if (!found)
return i;
}
return i;
}
public static RingRouter makeConnection(RingCoord rc)
{
switch (Config.router.connectionalgorithm)
{
case ConnectorAlgorithm.DIRECT_LINK:
return new Connector(rc, false);
//case ConnectorAlgorithm.RING_LINK:
// return new Connector_Ring(rc);
default: throw new Exception("Invalid connector");
}
}
public static RingRouter makeNodeRouter(RingCoord rc)
{
return new RingRouter_Simple(rc, true);
}
public static Router MakeRouter(Coord c)
{
switch (Config.router.algorithm)
{
case RouterAlgorithm.DR_AFC:
return new Router_AFC(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_CTLR:
return new Router_Flit_Ctlr(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_OLDEST_FIRST:
return new Router_Flit_OldestFirst(c);
case RouterAlgorithm.DR_SCARAB:
return new Router_SCARAB(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_GP:
return new Router_Flit_GP(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_CALF:
return new Router_SortNet_GP(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_CALF_OF:
return new Router_SortNet_OldestFirst(c);
case RouterAlgorithm.DR_FLIT_SWITCHED_RANDOM:
return new Router_Flit_Random(c);
case RouterAlgorithm.ROUTER_FLIT_EXHAUSTIVE:
return new Router_Flit_Exhaustive(c);
case RouterAlgorithm.OLDEST_FIRST_DO_ROUTER:
return new OldestFirstDORouter(c);
case RouterAlgorithm.ROUND_ROBIN_DO_ROUTER:
return new RoundRobinDORouter(c);
case RouterAlgorithm.STC_DO_ROUTER:
return new STC_DORouter(c);
case RouterAlgorithm.NEW_OF:
return new Router_New_OldestFirst(c);
case RouterAlgorithm.NEW_CF:
return new Router_New_ClosestFirst(c);
case RouterAlgorithm.NEW_GP:
return new Router_New_GP(c);
case RouterAlgorithm.ROR_RANDOM:
return new Router_RoR_Random(c);
case RouterAlgorithm.ROR_OLDEST_FIRST:
return new Router_RoR_OldestFirst(c);
case RouterAlgorithm.ROR_CLOSEST_FIRST:
return new Router_RoR_ClosestFirst(c);
case RouterAlgorithm.ROR_GP:
return new Router_RoR_GP(c);
//case RouterAlgorithm.RINGROUTER_SIMPLE:
// return new RingRouter_Simple(ingCoord.getRingIDfromID(c.ID));
default:
throw new Exception("invalid routing algorithm " + Config.router.algorithm);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Runtime.Versioning;
using Microsoft.VisualStudio.Shell;
using NuGet.Client.ProjectSystem;
using NuGet.PowerShell.Commands;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Resources;
using NuGetConsole.Host.PowerShell.Implementation;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Interop;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
#endif
namespace NuGet.Client.VisualStudio.PowerShell
{
/// <summary>
/// This command process the specified package against the specified project.
/// </summary>
public abstract class NuGetPowerShellBaseCommand : PSCmdlet, IExecutionContext, IErrorHandler
{
private VsSourceRepositoryManager _repoManager;
private IVsPackageSourceProvider _packageSourceProvider;
private IPackageRepositoryFactory _repositoryFactory;
private SVsServiceProvider _serviceProvider;
private IVsPackageManagerFactory _packageManagerFactory;
private ISolutionManager _solutionManager;
private VsPackageManagerContext _VsContext;
private readonly IHttpClientEvents _httpClientEvents;
internal const string PSCommandsUserAgentClient = "NuGet VS PowerShell Console";
internal const string PowerConsoleHostName = "Package Manager Host";
private readonly Lazy<string> _psCommandsUserAgent = new Lazy<string>(
() => HttpUtility.CreateUserAgentString(PSCommandsUserAgentClient, VsVersionHelper.FullVsEdition));
private ProgressRecordCollection _progressRecordCache;
private bool _overwriteAll, _ignoreAll;
public NuGetPowerShellBaseCommand(
IVsPackageSourceProvider packageSourceProvider,
IPackageRepositoryFactory packageRepositoryFactory,
SVsServiceProvider svcServceProvider,
IVsPackageManagerFactory packageManagerFactory,
ISolutionManager solutionManager,
IHttpClientEvents clientEvents)
{
_packageSourceProvider = packageSourceProvider;
_repositoryFactory = packageRepositoryFactory;
_serviceProvider = svcServceProvider;
_packageManagerFactory = packageManagerFactory;
_solutionManager = solutionManager;
_repoManager = new VsSourceRepositoryManager(_packageSourceProvider, _repositoryFactory);
_VsContext = new VsPackageManagerContext(_repoManager, _serviceProvider, _solutionManager, _packageManagerFactory);
_httpClientEvents = clientEvents;
}
internal VsSolution Solution
{
get
{
return _VsContext.GetCurrentVsSolution();
}
}
internal VsSourceRepositoryManager RepositoryManager
{
get
{
return _repoManager;
}
set
{
_repoManager = value;
}
}
internal IVsPackageManagerFactory PackageManagerFactory
{
get
{
return _packageManagerFactory;
}
set
{
_packageManagerFactory = value;
}
}
internal ISolutionManager SolutionManager
{
get
{
return _solutionManager;
}
}
internal bool IsSyncMode
{
get
{
if (Host == null || Host.PrivateData == null)
{
return false;
}
PSObject privateData = Host.PrivateData;
var syncModeProp = privateData.Properties["IsSyncMode"];
return syncModeProp != null && (bool)syncModeProp.Value;
}
}
protected virtual void LogCore(Client.MessageLevel level, string formattedMessage)
{
switch (level)
{
case MessageLevel.Debug:
WriteVerbose(formattedMessage);
break;
case Client.MessageLevel.Info:
WriteLine(formattedMessage);
break;
case Client.MessageLevel.Error:
WriteError(formattedMessage);
break;
}
}
internal void Execute()
{
switch (level)
{
case MessageLevel.Warning:
WriteWarning(formattedMessage);
break;
case Client.MessageLevel.Info:
WriteLine(formattedMessage);
break;
case Client.MessageLevel.Error:
WriteError(formattedMessage);
break;
}
BeginProcessing();
ProcessRecord();
EndProcessing();
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to display friendly message to the console.")]
protected sealed override void ProcessRecord()
{
try
{
ProcessRecordCore();
}
catch (Exception ex)
{
// unhandled exceptions should be terminating
ErrorHandler.HandleException(ex, terminating: true);
}
finally
{
UnsubscribeEvents();
}
}
/// <summary>
/// Derived classess must implement this method instead of ProcessRecord(), which is sealed by NuGetBaseCmdlet.
/// </summary>
protected abstract void ProcessRecordCore();
protected override void BeginProcessing()
{
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest += OnSendingRequest;
}
}
protected override void StopProcessing()
{
UnsubscribeEvents();
base.StopProcessing();
}
protected void UnsubscribeEvents()
{
if (_httpClientEvents != null)
{
_httpClientEvents.SendingRequest -= OnSendingRequest;
}
}
protected virtual void OnSendingRequest(object sender, WebRequestEventArgs e)
{
HttpUtility.SetUserAgent(e.Request, _psCommandsUserAgent.Value);
}
protected IErrorHandler ErrorHandler
{
get
{
return this;
}
}
#region Logging
public void Log(Client.MessageLevel level, string message, params object[] args)
{
string formattedMessage = String.Format(CultureInfo.CurrentCulture, message, args);
LogCore(level, formattedMessage);
}
public virtual FileConflictAction ResolveFileConflict(string message)
{
if (_overwriteAll)
{
return FileConflictAction.OverwriteAll;
}
if (_ignoreAll)
{
return FileConflictAction.IgnoreAll;
}
var choices = new Collection<ChoiceDescription>
{
new ChoiceDescription(Resources.Cmdlet_Yes, Resources.Cmdlet_FileConflictYesHelp),
new ChoiceDescription(Resources.Cmdlet_YesAll, Resources.Cmdlet_FileConflictYesAllHelp),
new ChoiceDescription(Resources.Cmdlet_No, Resources.Cmdlet_FileConflictNoHelp),
new ChoiceDescription(Resources.Cmdlet_NoAll, Resources.Cmdlet_FileConflictNoAllHelp)
};
int choice = Host.UI.PromptForChoice(VsResources.FileConflictTitle, message, choices, defaultChoice: 2);
Debug.Assert(choice >= 0 && choice < 4);
switch (choice)
{
case 0:
return FileConflictAction.Overwrite;
case 1:
_overwriteAll = true;
return FileConflictAction.OverwriteAll;
case 2:
return FileConflictAction.Ignore;
case 3:
_ignoreAll = true;
return FileConflictAction.IgnoreAll;
}
return FileConflictAction.Ignore;
}
void IErrorHandler.HandleError(ErrorRecord errorRecord, bool terminating)
{
if (terminating)
{
ThrowTerminatingError(errorRecord);
}
else
{
WriteError(errorRecord);
}
}
void IErrorHandler.HandleException(Exception exception, bool terminating,
string errorId, ErrorCategory category, object target)
{
exception = ExceptionUtility.Unwrap(exception);
var error = new ErrorRecord(exception, errorId, category, target);
ErrorHandler.HandleError(error, terminating: terminating);
}
protected void WriteLine(string message = null)
{
if (Host == null)
{
// Host is null when running unit tests. Simply return in this case
return;
}
if (message == null)
{
Host.UI.WriteLine();
}
else
{
Host.UI.WriteLine(message);
}
}
protected void WriteProgress(int activityId, string operation, int percentComplete)
{
if (IsSyncMode)
{
// don't bother to show progress if we are in synchronous mode
return;
}
ProgressRecord progressRecord;
// retrieve the ProgressRecord object for this particular activity id from the cache.
if (ProgressRecordCache.Contains(activityId))
{
progressRecord = ProgressRecordCache[activityId];
}
else
{
progressRecord = new ProgressRecord(activityId, operation, operation);
ProgressRecordCache.Add(progressRecord);
}
progressRecord.CurrentOperation = operation;
progressRecord.PercentComplete = percentComplete;
WriteProgress(progressRecord);
}
private void OnProgressAvailable(object sender, ProgressEventArgs e)
{
WriteProgress(ProgressActivityIds.DownloadPackageId, e.Operation, e.PercentComplete);
}
protected void SubscribeToProgressEvents()
{
if (!IsSyncMode && _httpClientEvents != null)
{
_httpClientEvents.ProgressAvailable += OnProgressAvailable;
}
}
protected void UnsubscribeFromProgressEvents()
{
if (_httpClientEvents != null)
{
_httpClientEvents.ProgressAvailable -= OnProgressAvailable;
}
}
[SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes", Justification = "This exception is passed to PowerShell. We really don't care about the type of exception here.")]
protected void WriteError(string message)
{
if (!String.IsNullOrEmpty(message))
{
WriteError(new Exception(message));
}
}
protected void WriteError(Exception exception)
{
ErrorHandler.HandleException(exception, terminating: false);
}
private ProgressRecordCollection ProgressRecordCache
{
get
{
if (_progressRecordCache == null)
{
_progressRecordCache = new ProgressRecordCollection();
}
return _progressRecordCache;
}
}
void IErrorHandler.WriteProjectNotFoundError(string projectName, bool terminating)
{
var notFoundException =
new ItemNotFoundException(
String.Format(
CultureInfo.CurrentCulture,
Resources.Cmdlet_ProjectNotFound, projectName));
ErrorHandler.HandleError(
new ErrorRecord(
notFoundException,
NuGetErrorId.ProjectNotFound, // This is your locale-agnostic error id.
ErrorCategory.ObjectNotFound,
projectName),
terminating: terminating);
}
void IErrorHandler.ThrowSolutionNotOpenTerminatingError()
{
ErrorHandler.HandleException(
new InvalidOperationException(Resources.Cmdlet_NoSolution),
terminating: true,
errorId: NuGetErrorId.NoActiveSolution,
category: ErrorCategory.InvalidOperation);
}
void IErrorHandler.ThrowNoCompatibleProjectsTerminatingError()
{
ErrorHandler.HandleException(
new InvalidOperationException(Resources.Cmdlet_NoCompatibleProjects),
terminating: true,
errorId: NuGetErrorId.NoCompatibleProjects,
category: ErrorCategory.InvalidOperation);
}
#endregion Logging
#region Project APIs
/// <summary>
/// Return all projects in the solution matching the provided names. Wildcards are supported.
/// This method will automatically generate error records for non-wildcarded project names that
/// are not found.
/// </summary>
/// <param name="projectNames">An array of project names that may or may not include wildcards.</param>
/// <returns>Projects matching the project name(s) provided.</returns>
protected IEnumerable<EnvDTE.Project> GetProjectsByName(string[] projectNames)
{
var allValidProjectNames = GetAllValidProjectNames().ToList();
foreach (string projectName in projectNames)
{
// if ctrl+c hit, leave immediately
if (Stopping)
{
break;
}
// Treat every name as a wildcard; results in simpler code
var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase);
var matches = from s in allValidProjectNames
where pattern.IsMatch(s)
select _solutionManager.GetProject(s);
int count = 0;
foreach (var project in matches)
{
count++;
yield return project;
}
// We only emit non-terminating error record if a non-wildcarded name was not found.
// This is consistent with built-in cmdlets that support wildcarded search.
// A search with a wildcard that returns nothing should not be considered an error.
if ((count == 0) && !WildcardPattern.ContainsWildcardCharacters(projectName))
{
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
}
}
}
/// <summary>
/// Return all projects in current solution.
/// </summary>
/// <returns></returns>
public IEnumerable<VsProject> GetAllProjectsInSolution()
{
IEnumerable<string> projectNames = GetAllValidProjectNames();
return GetProjectsByName(projectNames);
}
/// <summary>
/// Return all projects in the solution matching the provided names. Wildcards are supported.
/// This method will automatically generate error records for non-wildcarded project names that
/// are not found.
/// </summary>
/// <param name="projectNames">An array of project names that may or may not include wildcards.</param>
/// <returns>Projects matching the project name(s) provided.</returns>
protected IEnumerable<VsProject> GetProjectsByName(IEnumerable<string> projectNames)
{
var allValidProjectNames = GetAllValidProjectNames().ToList();
foreach (string projectName in projectNames)
{
// if ctrl+c hit, leave immediately
if (Stopping)
{
break;
}
// Treat every name as a wildcard; results in simpler code
var pattern = new WildcardPattern(projectName, WildcardOptions.IgnoreCase);
var matches = from s in allValidProjectNames
where pattern.IsMatch(s)
select _solutionManager.GetProject(s);
int count = 0;
foreach (var project in matches)
{
count++;
VsProject proj = Solution.GetProject(project);
yield return proj;
}
// We only emit non-terminating error record if a non-wildcarded name was not found.
// This is consistent with built-in cmdlets that support wildcarded search.
// A search with a wildcard that returns nothing should not be considered an error.
if ((count == 0) && !WildcardPattern.ContainsWildcardCharacters(projectName))
{
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
}
}
}
/// <summary>
/// Return all possibly valid project names in the current solution. This includes all
/// unique names and safe names.
/// </summary>
/// <returns></returns>
protected IEnumerable<string> GetAllValidProjectNames()
{
var safeNames = _solutionManager.GetProjects().Select(p => _solutionManager.GetProjectSafeName(p));
var uniqueNames = _solutionManager.GetProjects().Select(p => p.GetCustomUniqueName());
return uniqueNames.Concat(safeNames).Distinct();
}
/// <summary>
/// This method will set the default project of PowerShell Console by project name.
/// </summary>
/// <param name="projectNames">The project name to be set to.</param>
/// <returns>Boolean indicating success or failure.</returns>
protected bool SetProjectsByName(string projectName)
{
var host = PowerShellHostService.CreateHost(PowerConsoleHostName, false);
var allValidProjectNames = host.GetAvailableProjects().ToList();
string match = allValidProjectNames.Where(p => string.Equals(p, projectName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
int matchIndex;
if (string.IsNullOrEmpty(match))
{
ErrorHandler.WriteProjectNotFoundError(projectName, terminating: false);
return false;
}
else
{
try
{
matchIndex = allValidProjectNames.IndexOf(match);
host.SetDefaultProjectIndex(matchIndex);
_solutionManager.DefaultProjectName = match;
Log(Client.MessageLevel.Info, Resources.Cmdlet_ProjectSet, match);
return true;
}
catch (Exception ex)
{
WriteError(ex);
return false;
}
}
}
#endregion Project APIs
/// <summary>
/// Create a package repository from the source by trying to resolve relative paths.
/// </summary>
protected SourceRepository CreateRepositoryFromSource(string source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
UriFormatException uriException = null;
string url = _packageSourceProvider.ResolveSource(source);
try
{
PackageSource packageSource = new PackageSource(source, url);
var sourceRepo = new AutoDetectSourceRepository(packageSource, PSCommandsUserAgentClient, _repositoryFactory);
return sourceRepo;
}
catch (UriFormatException ex)
{
// if the source is relative path, it can result in invalid uri exception
uriException = ex;
}
return null;
}
public void ExecuteScript(string packageInstallPath, string scriptRelativePath, object packageObject, Installation.InstallationTarget target)
{
IPackage package = (IPackage)packageObject;
// If we don't have a project, we're at solution level
string projectName = target.Name;
FrameworkName targetFramework = target.GetSupportedFrameworks().FirstOrDefault();
VsProject targetProject = target as VsProject;
EnvDTE.Project project = targetProject == null ? null : targetProject.DteProject;
string fullPath = Path.Combine(packageInstallPath, scriptRelativePath);
if (!File.Exists(fullPath))
{
VsNuGetTraceSources.VsPowerShellScriptExecutionFeature.Error(
"missing_script",
"[{0}] Unable to locate expected script file: {1}",
projectName,
fullPath);
}
else
{
var psVariable = SessionState.PSVariable;
string toolsPath = Path.GetDirectoryName(fullPath);
// set temp variables to pass to the script
psVariable.Set("__rootPath", packageInstallPath);
psVariable.Set("__toolsPath", toolsPath);
psVariable.Set("__package", package);
psVariable.Set("__project", project);
string command = "& " + PathHelper.EscapePSPath(fullPath) + " $__rootPath $__toolsPath $__package $__project";
Log(MessageLevel.Info, String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath));
InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null);
// clear temp variables
psVariable.Remove("__rootPath");
psVariable.Remove("__toolsPath");
psVariable.Remove("__package");
psVariable.Remove("__project");
}
}
public void OpenFile(string fullPath)
{
var commonOperations = ServiceLocator.GetInstance<IVsCommonOperations>();
commonOperations.OpenFile(fullPath);
}
}
public class ProgressRecordCollection : KeyedCollection<int, ProgressRecord>
{
protected override int GetKeyForItem(ProgressRecord item)
{
return item.ActivityId;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Note: This implementation was written to match the Itanium ABI. For further details, please
// reference the Itanium ABI (http://mentorembedded.github.io/cxx-abi/abi-eh.html) and LLVM's
// libc++abi (http://libcxxabi.llvm.org/).
#define ARM_EABI
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Zelig.Runtime.TypeSystem;
public static class Unwind
{
/// <summary>
/// Status flags describing the unwind phase and options. Should match _Unwind_Action in ABI.
/// </summary>
[Flags]
public enum UnwindActions
{
SearchPhase = 0x01, // Mutually exclusive with CleanupPhase
CleanupPhase = 0x02, // Mutually exclusive with SearchPhase
HandlerFrame = 0x04,
ForceUnwind = 0x08,
EndOfStack = 0x16,
}
/// <summary>
/// Result of any given unwind operation; values should match _Unwind_Reason_Code.
/// </summary>
public enum UnwindReasonCode
{
NoReason = 0,
ForeignExceptionCaught,
Phase2Error,
Phase1Error,
NormalStop,
EndOfStack,
HandlerFound,
InstallContext,
ContinueUnwind,
Failure,
}
/// <summary>
/// DWARF encoding types for variable-length data.
/// </summary>
[Flags]
private enum DwarfEncoding : byte
{
// Encoding types:
Pointer = 0x00,
Uleb128 = 0x01,
Udata2 = 0x02,
Udata4 = 0x03,
Udata8 = 0x04,
Sleb128 = 0x09,
Sdata2 = 0x0a,
Sdata4 = 0x0b,
Sdata8 = 0x0c,
TypeMask = 0x0f,
// Encoding modifiers:
Absolute = 0x00,
PcRelative = 0x10,
TextRelative = 0x20,
DataRelative = 0x30,
FunctionRelative = 0x40,
Aligned = 0x50,
ModifierMask = 0x70,
// Special values:
Indirect = 0x80,
Omit = 0xff,
}
internal const ulong ExceptionClass = 0x000023435446534d; // "MSFTC#\0\0"
[ExportedMethod]
static public unsafe UnwindReasonCode LLOS_Unwind_Personality(
UnwindActions actions,
UInt64 exceptionClass,
UIntPtr exceptionObject,
UIntPtr context)
{
// TODO: Should we execute cleanup pads?
if (exceptionClass != ExceptionClass)
{
// We have been notified of a foreign exception being thrown, and we therefore need to
// execute cleanup landing pads.
return UnwindReasonCode.ContinueUnwind;
}
byte* lsda = (byte*)LLOS_Unwind_GetLanguageSpecificData(context);
if (lsda == null)
{
return UnwindReasonCode.ContinueUnwind;
}
// Get the current instruction pointer and offset it before next instruction in the current
// frame which threw the exception.
ulong pc = (ulong)LLOS_Unwind_GetIP(context) - 1;
// Get beginning current frame's code (as defined by the emitted dwarf code)
ulong funcStart = (ulong)LLOS_Unwind_GetRegionStart(context);
ulong pcOffset = pc - funcStart;
// Get the landing pad's base address; defaults to the start of the function.
DwarfEncoding landingPadBaseEncoding = (DwarfEncoding)(*lsda);
++lsda;
if (landingPadBaseEncoding != DwarfEncoding.Omit)
{
funcStart = ReadEncodedPointer(ref lsda, landingPadBaseEncoding);
}
DwarfEncoding typeEncoding = (DwarfEncoding)(*lsda);
++lsda;
// Get the type info list; this is an array of pointers to type info, in our case VTable*.
// It points to the end of the table and expects a one-based index.
UIntPtr classInfo = UIntPtr.Zero;
if (typeEncoding != DwarfEncoding.Omit)
{
ulong classInfoOffset = ReadULEB128(ref lsda);
classInfo = (UIntPtr)(lsda + classInfoOffset);
}
DwarfEncoding callSiteEncoding = (DwarfEncoding)(*lsda);
++lsda;
uint callSiteTableLength = (uint)ReadULEB128(ref lsda);
byte* callSiteTableStart = lsda;
byte* callSiteTableEnd = callSiteTableStart + callSiteTableLength;
byte* actionTableStart = callSiteTableEnd;
byte* callSitePtr = callSiteTableStart;
UIntPtr landingPad = UIntPtr.Zero;
ulong actionEntry = 0;
// Walk the call sites to find which region the PC falls in.
while (callSitePtr < callSiteTableEnd)
{
// These values are offsets from the function start.
ulong start = ReadEncodedPointer(ref callSitePtr, callSiteEncoding);
ulong length = ReadEncodedPointer(ref callSitePtr, callSiteEncoding);
ulong pad = ReadEncodedPointer(ref callSitePtr, callSiteEncoding);
// One-based currentByte offset into the action table.
actionEntry = ReadULEB128(ref callSitePtr);
if ((start <= pcOffset) && (pcOffset < (start + length)))
{
// Landing pad may be zero to indicate this region has no handlers.
landingPad = (UIntPtr)pad;
break;
}
}
if (landingPad == UIntPtr.Zero)
{
// No landing pad for this frame.
return UnwindReasonCode.ContinueUnwind;
}
landingPad = AddressMath.Increment(landingPad, (uint)funcStart);
// Action entry of zero means this is a cleanup pad.
if (actionEntry == 0)
{
if (((actions & UnwindActions.CleanupPhase) != 0) &&
((actions & UnwindActions.HandlerFrame) == 0))
{
return UnwindReasonCode.HandlerFound;
}
return UnwindReasonCode.ContinueUnwind;
}
object thrownException = LLOS_GetExceptionObject(exceptionObject);
byte* action = actionTableStart + actionEntry - 1;
for (int i = 0; true; ++i)
{
ulong typeIndex = ReadSLEB128(ref action);
if (typeIndex > 0)
{
// This is a catch clause. Get the associated vtable and see if it matches the thrown exception.
bool foundMatch = false;
VTable entryVTable = GetEntryVTable(typeIndex, typeEncoding, classInfo);
if (entryVTable == null)
{
// Null clause means we should match anything.
foundMatch = true;
}
else if (TypeSystemManager.CastToTypeNoThrow(thrownException, entryVTable) != null)
{
// Thrown exception is a subclass of the clause's vtable.
foundMatch = true;
}
if (foundMatch)
{
if ((actions & UnwindActions.SearchPhase) != 0)
{
return UnwindReasonCode.HandlerFound;
}
if ((actions & UnwindActions.HandlerFrame) != 0)
{
LLOS_Unwind_SetRegisters(context, landingPad, exceptionObject, (UIntPtr)(i + 1));
return UnwindReasonCode.InstallContext;
}
// If this isn't a search or a handler phase, then it must be a force unwind.
if ((actions & UnwindActions.ForceUnwind) == 0)
{
LLOS_Terminate();
}
}
}
else if (typeIndex == 0)
{
// This is a cleanup pad. If this is the cleanup phase, handle it. We intentionally
// pass an invalid (zero) selector so the landing pad doesn't execute any catch handlers.
if (((actions & UnwindActions.CleanupPhase) != 0) &&
((actions & UnwindActions.HandlerFrame) == 0))
{
LLOS_Unwind_SetRegisters(context, landingPad, exceptionObject, UIntPtr.Zero);
return UnwindReasonCode.InstallContext;
}
}
else
{
// This is a filter clause; ignore it.
}
// Move to the next handler. If there isn't one, we didn't find an appropriate clause.
byte* tempAction = action;
ulong actionOffset = ReadSLEB128(ref tempAction);
if (actionOffset == 0)
{
return UnwindReasonCode.ContinueUnwind;
}
action += actionOffset;
}
}
private static unsafe VTable GetEntryVTable(
ulong typeIndex,
DwarfEncoding typeEncoding,
UIntPtr classInfo)
{
UIntPtr typePointer = AddressMath.Decrement(classInfo, (uint)typeIndex * GetEncodingSize(typeEncoding));
#if ARM_EABI
UIntPtr offset = *(UIntPtr*)typePointer;
if (offset == UIntPtr.Zero)
{
return null;
}
UIntPtr vtablePointer = AddressMath.Increment(typePointer, offset.ToUInt32());
#else // ARM_EABI
byte* tempTypePointer = (byte*)typePointer.ToPointer();
UIntPtr vtablePointer = (UIntPtr)ReadEncodedPointer(ref tempTypePointer, typeEncoding);
#endif // ARM_EABI
// Note: We need to adjust the VTable pointer past the object header due to the LLVM bug cited
// in Translate_LandingPadOperator. When this issue is resolved we can remove the adjustment.
return (VTable)(object)ObjectHeader.CastAsObjectHeader(vtablePointer).Pack();
}
// Decode an unsigned leb128 value and advance the data pointer.
// See (7.6) Variable Length Data in: http://dwarfstd.org/doc/DWARF4.pdf
private static unsafe ulong ReadULEB128(ref byte* data)
{
ulong result = 0;
int shift = 0;
byte currentByte;
do
{
currentByte = *(data++);
result |= ((ulong)(currentByte & 0x7f)) << shift;
shift += 7;
} while ((currentByte & 0x80) != 0);
return result;
}
// Decode a signed leb128 value and advance the data pointer.
// See (7.6) Variable Length Data in: http://dwarfstd.org/doc/DWARF4.pdf
private static unsafe ulong ReadSLEB128(ref byte* data)
{
ulong result = 0;
int shift = 0;
byte currentByte;
do
{
currentByte = *(data++);
result |= ((ulong)(currentByte & 0x7f)) << shift;
shift += 7;
} while ((currentByte & 0x80) != 0);
// If the high bit is set on the last (highest order) byte, sign-extend the entire value.
if (((currentByte & 0x40) != 0) && (shift < (sizeof(ulong) * 8)))
{
result |= (ulong.MaxValue << shift);
}
return result;
}
// Decode a pointer value and advance the data pointer.
private static unsafe ulong ReadEncodedPointer(ref byte* data, DwarfEncoding encoding)
{
if (encoding == DwarfEncoding.Omit)
{
return 0;
}
ulong result = 0;
switch (encoding & DwarfEncoding.TypeMask)
{
case DwarfEncoding.Pointer:
result = (*(UIntPtr*)data).ToUInt64();
data += sizeof(UIntPtr);
break;
case DwarfEncoding.Udata2:
case DwarfEncoding.Sdata2:
result = *(UInt16*)data;
data += sizeof(UInt16);
break;
case DwarfEncoding.Udata4:
case DwarfEncoding.Sdata4:
result = *(UInt32*)data;
data += sizeof(UInt32);
break;
case DwarfEncoding.Udata8:
case DwarfEncoding.Sdata8:
result = *(UInt64*)data;
data += sizeof(UInt64);
break;
case DwarfEncoding.Uleb128:
result = ReadULEB128(ref data);
break;
case DwarfEncoding.Sleb128:
result = ReadSLEB128(ref data);
break;
default:
LLOS_Terminate();
break;
}
// Adjust the value.
switch (encoding & DwarfEncoding.ModifierMask)
{
case DwarfEncoding.Absolute:
break;
case DwarfEncoding.PcRelative:
if (result != 0)
{
result += (ulong)data;
}
break;
default:
LLOS_Terminate();
break;
}
// Indirect the value if necessary.
if ((encoding & DwarfEncoding.Indirect) != 0)
{
result = *(ulong*)result;
}
return result;
}
private static uint GetEncodingSize(DwarfEncoding encoding)
{
if (encoding == DwarfEncoding.Omit)
{
return 0;
}
switch (encoding & DwarfEncoding.TypeMask)
{
case DwarfEncoding.Pointer:
return (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(UIntPtr));
case DwarfEncoding.Udata2:
case DwarfEncoding.Sdata2:
return 2;
case DwarfEncoding.Udata4:
case DwarfEncoding.Sdata4:
return 4;
case DwarfEncoding.Udata8:
case DwarfEncoding.Sdata8:
return 8;
default:
LLOS_Terminate();
return 0;
}
}
[DllImport("C")]
internal static extern UIntPtr LLOS_AllocateException(object exception, UInt64 exceptionClass);
[DllImport("C")]
internal static extern object LLOS_GetExceptionObject(UIntPtr exception);
[DllImport("C")]
internal static extern UIntPtr LLOS_Unwind_GetIP(UIntPtr context);
[DllImport("C")]
internal static extern UIntPtr LLOS_Unwind_GetLanguageSpecificData(UIntPtr context);
[DllImport("C")]
internal static extern UIntPtr LLOS_Unwind_GetRegionStart(UIntPtr context);
[DllImport("C")]
internal static extern void LLOS_Unwind_SetRegisters(
UIntPtr context,
UIntPtr landingPad,
UIntPtr exceptionObject,
UIntPtr selector);
[NoReturn]
[DllImport("C")]
internal static extern void LLOS_Unwind_RaiseException(UIntPtr exceptionObject);
[NoReturn]
[DllImport("C")]
internal static extern void LLOS_Terminate();
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Collections;
using Cassandra.Serialization;
using Cassandra.Tasks;
namespace Cassandra
{
/// <summary>
/// Represents a pool of connections to a host
/// </summary>
internal class HostConnectionPool : IDisposable
{
private const int ConnectionIndexOverflow = int.MaxValue - 100000;
private readonly static Logger Logger = new Logger(typeof(HostConnectionPool));
private readonly static Connection[] EmptyConnectionsArray = new Connection[0];
//Safe iteration of connections
private readonly CopyOnWriteList<Connection> _connections = new CopyOnWriteList<Connection>();
private readonly Host _host;
private readonly HostDistance _distance;
private readonly Configuration _config;
private readonly Serializer _serializer;
private readonly HashedWheelTimer _timer;
private int _connectionIndex;
private HashedWheelTimer.ITimeout _timeout;
private volatile bool _isShuttingDown;
private int _isIncreasingSize;
private TaskCompletionSource<Connection[]> _creationTcs;
private volatile bool _isDisposed;
/// <summary>
/// Gets a list of connections already opened to the host
/// </summary>
public IEnumerable<Connection> OpenConnections
{
get { return _connections; }
}
public HostConnectionPool(Host host, HostDistance distance, Configuration config, Serializer serializer)
{
_host = host;
_host.CheckedAsDown += OnHostCheckedAsDown;
_host.Down += OnHostDown;
_host.Up += OnHostUp;
_host.Remove += OnHostRemoved;
_distance = distance;
_config = config;
_serializer = serializer;
_timer = config.Timer;
}
/// <summary>
/// Gets an open connection from the host pool (creating if necessary).
/// It returns null if the load balancing policy didn't allow connections to this host.
/// </summary>
public Task<Connection> BorrowConnection()
{
return MaybeCreateFirstConnection().ContinueSync(poolConnections =>
{
if (poolConnections.Length == 0)
{
//The load balancing policy stated no connections for this host
return null;
}
var connection = MinInFlight(poolConnections, ref _connectionIndex);
MaybeIncreasePoolSize(connection.InFlight);
return connection;
});
}
/// <summary>
/// Gets the connection with the minimum number of InFlight requests.
/// Only checks for index + 1 and index, to avoid a loop of all connections.
/// </summary>
public static Connection MinInFlight(Connection[] connections, ref int connectionIndex)
{
if (connections.Length == 1)
{
return connections[0];
}
//It is very likely that the amount of InFlight requests per connection is the same
//Do round robin between connections, skipping connections that have more in flight requests
var index = Interlocked.Increment(ref connectionIndex);
if (index > ConnectionIndexOverflow)
{
//Overflow protection, not exactly thread-safe but we can live with it
Interlocked.Exchange(ref connectionIndex, 0);
}
var currentConnection = connections[index % connections.Length];
var previousConnection = connections[(index - 1)%connections.Length];
if (previousConnection.InFlight < currentConnection.InFlight)
{
return previousConnection;
}
return currentConnection;
}
/// <exception cref="System.Net.Sockets.SocketException">Throws a SocketException when the connection could not be established with the host</exception>
/// <exception cref="AuthenticationException" />
/// <exception cref="UnsupportedProtocolVersionException"></exception>
internal virtual Task<Connection> CreateConnection()
{
Logger.Info("Creating a new connection to the host " + _host.Address);
var c = new Connection(_serializer, _host.Address, _config);
return c.Open().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_config.GetPoolingOptions(_serializer.ProtocolVersion).GetHeartBeatInterval() > 0)
{
//Heartbeat is enabled, subscribe for possible exceptions
c.OnIdleRequestException += OnIdleRequestException;
}
return c;
}
Logger.Info("The connection to {0} could not be opened", _host.Address);
c.Dispose();
if (t.Exception != null)
{
t.Exception.Handle(_ => true);
Logger.Error(t.Exception.InnerException);
throw t.Exception.InnerException;
}
throw new TaskCanceledException("The connection creation task was cancelled");
}, TaskContinuationOptions.ExecuteSynchronously);
}
/// <summary>
/// Handler that gets invoked when if there is a socket exception when making a heartbeat/idle request
/// </summary>
private void OnIdleRequestException(Exception ex)
{
_host.SetDown();
}
internal void OnHostCheckedAsDown(Host h, long delay)
{
if (!_host.SetAttemptingReconnection())
{
//Another pool is attempting reconnection
//Eventually Host.Up event is going to be fired.
return;
}
//Schedule next reconnection attempt (without using the timer thread)
//Cancel the previous one
var nextTimeout = _timer.NewTimeout(_ => Task.Factory.StartNew(AttemptReconnection), null, delay);
SetReconnectionTimeout(nextTimeout);
}
/// <summary>
/// Handles the reconnection attempts.
/// If it succeeds, it marks the host as UP.
/// If not, it marks the host as DOWN
/// </summary>
internal void AttemptReconnection()
{
_isShuttingDown = false;
if (_isDisposed)
{
return;
}
var tcs = new TaskCompletionSource<Connection[]>();
//While there is a single thread here, there might be another thread
//Calling MaybeCreateFirstConnection()
//Guard for multiple creations
var creationTcs = Interlocked.CompareExchange(ref _creationTcs, tcs, null);
if (creationTcs != null || _connections.Count > 0)
{
//Already creating as host is back UP (possibly via events)
return;
}
Logger.Info("Attempting reconnection to host {0}", _host.Address);
//There is a single thread creating a connection
CreateConnection().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_isShuttingDown)
{
t.Result.Dispose();
TransitionCreationTask(tcs, EmptyConnectionsArray);
return;
}
_connections.Add(t.Result);
Logger.Info("Reconnection attempt to host {0} succeeded", _host.Address);
_host.BringUpIfDown();
TransitionCreationTask(tcs, new [] { t.Result });
return;
}
Logger.Info("Reconnection attempt to host {0} failed", _host.Address);
Exception ex = null;
if (t.Exception != null)
{
t.Exception.Handle(e => true);
ex = t.Exception.InnerException;
//This makes sure that the exception is observed, but still sets _creationTcs' exception
//for MaybeCreateFirstConnection
tcs.Task.ContinueWith(x =>
{
if (x.Exception != null)
x.Exception.Handle(_ => true);
});
}
TransitionCreationTask(tcs, EmptyConnectionsArray, ex);
_host.SetDown(failedReconnection: true);
}, TaskContinuationOptions.ExecuteSynchronously);
}
private void OnHostUp(Host host)
{
_isShuttingDown = false;
SetReconnectionTimeout(null);
//The host is back up, we can start creating the pool (if applies)
MaybeCreateFirstConnection();
}
private void OnHostDown(Host h, long delay)
{
Shutdown();
}
/// <summary>
/// Cancels the previous and set the next reconnection timeout, as an atomic operation.
/// </summary>
private void SetReconnectionTimeout(HashedWheelTimer.ITimeout nextTimeout)
{
var timeout = Interlocked.Exchange(ref _timeout, nextTimeout);
if (timeout != null)
{
timeout.Cancel();
}
}
/// <summary>
/// Create the min amount of connections, if the pool is empty.
/// It may return an empty array if its being closed.
/// It may return an array of connections being closed.
/// </summary>
internal Task<Connection[]> MaybeCreateFirstConnection()
{
var tcs = new TaskCompletionSource<Connection[]>();
var connections = _connections.GetSnapshot();
if (connections.Length > 0)
{
tcs.SetResult(connections);
return tcs.Task;
}
var creationTcs = Interlocked.CompareExchange(ref _creationTcs, tcs, null);
if (creationTcs != null)
{
return creationTcs.Task;
}
//Could have transitioned
connections = _connections.GetSnapshot();
if (connections.Length > 0)
{
TransitionCreationTask(tcs, connections);
return tcs.Task;
}
if (_isShuttingDown)
{
//It transitioned to DOWN, avoid try to create new Connections
TransitionCreationTask(tcs, EmptyConnectionsArray);
return tcs.Task;
}
Logger.Info("Initializing pool to {0}", _host.Address);
//There is a single thread creating a single connection
CreateConnection().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_isShuttingDown)
{
//Is shutting down
t.Result.Dispose();
TransitionCreationTask(tcs, EmptyConnectionsArray);
return;
}
_connections.Add(t.Result);
_host.BringUpIfDown();
TransitionCreationTask(tcs, new[] { t.Result });
return;
}
if (t.Exception != null)
{
TransitionCreationTask(tcs, null, t.Exception.InnerException);
return;
}
TransitionCreationTask(tcs, EmptyConnectionsArray);
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
private void TransitionCreationTask(TaskCompletionSource<Connection[]> tcs, Connection[] result, Exception ex = null)
{
if (ex != null)
{
tcs.TrySetException(ex);
}
else if (result != null)
{
tcs.TrySetResult(result);
}
else
{
tcs.TrySetException(new DriverInternalError("Creation task must transition from a result or an exception"));
}
Interlocked.Exchange(ref _creationTcs, null);
}
/// <summary>
/// Increases the size of the pool from 1 to core and from core to max
/// </summary>
/// <returns>True if it is creating a new connection</returns>
internal bool MaybeIncreasePoolSize(int inFlight)
{
var protocolVersion = _serializer.ProtocolVersion;
var coreConnections = _config.GetPoolingOptions(protocolVersion).GetCoreConnectionsPerHost(_distance);
var connections = _connections.GetSnapshot();
if (connections.Length == 0)
{
return false;
}
if (connections.Length >= coreConnections)
{
var maxInFlight = _config.GetPoolingOptions(protocolVersion).GetMaxSimultaneousRequestsPerConnectionTreshold(_distance);
var maxConnections = _config.GetPoolingOptions(protocolVersion).GetMaxConnectionPerHost(_distance);
if (inFlight < maxInFlight)
{
return false;
}
if (_connections.Count >= maxConnections)
{
return false;
}
}
var isAlreadyIncreasing = Interlocked.CompareExchange(ref _isIncreasingSize, 1, 0) == 1;
if (isAlreadyIncreasing)
{
return true;
}
if (_isShuttingDown || _connections.Count == 0)
{
Interlocked.Exchange(ref _isIncreasingSize, 0);
return false;
}
CreateConnection().ContinueWith(t =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
if (_isShuttingDown)
{
//Is shutting down
t.Result.Dispose();
}
else
{
_connections.Add(t.Result);
}
}
if (t.Exception != null)
{
Logger.Error("Error while increasing pool size", t.Exception.InnerException);
}
Interlocked.Exchange(ref _isIncreasingSize, 0);
}, TaskContinuationOptions.ExecuteSynchronously);
return true;
}
public void CheckHealth(Connection c)
{
if (c.TimedOutOperations < _config.SocketOptions.DefunctReadTimeoutThreshold)
{
return;
}
//We are in the default thread-pool (non-io thread)
//Defunct: close it and remove it from the pool
_connections.Remove(c);
c.Dispose();
}
public void Shutdown()
{
_isShuttingDown = true;
var connections = _connections.ClearAndGet();
if (connections.Length == 0)
{
return;
}
Logger.Info(string.Format("Shutting down pool to {0}, closing {1} connection(s).", _host.Address, connections.Length));
foreach (var c in connections)
{
c.Dispose();
}
}
private void OnHostRemoved()
{
Dispose();
}
/// <summary>
/// Releases the resources associated with the pool.
/// </summary>
public void Dispose()
{
_isDisposed = true;
SetReconnectionTimeout(null);
Shutdown();
_host.CheckedAsDown -= OnHostCheckedAsDown;
_host.Up -= OnHostUp;
_host.Down -= OnHostDown;
_host.Remove -= OnHostRemoved;
}
}
}
| |
// 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.Globalization;
namespace System.Net
{
internal static class GlobalLog
{
[ThreadStatic]
private static Stack<ThreadKinds> t_threadKindStack;
private static Stack<ThreadKinds> ThreadKindStack
{
get
{
if (t_threadKindStack == null)
{
t_threadKindStack = new Stack<ThreadKinds>();
}
return t_threadKindStack;
}
}
internal static ThreadKinds CurrentThreadKind
{
get
{
return ThreadKindStack.Count > 0 ? ThreadKindStack.Peek() : ThreadKinds.Other;
}
}
internal static IDisposable SetThreadKind(ThreadKinds kind)
{
if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown)
{
throw new InternalException();
}
// Ignore during shutdown.
if (Environment.HasShutdownStarted)
{
return null;
}
ThreadKinds threadKind = CurrentThreadKind;
ThreadKinds source = threadKind & ThreadKinds.SourceMask;
// Special warnings when doing dangerous things on a thread.
if ((threadKind & ThreadKinds.User) != 0 && (kind & ThreadKinds.System) != 0)
{
EventSourceLogging.Log.WarningMessage("Thread changed from User to System; user's thread shouldn't be hijacked.");
}
if ((threadKind & ThreadKinds.Async) != 0 && (kind & ThreadKinds.Sync) != 0)
{
EventSourceLogging.Log.WarningMessage("Thread changed from Async to Sync, may block an Async thread.");
}
else if ((threadKind & (ThreadKinds.Other | ThreadKinds.CompletionPort)) == 0 && (kind & ThreadKinds.Sync) != 0)
{
EventSourceLogging.Log.WarningMessage("Thread from a limited resource changed to Sync, may deadlock or bottleneck.");
}
ThreadKindStack.Push(
(((kind & ThreadKinds.OwnerMask) == 0 ? threadKind : kind) & ThreadKinds.OwnerMask) |
(((kind & ThreadKinds.SyncMask) == 0 ? threadKind : kind) & ThreadKinds.SyncMask) |
(kind & ~(ThreadKinds.OwnerMask | ThreadKinds.SyncMask)) |
source);
if (CurrentThreadKind != threadKind && IsEnabled)
{
Print("Thread becomes:(" + CurrentThreadKind.ToString() + ")");
}
return new ThreadKindFrame();
}
private class ThreadKindFrame : IDisposable
{
private readonly int _frameNumber;
internal ThreadKindFrame()
{
_frameNumber = ThreadKindStack.Count;
}
void IDisposable.Dispose()
{
// Ignore during shutdown.
if (Environment.HasShutdownStarted)
{
return;
}
if (_frameNumber != ThreadKindStack.Count)
{
throw new InternalException();
}
ThreadKinds previous = ThreadKindStack.Pop();
if (CurrentThreadKind != previous && IsEnabled)
{
Print("Thread reverts:(" + CurrentThreadKind.ToString() + ")");
}
}
}
internal static void SetThreadSource(ThreadKinds source)
{
if ((source & ThreadKinds.SourceMask) != source || source == ThreadKinds.Unknown)
{
throw new ArgumentException("Must specify the thread source.", nameof(source));
}
if (ThreadKindStack.Count == 0)
{
ThreadKindStack.Push(source);
return;
}
if (ThreadKindStack.Count > 1)
{
EventSourceLogging.Log.WarningMessage("SetThreadSource must be called at the base of the stack, or the stack has been corrupted.");
while (ThreadKindStack.Count > 1)
{
ThreadKindStack.Pop();
}
}
if (ThreadKindStack.Peek() != source)
{
EventSourceLogging.Log.WarningMessage("The stack has been corrupted.");
ThreadKinds last = ThreadKindStack.Pop() & ThreadKinds.SourceMask;
if (last != source && last != ThreadKinds.Other && IsEnabled)
{
AssertFormat("Thread source changed.|Was:({0}) Now:({1})", last, source);
}
ThreadKindStack.Push(source);
}
}
internal static void ThreadContract(ThreadKinds kind, string errorMsg)
{
ThreadContract(kind, ThreadKinds.SafeSources, errorMsg);
}
internal static void ThreadContract(ThreadKinds kind, ThreadKinds allowedSources, string errorMsg)
{
if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown || (allowedSources & ThreadKinds.SourceMask) != allowedSources)
{
throw new InternalException();
}
if (IsEnabled)
{
ThreadKinds threadKind = CurrentThreadKind;
if ((threadKind & allowedSources) != 0)
{
AssertFormat(errorMsg, "Thread Contract Violation.|Expected source:({0}) Actual source:({1})", allowedSources, threadKind & ThreadKinds.SourceMask);
}
if ((threadKind & kind) == kind)
{
AssertFormat(errorMsg, "Thread Contract Violation.|Expected kind:({0}) Actual kind:({1})", kind, threadKind & ~ThreadKinds.SourceMask);
}
}
}
public static void Print(string msg)
{
EventSourceLogging.Log.DebugMessage(msg);
}
public static void Enter(string functionName)
{
EventSourceLogging.Log.FunctionStart(functionName);
}
public static void Enter(string functionName, string parameters)
{
EventSourceLogging.Log.FunctionStart(functionName, parameters);
}
public static void AssertFormat(string messageFormat, params object[] data)
{
string fullMessage = string.Format(CultureInfo.InvariantCulture, messageFormat, data);
int pipeIndex = fullMessage.IndexOf('|');
if (pipeIndex == -1)
{
Assert(fullMessage);
}
else
{
int detailLength = fullMessage.Length - pipeIndex - 1;
Assert(fullMessage.Substring(0, pipeIndex), detailLength > 0 ? fullMessage.Substring(pipeIndex + 1, detailLength) : null);
}
}
public static void Assert(string message)
{
Assert(message, null);
}
public static void Assert(string message, string detailMessage)
{
EventSourceLogging.Log.AssertFailed(message, detailMessage);
}
public static void Leave(string functionName)
{
EventSourceLogging.Log.FunctionStop(functionName);
}
public static void Leave(string functionName, string result)
{
EventSourceLogging.Log.FunctionStop(functionName, result);
}
public static void Leave(string functionName, int returnval)
{
EventSourceLogging.Log.FunctionStop(functionName, returnval.ToString());
}
public static void Leave(string functionName, bool returnval)
{
EventSourceLogging.Log.FunctionStop(functionName, returnval.ToString());
}
public static void Dump(byte[] buffer, int length)
{
Dump(buffer, 0, length);
}
public static void Dump(byte[] buffer, int offset, int length)
{
string warning =
buffer == null ? "buffer is null" :
offset >= buffer.Length ? "offset out of range" :
(length < 0) || (length > buffer.Length - offset) ? "length out of range" :
null;
if (warning != null)
{
EventSourceLogging.Log.WarningDumpArray(warning);
return;
}
var bufferSegment = new byte[length];
Buffer.BlockCopy(buffer, offset, bufferSegment, 0, length);
EventSourceLogging.Log.DebugDumpArray(bufferSegment);
}
public static bool IsEnabled { get { return EventSourceLogging.Log.IsEnabled(); } }
}
[Flags]
internal enum ThreadKinds
{
Unknown = 0x0000,
// Mutually exclusive.
User = 0x0001, // Thread has entered via an API.
System = 0x0002, // Thread has entered via a system callback (e.g. completion port) or is our own thread.
// Mutually exclusive.
Sync = 0x0004, // Thread should block.
Async = 0x0008, // Thread should not block.
// Mutually exclusive, not always known for a user thread. Never changes.
Timer = 0x0010, // Thread is the timer thread. (Can't call user code.)
CompletionPort = 0x0020, // Thread is a ThreadPool completion-port thread.
Worker = 0x0040, // Thread is a ThreadPool worker thread.
Finalization = 0x0080, // Thread is the finalization thread.
Other = 0x0100, // Unknown source.
OwnerMask = User | System,
SyncMask = Sync | Async,
SourceMask = Timer | CompletionPort | Worker | Finalization | Other,
// Useful "macros"
SafeSources = SourceMask & ~(Timer | Finalization), // Methods that "unsafe" sources can call must be explicitly marked.
ThreadPool = CompletionPort | Worker, // Like Thread.CurrentThread.IsThreadPoolThread
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureParameterGrouping
{
using Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ParameterGroupingOperations operations.
/// </summary>
internal partial class ParameterGroupingOperations : IServiceOperations<AutoRestParameterGroupingTestService>, IParameterGroupingOperations
{
/// <summary>
/// Initializes a new instance of the ParameterGroupingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ParameterGroupingOperations(AutoRestParameterGroupingTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestParameterGroupingTestService
/// </summary>
public AutoRestParameterGroupingTestService Client { get; private set; }
/// <summary>
/// Post a bunch of required parameters grouped
/// </summary>
/// <param name='parameterGroupingPostRequiredParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostRequiredWithHttpMessagesAsync(ParameterGroupingPostRequiredParameters parameterGroupingPostRequiredParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (parameterGroupingPostRequiredParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameterGroupingPostRequiredParameters");
}
if (parameterGroupingPostRequiredParameters != null)
{
parameterGroupingPostRequiredParameters.Validate();
}
int body = default(int);
if (parameterGroupingPostRequiredParameters != null)
{
body = parameterGroupingPostRequiredParameters.Body;
}
string customHeader = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
customHeader = parameterGroupingPostRequiredParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostRequiredParameters != null)
{
query = parameterGroupingPostRequiredParameters.Query;
}
string path = default(string);
if (parameterGroupingPostRequiredParameters != null)
{
path = parameterGroupingPostRequiredParameters.Path;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("body", body);
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("path", path);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostRequired", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postRequired/{path}").ToString();
_url = _url.Replace("{path}", System.Uri.EscapeDataString(path));
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post a bunch of optional parameters grouped
/// </summary>
/// <param name='parameterGroupingPostOptionalParameters'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostOptionalWithHttpMessagesAsync(ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = default(ParameterGroupingPostOptionalParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string customHeader = default(string);
if (parameterGroupingPostOptionalParameters != null)
{
customHeader = parameterGroupingPostOptionalParameters.CustomHeader;
}
int? query = default(int?);
if (parameterGroupingPostOptionalParameters != null)
{
query = parameterGroupingPostOptionalParameters.Query;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("customHeader", customHeader);
tracingParameters.Add("query", query);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostOptional", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postOptional").ToString();
List<string> _queryParameters = new List<string>();
if (query != null)
{
_queryParameters.Add(string.Format("query={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(query, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeader != null)
{
if (_httpRequest.Headers.Contains("customHeader"))
{
_httpRequest.Headers.Remove("customHeader");
}
_httpRequest.Headers.TryAddWithoutValidation("customHeader", customHeader);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters from multiple different parameter groups
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='parameterGroupingPostMultiParamGroupsSecondParamGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostMultiParamGroupsWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = default(ParameterGroupingPostMultiParamGroupsSecondParamGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
string headerTwo = default(string);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.HeaderTwo;
}
int? queryTwo = default(int?);
if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null)
{
queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.QueryTwo;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("headerTwo", headerTwo);
tracingParameters.Add("queryTwo", queryTwo);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostMultiParamGroups", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/postMultipleParameterGroups").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"'))));
}
if (queryTwo != null)
{
_queryParameters.Add(string.Format("query-two={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryTwo, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (headerTwo != null)
{
if (_httpRequest.Headers.Contains("header-two"))
{
_httpRequest.Headers.Remove("header-two");
}
_httpRequest.Headers.TryAddWithoutValidation("header-two", headerTwo);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Post parameters with a shared parameter group object
/// </summary>
/// <param name='firstParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PostSharedParameterGroupObjectWithHttpMessagesAsync(FirstParameterGroup firstParameterGroup = default(FirstParameterGroup), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string headerOne = default(string);
if (firstParameterGroup != null)
{
headerOne = firstParameterGroup.HeaderOne;
}
int? queryOne = default(int?);
if (firstParameterGroup != null)
{
queryOne = firstParameterGroup.QueryOne;
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("headerOne", headerOne);
tracingParameters.Add("queryOne", queryOne);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostSharedParameterGroupObject", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "parameterGrouping/sharedParameterGroupObject").ToString();
List<string> _queryParameters = new List<string>();
if (queryOne != null)
{
_queryParameters.Add(string.Format("query-one={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(queryOne, Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (headerOne != null)
{
if (_httpRequest.Headers.Contains("header-one"))
{
_httpRequest.Headers.Remove("header-one");
}
_httpRequest.Headers.TryAddWithoutValidation("header-one", headerOne);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// <copyright file="MultinomialTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Linq;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Statistics;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.DistributionTests.Multivariate
{
/// <summary>
/// Multinomial distribution tests.
/// </summary>
[TestFixture, Category("Distributions")]
public class MultinomialTests
{
/// <summary>
/// Bad proportion of ratios.
/// </summary>
private double[] _badP;
/// <summary>
/// Another bad proportion of ratios.
/// </summary>
private double[] _badP2;
/// <summary>
/// Small array with proportion of ratios
/// </summary>
private double[] _smallP;
/// <summary>
/// Large array with proportion of ratios
/// </summary>
private double[] _largeP;
/// <summary>
/// Set-up tests parameters.
/// </summary>
[SetUp]
public void SetUp()
{
Control.CheckDistributionParameters = true;
_badP = new[] { -1.0, 1.0 };
_badP2 = new[] { 0.0, 0.0 };
_smallP = new[] { 1.0, 1.0, 1.0 };
_largeP = new[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };
}
/// <summary>
/// Can create Multinomial
/// </summary>
[Test]
public void CanCreateMultinomial()
{
var m = new Multinomial(_largeP, 4);
CollectionAssert.AreEqual(_largeP, m.P);
}
/// <summary>
/// Can create Multinomial from a histogram.
/// </summary>
[Test]
public void CanCreateMultinomialFromHistogram()
{
double[] smallDataset = { 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5 };
var hist = new Histogram(smallDataset, 10, 0.0, 10.0);
var m = new Multinomial(hist, 7);
foreach (var t in m.P)
{
Assert.AreEqual(1.0, t);
}
}
/// <summary>
/// Multinomial create fails with <c>null</c> histogram.
/// </summary>
[Test]
public void MultinomialCreateFailsWithNullHistogram()
{
Histogram h = null;
// ReSharper disable ExpressionIsAlwaysNull
Assert.That(() => new Categorical(h), Throws.TypeOf<ArgumentNullException>());
// ReSharper restore ExpressionIsAlwaysNull
}
/// <summary>
/// Multinomial create fails with negative ratios.
/// </summary>
[Test]
public void MultinomialCreateFailsWithNegativeRatios()
{
Assert.That(() => new Multinomial(_badP, 4), Throws.ArgumentException);
}
/// <summary>
/// Multinomial create fails with all zero ratios.
/// </summary>
[Test]
public void MultinomialCreateFailsWithAllZeroRatios()
{
Assert.That(() => new Multinomial(_badP2, 4), Throws.ArgumentException);
}
/// <summary>
/// Validate ToString.
/// </summary>
[Test]
public void ValidateToString()
{
var b = new Multinomial(_smallP, 4);
Assert.AreEqual("Multinomial(Dimension = 3, Number of Trails = 4)", b.ToString());
}
/// <summary>
/// Validate skewness.
/// </summary>
/// <param name="p">Proportion of ratios.</param>
/// <param name="n">Number of trials.</param>
/// <param name="res">Expected value.</param>
[TestCase(new[] { 0.3, 0.7 }, 5, new[] { 0.390360029179413, -0.390360029179413 })]
[TestCase(new[] { 0.1, 0.3, 0.6 }, 10, new[] { 0.843274042711568, 0.276026223736942, -0.129099444873581 })]
[TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, 20, new[] { 0.438357003759605, 0.140642169281549, 0.195180014589707, 0.335410196624968 })]
public void ValidateSkewness(double[] p, int n, double[] res)
{
var b = new Multinomial(p, n);
for (var i = 0; i < b.P.Length; i++)
{
AssertHelpers.AlmostEqualRelative(res[i], b.Skewness[i], 12);
}
}
/// <summary>
/// Validate variance.
/// </summary>
/// <param name="p">Proportion of ratios.</param>
/// <param name="n">Number of trials.</param>
/// <param name="res">Expected value.</param>
[TestCase(new[] { 0.3, 0.7 }, 5, new[] { 1.05, 1.05 })]
[TestCase(new[] { 0.1, 0.3, 0.6 }, 10, new[] { 0.9, 2.1, 2.4 })]
[TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, 20, new[] { 2.55, 4.55, 4.2, 3.2 })]
public void ValidateVariance(double[] p, int n, double[] res)
{
var b = new Multinomial(p, n);
for (var i = 0; i < b.P.Length; i++)
{
AssertHelpers.AlmostEqualRelative(res[i], b.Variance[i], 12);
}
}
/// <summary>
/// Validate mean.
/// </summary>
/// <param name="p">Proportion of ratios.</param>
/// <param name="n">Number of trials.</param>
/// <param name="res">Expected value.</param>
[TestCase(new[] { 0.3, 0.7 }, 5, new[] { 1.5, 3.5 })]
[TestCase(new[] { 0.1, 0.3, 0.6 }, 10, new[] { 1.0, 3.0, 6.0 })]
[TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, 20, new[] { 3.0, 7.0, 6.0, 4.0 })]
public void ValidateMean(double[] p, int n, double[] res)
{
var b = new Multinomial(p, n);
for (var i = 0; i < b.P.Length; i++)
{
AssertHelpers.AlmostEqualRelative(res[i], b.Mean[i], 12);
}
}
/// <summary>
/// Validate probability.
/// </summary>
/// <param name="p">Proportion of ratios.</param>
/// <param name="x">Input X value.</param>
/// <param name="res">Expected value.</param>
[TestCase(new[] { 0.3, 0.7 }, new[] { 1, 9 }, 0.121060821)]
[TestCase(new[] { 0.1, 0.3, 0.6 }, new[] { 1, 3, 6 }, 0.105815808)]
[TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, new[] { 1, 1, 1, 7 }, 0.000145152)]
public void ValidateProbability(double[] p, int[] x, double res)
{
var b = new Multinomial(p, x.Sum());
AssertHelpers.AlmostEqualRelative(b.Probability(x), res, 12);
}
/// <summary>
/// Validate probability log.
/// </summary>
/// <param name="x">Input X value.</param>
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })]
[TestCase(new[] { 1, 1, 1, 2, 2, 2, 3, 3, 3 })]
[TestCase(new[] { 5, 6, 7, 8, 7, 6, 5, 4, 3 })]
public void ValidateProbabilityLn(int[] x)
{
var b = new Multinomial(_largeP, x.Sum());
AssertHelpers.AlmostEqualRelative(b.ProbabilityLn(x), Math.Log(b.Probability(x)), 12);
}
/// <summary>
/// Can sample static.
/// </summary>
[Test]
public void CanSampleStatic()
{
Multinomial.Sample(new System.Random(0), _largeP, 4);
}
/// <summary>
/// Sample static fails with bad parameters.
/// </summary>
[Test]
public void FailSampleStatic()
{
Assert.That(() => Multinomial.Sample(new System.Random(0), _badP, 4), Throws.ArgumentException);
}
/// <summary>
/// Can sample.
/// </summary>
[Test]
public void CanSample()
{
var n = new Multinomial(_largeP, 4);
n.Sample();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public partial class ParallelQueryCombinationTests
{
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Aggregate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate((x, y) => x + y));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Aggregate_Seed(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Aggregate_Result(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y, r => r));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Aggregate_Accumulator(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Aggregate_SeedFactory(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize),
operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void All_False(LabeledOperation source, LabeledOperation operation)
{
Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => false));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void All_True(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Any_False(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => !seen.Add(x)));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Any_True(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => true));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Average(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double)DefaultSize,
operation.Item(DefaultStart, DefaultSize, source.Item).Average());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Average_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double?)DefaultSize,
operation.Item(DefaultStart, DefaultSize, source.Item).Average(x => (int?)x));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Cast(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int? i in operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>())
{
Assert.True(i.HasValue);
Assert.Equal(seen++, i.Value);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Cast_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Contains_True(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Contains_False(LabeledOperation source, LabeledOperation operation)
{
Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Count_Elements(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Count());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Count_Predicate_Some(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Count_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void DefaultIfEmpty(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty())
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void DefaultIfEmpty_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Distinct(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct();
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Distinct_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct();
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void ElementAt(LabeledOperation source, LabeledOperation operation)
{
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item);
int seen = DefaultStart;
for (int i = 0; i < DefaultSize; i++)
{
Assert.Equal(seen++, query.ElementAt(i));
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void ElementAtOrDefault(LabeledOperation source, LabeledOperation operation)
{
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item);
int seen = DefaultStart;
for (int i = 0; i < DefaultSize; i++)
{
Assert.Equal(seen++, query.ElementAtOrDefault(i));
}
Assert.Equal(DefaultStart + DefaultSize, seen);
Assert.Equal(default(int), query.ElementAtOrDefault(-1));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Except(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)
.Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item));
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Except_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)
.Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item));
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void First(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).First());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void First_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).First(x => x >= DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void FirstOrDefault(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void FirstOrDefault_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => x >= DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void FirstOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void ForAll(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
operation.Item(DefaultStart, DefaultSize, source.Item).ForAll(x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void GetEnumerator(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, source.Item).GetEnumerator();
while (enumerator.MoveNext())
{
int current = enumerator.Current;
Assert.Equal(seen++, current);
Assert.Equal(current, enumerator.Current);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
Assert.Throws<NotSupportedException>(() => enumerator.Reset());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void GroupBy(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor))
{
Assert.Equal(seenKey++, group.Key);
int seenElement = group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement++, x));
Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void GroupBy_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor).ToList())
{
Assert.Equal(seenKey++, group.Key);
int seenElement = group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement++, x));
Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void GroupBy_ElementSelector(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y))
{
Assert.Equal(seenKey++, group.Key);
int seenElement = -group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement--, x));
Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void GroupBy_ElementSelector_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seenKey = DefaultStart / GroupFactor;
foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y).ToList())
{
Assert.Equal(seenKey++, group.Key);
int seenElement = -group.Key * GroupFactor;
Assert.All(group, x => Assert.Equal(seenElement--, x));
Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement);
}
Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Intersect(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item)
.Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item));
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Intersect_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item)
.Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item));
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Last(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Last_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void LastOrDefault(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void LastOrDefault_Predicate(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void LastOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => false));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void LongCount_Elements(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void LongCount_Predicate_Some(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void LongCount_Predicate_None(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Max(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Max_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max(x => (int?)x));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Min(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Min_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min(x => (int?)x));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void OfType(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void OfType_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void OfType_Other(LabeledOperation source, LabeledOperation operation)
{
Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void OfType_Other_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>().ToList());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderBy_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderBy_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderByDescending_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void OrderByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Reverse(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse())
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Reverse_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse().ToList())
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Select(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Select_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Select_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; }))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Select_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; }).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany_ResultSelector(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany_Indexed_ResultSelector(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x))
{
Assert.Equal(seen--, i);
}
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SelectMany_Indexed_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = -DefaultStart;
Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x));
Assert.Equal(-DefaultStart - DefaultSize * 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SequenceEqual(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered()));
Assert.True(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered().SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item)));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SequenceEqual_Self(LabeledOperation source, LabeledOperation operation)
{
Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item)));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void Single(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).Single());
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Single(x => x == DefaultStart + DefaultSize / 2));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void SingleOrDefault(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).SingleOrDefault());
Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2));
if (!operation.ToString().StartsWith("DefaultIfEmpty"))
{
Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault());
Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2));
}
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Skip(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Skip_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SkipWhile(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SkipWhile_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SkipWhile_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void SkipWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize / 2;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void Sum(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum());
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void Sum_Nullable(LabeledOperation source, LabeledOperation operation)
{
Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum(x => (int?)x));
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Take(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Take_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void TakeWhile(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void TakeWhile_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void TakeWhile_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void TakeWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenBy_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenBy_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenByDescending_Initial(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x))
{
Assert.Equal(--seen, i);
}
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ThenByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart + DefaultSize;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x).ToList(), x => Assert.Equal(--seen, x));
Assert.Equal(DefaultStart, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void ToArray(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToArray(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ToDictionary(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x * 2),
p =>
{
seen.Add(p.Key / 2);
Assert.Equal(p.Key, p.Value * 2);
});
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ToDictionary_ElementSelector(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize);
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x, y => y * 2),
p =>
{
seen.Add(p.Key);
Assert.Equal(p.Key * 2, p.Value);
});
seen.AssertComplete();
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void ToList(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ToLookup(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2);
ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
[MemberData(nameof(UnaryUnorderedOperators))]
[MemberData(nameof(BinaryUnorderedOperators))]
public static void ToLookup_ElementSelector(LabeledOperation source, LabeledOperation operation)
{
IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2);
ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2, y => -y);
Assert.All(lookup,
group =>
{
seenOuter.Add(group.Key);
IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2);
Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); });
seenInner.AssertComplete();
});
seenOuter.AssertComplete();
Assert.Empty(lookup[-1]);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Where(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Where_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Where_Indexed(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2))
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Where_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize / 2, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Zip(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize, source.Item)
.Zip(operation.Item(0, DefaultSize, source.Item), (x, y) => (x + y) / 2);
foreach (int i in query)
{
Assert.Equal(seen++, i);
}
Assert.Equal(DefaultStart + DefaultSize, seen);
}
[Theory]
[MemberData(nameof(UnaryOperators))]
[MemberData(nameof(BinaryOperators))]
public static void Zip_NotPipelined(LabeledOperation source, LabeledOperation operation)
{
int seen = DefaultStart;
ParallelQuery<int> query = operation.Item(0, DefaultSize, source.Item)
.Zip(operation.Item(DefaultStart * 2, DefaultSize, source.Item), (x, y) => (x + y) / 2);
Assert.All(query.ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(DefaultStart + DefaultSize, seen);
}
}
}
| |
#region BSD License
/*
Copyright (c) 2011, Clarius Consulting
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of Clarius Consulting nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/
#endregion
namespace Clide.Diagnostics
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.XPath;
/// <summary>
/// Implements the common tracer interface using <see cref="TraceSource"/> instances.
/// </summary>
/// <remarks>
/// All tracing is performed asynchronously transparently for faster speed.
/// </remarks>
/// <nuget id="Tracer.SystemDiagnostics" />
partial class TracerManager : ITracerManager, IDisposable
{
/// <summary>
/// Implicit default trace source name which can be used to setup
/// global tracing and listeners.
/// </summary>
public const string DefaultSourceName = "*";
// To handle concurrency for the async tracing.
private BlockingCollection<Tuple<ExecutionContext, Action>> traceQueue = new BlockingCollection<Tuple<ExecutionContext, Action>>();
private CancellationTokenSource cancellation = new CancellationTokenSource();
/// <summary>
/// Initializes a new instance of the <see cref="TracerManager"/> class.
/// </summary>
public TracerManager()
{
// Note we have only one async task to perform all tracing. This
// is an optimization, so that we don't consume too much resources
// from the running app for this.
Task.Factory.StartNew(DoTrace, cancellation.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
InitializeConfiguredSources();
}
private void InitializeConfiguredSources()
{
var configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
if (!File.Exists(configFile))
return;
var sourceNames = from diagnostics in XDocument.Load(configFile).Root.Elements("system.diagnostics")
from sources in diagnostics.Elements("sources")
from source in sources.Elements("source")
select source.Attribute("name").Value;
foreach (var sourceName in sourceNames)
{
// Cause eager initialization, which is needed for the trace source configuration
// to be properly read.
GetSource(sourceName);
}
}
/// <summary>
/// Gets a tracer instance with the specified name.
/// </summary>
public ITracer Get(string name)
{
return new AggregateTracer(this, name, CompositeFor(name)
.Select(tracerName => new DiagnosticsTracer(
this.GetOrAdd(tracerName, sourceName => CreateSource(sourceName)))));
}
/// <summary>
/// Gets the underlying <see cref="TraceSource"/> for the given name.
/// </summary>
public TraceSource GetSource(string name)
{
return this.GetOrAdd(name, sourceName => CreateSource(sourceName));
}
/// <summary>
/// Adds a listener to the source with the given <paramref name="sourceName"/>.
/// </summary>
public void AddListener(string sourceName, TraceListener listener)
{
this.GetOrAdd(sourceName, name => CreateSource(name)).Listeners.Add(listener);
}
/// <summary>
/// Removes a listener from the source with the given <paramref name="sourceName"/>.
/// </summary>
public void RemoveListener(string sourceName, TraceListener listener)
{
this.GetOrAdd(sourceName, name => CreateSource(name)).Listeners.Remove(listener);
}
/// <summary>
/// Removes a listener from the source with the given <paramref name="sourceName"/>.
/// </summary>
public void RemoveListener(string sourceName, string listenerName)
{
this.GetOrAdd(sourceName, name => CreateSource(name)).Listeners.Remove(listenerName);
}
/// <summary>
/// Sets the tracing level for the source with the given <paramref name="sourceName"/>
/// </summary>
public void SetTracingLevel(string sourceName, SourceLevels level)
{
this.GetOrAdd(sourceName, name => CreateSource(name)).Switch.Level = level;
}
/// <summary>
/// Cleans up the manager, cancelling any pending tracing
/// messages.
/// </summary>
public void Dispose()
{
cancellation.Cancel();
traceQueue.Dispose();
}
/// <summary>
/// Enqueues the specified trace action to be executed by the trace
/// async task.
/// </summary>
internal void Enqueue(Action traceAction)
{
traceQueue.Add(Tuple.Create(ExecutionContext.Capture(), traceAction));
}
private TraceSource CreateSource(string name)
{
var source = new TraceSource(name);
source.TraceInformation("Initialized with initial level {0}", source.Switch.Level);
return source;
}
private void DoTrace()
{
foreach (var action in traceQueue.GetConsumingEnumerable())
{
if (cancellation.IsCancellationRequested)
break;
// Tracing should never cause the app to fail.
// Since this is async, it might if we don't catch.
try
{
ExecutionContext.Run(action.Item1, state => action.Item2(), null);
}
catch { }
}
}
/// <summary>
/// Gets the list of trace source names that are used to inherit trace source logging for the given <paramref name="name"/>.
/// </summary>
private static IEnumerable<string> CompositeFor(string name)
{
if (name != DefaultSourceName)
yield return DefaultSourceName;
var indexOfGeneric = name.IndexOf('<');
var indexOfLastDot = name.LastIndexOf('.');
if (indexOfGeneric == -1 && indexOfLastDot == -1)
{
yield return name;
yield break;
}
var parts = default(string[]);
if (indexOfGeneric == -1)
parts = name
.Substring(0, name.LastIndexOf('.'))
.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
else
parts = name
.Substring(0, indexOfGeneric)
.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 1; i <= parts.Length; i++)
{
yield return string.Join(".", parts, 0, i);
}
yield return name;
}
/// <summary>
/// Gets an AppDomain-cached trace source of the given name, or creates it.
/// This means that even if multiple libraries are using their own
/// trace manager instance, they will all still share the same
/// underlying sources.
/// </summary>
private TraceSource GetOrAdd(string sourceName, Func<string, TraceSource> factory)
{
var cachedSources = AppDomain.CurrentDomain.GetData<Dictionary<string, TraceSource>>();
if (cachedSources == null)
{
// This lock guarantees that throughout the current
// app domain, only a single root trace source is
// created ever.
lock (AppDomain.CurrentDomain)
{
cachedSources = AppDomain.CurrentDomain.GetData<Dictionary<string, TraceSource>>();
if (cachedSources == null)
{
cachedSources = new Dictionary<string, TraceSource>();
AppDomain.CurrentDomain.SetData(cachedSources);
}
}
}
return cachedSources.GetOrAdd(sourceName, factory);
}
/// <summary>
/// Logs to multiple tracers simulateously. Used for the
/// source "inheritance"
/// </summary>
private class AggregateTracer : ITracer
{
private TracerManager manager;
private List<DiagnosticsTracer> tracers;
private string name;
public AggregateTracer(TracerManager manager, string name, IEnumerable<DiagnosticsTracer> tracers)
{
this.manager = manager;
this.name = name;
this.tracers = tracers.ToList();
}
/// <summary>
/// Traces the specified message with the given <see cref="TraceEventType"/>.
/// </summary>
public void Trace(TraceEventType type, object message)
{
manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, message)));
}
/// <summary>
/// Traces the specified formatted message with the given <see cref="TraceEventType"/>.
/// </summary>
public void Trace(TraceEventType type, string format, params object[] args)
{
manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, format, args)));
}
/// <summary>
/// Traces an exception with the specified message and <see cref="TraceEventType"/>.
/// </summary>
public void Trace(TraceEventType type, Exception exception, object message)
{
manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, exception, message)));
}
/// <summary>
/// Traces an exception with the specified formatted message and <see cref="TraceEventType"/>.
/// </summary>
public void Trace(TraceEventType type, Exception exception, string format, params object[] args)
{
manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, exception, format, args)));
}
public override string ToString()
{
return "Aggregate for " + this.name;
}
}
partial class DiagnosticsTracer
{
private TraceSource source;
public DiagnosticsTracer(TraceSource source)
{
this.source = source;
}
public void Trace(string sourceName, TraceEventType type, object message)
{
// Because we know there is a single tracer thread executing these,
// we know it's safe to replace the name without locking.
using (new SourceNameReplacer(source, sourceName))
{
// Add support for Xml-based Service Trace Viewer-compatible
// activity tracing.
var data = message as XPathNavigator;
// Transfers with a Guid payload should instead trace a transfer
// with that as the related Guid.
var guid = message as Guid?;
if (data != null)
source.TraceData(type, 0, data);
else if (guid != null && type == TraceEventType.Transfer)
source.TraceTransfer(0, "", guid.Value);
else
source.TraceEvent(type, 0, message.ToString());
}
}
public void Trace(string sourceName, TraceEventType type, string format, params object[] args)
{
// Because we know there is a single tracer thread executing these,
// we know it's safe to replace the name without locking.
using (new SourceNameReplacer(source, sourceName))
{
source.TraceEvent(type, 0, format, args);
}
}
public void Trace(string sourceName, TraceEventType type, Exception exception, object message)
{
// Because we know there is a single tracer thread executing these,
// we know it's safe to replace the name without locking.
using (new SourceNameReplacer(source, sourceName))
{
source.TraceEvent(type, 0, message.ToString() + Environment.NewLine + exception);
}
}
public void Trace(string sourceName, TraceEventType type, Exception exception, string format, params object[] args)
{
// Because we know there is a single tracer thread executing these,
// we know it's safe to replace the name without locking.
using (new SourceNameReplacer(source, sourceName))
{
source.TraceEvent(type, 0, string.Format(format, args) + Environment.NewLine + exception);
}
}
/// <summary>
/// The TraceSource instance name matches the name of each of the "segments"
/// we built the aggregate source from. This means that when we trace, we issue
/// multiple trace statements, one for each. If a listener is added to (say) "*"
/// source name, all traces done through it will appear as coming from the source
/// "*", rather than (say) "Foo.Bar" which might be the actual source class.
/// This diminishes the usefulness of hierarchical loggers significantly, since
/// it now means that you need to add listeners too all trace sources you're
/// interested in receiving messages from, and all its "children" potentially,
/// some of them which might not have been created even yet. This is not feasible.
/// Instead, since we issue the trace call to each trace source (which is what
/// enables the configurability of all those sources in the app.config file),
/// we need to fix the source name right before tracing, so that a configured
/// listener at "*" still receives as the source name the original (aggregate) one,
/// and not "*". This requires some private reflection, and a lock to guarantee
/// proper logging, but this decreases its performance. However, since we log
/// asynchronously, it's fine.
/// </summary>
private class SourceNameReplacer : IDisposable
{
// Private reflection needed here in order to make the inherited source names still
// log as if the original source name was the one logging, so as not to lose the
// originating class name.
private static readonly FieldInfo sourceNameField = typeof(TraceSource).GetField("sourceName", BindingFlags.Instance | BindingFlags.NonPublic);
private TraceSource source;
private string originalName;
public SourceNameReplacer(TraceSource source, string sourceName)
{
this.source = source;
this.originalName = source.Name;
// Transient change of the source name while the trace call
// is issued. Multi-threading might still cause messages to come
// out with wrong source names :(
sourceNameField.SetValue(source, sourceName);
}
public void Dispose()
{
sourceNameField.SetValue(source, originalName);
}
}
}
}
}
| |
// --------------------------------------------------------------------------------------------
#region // Copyright (c) 2020, SIL International. All Rights Reserved.
// <copyright from='2011' to='2020' company='SIL International'>
// Copyright (c) 2020, SIL International. All Rights Reserved.
//
// Distributable under the terms of the MIT License (https://sil.mit-license.org/)
// </copyright>
#endregion
// --------------------------------------------------------------------------------------------
using System.Collections.Generic;
using System.IO;
using SIL.IO;
namespace HearThis.Script
{
public class BibleStatsBase
{
public const int kCanonicalBookCount = 66;
private static readonly List<string> s_bookNames;
private static readonly List<string> s_threeLetterAbbreviations;
static BibleStatsBase()
{
s_threeLetterAbbreviations = new List<string>(new[]
{
"Gen",
"Exo",
"Lev",
"Num",
"Deu",
"Jos",
"Jdg",
"Rut",
"1sa",
"2sa",
"1ki",
"2ki",
"1ch",
"2ch",
"Ezr",
"Neh",
"Est",
"Job",
"Psa",
"Pro",
"Ecc",
"Sng",
"Isa",
"Jer",
"Lam",
"Ezk",
"Dan",
"Hos",
"Jol",
"Amo",
"Oba",
"Jon",
"Mic",
"Nam",
"Hab",
"Zep",
"Hag",
"Zec",
"Mal",
"Mat",
"Mrk",
"Luk",
"Jhn",
"Act",
"Rom",
"1co",
"2co",
"Gal",
"Eph",
"Php",
"Col",
"1th",
"2th",
"1ti",
"2ti",
"Tit",
"Phm",
"Heb",
"Jas",
"1pe",
"2pe",
"1jn",
"2jn",
"3jn",
"Jud",
"Rev"
});
s_bookNames = new List<string>(new[]
{
"Genesis",
"Exodus",
"Leviticus",
"Numbers",
"Deuteronomy",
"Joshua",
"Judges",
"Ruth",
"1 Samuel",
"2 Samuel",
"1 Kings",
"2 Kings",
"1 Chronicles",
"2 Chronicles",
"Ezra",
"Nehemiah",
"Esther",
"Job",
"Psalms",
"Proverbs",
"Ecclesiastes",
"Song of Songs",
"Isaiah",
"Jeremiah",
"Lamentations",
"Ezekiel",
"Daniel",
"Hosea",
"Joel",
"Amos",
"Obadiah",
"Jonah",
"Micah",
"Nahum",
"Habakkuk",
"Zephaniah",
"Haggai",
"Zechariah",
"Malachi",
"Matthew",
"Mark",
"Luke",
"John",
"Acts",
"Romans",
"1 Corinthians",
"2 Corinthians",
"Galatians",
"Ephesians",
"Philippians",
"Colossians",
"1 Thessalonians",
"2 Thessalonians",
"1 Timothy",
"2 Timothy",
"Titus",
"Philemon",
"Hebrews",
"James",
"1 Peter",
"2 Peter",
"1 John",
"2 John",
"3 John",
"Jude",
"Revelation"
});
}
public int BookCount => s_bookNames.Count;
/// <summary>Gets the 0-based book index</summary>
public int GetBookNumber(string bookName)
{
return s_bookNames.FindIndex(0, b => b == bookName);
}
/// <summary>Gets the 0-based book index</summary>
public int GetBookNumberFromCode(string bookCode)
{
return s_threeLetterAbbreviations.FindIndex(0, b => b.ToLowerInvariant() == bookCode.ToLowerInvariant());
}
public string GetBookCode(int bookNumber0Based)
{
return s_threeLetterAbbreviations[bookNumber0Based];
}
public string GetBookName(int bookNumber0Based)
{
return s_bookNames[bookNumber0Based];
}
}
public class BibleStats : BibleStatsBase, IBibleStats
{
private readonly List<int> _chaptersPerBook;
private readonly Dictionary<int, int[]> _versesPerChapterPerBook;
public BibleStats()
{
_chaptersPerBook = new List<int>(kCanonicalBookCount);
_versesPerChapterPerBook = new Dictionary<int, int[]>();
int index = 0;
foreach (string line in File.ReadAllLines(FileLocationUtilities.GetFileDistributedWithApplication("chapterCounts.txt")))
{
var parts = line.Trim().Split('\t');
if (parts.Length > 3)
{
_chaptersPerBook.Add(int.Parse(parts[1]));
var verseArray = new List<int>();
for (int i = 3; i < parts.Length; i++)
verseArray.Add(int.Parse(parts[i]));
_versesPerChapterPerBook.Add(index, verseArray.ToArray());
}
++index;
}
}
public int GetVersesInChapter(int bookNumber0Based, int chapterOneBased)
{
return _versesPerChapterPerBook[bookNumber0Based][chapterOneBased - 1];
}
public int GetChaptersInBook(int bookNumber0Based)
{
return _chaptersPerBook[bookNumber0Based];
}
}
}
| |
// 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;
/// <summary>
/// System.Collections.Generic.ICollection<T>.CopyTo(T[],System.Int32)
/// </summary>
public class ICollectionCopyTo
{
private int c_MINI_STRING_LENGTH = 8;
private int c_MAX_STRING_LENGTH = 256;
public static int Main(string[] args)
{
ICollectionCopyTo testObj = new ICollectionCopyTo();
TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.ICollection<T>.CopyTo(T[],System.Int32)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
TestLibrary.TestFramework.LogInformation("[Netativ]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Using List<T> which implemented the CopyTo method in ICollection<T> and Type is Byte...";
const string c_TEST_ID = "P001";
int capacity = 10;
Byte[] byteValue = new Byte[capacity];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
Byte[] array = new Byte[capacity];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).CopyTo(array,0);
for(int i=0;i<capacity;i++)
{
if (list[i] != array[i])
{
string errorDesc = "Value is not " + list[i].ToString() + " as expected: Actual(" + array[i].ToString() + ")";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the CopyTo method in ICollection<T> and Type is a reference type...";
const string c_TEST_ID = "P002";
int capacity = 10;
String[] strValue = new String[capacity];
for (int i = 0; i < capacity; i++)
{
strValue[i] = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
}
List<String> list = new List<String>(strValue);
String[] array = new String[capacity];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<String>)list).CopyTo(array,0);
for(int i=0;i<capacity;i++)
{
if (list[i] != array[i])
{
string errorDesc = "Value is not " + list[i] + " as expected: Actual(" + array[i]+ ")";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Using List<T> which implemented the CopyTo method in ICollection<T> and Type is a user-defined type...";
const string c_TEST_ID = "P003";
int capacity = 10;
List<MyClass> list = new List<MyClass>();
for (int i = 0; i < capacity; i++)
{
list.Add(new MyClass());
}
MyClass[] array = new MyClass[10];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<MyClass>)list).CopyTo(array,0);
for(int i=0;i<capacity;i++)
{
if (list[i] != array[i])
{
string errorDesc = "Value is not " + list[i].ToString() + " as expected: Actual(" + array[i].ToString()+ ")";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Using customer class which implemented the CopyTo method in ICollection<T> and Type is int...";
const string c_TEST_ID = "P004";
int capacity = 10;
MyCollection<int> myC = new MyCollection<int>();
for (int i = 0; i < capacity; i++)
{
myC.Add(TestLibrary.Generator.GetInt32(-55));
}
int[] array = new int[capacity];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<int>)myC).CopyTo(array, 0);
for (int i = 0; i < capacity; i++)
{
if (myC[i] != array[i])
{
string errorDesc = "Value is not " + myC[i].ToString() + " as expected: Actual(" + array[i].ToString() + ")";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest5: Using List<T> which implemented the CopyTo method in ICollection<T> and Index is greater than zero...";
const string c_TEST_ID = "P005";
int capacity = 10;
Byte[] byteValue = new Byte[capacity];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
Random rand = new Random(-55);
int index = rand.Next(1, 100);
Byte[] array = new Byte[capacity+index];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).CopyTo(array, index);
for (int i = 0; i < capacity; i++)
{
if (list[i] != array[i+index])
{
string errorDesc = "Value is not " + list[i].ToString() + " as expected: Actual(" + array[i+index].ToString() + ")";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Using List<T> which implemented the CopyTo method in ICollection<T> and Array is a null reference...";
const string c_TEST_ID = "N001";
int capacity = 10;
Byte[] byteValue = new Byte[capacity];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
Byte[] array = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).CopyTo(array, 0);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "The ArgumentNullException was not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: Using List<T> which implemented the CopyTo method in ICollection<T> and arrayIndex is less than zero...";
const string c_TEST_ID = "N002";
int capacity = 10;
Byte[] byteValue = new Byte[capacity];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
Byte[] array = new Byte[capacity];
int index =TestLibrary.Generator.GetInt32(-55);
index = -index;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).CopyTo(array, index);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "The ArgumentOutOfRangeException was not thrown as expected when arrayindex is " + index.ToString());
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: Using List<T> which implemented the CopyTo method in ICollection<T> and arrayIndex is equal length of array...";
const string c_TEST_ID = "N003";
int capacity = 10;
Byte[] byteValue = new Byte[capacity];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
Byte[] array = new Byte[capacity];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).CopyTo(array, capacity);
TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "The ArgumentException was not thrown as expected");
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest4: Using List<T> which implemented the CopyTo method in ICollection<T> and arrayIndex is grater than length of array...";
const string c_TEST_ID = "N004";
int capacity = 10;
Byte[] byteValue = new Byte[capacity];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
Random rand = new Random(-55);
int index = rand.Next(capacity, 100);
Byte[] array = new Byte[capacity];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).CopyTo(array, index);
TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, "The ArgumentException was not thrown as expected when arrayindex is " + index.ToString());
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest5: Using List<T> which implemented the CopyTo method in ICollection<T> and The number of elements in the list<T> is greater than the available space from arrayIndex to the end of array...";
const string c_TEST_ID = "N005";
int capacity = 10;
Byte[] byteValue = new Byte[capacity];
TestLibrary.Generator.GetBytes(-55, byteValue);
List<Byte> list = new List<Byte>(byteValue);
Random rand = new Random(-55);
int index = rand.Next(1, 10);
Byte[] array = new Byte[capacity];
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((ICollection<Byte>)list).CopyTo(array, index);
TestLibrary.TestFramework.LogError("019" + " TestId-" + c_TEST_ID, "The ArgumentException was not thrown as expected when arrayindex is " + index.ToString());
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help Class
public class MyCollection<T> : ICollection<T>
{
public T[] _items;
protected int length;
public bool isReadOnly = false;
public MyCollection()
{
_items = new T[10];
length = 0;
}
public T this[int index]
{
get
{
// Fllowing trick can reduce the range check by one
if ((uint)index >= (uint)length)
{
throw new ArgumentOutOfRangeException();
}
return _items[index];
}
}
#region ICollection<T> Members
public void Add(T item)
{
if (isReadOnly)
{
throw new NotSupportedException();
}
else
{
_items[length] = item;
length++;
}
}
public void Clear()
{
if (isReadOnly)
{
throw new NotSupportedException();
}
else
{
Array.Clear(_items, 0, length);
length = 0;
}
}
public bool Contains(T item)
{
throw new Exception("The method or operation is not implemented.");
}
public void CopyTo(T[] array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, length);
}
public int Count
{
get { return length; }
}
public bool IsReadOnly
{
get { return isReadOnly; }
}
public bool Remove(T item)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<T> GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
public class MyClass
{ }
#endregion
}
| |
using System.Collections.Generic;
using BlackBox.Service;
using IFC2X3;
using EbInstanceModel;
namespace BlackBox.Predefined
{
/// <summary>
/// Sem definition for material
/// </summary>
public partial class BbMaterial : BbBase
{
[EarlyBindingInstance]
public IfcMaterial IfcMaterial { get; private set; }
[EarlyBindingInstance]
public IfcRelAssociatesMaterial IfcRelAssociatesMaterial { get; private set; }
[EarlyBindingInstance]
public IfcMaterialClassificationRelationship IfcMaterialClassificationRelationship { get; private set; }
[EarlyBindingInstance]
public IfcClassification IfcClassification { get; private set; }
[EarlyBindingInstance]
public IfcClassificationReference IfcClassificationReference { get; private set; }
private List<BbElement> elements;
public string Name
{
get { return IfcMaterial.Name; }
set { IfcMaterial.Name = value; }
}
public string MaterialID { get; private set; }
public string MaterialCert { get; private set; }
public string MaterialGrade { get; private set; }
public string MaterialType { get; private set; }
public BbPropertySet BbPropertySet { get; private set; }
/// <summary>
/// do not use obsolete
/// </summary>
/// <param name="location"></param>
/// <param name="itemReference"></param>
/// <param name="name"></param>
BbMaterial(string location, string itemReference, string name)
{
IfcMaterial = new IfcMaterial
{
Name = name
};
IfcMaterialClassificationRelationship
= new IfcMaterialClassificationRelationship
{
MaterialClassifications = new List<IfcClassificationNotationSelect>(),
ClassifiedMaterial = IfcMaterial,
};
IfcClassificationReference
= new IfcClassificationReference
{
Location = location,
ItemReference = itemReference,
Name = name,
};
var ns
= new IfcClassificationNotationSelect
{
Value = IfcClassificationReference,
};
IfcMaterialClassificationRelationship.MaterialClassifications.Add(ns);
//var ifcMaterialLayer = new IfcMaterialLayer
// {
// Material = IfcMaterial,
// LayerThickness = new IfcPositiveLengthMeasure { Value = 0.0 },
// };
//var ifcMaterialLayerSet = new IfcMaterialLayerSet
// {
// MaterialLayers = new List<IfcMaterialLayer>(),
// };
//ifcMaterialLayerSet.MaterialLayers.Add(ifcMaterialLayer);
//var ifcMaterialLayerSetUsage = new IfcMaterialLayerSetUsage
// {
// ForLayerSet = ifcMaterialLayerSet,
// LayerSetDirection = IfcLayerSetDirectionEnum.
// };
}
private BbMaterial()
{
}
BbMaterial(string name)
{
IfcMaterial = new IfcMaterial
{
Name = name
};
}
public static BbMaterial Create(string location, string itemReference, string name)
{
var material = new BbMaterial(location, itemReference, name);
BbInstanceDB.AddToExport(material);
return material;
}
public static BbMaterial Create(string name,
BbPropertySet bbPropertySet,
string materialID,
string materialCert,
string materialGrade,
string materialType)
{
var material = new BbMaterial(name);
material.AddMaterialProperty(bbPropertySet, materialID, materialCert, materialGrade, materialType);
BbInstanceDB.AddToExport(material);
return material;
}
public void AddMaterialProperty(
BbPropertySet bbPropertySet,
string materialID,
string materialCert,
string materialGrade,
string materialType)
{
BbPropertySet = bbPropertySet;
MaterialID = materialID;
MaterialCert = materialCert;
MaterialGrade = materialGrade;
MaterialType = materialType;
if (!string.IsNullOrWhiteSpace(materialID))
BbPropertySet.AddProperty(BbSingleProperty.Create("Material ID", materialID, true));
if (!string.IsNullOrWhiteSpace(materialCert))
BbPropertySet.AddProperty(BbSingleProperty.Create("Material Certification", materialCert, true));
if (!string.IsNullOrWhiteSpace(materialGrade))
BbPropertySet.AddProperty(BbSingleProperty.Create("Material Grade", materialGrade, true));
if (!string.IsNullOrWhiteSpace(materialType))
BbPropertySet.AddProperty(BbSingleProperty.Create("Material Type", materialType, true));
}
public void AssociateTo(BbElement element)
{
if (IfcRelAssociatesMaterial == null)
{
IfcRelAssociatesMaterial = new IfcRelAssociatesMaterial
{
GlobalId = IfcGloballyUniqueId.NewGuid(),
OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
RelatingMaterial = new IfcMaterialSelect(),
RelatedObjects = new List<IfcRoot>(),
};
IfcRelAssociatesMaterial.RelatingMaterial.Value = IfcMaterial;
}
if (elements == null)
{
elements = new List<BbElement>();
}
elements.Add(element);
IfcRelAssociatesMaterial.RelatedObjects.Add(element.IfcObject);
AssignTo(element);
}
void AssignTo(BbElement element)
{
//element.IfcElement.Name = Name;
BbPropertySet.AssignTo(element);
}
// todo material representation
public override bool Validate(bool doValidate)
{
if (IfcMaterial == null) return false;
// todo validation of IfcMaterial itself, should do it in itself or here?
// todo validate EIN here? for IfcMaterial.EIN
if (string.IsNullOrWhiteSpace(Name)) return false;
return true;
}
public static BbMaterial Retrieve(BbElement element)
{
var ret = new BbMaterial();
//if (!EarlyBindingInstanceModel.TheModel.DataByType.ContainsKey("IfcRelAssociatesMaterial")) return null;
var collection = EarlyBindingInstanceModel.GetDataByType("IfcRelAssociatesMaterial").Values;
//if (collection.Count != 1) throw new NotImplementedException();
foreach (var item in collection)
{
var theItem = item as IfcRelAssociatesMaterial;
if (theItem == null) continue;
//if (theItem.RelatingMaterial.AIfcMaterial.EIN == element.IfcElement.EIN)
foreach (var a in theItem.RelatedObjects)
{
if (a.EIN == element.IfcObject.EIN)
{
//if (!EarlyBindingInstanceModel.TheModel.DataByType.ContainsKey("IfcMaterial")) return null;
var collection2 = EarlyBindingInstanceModel.GetDataByType("IfcMaterial").Values;
foreach (var item2 in collection2)
{
if (item2.EIN == theItem.RelatingMaterial.AIfcMaterial.EIN)
{
var material = item as IfcMaterial;
if (material == null) continue;
var pieceMaterial = new BbMaterial { IfcMaterial = material };
BbInstanceDB.AddToExport(pieceMaterial);
ret = pieceMaterial;
}
}
}
else { ret = null; }
}
}
return ret;
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright 2011 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Websites.Services.WebEntities
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Utilities;
public interface ISiteConfig
{
int? NumberOfWorkers { get; set; }
string[] DefaultDocuments { get; set; }
string NetFrameworkVersion { get; set; }
string PhpVersion { get; set; }
bool? RequestTracingEnabled { get; set; }
bool? HttpLoggingEnabled { get; set; }
bool? DetailedErrorLoggingEnabled { get; set; }
Hashtable AppSettings { get; set; }
List<NameValuePair> Metadata { get; set; }
ConnStringPropertyBag ConnectionStrings { get; set; }
HandlerMapping[] HandlerMappings { get; set; }
}
public class SiteWithConfig : ISite, ISiteConfig
{
private Site Site { get; set; }
private SiteConfig SiteConfig { set; get; }
public SiteWithConfig()
{
Site = new Site();
SiteConfig = new SiteConfig();
AppSettings = new Hashtable();
}
public SiteWithConfig(Site site, SiteConfig siteConfig)
{
Site = site;
SiteConfig = siteConfig;
AppSettings = new Hashtable();
if (SiteConfig.AppSettings != null)
{
foreach (var setting in SiteConfig.AppSettings)
{
AppSettings[setting.Name] = setting.Value;
}
}
}
public SiteConfig GetSiteConfig()
{
if (AppSettings != null)
{
SiteConfig.AppSettings = new List<NameValuePair>();
foreach (var setting in AppSettings.Keys)
{
SiteConfig.AppSettings.Add(new NameValuePair
{
Name = (string)setting,
Value = (string)AppSettings[setting]
});
}
}
return SiteConfig;
}
public Site GetSite()
{
return Site;
}
public int? NumberOfWorkers
{
get { return SiteConfig.NumberOfWorkers; }
set { SiteConfig.NumberOfWorkers = value; }
}
public string[] DefaultDocuments
{
get { return SiteConfig.DefaultDocuments; }
set { SiteConfig.DefaultDocuments = value; }
}
public string NetFrameworkVersion
{
get { return SiteConfig.NetFrameworkVersion; }
set { SiteConfig.NetFrameworkVersion = value; }
}
public string PhpVersion
{
get { return SiteConfig.PhpVersion; }
set { SiteConfig.PhpVersion = value; }
}
public bool? RequestTracingEnabled
{
get { return SiteConfig.RequestTracingEnabled; }
set { SiteConfig.RequestTracingEnabled = value; }
}
public bool? HttpLoggingEnabled
{
get { return SiteConfig.HttpLoggingEnabled; }
set { SiteConfig.HttpLoggingEnabled = value; }
}
public bool? DetailedErrorLoggingEnabled
{
get { return SiteConfig.DetailedErrorLoggingEnabled; }
set { SiteConfig.DetailedErrorLoggingEnabled = value; }
}
public string PublishingUsername
{
get { return SiteConfig.PublishingUsername; }
set { SiteConfig.PublishingUsername = value; }
}
public string PublishingPassword
{
get { return SiteConfig.PublishingPassword; }
set { SiteConfig.PublishingPassword = value; }
}
public Hashtable AppSettings { get; set; }
public List<NameValuePair> Metadata
{
get { return SiteConfig.Metadata; }
set { SiteConfig.Metadata = value; }
}
public ConnStringPropertyBag ConnectionStrings
{
get { return SiteConfig.ConnectionStrings; }
set { SiteConfig.ConnectionStrings = value; }
}
public HandlerMapping[] HandlerMappings
{
get { return SiteConfig.HandlerMappings; }
set { SiteConfig.HandlerMappings = value; }
}
public string Name
{
get { return Site.Name; }
set { Site.Name = value; }
}
public string State
{
get { return Site.State; }
set { Site.State = value; }
}
public string[] HostNames
{
get { return Site.HostNames; }
set { Site.HostNames = value; }
}
public string WebSpace
{
get { return Site.WebSpace; }
set { Site.WebSpace = value; }
}
public Uri SelfLink
{
get { return Site.SelfLink; }
set { Site.SelfLink = value; }
}
public string RepositorySiteName
{
get { return Site.RepositorySiteName; }
set { Site.RepositorySiteName = value; }
}
public string Owner
{
get { return Site.Owner; }
set { Site.Owner = value; }
}
public UsageState UsageState
{
get { return Site.UsageState; }
set { Site.UsageState = value; }
}
public bool? Enabled
{
get { return Site.Enabled; }
set { Site.Enabled = value; }
}
public bool? AdminEnabled
{
get { return Site.AdminEnabled; }
set { Site.AdminEnabled = value; }
}
public string[] EnabledHostNames
{
get { return Site.EnabledHostNames; }
set { Site.EnabledHostNames = value; }
}
public SiteProperties SiteProperties
{
get { return Site.SiteProperties; }
set { Site.SiteProperties = value; }
}
public SiteAvailabilityState AvailabilityState
{
get { return Site.AvailabilityState; }
set { Site.AvailabilityState = value; }
}
public Certificate[] SSLCertificates
{
get { return Site.SSLCertificates; }
set { Site.SSLCertificates = value; }
}
public string SiteMode
{
get { return Site.SiteMode; }
set { Site.SiteMode = value; }
}
public HostNameSslStates HostNameSslStates
{
get { return Site.HostNameSslStates; }
set { Site.HostNameSslStates = value; }
}
}
[DataContract(Namespace = UriElements.ServiceNamespace)]
public class SiteConfig
{
[DataMember(IsRequired = false)]
public int? NumberOfWorkers { get; set; }
[DataMember(IsRequired = false)]
public string[] DefaultDocuments { get; set; }
[DataMember(IsRequired = false)]
public string NetFrameworkVersion { get; set; }
[DataMember(IsRequired = false)]
public string PhpVersion { get; set; }
[DataMember(IsRequired = false)]
public bool? RequestTracingEnabled { get; set; }
[DataMember(IsRequired = false)]
public bool? HttpLoggingEnabled { get; set; }
[DataMember(IsRequired = false)]
public bool? DetailedErrorLoggingEnabled { get; set; }
[DataMember(IsRequired = false)]
public string PublishingUsername { get; set; }
[DataMember(IsRequired = false)]
[PIIValue]
public string PublishingPassword { get; set; }
[DataMember(IsRequired = false)]
public List<NameValuePair> AppSettings { get; set; }
[DataMember(IsRequired = false)]
public List<NameValuePair> Metadata { get; set; }
[DataMember(IsRequired = false)]
public ConnStringPropertyBag ConnectionStrings { get; set; }
[DataMember(IsRequired = false)]
public HandlerMapping[] HandlerMappings { get; set; }
}
}
| |
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text;
using Pash;
using Pash.Implementation;
namespace System.Management.Automation
{
/// <summary>
/// Represents and contains information about a cmdlet.
/// </summary>
public class CmdletInfo : CommandInfo, IScopedItem
{
public string HelpFile { get; private set; }
public Type ImplementingType { get; private set; }
public string Noun { get; private set; }
public PSSnapInInfo PSSnapIn { get; private set; }
public string Verb { get; private set; }
public ReadOnlyCollection<CommandParameterSetInfo> ParameterSets { get; private set; }
public override ReadOnlyCollection<PSTypeName> OutputType {
get { return outputType; }
}
internal Dictionary<string, CommandParameterInfo> ParameterInfoLookupTable { get; private set; }
private Exception _validationException;
private ReadOnlyCollection<PSTypeName> outputType;
internal CmdletInfo(string name, Type implementingType, string helpFile)
: this(name, implementingType, helpFile, null, null)
{
}
internal CmdletInfo(string name, Type implementingType, string helpFile, PSSnapInInfo snapin)
: this(name, implementingType, helpFile, snapin, null)
{
}
internal CmdletInfo(string name, Type implementingType, string helpFile, PSModuleInfo module)
: this(name, implementingType, helpFile, null, module)
{
}
internal CmdletInfo(string name, Type implementingType, string helpFile, PSSnapInInfo snapin, PSModuleInfo module)
: base(name, CommandTypes.Cmdlet)
{
int i = name.IndexOf('-');
if (i == -1)
{
throw new Exception("InvalidCmdletNameFormat " + name);
}
ParameterInfoLookupTable = new Dictionary<string, CommandParameterInfo>(StringComparer.CurrentCultureIgnoreCase);
Verb = name.Substring(0, i);
Noun = name.Substring(i + 1);
ImplementingType = implementingType;
HelpFile = helpFile;
_validationException = null;
PSSnapIn = snapin;
Module = module;
InitializeParameterSetInfo(implementingType);
InitializeOutputTypes(implementingType);
}
public override string Definition
{
get
{
StringBuilder str = new StringBuilder();
foreach (CommandParameterSetInfo pSet in ParameterSets)
{
str.AppendLine(string.Format("{0}-{1} {2}", Verb, Noun, pSet));
}
return str.ToString();
}
}
internal override void Validate()
{
if (_validationException != null)
{
throw _validationException;
}
}
private void RegisterParameterInLookupTable(CommandParameterInfo parameterInfo)
{
// also add it to lookuptable and check for unuque names/aliases
var allNames = parameterInfo.Aliases.ToList();
allNames.Add(parameterInfo.Name);
foreach (var curName in allNames)
{
if (ParameterInfoLookupTable.ContainsKey(curName))
{
// save exception to be thrown when this object is validated, not now
var msg = String.Format("The name or alias '{0}' is used multiple times.", curName);
_validationException = new MetadataException(msg);
continue;
}
ParameterInfoLookupTable[curName] = parameterInfo;
}
}
internal CommandParameterInfo LookupParameter(string name)
{
// check for complete name first
if (ParameterInfoLookupTable.ContainsKey(name))
{
return ParameterInfoLookupTable[name];
}
// if we didn't find it by name or alias, try to find it by prefix
var candidates = (from key in ParameterInfoLookupTable.Keys
where key.StartsWith(name, StringComparison.OrdinalIgnoreCase)
select key).ToList();
if (candidates.Count < 1)
{
return null;
}
if (candidates.Count > 1)
{
var msg = String.Format("Supplied parmameter '{0}' is ambiguous, possibilities are: {1}",
name, String.Join(", ", candidates));
throw new ParameterBindingException(msg, "AmbiguousParameter");
}
return ParameterInfoLookupTable[candidates[0]];
}
private void AddParameterToParameterSet(Dictionary<string, Collection<CommandParameterInfo>> paramSets,
CommandParameterInfo paramInfo)
{
var paramSetName = paramInfo.ParameterSetName;
// create the parameter set if it doesn't exist, yet
if (!paramSets.ContainsKey(paramSetName))
{
paramSets.Add(paramSetName, new Collection<CommandParameterInfo>());
}
Collection<CommandParameterInfo> paramSet = paramSets[paramSetName];
// actually add parameter to the set
paramSet.Add(paramInfo);
}
/// <remarks>
/// From MSDN article: http://msdn2.microsoft.com/en-us/library/ms714348(VS.85).aspx
///
/// * A cmdlet can have any number of parameters. However, for a better user experience the number
/// of parameters should be limited when possible.
/// * Parameters must be declared on public non-static fields or properties. It is preferred for
/// parameters to be declared on properties. The property must have a public setter, and if ValueFromPipeline
/// or ValueFromPipelineByPropertyName is specified the property must have a public getter.
/// * When specifying positional parameters, note the following.
/// * Limit the number of positional parameters in a parameter set to less than five if possible.
/// * Positional parameters do not have to be sequential; positions 5, 100, 250 works the same as positions 0, 1, 2.
/// * When the Position keyword is not specified, the cmdlet parameter must be referenced by its name.
/// * When using parameter sets, no parameter set should contain more than one positional parameter with the same position.
/// * In addition, only one parameter in a set should declare ValueFromPipeline = true. Multiple parameters may define ValueFromPipelineByPropertyName = true.
///
/// </remarks>
private void InitializeParameterSetInfo(Type cmdletType)
{
Dictionary<string, Collection<CommandParameterInfo>> paramSets = new Dictionary<string, Collection<CommandParameterInfo>>(StringComparer.CurrentCultureIgnoreCase);
// TODO: When using parameter sets, no parameter set should contain more than one positional parameter with the same position.
// TODO: If not parameters have a position declared then positions for all the parameters should be automatically declaredin the order they are specified
// TODO: Only one parameter in a set should declare ValueFromRemainingArguments = true
// TODO: Only one parameter in a set should declare ValueFromPipeline = true. Multiple parameters may define ValueFromPipelineByPropertyName = true.
// TODO: Currently due to the way parameters are loaded into sets from all set at the end the parameter end up in incorrect order.
// get the name of the default parameter set
string strDefaultParameterSetName = null;
object[] cmdLetAttrs = cmdletType.GetCustomAttributes(typeof(CmdletAttribute), false);
if (cmdLetAttrs.Length > 0)
{
strDefaultParameterSetName = ((CmdletAttribute)cmdLetAttrs[0]).DefaultParameterSetName;
// If a default set is specified, it has to exist, even if it's empty.
// See NonExisitingDefaultParameterSetIsEmptyPatameterSet reference test
if (!String.IsNullOrEmpty(strDefaultParameterSetName))
{
paramSets.Add(strDefaultParameterSetName, new Collection<CommandParameterInfo>());
}
}
// always have a parameter set for all parameters. even if we don't have any parameters or no parameters
// that are in all sets. This will nevertheless save various checks
if (!paramSets.ContainsKey(ParameterAttribute.AllParameterSets)) {
paramSets.Add(ParameterAttribute.AllParameterSets, new Collection<CommandParameterInfo>());
}
var parameterDiscovery = new CommandParameterDiscovery(cmdletType);
// first add the parameters to the parameter sets
foreach (var parameter in parameterDiscovery.AllParameters)
{
AddParameterToParameterSet(paramSets, parameter);
}
// now add each parameter member to the lookup table
foreach (var namedParam in parameterDiscovery.NamedParameters.Values)
{
RegisterParameterInLookupTable(namedParam);
}
// Create param-sets collection. Add the parameters from the AllParameterSets set to all other sets
Collection<CommandParameterSetInfo> paramSetInfo = new Collection<CommandParameterSetInfo>();
foreach (string paramSetName in paramSets.Keys)
{
// If a parameter set is not specified for a parmeter, then the parameter belongs to all the parameter sets,
// therefore if this is not the AllParameterSets Set then add all parameters from the AllParameterSets Set to it...
if (!paramSetName.Equals(ParameterAttribute.AllParameterSets))
{
foreach (CommandParameterInfo cpi in paramSets[ParameterAttribute.AllParameterSets])
{
paramSets[paramSetName].Add(cpi);
}
}
// add the set to the setInfo collection
bool bIsDefaultParamSet = paramSetName.Equals(strDefaultParameterSetName);
paramSetInfo.Add(new CommandParameterSetInfo(paramSetName, bIsDefaultParamSet, paramSets[paramSetName]));
}
ParameterSets = new ReadOnlyCollection<CommandParameterSetInfo>(paramSetInfo);
// last, but not least, at all common parameters to all parameter sets
AddParametersToAllSets(CommonCmdletParameters.ParameterDiscovery);
}
internal CommandParameterSetInfo GetParameterSetByName(string strParamSetName)
{
foreach (CommandParameterSetInfo paramSetInfo in ParameterSets)
{
if (string.Compare(strParamSetName, paramSetInfo.Name, true) == 0)
return paramSetInfo;
}
return null;
}
internal CommandParameterSetInfo GetDefaultParameterSet()
{
// TODO: get by name
foreach (CommandParameterSetInfo paramSetInfo in ParameterSets)
{
if (paramSetInfo.IsDefault)
return paramSetInfo;
}
return null;
}
internal ReadOnlyCollection<CommandParameterSetInfo> GetNonDefaultParameterSets()
{
return new ReadOnlyCollection<CommandParameterSetInfo>(ParameterSets.Where(x => !x.IsDefault).ToList());
}
internal void AddParametersToAllSets(CommandParameterDiscovery discovery)
{
// add the parameters to all sets
var updatedParameterSets = new List<CommandParameterSetInfo>();
foreach (CommandParameterSetInfo parameterSet in ParameterSets)
{
List<CommandParameterInfo> updatedParameters = parameterSet.Parameters.ToList();
updatedParameters.AddRange(discovery.AllParameters);
updatedParameterSets.Add(new CommandParameterSetInfo(
parameterSet.Name,
parameterSet.IsDefault,
new Collection<CommandParameterInfo>(updatedParameters)));
}
ParameterSets = new ReadOnlyCollection<CommandParameterSetInfo>(updatedParameterSets);
// register all parameter names in the lookup table
foreach (var namedParameter in discovery.NamedParameters.Values)
{
RegisterParameterInLookupTable(namedParameter);
}
}
private void InitializeOutputTypes(Type cmdletType)
{
var types = new List<PSTypeName>();
foreach (OutputTypeAttribute attribute in cmdletType.GetCustomAttributes(typeof(OutputTypeAttribute), false))
{
types.AddRange(attribute.Type);
}
outputType = new ReadOnlyCollection<PSTypeName>(types);
}
#region IScopedItem Members
public string ItemName
{
get { return Name; }
}
public ScopedItemOptions ItemOptions
{
get { return ScopedItemOptions.None; }
set { throw new NotImplementedException("Setting scope options for cmdlets is not supported"); }
}
#endregion
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using Lucene.Net.Support.IO;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Util
{
//using RandomInts = com.carrotsearch.randomizedtesting.generators.RandomInts;
//using RandomPicks = com.carrotsearch.randomizedtesting.generators.RandomPicks;
using AtomicReader = Lucene.Net.Index.AtomicReader;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BinaryDocValuesField = BinaryDocValuesField;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Codec = Lucene.Net.Codecs.Codec;
//using CheckIndex = Lucene.Net.Index.CheckIndex;
using Directory = Lucene.Net.Store.Directory;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using Document = Documents.Document;
using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat;
using DocValuesType = Lucene.Net.Index.DocValuesType;
using DoubleField = DoubleField;
using Field = Field;
using FieldDoc = Lucene.Net.Search.FieldDoc;
using FieldType = FieldType;
using FilteredQuery = Lucene.Net.Search.FilteredQuery;
using IIndexableField = Lucene.Net.Index.IIndexableField;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Int32Field = Int32Field;
using Int64Field = Int64Field;
using LogMergePolicy = Lucene.Net.Index.LogMergePolicy;
using Lucene46Codec = Lucene.Net.Codecs.Lucene46.Lucene46Codec;
using MergePolicy = Lucene.Net.Index.MergePolicy;
using MergeScheduler = Lucene.Net.Index.MergeScheduler;
using MultiFields = Lucene.Net.Index.MultiFields;
using NumericDocValuesField = NumericDocValuesField;
using PerFieldDocValuesFormat = Lucene.Net.Codecs.PerField.PerFieldDocValuesFormat;
using PerFieldPostingsFormat = Lucene.Net.Codecs.PerField.PerFieldPostingsFormat;
using PostingsFormat = Lucene.Net.Codecs.PostingsFormat;
using ScoreDoc = Lucene.Net.Search.ScoreDoc;
using SingleField = SingleField;
using SortedDocValuesField = SortedDocValuesField;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TieredMergePolicy = Lucene.Net.Index.TieredMergePolicy;
using TopDocs = Lucene.Net.Search.TopDocs;
/// <summary>
/// General utility methods for Lucene unit tests.
/// </summary>
public static class TestUtil
{
public static void Rm(params DirectoryInfo[] locations)
{
HashSet<FileSystemInfo> unremoved = Rm(new HashSet<FileSystemInfo>(), locations);
if (unremoved.Any())
{
StringBuilder b = new StringBuilder("Could not remove the following files (in the order of attempts):\n");
foreach (var f in unremoved)
{
b.append(" ")
.append(f.FullName)
.append("\n");
}
throw new IOException(b.toString());
}
}
private static HashSet<FileSystemInfo> Rm(HashSet<FileSystemInfo> unremoved, params DirectoryInfo[] locations)
{
foreach (DirectoryInfo location in locations)
{
if (location.Exists)
{
// Try to delete all of the files in the directory
Rm(unremoved, location.GetFiles());
//Delete will throw if not empty when deleted
try
{
location.Delete();
}
catch (Exception)
{
unremoved.Add(location);
}
}
}
return unremoved;
}
private static HashSet<FileSystemInfo> Rm(HashSet<FileSystemInfo> unremoved, params FileInfo[] locations)
{
foreach (FileInfo file in locations)
{
if (file.Exists)
{
try
{
file.Delete();
}
catch (Exception delFailed)
{
Console.WriteLine(delFailed.Message);
unremoved.Add(file);
}
}
}
return unremoved;
}
public static void Unzip(Stream zipFileStream, DirectoryInfo destDir)
{
Rm(destDir);
destDir.Create();
using (ZipArchive zip = new ZipArchive(zipFileStream))
{
foreach (var entry in zip.Entries)
{
// Ignore internal folders - these are tacked onto the FullName anyway
if (entry.FullName.EndsWith("/", StringComparison.Ordinal) || entry.FullName.EndsWith("\\", StringComparison.Ordinal))
{
continue;
}
using (Stream input = entry.Open())
{
FileInfo targetFile = new FileInfo(CorrectPath(Path.Combine(destDir.FullName, entry.FullName)));
if (!targetFile.Directory.Exists)
{
targetFile.Directory.Create();
}
using (Stream output = new FileStream(targetFile.FullName, FileMode.Create, FileAccess.Write))
{
input.CopyTo(output);
}
}
}
}
}
private static string CorrectPath(string input)
{
if (Path.DirectorySeparatorChar.Equals('/'))
{
return input.Replace('\\', '/');
}
return input.Replace('/', '\\');
}
public static void SyncConcurrentMerges(IndexWriter writer)
{
SyncConcurrentMerges(writer.Config.MergeScheduler);
}
public static void SyncConcurrentMerges(IMergeScheduler ms)
{
if (ms is IConcurrentMergeScheduler)
{
((IConcurrentMergeScheduler)ms).Sync();
}
}
/// <summary>
/// this runs the CheckIndex tool on the index in. If any
/// issues are hit, a RuntimeException is thrown; else,
/// true is returned.
/// </summary>
public static CheckIndex.Status CheckIndex(Directory dir)
{
return CheckIndex(dir, true);
}
public static CheckIndex.Status CheckIndex(Directory dir, bool crossCheckTermVectors)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
CheckIndex checker = new CheckIndex(dir);
checker.CrossCheckTermVectors = crossCheckTermVectors;
checker.InfoStream = new StreamWriter(bos, Encoding.UTF8);
CheckIndex.Status indexStatus = checker.DoCheckIndex(null);
if (indexStatus == null || indexStatus.Clean == false)
{
Console.WriteLine("CheckIndex failed");
checker.FlushInfoStream();
Console.WriteLine(bos.ToString());
throw new Exception("CheckIndex failed");
}
else
{
if (LuceneTestCase.INFOSTREAM)
{
checker.FlushInfoStream();
Console.WriteLine(bos.ToString());
}
return indexStatus;
}
}
/// <summary>
/// this runs the CheckIndex tool on the Reader. If any
/// issues are hit, a RuntimeException is thrown
/// </summary>
public static void CheckReader(IndexReader reader)
{
foreach (AtomicReaderContext context in reader.Leaves)
{
CheckReader(context.AtomicReader, true);
}
}
public static void CheckReader(AtomicReader reader, bool crossCheckTermVectors)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
StreamWriter infoStream = new StreamWriter(bos, Encoding.UTF8);
reader.CheckIntegrity();
CheckIndex.Status.FieldNormStatus fieldNormStatus = Index.CheckIndex.TestFieldNorms(reader, infoStream);
CheckIndex.Status.TermIndexStatus termIndexStatus = Index.CheckIndex.TestPostings(reader, infoStream);
CheckIndex.Status.StoredFieldStatus storedFieldStatus = Index.CheckIndex.TestStoredFields(reader, infoStream);
CheckIndex.Status.TermVectorStatus termVectorStatus = Index.CheckIndex.TestTermVectors(reader, infoStream, false, crossCheckTermVectors);
CheckIndex.Status.DocValuesStatus docValuesStatus = Index.CheckIndex.TestDocValues(reader, infoStream);
if (fieldNormStatus.Error != null || termIndexStatus.Error != null || storedFieldStatus.Error != null || termVectorStatus.Error != null || docValuesStatus.Error != null)
{
Console.WriteLine("CheckReader failed");
infoStream.Flush();
Console.WriteLine(bos.ToString());
throw new Exception("CheckReader failed");
}
else
{
if (LuceneTestCase.INFOSTREAM)
{
Console.WriteLine(bos.ToString());
}
}
}
/// <summary>
/// start and end are BOTH inclusive </summary>
public static int NextInt(Random r, int start, int end)
{
return RandomInts.NextIntBetween(r, start, end);
}
/// <summary>
/// start and end are BOTH inclusive </summary>
public static long NextLong(Random r, long start, long end)
{
Assert.True(end >= start);
BigInteger range = (BigInteger)end + (BigInteger)1 - (BigInteger)start;
if (range.CompareTo((BigInteger)int.MaxValue) <= 0)
{
return start + r.Next((int)range);
}
else
{
// probably not evenly distributed when range is large, but OK for tests
BigInteger augend = new BigInteger(end + 1 - start) * (BigInteger)(r.NextDouble());
long result = start + (long)augend;
Assert.True(result >= start);
Assert.True(result <= end);
return result;
}
}
public static string RandomSimpleString(Random r, int maxLength)
{
return RandomSimpleString(r, 0, maxLength);
}
public static string RandomSimpleString(Random r, int minLength, int maxLength)
{
int end = NextInt(r, minLength, maxLength);
if (end == 0)
{
// allow 0 length
return "";
}
char[] buffer = new char[end];
for (int i = 0; i < end; i++)
{
buffer[i] = (char)TestUtil.NextInt(r, 'a', 'z');
}
return new string(buffer, 0, end);
}
public static string RandomSimpleStringRange(Random r, char minChar, char maxChar, int maxLength)
{
int end = NextInt(r, 0, maxLength);
if (end == 0)
{
// allow 0 length
return "";
}
char[] buffer = new char[end];
for (int i = 0; i < end; i++)
{
buffer[i] = (char)TestUtil.NextInt(r, minChar, maxChar);
}
return new string(buffer, 0, end);
}
public static string RandomSimpleString(Random r)
{
return RandomSimpleString(r, 0, 20);
}
/// <summary>
/// Returns random string, including full unicode range. </summary>
public static string RandomUnicodeString(Random r)
{
return RandomUnicodeString(r, 20);
}
/// <summary>
/// Returns a random string up to a certain length.
/// </summary>
public static string RandomUnicodeString(Random r, int maxLength)
{
int end = NextInt(r, 0, maxLength);
if (end == 0)
{
// allow 0 length
return "";
}
char[] buffer = new char[end];
RandomFixedLengthUnicodeString(r, buffer, 0, buffer.Length);
return new string(buffer, 0, end);
}
/// <summary>
/// Fills provided char[] with valid random unicode code
/// unit sequence.
/// </summary>
public static void RandomFixedLengthUnicodeString(Random random, char[] chars, int offset, int length)
{
int i = offset;
int end = offset + length;
while (i < end)
{
int t = random.Next(5);
if (0 == t && i < length - 1)
{
// Make a surrogate pair
// High surrogate
chars[i++] = (char)NextInt(random, 0xd800, 0xdbff);
// Low surrogate
chars[i++] = (char)NextInt(random, 0xdc00, 0xdfff);
}
else if (t <= 1)
{
chars[i++] = (char)random.Next(0x80);
}
else if (2 == t)
{
chars[i++] = (char)NextInt(random, 0x80, 0x7ff);
}
else if (3 == t)
{
chars[i++] = (char)NextInt(random, 0x800, 0xd7ff);
}
else if (4 == t)
{
chars[i++] = (char)NextInt(random, 0xe000, 0xffff);
}
}
}
/// <summary>
/// Returns a String thats "regexpish" (contains lots of operators typically found in regular expressions)
/// If you call this enough times, you might get a valid regex!
/// </summary>
public static string RandomRegexpishString(Random r)
{
return RandomRegexpishString(r, 20);
}
/// <summary>
/// Maximum recursion bound for '+' and '*' replacements in
/// <seealso cref="#randomRegexpishString(Random, int)"/>.
/// </summary>
private const int MaxRecursionBound = 5;
/// <summary>
/// Operators for <seealso cref="#randomRegexpishString(Random, int)"/>.
/// </summary>
private static readonly IList<string> Ops = Arrays.AsList(".", "?", "{0," + MaxRecursionBound + "}", "{1," + MaxRecursionBound + "}", "(", ")", "-", "[", "]", "|"); // bounded replacement for '+' - bounded replacement for '*'
/// <summary>
/// Returns a String thats "regexpish" (contains lots of operators typically found in regular expressions)
/// If you call this enough times, you might get a valid regex!
///
/// <P>Note: to avoid practically endless backtracking patterns we replace asterisk and plus
/// operators with bounded repetitions. See LUCENE-4111 for more info.
/// </summary>
/// <param name="maxLength"> A hint about maximum length of the regexpish string. It may be exceeded by a few characters. </param>
public static string RandomRegexpishString(Random r, int maxLength)
{
StringBuilder regexp = new StringBuilder(maxLength);
for (int i = NextInt(r, 0, maxLength); i > 0; i--)
{
if (r.NextBoolean())
{
regexp.Append((char)RandomInts.NextIntBetween(r, 'a', 'z'));
}
else
{
regexp.Append(RandomInts.RandomFrom(r, Ops));
}
}
return regexp.ToString();
}
private static readonly string[] HTML_CHAR_ENTITIES = new string[]
{
"AElig", "Aacute", "Acirc", "Agrave", "Alpha", "AMP", "Aring", "Atilde", "Auml", "Beta", "COPY", "Ccedil", "Chi",
"Dagger", "Delta", "ETH", "Eacute", "Ecirc", "Egrave", "Epsilon", "Eta", "Euml", "Gamma", "GT", "Iacute", "Icirc",
"Igrave", "Iota", "Iuml", "Kappa", "Lambda", "LT", "Mu", "Ntilde", "Nu", "OElig", "Oacute", "Ocirc", "Ograve",
"Omega", "Omicron", "Oslash", "Otilde", "Ouml", "Phi", "Pi", "Prime", "Psi", "QUOT", "REG", "Rho", "Scaron",
"Sigma", "THORN", "Tau", "Theta", "Uacute", "Ucirc", "Ugrave", "Upsilon", "Uuml", "Xi", "Yacute", "Yuml", "Zeta",
"aacute", "acirc", "acute", "aelig", "agrave", "alefsym", "alpha", "amp", "and", "ang", "apos", "aring", "asymp",
"atilde", "auml", "bdquo", "beta", "brvbar", "bull", "cap", "ccedil", "cedil", "cent", "chi", "circ", "clubs",
"cong", "copy", "crarr", "cup", "curren", "dArr", "dagger", "darr", "deg", "delta", "diams", "divide", "eacute",
"ecirc", "egrave", "empty", "emsp", "ensp", "epsilon", "equiv", "eta", "eth", "euml", "euro", "exist", "fnof",
"forall", "frac12", "frac14", "frac34", "frasl", "gamma", "ge", "gt", "hArr", "harr", "hearts", "hellip", "iacute",
"icirc", "iexcl", "igrave", "image", "infin", "int", "iota", "iquest", "isin", "iuml", "kappa", "lArr", "lambda",
"lang", "laquo", "larr", "lceil", "ldquo", "le", "lfloor", "lowast", "loz", "lrm", "lsaquo", "lsquo", "lt", "macr",
"mdash", "micro", "middot", "minus", "mu", "nabla", "nbsp", "ndash", "ne", "ni", "not", "notin", "nsub", "ntilde",
"nu", "oacute", "ocirc", "oelig", "ograve", "oline", "omega", "omicron", "oplus", "or", "ordf", "ordm", "oslash",
"otilde", "otimes", "ouml", "para", "part", "permil", "perp", "phi", "pi", "piv", "plusmn", "pound", "prime", "prod",
"prop", "psi", "quot", "rArr", "radic", "rang", "raquo", "rarr", "rceil", "rdquo", "real", "reg", "rfloor", "rho",
"rlm", "rsaquo", "rsquo", "sbquo", "scaron", "sdot", "sect", "shy", "sigma", "sigmaf", "sim", "spades", "sub", "sube",
"sum", "sup", "sup1", "sup2", "sup3", "supe", "szlig", "tau", "there4", "theta", "thetasym", "thinsp", "thorn", "tilde",
"times", "trade", "uArr", "uacute", "uarr", "ucirc", "ugrave", "uml", "upsih", "upsilon", "uuml", "weierp", "xi",
"yacute", "yen", "yuml", "zeta", "zwj", "zwnj"
};
public static string RandomHtmlishString(Random random, int numElements)
{
int end = NextInt(random, 0, numElements);
if (end == 0)
{
// allow 0 length
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < end; i++)
{
int val = random.Next(25);
switch (val)
{
case 0:
sb.Append("<p>");
break;
case 1:
{
sb.Append("<");
sb.Append(" ".Substring(NextInt(random, 0, 4)));
sb.Append(RandomSimpleString(random));
for (int j = 0; j < NextInt(random, 0, 10); ++j)
{
sb.Append(' ');
sb.Append(RandomSimpleString(random));
sb.Append(" ".Substring(NextInt(random, 0, 1)));
sb.Append('=');
sb.Append(" ".Substring(NextInt(random, 0, 1)));
sb.Append("\"".Substring(NextInt(random, 0, 1)));
sb.Append(RandomSimpleString(random));
sb.Append("\"".Substring(NextInt(random, 0, 1)));
}
sb.Append(" ".Substring(NextInt(random, 0, 4)));
sb.Append("/".Substring(NextInt(random, 0, 1)));
sb.Append(">".Substring(NextInt(random, 0, 1)));
break;
}
case 2:
{
sb.Append("</");
sb.Append(" ".Substring(NextInt(random, 0, 4)));
sb.Append(RandomSimpleString(random));
sb.Append(" ".Substring(NextInt(random, 0, 4)));
sb.Append(">".Substring(NextInt(random, 0, 1)));
break;
}
case 3:
sb.Append(">");
break;
case 4:
sb.Append("</p>");
break;
case 5:
sb.Append("<!--");
break;
case 6:
sb.Append("<!--#");
break;
case 7:
sb.Append("<script><!-- f('");
break;
case 8:
sb.Append("</script>");
break;
case 9:
sb.Append("<?");
break;
case 10:
sb.Append("?>");
break;
case 11:
sb.Append("\"");
break;
case 12:
sb.Append("\\\"");
break;
case 13:
sb.Append("'");
break;
case 14:
sb.Append("\\'");
break;
case 15:
sb.Append("-->");
break;
case 16:
{
sb.Append("&");
switch (NextInt(random, 0, 2))
{
case 0:
sb.Append(RandomSimpleString(random));
break;
case 1:
sb.Append(HTML_CHAR_ENTITIES[random.Next(HTML_CHAR_ENTITIES.Length)]);
break;
}
sb.Append(";".Substring(NextInt(random, 0, 1)));
break;
}
case 17:
{
sb.Append("&#");
if (0 == NextInt(random, 0, 1))
{
sb.Append(NextInt(random, 0, int.MaxValue - 1));
sb.Append(";".Substring(NextInt(random, 0, 1)));
}
break;
}
case 18:
{
sb.Append("&#x");
if (0 == NextInt(random, 0, 1))
{
sb.Append(Convert.ToString(NextInt(random, 0, int.MaxValue - 1), 16));
sb.Append(";".Substring(NextInt(random, 0, 1)));
}
break;
}
case 19:
sb.Append(";");
break;
case 20:
sb.Append(NextInt(random, 0, int.MaxValue - 1));
break;
case 21:
sb.Append("\n");
break;
case 22:
sb.Append(" ".Substring(NextInt(random, 0, 10)));
break;
case 23:
{
sb.Append("<");
if (0 == NextInt(random, 0, 3))
{
sb.Append(" ".Substring(NextInt(random, 1, 10)));
}
if (0 == NextInt(random, 0, 1))
{
sb.Append("/");
if (0 == NextInt(random, 0, 3))
{
sb.Append(" ".Substring(NextInt(random, 1, 10)));
}
}
switch (NextInt(random, 0, 3))
{
case 0:
sb.Append(RandomlyRecaseString(random, "script"));
break;
case 1:
sb.Append(RandomlyRecaseString(random, "style"));
break;
case 2:
sb.Append(RandomlyRecaseString(random, "br"));
break;
// default: append nothing
}
sb.Append(">".Substring(NextInt(random, 0, 1)));
break;
}
default:
sb.Append(RandomSimpleString(random));
break;
}
}
return sb.ToString();
}
/// <summary>
/// Randomly upcases, downcases, or leaves intact each code point in the given string
/// </summary>
public static string RandomlyRecaseString(Random random, string str)
{
var builder = new StringBuilder();
int pos = 0;
while (pos < str.Length)
{
string toRecase;
// check if the next char sequence is a surrogate pair
if (pos + 1 < str.Length && char.IsSurrogatePair(str[pos], str[pos+1]))
{
toRecase = str.Substring(pos, 2);
}
else
{
toRecase = str.Substring(pos, 1);
}
pos += toRecase.Length;
switch (NextInt(random, 0, 2))
{
case 0:
builder.Append(toRecase.ToUpper()); // LUCENENET NOTE: Intentionally using current culture
break;
case 1:
builder.Append(toRecase.ToLower()); // LUCENENET NOTE: Intentionally using current culture
break;
case 2:
builder.Append(toRecase);
break;
}
}
return builder.ToString();
}
private static readonly int[] BlockStarts = new int[]
{
0x0000, 0x0080, 0x0100, 0x0180, 0x0250, 0x02B0, 0x0300, 0x0370, 0x0400, 0x0500, 0x0530, 0x0590, 0x0600, 0x0700,
0x0750, 0x0780, 0x07C0, 0x0800, 0x0900, 0x0980, 0x0A00, 0x0A80, 0x0B00, 0x0B80, 0x0C00, 0x0C80, 0x0D00, 0x0D80,
0x0E00, 0x0E80, 0x0F00, 0x1000, 0x10A0, 0x1100, 0x1200, 0x1380, 0x13A0, 0x1400, 0x1680, 0x16A0, 0x1700, 0x1720,
0x1740, 0x1760, 0x1780, 0x1800, 0x18B0, 0x1900, 0x1950, 0x1980, 0x19E0, 0x1A00, 0x1A20, 0x1B00, 0x1B80, 0x1C00,
0x1C50, 0x1CD0, 0x1D00, 0x1D80, 0x1DC0, 0x1E00, 0x1F00, 0x2000, 0x2070, 0x20A0, 0x20D0, 0x2100, 0x2150, 0x2190,
0x2200, 0x2300, 0x2400, 0x2440, 0x2460, 0x2500, 0x2580, 0x25A0, 0x2600, 0x2700, 0x27C0, 0x27F0, 0x2800, 0x2900,
0x2980, 0x2A00, 0x2B00, 0x2C00, 0x2C60, 0x2C80, 0x2D00, 0x2D30, 0x2D80, 0x2DE0, 0x2E00, 0x2E80, 0x2F00, 0x2FF0,
0x3000, 0x3040, 0x30A0, 0x3100, 0x3130, 0x3190, 0x31A0, 0x31C0, 0x31F0, 0x3200, 0x3300, 0x3400, 0x4DC0, 0x4E00,
0xA000, 0xA490, 0xA4D0, 0xA500, 0xA640, 0xA6A0, 0xA700, 0xA720, 0xA800, 0xA830, 0xA840, 0xA880, 0xA8E0, 0xA900,
0xA930, 0xA960, 0xA980, 0xAA00, 0xAA60, 0xAA80, 0xABC0, 0xAC00, 0xD7B0, 0xE000, 0xF900, 0xFB00, 0xFB50, 0xFE00,
0xFE10, 0xFE20, 0xFE30, 0xFE50, 0xFE70, 0xFF00, 0xFFF0, 0x10000, 0x10080, 0x10100, 0x10140, 0x10190, 0x101D0,
0x10280, 0x102A0, 0x10300, 0x10330, 0x10380, 0x103A0, 0x10400, 0x10450, 0x10480, 0x10800, 0x10840, 0x10900,
0x10920, 0x10A00, 0x10A60, 0x10B00, 0x10B40, 0x10B60, 0x10C00, 0x10E60, 0x11080, 0x12000, 0x12400, 0x13000,
0x1D000, 0x1D100, 0x1D200, 0x1D300, 0x1D360, 0x1D400, 0x1F000, 0x1F030, 0x1F100, 0x1F200, 0x20000, 0x2A700,
0x2F800, 0xE0000, 0xE0100, 0xF0000, 0x100000
};
private static readonly int[] BlockEnds = new int[]
{
0x007F, 0x00FF, 0x017F, 0x024F, 0x02AF, 0x02FF, 0x036F, 0x03FF, 0x04FF, 0x052F, 0x058F, 0x05FF, 0x06FF, 0x074F,
0x077F, 0x07BF, 0x07FF, 0x083F, 0x097F, 0x09FF, 0x0A7F, 0x0AFF, 0x0B7F, 0x0BFF, 0x0C7F, 0x0CFF, 0x0D7F, 0x0DFF,
0x0E7F, 0x0EFF, 0x0FFF, 0x109F, 0x10FF, 0x11FF, 0x137F, 0x139F, 0x13FF, 0x167F, 0x169F, 0x16FF, 0x171F, 0x173F,
0x175F, 0x177F, 0x17FF, 0x18AF, 0x18FF, 0x194F, 0x197F, 0x19DF, 0x19FF, 0x1A1F, 0x1AAF, 0x1B7F, 0x1BBF, 0x1C4F,
0x1C7F, 0x1CFF, 0x1D7F, 0x1DBF, 0x1DFF, 0x1EFF, 0x1FFF, 0x206F, 0x209F, 0x20CF, 0x20FF, 0x214F, 0x218F, 0x21FF,
0x22FF, 0x23FF, 0x243F, 0x245F, 0x24FF, 0x257F, 0x259F, 0x25FF, 0x26FF, 0x27BF, 0x27EF, 0x27FF, 0x28FF, 0x297F,
0x29FF, 0x2AFF, 0x2BFF, 0x2C5F, 0x2C7F, 0x2CFF, 0x2D2F, 0x2D7F, 0x2DDF, 0x2DFF, 0x2E7F, 0x2EFF, 0x2FDF, 0x2FFF,
0x303F, 0x309F, 0x30FF, 0x312F, 0x318F, 0x319F, 0x31BF, 0x31EF, 0x31FF, 0x32FF, 0x33FF, 0x4DBF, 0x4DFF, 0x9FFF,
0xA48F, 0xA4CF, 0xA4FF, 0xA63F, 0xA69F, 0xA6FF, 0xA71F, 0xA7FF, 0xA82F, 0xA83F, 0xA87F, 0xA8DF, 0xA8FF, 0xA92F,
0xA95F, 0xA97F, 0xA9DF, 0xAA5F, 0xAA7F, 0xAADF, 0xABFF, 0xD7AF, 0xD7FF, 0xF8FF, 0xFAFF, 0xFB4F, 0xFDFF, 0xFE0F,
0xFE1F, 0xFE2F, 0xFE4F, 0xFE6F, 0xFEFF, 0xFFEF, 0xFFFF, 0x1007F, 0x100FF, 0x1013F, 0x1018F, 0x101CF, 0x101FF,
0x1029F, 0x102DF, 0x1032F, 0x1034F, 0x1039F, 0x103DF, 0x1044F, 0x1047F, 0x104AF, 0x1083F, 0x1085F, 0x1091F,
0x1093F, 0x10A5F, 0x10A7F, 0x10B3F, 0x10B5F, 0x10B7F, 0x10C4F, 0x10E7F, 0x110CF, 0x123FF, 0x1247F, 0x1342F,
0x1D0FF, 0x1D1FF, 0x1D24F, 0x1D35F, 0x1D37F, 0x1D7FF, 0x1F02F, 0x1F09F, 0x1F1FF, 0x1F2FF, 0x2A6DF, 0x2B73F,
0x2FA1F, 0xE007F, 0xE01EF, 0xFFFFF, 0x10FFFF
};
/// <summary>
/// Returns random string of length between 0-20 codepoints, all codepoints within the same unicode block. </summary>
public static string RandomRealisticUnicodeString(Random r)
{
return RandomRealisticUnicodeString(r, 20);
}
/// <summary>
/// Returns random string of length up to maxLength codepoints , all codepoints within the same unicode block. </summary>
public static string RandomRealisticUnicodeString(Random r, int maxLength)
{
return RandomRealisticUnicodeString(r, 0, maxLength);
}
/// <summary>
/// Returns random string of length between min and max codepoints, all codepoints within the same unicode block. </summary>
public static string RandomRealisticUnicodeString(Random r, int minLength, int maxLength)
{
int end = NextInt(r, minLength, maxLength);
int block = r.Next(BlockStarts.Length);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < end; i++)
{
sb.AppendCodePoint(NextInt(r, BlockStarts[block], BlockEnds[block]));
}
return sb.ToString();
}
/// <summary>
/// Returns random string, with a given UTF-8 byte length </summary>
public static string RandomFixedByteLengthUnicodeString(Random r, int length)
{
char[] buffer = new char[length * 3];
int bytes = length;
int i = 0;
for (; i < buffer.Length && bytes != 0; i++)
{
int t;
if (bytes >= 4)
{
t = r.Next(5);
}
else if (bytes >= 3)
{
t = r.Next(4);
}
else if (bytes >= 2)
{
t = r.Next(2);
}
else
{
t = 0;
}
if (t == 0)
{
buffer[i] = (char)r.Next(0x80);
bytes--;
}
else if (1 == t)
{
buffer[i] = (char)NextInt(r, 0x80, 0x7ff);
bytes -= 2;
}
else if (2 == t)
{
buffer[i] = (char)NextInt(r, 0x800, 0xd7ff);
bytes -= 3;
}
else if (3 == t)
{
buffer[i] = (char)NextInt(r, 0xe000, 0xffff);
bytes -= 3;
}
else if (4 == t)
{
// Make a surrogate pair
// High surrogate
buffer[i++] = (char)NextInt(r, 0xd800, 0xdbff);
// Low surrogate
buffer[i] = (char)NextInt(r, 0xdc00, 0xdfff);
bytes -= 4;
}
}
return new string(buffer, 0, i);
}
/// <summary>
/// Return a Codec that can read any of the
/// default codecs and formats, but always writes in the specified
/// format.
/// </summary>
public static Codec AlwaysPostingsFormat(PostingsFormat format)
{
// TODO: we really need for postings impls etc to announce themselves
// (and maybe their params, too) to infostream on flush and merge.
// otherwise in a real debugging situation we won't know whats going on!
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("forcing postings format to:" + format);
}
return new Lucene46CodecAnonymousInnerClassHelper(format);
}
private class Lucene46CodecAnonymousInnerClassHelper : Lucene46Codec
{
private PostingsFormat format;
public Lucene46CodecAnonymousInnerClassHelper(PostingsFormat format)
{
this.format = format;
}
public override PostingsFormat GetPostingsFormatForField(string field)
{
return format;
}
}
/// <summary>
/// Return a Codec that can read any of the
/// default codecs and formats, but always writes in the specified
/// format.
/// </summary>
public static Codec AlwaysDocValuesFormat(DocValuesFormat format)
{
// TODO: we really need for docvalues impls etc to announce themselves
// (and maybe their params, too) to infostream on flush and merge.
// otherwise in a real debugging situation we won't know whats going on!
if (LuceneTestCase.VERBOSE)
{
Console.WriteLine("forcing docvalues format to:" + format);
}
return new Lucene46CodecAnonymousInnerClassHelper2(format);
}
private class Lucene46CodecAnonymousInnerClassHelper2 : Lucene46Codec
{
private DocValuesFormat format;
public Lucene46CodecAnonymousInnerClassHelper2(DocValuesFormat format)
{
this.format = format;
}
public override DocValuesFormat GetDocValuesFormatForField(string field)
{
return format;
}
}
// TODO: generalize all 'test-checks-for-crazy-codecs' to
// annotations (LUCENE-3489)
public static string GetPostingsFormat(string field)
{
return GetPostingsFormat(Codec.Default, field);
}
public static string GetPostingsFormat(Codec codec, string field)
{
PostingsFormat p = codec.PostingsFormat;
if (p is PerFieldPostingsFormat)
{
return ((PerFieldPostingsFormat)p).GetPostingsFormatForField(field).Name;
}
else
{
return p.Name;
}
}
public static string GetDocValuesFormat(string field)
{
return GetDocValuesFormat(Codec.Default, field);
}
public static string GetDocValuesFormat(Codec codec, string field)
{
DocValuesFormat f = codec.DocValuesFormat;
if (f is PerFieldDocValuesFormat)
{
return ((PerFieldDocValuesFormat)f).GetDocValuesFormatForField(field).Name;
}
else
{
return f.Name;
}
}
// TODO: remove this, push this test to Lucene40/Lucene42 codec tests
public static bool FieldSupportsHugeBinaryDocValues(string field)
{
string dvFormat = GetDocValuesFormat(field);
if (dvFormat.Equals("Lucene40", StringComparison.Ordinal)
|| dvFormat.Equals("Lucene42", StringComparison.Ordinal)
|| dvFormat.Equals("Memory", StringComparison.Ordinal))
{
return false;
}
return true;
}
public static bool AnyFilesExceptWriteLock(Directory dir)
{
string[] files = dir.ListAll();
if (files.Length > 1 || (files.Length == 1 && !files[0].Equals("write.lock", StringComparison.Ordinal)))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// just tries to configure things to keep the open file
/// count lowish
/// </summary>
public static void ReduceOpenFiles(IndexWriter w)
{
// keep number of open files lowish
MergePolicy mp = w.Config.MergePolicy;
if (mp is LogMergePolicy)
{
LogMergePolicy lmp = (LogMergePolicy)mp;
lmp.MergeFactor = Math.Min(5, lmp.MergeFactor);
lmp.NoCFSRatio = 1.0;
}
else if (mp is TieredMergePolicy)
{
TieredMergePolicy tmp = (TieredMergePolicy)mp;
tmp.MaxMergeAtOnce = Math.Min(5, tmp.MaxMergeAtOnce);
tmp.SegmentsPerTier = Math.Min(5, tmp.SegmentsPerTier);
tmp.NoCFSRatio = 1.0;
}
IMergeScheduler ms = w.Config.MergeScheduler;
if (ms is IConcurrentMergeScheduler)
{
// wtf... shouldnt it be even lower since its 1 by default?!?!
((IConcurrentMergeScheduler)ms).SetMaxMergesAndThreads(3, 2);
}
}
/// <summary>
/// Checks some basic behaviour of an AttributeImpl </summary>
/// <param name="att">Attribute to reflect</param>
/// <param name="reflectedValues"> contains a map with "AttributeClass#key" as values </param>
public static void AssertAttributeReflection(Attribute att, IDictionary<string, object> reflectedValues)
{
IDictionary<string, object> map = new Dictionary<string, object>();
att.ReflectWith(new AttributeReflectorAnonymousInnerClassHelper(map));
IDictionary<string, object> newReflectedObjects = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> de in reflectedValues)
newReflectedObjects.Add(de.Key, (object)de.Value);
CollectionAssert.AreEqual(newReflectedObjects, map, "Reflection does not produce same map");
}
private class AttributeReflectorAnonymousInnerClassHelper : IAttributeReflector
{
private IDictionary<string, object> Map;
public AttributeReflectorAnonymousInnerClassHelper(IDictionary<string, object> map)
{
this.Map = map;
}
public void Reflect<T>(string key, object value)
where T : IAttribute
{
Reflect(typeof(T), key, value);
}
public void Reflect(Type attClass, string key, object value)
{
Map[attClass.Name + '#' + key] = value;
}
}
public static void AssertEquals(TopDocs expected, TopDocs actual)
{
Assert.AreEqual(expected.TotalHits, actual.TotalHits, "wrong total hits");
Assert.AreEqual(expected.MaxScore, actual.MaxScore, "wrong maxScore");
Assert.AreEqual(expected.ScoreDocs.Length, actual.ScoreDocs.Length, "wrong hit count");
for (int hitIDX = 0; hitIDX < expected.ScoreDocs.Length; hitIDX++)
{
ScoreDoc expectedSD = expected.ScoreDocs[hitIDX];
ScoreDoc actualSD = actual.ScoreDocs[hitIDX];
Assert.AreEqual(expectedSD.Doc, actualSD.Doc, "wrong hit docID");
Assert.AreEqual(expectedSD.Score, actualSD.Score, "wrong hit score");
if (expectedSD is FieldDoc)
{
Assert.IsTrue(actualSD is FieldDoc);
Assert.AreEqual(((FieldDoc)expectedSD).Fields, ((FieldDoc)actualSD).Fields, "wrong sort field values");
}
else
{
Assert.IsFalse(actualSD is FieldDoc);
}
}
}
// NOTE: this is likely buggy, and cannot clone fields
// with tokenStreamValues, etc. Use at your own risk!!
// TODO: is there a pre-existing way to do this!!!
public static Document CloneDocument(Document doc1)
{
Document doc2 = new Document();
foreach (IIndexableField f in doc1.Fields)
{
Field field1 = (Field)f;
Field field2;
DocValuesType dvType = field1.FieldType.DocValueType;
NumericType numType = field1.FieldType.NumericType;
if (dvType != DocValuesType.NONE)
{
switch (dvType)
{
case DocValuesType.NUMERIC:
field2 = new NumericDocValuesField(field1.Name, field1.GetInt64Value().Value);
break;
case DocValuesType.BINARY:
field2 = new BinaryDocValuesField(field1.Name, field1.GetBinaryValue());
break;
case DocValuesType.SORTED:
field2 = new SortedDocValuesField(field1.Name, field1.GetBinaryValue());
break;
default:
throw new InvalidOperationException("unknown Type: " + dvType);
}
}
else if (numType != NumericType.NONE)
{
switch (numType)
{
case NumericType.INT32:
field2 = new Int32Field(field1.Name, field1.GetInt32Value().Value, field1.FieldType);
break;
case NumericType.SINGLE:
field2 = new SingleField(field1.Name, field1.GetInt32Value().Value, field1.FieldType);
break;
case NumericType.INT64:
field2 = new Int64Field(field1.Name, field1.GetInt32Value().Value, field1.FieldType);
break;
case NumericType.DOUBLE:
field2 = new DoubleField(field1.Name, field1.GetInt32Value().Value, field1.FieldType);
break;
default:
throw new InvalidOperationException("unknown Type: " + numType);
}
}
else
{
field2 = new Field(field1.Name, field1.GetStringValue(), field1.FieldType);
}
doc2.Add(field2);
}
return doc2;
}
// Returns a DocsEnum, but randomly sometimes uses a
// DocsAndFreqsEnum, DocsAndPositionsEnum. Returns null
// if field/term doesn't exist:
public static DocsEnum Docs(Random random, IndexReader r, string field, BytesRef term, IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
Terms terms = MultiFields.GetTerms(r, field);
if (terms == null)
{
return null;
}
TermsEnum termsEnum = terms.GetIterator(null);
if (!termsEnum.SeekExact(term))
{
return null;
}
return Docs(random, termsEnum, liveDocs, reuse, flags);
}
// Returns a DocsEnum from a positioned TermsEnum, but
// randomly sometimes uses a DocsAndFreqsEnum, DocsAndPositionsEnum.
public static DocsEnum Docs(Random random, TermsEnum termsEnum, IBits liveDocs, DocsEnum reuse, DocsFlags flags)
{
if (random.NextBoolean())
{
if (random.NextBoolean())
{
DocsAndPositionsFlags posFlags;
switch (random.Next(4))
{
case 0:
posFlags = 0;
break;
case 1:
posFlags = DocsAndPositionsFlags.OFFSETS;
break;
case 2:
posFlags = DocsAndPositionsFlags.PAYLOADS;
break;
default:
posFlags = DocsAndPositionsFlags.OFFSETS | DocsAndPositionsFlags.PAYLOADS;
break;
}
// TODO: cast to DocsAndPositionsEnum?
DocsAndPositionsEnum docsAndPositions = termsEnum.DocsAndPositions(liveDocs, null, posFlags);
if (docsAndPositions != null)
{
return docsAndPositions;
}
}
flags |= DocsFlags.FREQS;
}
return termsEnum.Docs(liveDocs, reuse, flags);
}
public static ICharSequence StringToCharSequence(string @string, Random random)
{
return BytesToCharSequence(new BytesRef(@string), random);
}
public static ICharSequence BytesToCharSequence(BytesRef @ref, Random random)
{
switch (random.Next(5))
{
case 4:
CharsRef chars = new CharsRef(@ref.Length);
UnicodeUtil.UTF8toUTF16(@ref.Bytes, @ref.Offset, @ref.Length, chars);
return chars;
//case 3:
//return CharBuffer.wrap(@ref.Utf8ToString());
default:
return new StringCharSequenceWrapper(@ref.Utf8ToString());
}
}
/// <summary>
/// Shutdown <seealso cref="ExecutorService"/> and wait for its.
/// </summary>
public static void ShutdownExecutorService(TaskScheduler ex)
{
/*if (ex != null)
{
try
{
ex.shutdown();
ex.awaitTermination(1, TimeUnit.SECONDS);
}
catch (ThreadInterruptedException e)
{
// Just report it on the syserr.
Console.Error.WriteLine("Could not properly shutdown executor service.");
Console.Error.WriteLine(e.StackTrace);
}
}*/
}
/// <summary>
/// Returns a valid (compiling) Pattern instance with random stuff inside. Be careful
/// when applying random patterns to longer strings as certain types of patterns
/// may explode into exponential times in backtracking implementations (such as Java's).
/// </summary>
public static Regex RandomPattern(Random random)
{
const string nonBmpString = "AB\uD840\uDC00C";
while (true)
{
try
{
Regex p = new Regex(TestUtil.RandomRegexpishString(random), RegexOptions.Compiled);
string replacement = p.Replace(nonBmpString, "_");
// Make sure the result of applying the pattern to a string with extended
// unicode characters is a valid utf16 string. See LUCENE-4078 for discussion.
if (replacement != null && UnicodeUtil.ValidUTF16String(replacement))
{
return p;
}
}
#pragma warning disable 168
catch (Exception ignored)
#pragma warning restore 168
{
// Loop trying until we hit something that compiles.
}
}
}
public static FilteredQuery.FilterStrategy RandomFilterStrategy(Random random)
{
switch (random.Next(6))
{
case 5:
case 4:
return new RandomAccessFilterStrategyAnonymousInnerClassHelper();
case 3:
return FilteredQuery.RANDOM_ACCESS_FILTER_STRATEGY;
case 2:
return FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY;
case 1:
return FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY;
case 0:
return FilteredQuery.QUERY_FIRST_FILTER_STRATEGY;
default:
return FilteredQuery.RANDOM_ACCESS_FILTER_STRATEGY;
}
}
private class RandomAccessFilterStrategyAnonymousInnerClassHelper : FilteredQuery.RandomAccessFilterStrategy
{
public RandomAccessFilterStrategyAnonymousInnerClassHelper()
{
}
protected override bool UseRandomAccess(IBits bits, int firstFilterDoc)
{
return LuceneTestCase.Random().NextBoolean();
}
}
/// <summary>
/// Returns a random string in the specified length range consisting
/// entirely of whitespace characters </summary>
/// <seealso cref= #WHITESPACE_CHARACTERS </seealso>
public static string RandomWhitespace(Random r, int minLength, int maxLength)
{
int end = NextInt(r, minLength, maxLength);
StringBuilder @out = new StringBuilder();
for (int i = 0; i < end; i++)
{
int offset = NextInt(r, 0, WHITESPACE_CHARACTERS.Length - 1);
char c = WHITESPACE_CHARACTERS[offset];
// sanity check
Assert.IsTrue(char.IsWhiteSpace(c), "Not really whitespace? (@" + offset + "): " + c);
@out.Append(c);
}
return @out.ToString();
}
public static string RandomAnalysisString(Random random, int maxLength, bool simple)
{
Assert.True(maxLength >= 0);
// sometimes just a purely random string
if (random.Next(31) == 0)
{
return RandomSubString(random, random.Next(maxLength), simple);
}
// otherwise, try to make it more realistic with 'words' since most tests use MockTokenizer
// first decide how big the string will really be: 0..n
maxLength = random.Next(maxLength);
int avgWordLength = TestUtil.NextInt(random, 3, 8);
StringBuilder sb = new StringBuilder();
while (sb.Length < maxLength)
{
if (sb.Length > 0)
{
sb.Append(' ');
}
int wordLength = -1;
while (wordLength < 0)
{
wordLength = (int)(random.NextDouble() * 3 + avgWordLength);
}
wordLength = Math.Min(wordLength, maxLength - sb.Length);
sb.Append(RandomSubString(random, wordLength, simple));
}
return sb.ToString();
}
public static string RandomSubString(Random random, int wordLength, bool simple)
{
if (wordLength == 0)
{
return "";
}
int evilness = TestUtil.NextInt(random, 0, 20);
StringBuilder sb = new StringBuilder();
while (sb.Length < wordLength)
{
;
if (simple)
{
sb.Append(random.NextBoolean() ? TestUtil.RandomSimpleString(random, wordLength) : TestUtil.RandomHtmlishString(random, wordLength));
}
else
{
if (evilness < 10)
{
sb.Append(TestUtil.RandomSimpleString(random, wordLength));
}
else if (evilness < 15)
{
Assert.AreEqual(0, sb.Length); // we should always get wordLength back!
sb.Append(TestUtil.RandomRealisticUnicodeString(random, wordLength, wordLength));
}
else if (evilness == 16)
{
sb.Append(TestUtil.RandomHtmlishString(random, wordLength));
}
else if (evilness == 17)
{
// gives a lot of punctuation
sb.Append(TestUtil.RandomRegexpishString(random, wordLength));
}
else
{
sb.Append(TestUtil.RandomUnicodeString(random, wordLength));
}
}
}
if (sb.Length > wordLength)
{
sb.Length = wordLength;
if (char.IsHighSurrogate(sb[wordLength - 1]))
{
sb.Length = wordLength - 1;
}
}
if (random.Next(17) == 0)
{
// mix up case
string mixedUp = TestUtil.RandomlyRecaseString(random, sb.ToString());
Assert.True(mixedUp.Length == sb.Length, "Lengths are not the same: mixedUp = " + mixedUp + ", length = " + mixedUp.Length + ", sb = " + sb + ", length = " + sb.Length);
return mixedUp;
}
else
{
return sb.ToString();
}
}
/// <summary>
/// List of characters that match <seealso cref="Character#isWhitespace"/> </summary>
public static readonly char[] WHITESPACE_CHARACTERS = new char[]
{
'\u0009', '\n', '\u000B', '\u000C', '\r', '\u001C', '\u001D', '\u001E', '\u001F', '\u0020', '\u1680', '\u180E', '\u2000',
'\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2008', '\u2009', '\u200A', '\u2028', '\u2029', '\u205F', '\u3000'
};
public static byte[] ToByteArray(this sbyte[] arr)
{
var unsigned = new byte[arr.Length];
System.Buffer.BlockCopy(arr, 0, unsigned, 0, arr.Length);
return unsigned;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartTitleRequest.
/// </summary>
public partial class WorkbookChartTitleRequest : BaseRequest, IWorkbookChartTitleRequest
{
/// <summary>
/// Constructs a new WorkbookChartTitleRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartTitleRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartTitle using POST.
/// </summary>
/// <param name="workbookChartTitleToCreate">The WorkbookChartTitle to create.</param>
/// <returns>The created WorkbookChartTitle.</returns>
public System.Threading.Tasks.Task<WorkbookChartTitle> CreateAsync(WorkbookChartTitle workbookChartTitleToCreate)
{
return this.CreateAsync(workbookChartTitleToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartTitle using POST.
/// </summary>
/// <param name="workbookChartTitleToCreate">The WorkbookChartTitle to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartTitle.</returns>
public async System.Threading.Tasks.Task<WorkbookChartTitle> CreateAsync(WorkbookChartTitle workbookChartTitleToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartTitle>(workbookChartTitleToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartTitle.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartTitle.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartTitle>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartTitle.
/// </summary>
/// <returns>The WorkbookChartTitle.</returns>
public System.Threading.Tasks.Task<WorkbookChartTitle> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartTitle.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartTitle.</returns>
public async System.Threading.Tasks.Task<WorkbookChartTitle> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartTitle>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartTitle using PATCH.
/// </summary>
/// <param name="workbookChartTitleToUpdate">The WorkbookChartTitle to update.</param>
/// <returns>The updated WorkbookChartTitle.</returns>
public System.Threading.Tasks.Task<WorkbookChartTitle> UpdateAsync(WorkbookChartTitle workbookChartTitleToUpdate)
{
return this.UpdateAsync(workbookChartTitleToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartTitle using PATCH.
/// </summary>
/// <param name="workbookChartTitleToUpdate">The WorkbookChartTitle to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartTitle.</returns>
public async System.Threading.Tasks.Task<WorkbookChartTitle> UpdateAsync(WorkbookChartTitle workbookChartTitleToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartTitle>(workbookChartTitleToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartTitleRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartTitleRequest Expand(Expression<Func<WorkbookChartTitle, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartTitleRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartTitleRequest Select(Expression<Func<WorkbookChartTitle, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartTitleToInitialize">The <see cref="WorkbookChartTitle"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartTitle workbookChartTitleToInitialize)
{
}
}
}
| |
#region References
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Raspberry.IO.Interop;
using Raspberry.Timers;
#endregion
namespace Raspberry.IO.GeneralPurpose
{
/// <summary>
/// Represents the default connection driver that uses memory for accesses and files for edge detection.
/// </summary>
public class GpioConnectionDriver : IGpioConnectionDriver
{
#region Fields
private const string gpioPath = "/sys/class/gpio";
private readonly IntPtr gpioAddress;
private readonly Dictionary<ProcessorPin, PinResistor> pinResistors = new Dictionary<ProcessorPin, PinResistor>();
private readonly Dictionary<ProcessorPin, PinPoll> pinPolls = new Dictionary<ProcessorPin, PinPoll>();
/// <summary>
/// The default timeout (5 seconds).
/// </summary>
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
/// <summary>
/// The minimum timeout (1 milliseconds)
/// </summary>
public static readonly TimeSpan MinimumTimeout = TimeSpan.FromMilliseconds(1);
private static readonly TimeSpan resistorSetDelay = TimeSpanUtility.FromMicroseconds(5);
#endregion
#region Instance Management
/// <summary>
/// Initializes a new instance of the <see cref="GpioConnectionDriver"/> class.
/// </summary>
public GpioConnectionDriver() {
using (var memoryFile = UnixFile.Open("/dev/mem", UnixFileMode.ReadWrite | UnixFileMode.Synchronized)) {
gpioAddress = MemoryMap.Create(
IntPtr.Zero,
Interop.BCM2835_BLOCK_SIZE,
MemoryProtection.ReadWrite,
MemoryFlags.Shared,
memoryFile.Descriptor,
GetProcessorBaseAddress(Board.Current.Processor));
}
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="GpioConnectionDriver"/> is reclaimed by garbage collection.
/// </summary>
~GpioConnectionDriver()
{
MemoryMap.Close(gpioAddress, Interop.BCM2835_BLOCK_SIZE);
}
#endregion
#region Methods
/// <summary>
/// Gets driver capabilities.
/// </summary>
/// <returns>The capabilites.</returns>
GpioConnectionDriverCapabilities IGpioConnectionDriver.GetCapabilities()
{
return GetCapabilities();
}
/// <summary>
/// Gets driver capabilities.
/// </summary>
/// <returns>The capabilites.</returns>
public static GpioConnectionDriverCapabilities GetCapabilities()
{
return GpioConnectionDriverCapabilities.CanSetPinResistor | GpioConnectionDriverCapabilities.CanSetPinDetectedEdges;
}
/// <summary>
/// Allocates the specified pin.
/// </summary>
/// <param name="pin">The pin.</param>
/// <param name="direction">The direction.</param>
public void Allocate(ProcessorPin pin, PinDirection direction)
{
var gpioId = string.Format("gpio{0}", (int)pin);
if (Directory.Exists(Path.Combine(gpioPath, gpioId)))
{
// Reinitialize pin virtual file
using (var streamWriter = new StreamWriter(Path.Combine(gpioPath, "unexport"), false))
streamWriter.Write((int) pin);
}
// Export pin for file mode
using (var streamWriter = new StreamWriter(Path.Combine(gpioPath, "export"), false))
streamWriter.Write((int)pin);
// Set the direction on the pin and update the exported list
SetPinMode(pin, direction == PinDirection.Input ? Interop.BCM2835_GPIO_FSEL_INPT : Interop.BCM2835_GPIO_FSEL_OUTP);
// Set direction in pin virtual file
var filePath = Path.Combine(gpioId, "direction");
using (var streamWriter = new StreamWriter(Path.Combine(gpioPath, filePath), false))
streamWriter.Write(direction == PinDirection.Input ? "in" : "out");
if (direction == PinDirection.Input)
{
PinResistor pinResistor;
if (!pinResistors.TryGetValue(pin, out pinResistor) || pinResistor != PinResistor.None)
SetPinResistor(pin, PinResistor.None);
SetPinDetectedEdges(pin, PinDetectedEdges.Both);
InitializePoll(pin);
}
}
/// <summary>
/// Sets the pin resistor.
/// </summary>
/// <param name="pin">The pin.</param>
/// <param name="resistor">The resistor.</param>
public void SetPinResistor(ProcessorPin pin, PinResistor resistor)
{
// Set the pullup/down resistor for a pin
//
// The GPIO Pull-up/down Clock Registers control the actuation of internal pull-downs on
// the respective GPIO pins. These registers must be used in conjunction with the GPPUD
// register to effect GPIO Pull-up/down changes. The following sequence of events is
// required:
// 1. Write to GPPUD to set the required control signal (i.e. Pull-up or Pull-Down or neither
// to remove the current Pull-up/down)
// 2. Wait 150 cycles ? this provides the required set-up time for the control signal
// 3. Write to GPPUDCLK0/1 to clock the control signal into the GPIO pads you wish to
// modify ? NOTE only the pads which receive a clock will be modified, all others will
// retain their previous state.
// 4. Wait 150 cycles ? this provides the required hold time for the control signal
// 5. Write to GPPUD to remove the control signal
// 6. Write to GPPUDCLK0/1 to remove the clock
//
// RPi has P1-03 and P1-05 with 1k8 pullup resistor
uint pud;
switch (resistor)
{
case PinResistor.None:
pud = Interop.BCM2835_GPIO_PUD_OFF;
break;
case PinResistor.PullDown:
pud = Interop.BCM2835_GPIO_PUD_DOWN;
break;
case PinResistor.PullUp:
pud = Interop.BCM2835_GPIO_PUD_UP;
break;
default:
throw new ArgumentOutOfRangeException("resistor", resistor, string.Format(CultureInfo.InvariantCulture, "{0} is not a valid value for pin resistor", resistor));
}
WriteResistor(pud);
HighResolutionTimer.Sleep(resistorSetDelay);
SetPinResistorClock(pin, true);
HighResolutionTimer.Sleep(resistorSetDelay);
WriteResistor(Interop.BCM2835_GPIO_PUD_OFF);
SetPinResistorClock(pin, false);
pinResistors[pin] = PinResistor.None;
}
/// <summary>
/// Sets the detected edges on an input pin.
/// </summary>
/// <param name="pin">The pin.</param>
/// <param name="edges">The edges.</param>
/// <remarks>By default, both edges may be detected on input pins.</remarks>
public void SetPinDetectedEdges(ProcessorPin pin, PinDetectedEdges edges)
{
var edgePath = Path.Combine(gpioPath, string.Format("gpio{0}/edge", (int)pin));
using (var streamWriter = new StreamWriter(edgePath, false))
streamWriter.Write(ToString(edges));
}
/// <summary>
/// Waits for the specified pin to be in the specified state.
/// </summary>
/// <param name="pin">The pin.</param>
/// <param name="waitForUp">if set to <c>true</c> waits for the pin to be up. Default value is <c>true</c>.</param>
/// <param name="timeout">The timeout. Default value is <see cref="TimeSpan.Zero" />.</param>
/// <remarks>
/// If <c>timeout</c> is set to <see cref="TimeSpan.Zero" />, a 5 seconds timeout is used.
/// </remarks>
public void Wait(ProcessorPin pin, bool waitForUp = true, TimeSpan timeout = new TimeSpan())
{
var pinPoll = pinPolls[pin];
if (Read(pin) == waitForUp)
return;
var actualTimeout = GetActualTimeout(timeout);
while (true)
{
// TODO: timeout after the remaining amount of time.
var waitResult = Interop.epoll_wait(pinPoll.PollDescriptor, pinPoll.OutEventPtr, 1, (int)actualTimeout.TotalMilliseconds);
if (waitResult > 0)
{
if (Read(pin) == waitForUp)
break;
}
else if (waitResult == 0)
throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, "Operation timed out after waiting {0}ms for the pin {1} to be {2}", actualTimeout, pin, (waitForUp ? "up" : "down")));
else
throw new IOException("Call to epoll_wait API failed");
}
}
/// <summary>
/// Releases the specified pin.
/// </summary>
/// <param name="pin">The pin.</param>
public void Release(ProcessorPin pin)
{
UninitializePoll(pin);
using (var streamWriter = new StreamWriter(Path.Combine(gpioPath, "unexport"), false))
streamWriter.Write((int)pin);
SetPinMode(pin, Interop.BCM2835_GPIO_FSEL_INPT);
}
/// <summary>
/// Modified the status of a pin.
/// </summary>
/// <param name="pin">The pin.</param>
/// <param name="value">The pin status.</param>
public void Write(ProcessorPin pin, bool value)
{
int shift;
var offset = Math.DivRem((int)pin, 32, out shift);
var pinGroupAddress = gpioAddress + (int)((value ? Interop.BCM2835_GPSET0 : Interop.BCM2835_GPCLR0) + offset);
SafeWriteUInt32(pinGroupAddress, (uint)1 << shift);
}
/// <summary>
/// Reads the status of the specified pin.
/// </summary>
/// <param name="pin">The pin.</param>
/// <returns>
/// The pin status.
/// </returns>
public bool Read(ProcessorPin pin)
{
int shift;
var offset = Math.DivRem((int)pin, 32, out shift);
var pinGroupAddress = gpioAddress + (int)(Interop.BCM2835_GPLEV0 + offset);
var value = SafeReadUInt32(pinGroupAddress);
return (value & (1 << shift)) != 0;
}
/// <summary>
/// Reads the status of the specified pins.
/// </summary>
/// <param name="pins">The pins.</param>
/// <returns>
/// The pins status.
/// </returns>
public ProcessorPins Read(ProcessorPins pins)
{
var pinGroupAddress = gpioAddress + (int)(Interop.BCM2835_GPLEV0 + (uint)0 * 4);
var value = SafeReadUInt32(pinGroupAddress);
return (ProcessorPins)((uint)pins & value);
}
#endregion
#region Private Methods
private static uint GetProcessorBaseAddress(Processor processor)
{
switch (processor)
{
case Processor.Bcm2708:
return Interop.BCM2835_GPIO_BASE;
case Processor.Bcm2709:
case Processor.Bcm2835:
return Interop.BCM2836_GPIO_BASE;
default:
throw new ArgumentOutOfRangeException("processor");
}
}
private static TimeSpan GetActualTimeout(TimeSpan timeout)
{
if (timeout > TimeSpan.Zero)
return timeout;
if (timeout < TimeSpan.Zero)
return MinimumTimeout;
return DefaultTimeout;
}
private void InitializePoll(ProcessorPin pin)
{
lock (pinPolls)
{
PinPoll poll;
if (pinPolls.TryGetValue(pin, out poll))
return;
var pinPoll = new PinPoll();
pinPoll.PollDescriptor = Interop.epoll_create(1);
if (pinPoll.PollDescriptor < 0)
throw new IOException("Call to epoll_create(1) API failed with the following return value: " + pinPoll.PollDescriptor);
var valuePath = Path.Combine(gpioPath, string.Format("gpio{0}/value", (int)pin));
pinPoll.FileDescriptor = UnixFile.OpenFileDescriptor(valuePath, UnixFileMode.ReadOnly | UnixFileMode.NonBlocking);
var ev = new Interop.epoll_event
{
events = (Interop.EPOLLIN | Interop.EPOLLET | Interop.EPOLLPRI),
data = new Interop.epoll_data { fd = pinPoll.FileDescriptor }
};
pinPoll.InEventPtr = Marshal.AllocHGlobal(64);
Marshal.StructureToPtr(ev, pinPoll.InEventPtr, false);
var controlResult = Interop.epoll_ctl(pinPoll.PollDescriptor, Interop.EPOLL_CTL_ADD, pinPoll.FileDescriptor, pinPoll.InEventPtr);
if (controlResult != 0)
throw new IOException("Call to epoll_ctl(EPOLL_CTL_ADD) API failed with the following return value: " + controlResult);
pinPoll.OutEventPtr = Marshal.AllocHGlobal(64);
pinPolls[pin] = pinPoll;
}
}
private void UninitializePoll(ProcessorPin pin)
{
PinPoll poll;
if (pinPolls.TryGetValue(pin, out poll))
{
pinPolls.Remove(pin);
var controlResult = poll.InEventPtr != IntPtr.Zero ? Interop.epoll_ctl(poll.PollDescriptor, Interop.EPOLL_CTL_DEL, poll.FileDescriptor, poll.InEventPtr) : 0;
Marshal.FreeHGlobal(poll.InEventPtr);
Marshal.FreeHGlobal(poll.OutEventPtr);
UnixFile.CloseFileDescriptor(poll.PollDescriptor);
UnixFile.CloseFileDescriptor(poll.FileDescriptor);
if (controlResult != 0)
throw new IOException("Call to epoll_ctl(EPOLL_CTL_DEL) API failed with the following return value: " + controlResult);
}
}
private static string ToString(PinDetectedEdges edges)
{
switch (edges)
{
case PinDetectedEdges.Both:
return "both";
case PinDetectedEdges.Rising:
return "rising";
case PinDetectedEdges.Falling:
return "falling";
case PinDetectedEdges.None:
return "none";
default:
throw new ArgumentOutOfRangeException("edges", edges, string.Format(CultureInfo.InvariantCulture, "{0} is not a valid value for edge detection", edges));
}
}
private void SetPinResistorClock(ProcessorPin pin, bool on)
{
int shift;
var offset = Math.DivRem((int)pin, 32, out shift);
var clockAddress = gpioAddress + (int)(Interop.BCM2835_GPPUDCLK0 + offset);
SafeWriteUInt32(clockAddress, (uint)(on ? 1 : 0) << shift);
}
private void WriteResistor(uint resistor)
{
var resistorPin = gpioAddress + (int)Interop.BCM2835_GPPUD;
SafeWriteUInt32(resistorPin, resistor);
}
private void SetPinMode(ProcessorPin pin, uint mode)
{
// Function selects are 10 pins per 32 bit word, 3 bits per pin
var pinModeAddress = gpioAddress + (int)(Interop.BCM2835_GPFSEL0 + 4 * ((int)pin / 10));
var shift = 3 * ((int)pin % 10);
var mask = Interop.BCM2835_GPIO_FSEL_MASK << shift;
var value = mode << shift;
WriteUInt32Mask(pinModeAddress, value, mask);
}
private static void WriteUInt32Mask(IntPtr address, uint value, uint mask)
{
var v = SafeReadUInt32(address);
v = (v & ~mask) | (value & mask);
SafeWriteUInt32(address, v);
}
private static uint SafeReadUInt32(IntPtr address)
{
// Make sure we dont return the _last_ read which might get lost
// if subsequent code changes to a different peripheral
var ret = ReadUInt32(address);
ReadUInt32(address);
return ret;
}
private static uint ReadUInt32(IntPtr address)
{
unchecked
{
return (uint)Marshal.ReadInt32(address);
}
}
private static void SafeWriteUInt32(IntPtr address, uint value)
{
// Make sure we don't rely on the first write, which may get
// lost if the previous access was to a different peripheral.
WriteUInt32(address, value);
WriteUInt32(address, value);
}
private static void WriteUInt32(IntPtr address, uint value)
{
unchecked
{
Marshal.WriteInt32(address, (int)value);
}
}
private struct PinPoll
{
public int FileDescriptor;
public int PollDescriptor;
public IntPtr InEventPtr;
public IntPtr OutEventPtr;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace DataMigration
{
/// <summary>
/// There's an instance of FeedProcessor for each DataSource in the Plan. It uses the
/// DataSourcePlan and the contained FeedFilePlans to figure out what files to process,
/// which parsers to use, which Stager to use, etc.
///
/// </summary>
public class FeedProcessor : IFeedProcessor
{
// Define some string constants that are used in multiple places.
public const string LoadNumberString = "LoadNum";
public const string DataSourceCodeString = "DataSourceCode";
public const string IdString = "Id";
public const string RowNumStr = "RowNumber";
public const string DestColumnStr = "DestColumn";
public const string ReasonStr = "Reason";
public const string ForeignIdStr = "ForeignId";
public const string RowDataStr = "RowData";
#region IFeedProcessor implementation
/// <summary>
/// The ready-to-use subplan is a collection of components that can be consumed; if
/// specified, then the datasource can get away without literally specifying the
/// stager, feedmanager, feedaccessor, and phaselogger explicitly.
/// </summary>
/// <value>The ready to use sub plan.</value>
public IReadyToUseSubPlan ReadyToUseSubPlan {get; set;}
/// <summary>
/// The phaseLogger is specified declaratively in the DataSourcePlan for this feed.
/// It's used to log the various stages/steps the feed goes through.
/// </summary>
public IPhaseLogger PhaseLogger { get; set; }
/// <summary>
/// The MonitoringPublisher is the facility for publishing data to be monitored by
/// operations.
/// </summary>
public IPublishMonitoringData MonitoringPublisher {get; set;}
/// <summary>
/// The DataMigrationPlan consists of multiple DataSourcePlans, which correspond to
/// each DataSourceCode that can be processed. Each DataSourcePlan describes to the
/// FeedProcessor the list of FeedFilePlans which it needs to process.
/// </summary>
public DataSourcePlan Plan { get; set; }
// Each FeedProcessor instance will be loaded with a set of MethodResolvers sufficient
// to resolve all the transform methods described by its Plan.
public IDictionary<string, IMethodResolver> MethodResolvers { get; set; }
// Each FeedProcessor instance will be loaded with a set of LitmusTestResolver objects
// sufficient to resolve all the litmusTest methods as specified in its Plan.
public IDictionary<string, ILitmusTestResolver> LitmusTestResolvers {get; set;}
// Each FeedProcessor instance will be loaded with a set of PostRowProcessor objects
// sufficient to resolve all the PostRowProcessor methods as specified in its Plan.
public IDictionary<string, IPostRowProcessorResolver>
PostRowProcessorResolvers {get; set;}
// The FeedProcessor instance will be loaded with a set of Lookups sufficient to
// resolve all the lookups described by the litmus tests in its FeedFilePlans.
public IDictionary<string, ILookup> Lookups { get; set; }
// The FeedProcessor instance will be loaded with a set of Existence objects
// sufficient to resolve all the existence objects needed by the Litmus test functions
// specified in its FeedFilePlans.
public IDictionary<string, IExistence> ExistenceObjects { get; set; }
/// <summary>
/// As the name implies, the RowProcessor processes each native row of parsed data,
/// and turns it into normalized data that can be ingested into our staging location.
/// </summary>
/// <value>The row processor.</value>
public IRowProcessor RowProcessor { get; set; }
/// <summary>
/// A feed processor has N post processors, which are very domain-specific. Normally,
/// there will just be one post-processor (e.g., pushing from staging table into
/// Camelot member table), but there could be more (i.e., pushing into Redis).
/// </summary>
/// <value>The post processors.</value>
public IList<IPostProcessor> PostProcessors { get; set; }
/// <summary>
/// This entry point implements the first stage of processing for a datasource. The
/// feed files have already been put in place (as a precondition), and this method will
/// then parse the feed files, transform them as described by their respective
/// transformMaps, and call the DataStager for this FeedProcessor to stage the
/// intermediate results (i.e. store them for further processing by the PostProcessing
/// entry point).
/// <returns>The loadnumber that was generated as part of the processing. It is
/// returned so it can be passed on to the PostProcessors.</returns>
/// </summary>
public int Process()
{
var batchSize = int.Parse (
ConfigurationManager.AppSettings ["XformRowsBatchSize"]);
// The Plan has all the information about local files to process, plus the
// transformMaps, plus the parser for each file (they can be different), plus the
// table to copy it to, etc.
var stager = GetFeedStager();
stager.BatchSize = batchSize;
var loadNumber = stager.GetLoadNumber ();
var dataSourceCode = Plan.DataSourceCode;
var existenceKeys = AddDataSourceSpecificExistences();
var lookupKeys = AddDataSourceSpecificLookups();
try {
foreach (var plan in Plan.FeedFilePlans) {
stager.Location = plan.StagingLocation;
stager.BadRowsLocation = plan.BadRowsStagingLocation;
stager.WarnRowsLocation = plan.WarnRowsStagingLocation;
var dataTable = SetUpDataTable(plan);
var badRowsDataTable = SetupBadOrWarnRowsDataTable();
var warnRowsDataTable = SetupBadOrWarnRowsDataTable();
var stopWatch = Stopwatch.StartNew();
using (var parser = AcquireParser(plan)) {
parser.Open(plan.LocalFile.FullName);
var message = String.Format("Starting processing of file {0}",
plan.LocalFile.FullName);
PhaseLogger.Log(new PhaseLogEntry {
LogSource = MigrationEngine.LogSource,
DataSourceCode = dataSourceCode,
LoadNumber = loadNumber,
Phase = DataMigrationPhase.ProcessingRows,
Description = message
});
// Skip over any initial lines as defined by config. Most commonly,
// this is the header row.
for (var i = 0; i < plan.SkipLines.GetValueOrDefault(0); i++) {
parser.NextRow();
}
IList<string> row = null;
// process in batches, bulkloading each batch before continuing.
do {
for (var i = 0; i < batchSize; i++) {
row = parser.NextRow();
if (row == null) {
break;
}
// Obtain the id that is designated by this feedplan as being
// the thing that is most useful to put in the 'ForeignId'
// column in the BadRows collection.
var foreignId = ProcessingHelper.GetForeignId(loadNumber,
dataSourceCode, plan, parser.CurrentRow, MethodResolvers,
ExistenceObjects, Lookups, row);
// Run the litmus tests. If any fail, stop right now, and put
// the row in the BadRows table.
var reason = ProcessLitmusTests(row, plan);
if (!String.IsNullOrEmpty(reason)) {
AddToBadOrWarnRowsDataTable(badRowsDataTable,
dataSourceCode, loadNumber, parser.CurrentRow,
"LitmusTestFailure", reason, foreignId, row);
continue;
}
var warnings = ProcessWarningTests(row, plan);
if (warnings.Count > 0) {
AddToWarnRowsDataTable(warnRowsDataTable, dataSourceCode,
loadNumber, parser.CurrentRow, "WarnTestFailure",
warnings, foreignId, row);
// Do not pass GO - this row still must be processed.
}
IDictionary<string, string> transformedRow = null;
try {
// This is the actual work being done.
transformedRow = RowProcessor.TransformRow(loadNumber,
dataSourceCode, parser.CurrentRow, plan, row);
} catch (BadRowException brex) {
// Add foreignId context to the exception, so auditors of
// the BadRows table can see what they want to see.
brex.ForeignId = foreignId;
AddToBadRowsDataTable(badRowsDataTable, dataSourceCode,
brex, row);
continue; // Go get the next row.
} catch (Exception ex) {
throw new Exception(String.Format("Process - error at row "
+ " {0} of feed file {1}",
parser.CurrentRow, plan.LocalFile.FullName), ex);
}
AssertPasswordSanity(transformedRow, parser.CurrentRow);
// After EVERYTHING else is done, and we know the row is good,
// execute the PostRowProcessors.
ProcessPostRowProcessors(loadNumber,row,transformedRow,plan);
RowProcessor.AddRowToDataTable(plan, loadNumber,
dataSourceCode, transformedRow, dataTable);
}
if (dataTable.Rows.Count > 0 || badRowsDataTable.Rows.Count > 0 ||
warnRowsDataTable.Rows.Count > 0) {
try {
stager.BulkLoad(dataTable, badRowsDataTable,
warnRowsDataTable);
}
catch (Exception ex) {
throw new Exception(String.Format("Error staging load" +
"number {0}, row {1}, error = {2}",
loadNumber, parser.CurrentRow, ex.Message));
}
dataTable.Rows.Clear();
badRowsDataTable.Clear();
}
} while (row != null);
}
stopWatch.Stop();
var logMessage = String.Format("DataSourceCode {0}, file {1} took {2} " +
"seconds to process and copy to staging.",
dataSourceCode, plan.FileName,
stopWatch.Elapsed.TotalSeconds);
PhaseLogger.Log(new PhaseLogEntry {
LogSource = MigrationEngine.LogSource,
DataSourceCode = Plan.DataSourceCode,
LoadNumber = loadNumber,
Phase = DataMigrationPhase.CompletedBulkCopy,
Description = logMessage
});
}
} catch (Exception ex) {
throw new Exception(String.Format("Error preprocessing load {0} = {1}",
loadNumber, ex.Message));
} finally {
RemoveDataSourceSpecificExistences(existenceKeys);
RemoveDataSourceSpecificLookups(lookupKeys);
}
return loadNumber;
}
/// <summary>
/// Just a check for a mistake that has been made for FFT. Makes sure that, if we have
/// calculated a PasswordImportState of "1", then there needs to be a PasswordHash.
/// </summary>
/// <param name="outRow">OutputRow we have built up.</param>
/// <param name="lineNumber">The line number of the feed.</param>
private static void AssertPasswordSanity(IDictionary<string, string> outRow,
int lineNumber)
{
if (!outRow.ContainsKey("PasswordImportState") ||
outRow["PasswordImportState"] != "1") {
return;
}
if (!outRow.ContainsKey("PasswordHash") ||
String.IsNullOrEmpty(outRow["PasswordHash"]) ||
!outRow.ContainsKey("PasswordHashSalt") ||
String.IsNullOrEmpty(outRow["PasswordHashSalt"])) {
throw new Exception(
String.Format(
"Something is wrong with this integration - line {0} - processed " +
"passwordImportState == 1, yet no PasswordHash - cannot continue - " +
"FIX THIS.", lineNumber));
}
}
/// <summary>
/// Helper which acquires the parser either from the description in the FeedFilePlan
/// (it favors this one), or if that's missing, from the ReadyToUseSubPlan.
/// </summary>
/// <param name="plan">FeedFilePlan for this file.</param>
/// <returns>An IParser instance.</returns>
private IParser AcquireParser(FeedFilePlan plan)
{
var parserDescriptor = plan.Parser ?? ReadyToUseSubPlan.ParserDescriptor;
if (null == parserDescriptor) {
throw new Exception(String.Format("AcquireParser - no parser defined for" +
" file {0}, either in feed file plan or in readyToUsePlan",
plan.FileName));
}
var parser = (IParser)Activator.CreateInstance(
Utilities.GetTypeFromFqName(parserDescriptor.Assembly));
parser.Properties = parserDescriptor.Properties;
return parser;
}
/// <summary>
/// Gets the feed stager from either the readyToUsePlan or instantiates it through
/// reflection from the main Plan.
/// </summary>
/// <returns>The feed stager.</returns>
private IFeedStager GetFeedStager()
{
if (Plan.FeedStager != null) {
// Intanstiate the IDataStager object for this group of files.
var type = Utilities.GetTypeFromFqName(Plan.FeedStager.Assembly);
var stager = (IFeedStager)Activator.CreateInstance(type);
var feedStagerDescriptor = Plan.FeedStager;
if (feedStagerDescriptor.Properties != null &&
feedStagerDescriptor.Properties.Length > 0) {
stager.Properties = feedStagerDescriptor.Properties;
}
return stager;
}
if (ReadyToUseSubPlan != null && ReadyToUseSubPlan.Stager != null) {
return ReadyToUseSubPlan.Stager;
}
throw new Exception(String.Format("No Feed Stager found for datasourcecode = {0}",
Plan.DataSourceCode));
}
/// <summary>
/// PostProcess is the final stage of processing, where business rules are applied
// against the data placed in staging by the Process() endpoint, and resultant rows
// inserted, modified, and/or deleted at the final location.
/// <param name="loadNum">The load number to perform post processing on.</param>
/// <param name="readyToUseSubPlan">A ReadyToUseSubPlan (can be null) that may
/// have additional PostProcessors to be run first.</param>
/// </summary>
public void PostProcess (int loadNum, IReadyToUseSubPlan readyToUseSubPlan)
{
if (!Plan.PostProcess) {
return;
}
AcquirePostPostProcessors (readyToUseSubPlan);
RunPostProcessors(loadNum, PostProcessors);
}
#endregion
private void RunPostProcessors(int loadNum, IEnumerable<IPostProcessor> postProcessors)
{
if (postProcessors == null) {
return;
}
foreach (var postProcessor in postProcessors) {
postProcessor.PostProcess(loadNum, Plan);
}
}
/// <summary>
/// Adds the data source specific existence Objects. These are described in the
/// DataSourcePlan. They will be instantiated, and then later removed from the global
/// set of Existence objects when processing this datasource is complete.
/// </summary>
/// <returns>The data source specific existences.</returns>
IEnumerable<string> AddDataSourceSpecificExistences()
{
var existenceKeys = new List<string>();
if (Plan.Existences != null) {
var datasourceSpecificExistences = MigrationEngine.AcquireExistenceObjects(
Plan.Existences);
foreach (var existenceKeyValuePair in datasourceSpecificExistences) {
var key = existenceKeyValuePair.Key;
var value = existenceKeyValuePair.Value;
if (!ExistenceObjects.ContainsKey(key)) {
ExistenceObjects[key] = value;
existenceKeys.Add(key);
}
}
}
return existenceKeys;
}
/// <summary>
/// Adds the data source specific lookups. These are also described in the
/// DataSourcePlan. They will be instantiated, and then later removed from the global
/// set of Lookup objects when processing this datasource is complete.
/// </summary>
/// <returns>The data source specific lookups.</returns>
IEnumerable<string> AddDataSourceSpecificLookups()
{
var lookupKeys = new List<string>();
if (Plan.Lookups != null) {
var dataSourceSpecificLookups = MigrationEngine.AcquireLookups(Plan.Lookups);
foreach (var lookupKeyValuePair in dataSourceSpecificLookups) {
var key = lookupKeyValuePair.Key;
var value = lookupKeyValuePair.Value;
if (!Lookups.ContainsKey(key)) {
Lookups[key] = value;
lookupKeys.Add(key);
}
}
}
return lookupKeys;
}
/// <summary>
/// Removes the data source specific lookups.
/// </summary>
/// <param name="lookupKeys">Lookup keys.</param>
void RemoveDataSourceSpecificLookups(IEnumerable<string> lookupKeys)
{
foreach (var lookupKey in lookupKeys) {
if (Lookups.ContainsKey(lookupKey)) {
Lookups.Remove(lookupKey);
}
}
}
/// <summary>
/// Removes the data source specific existences.
/// </summary>
/// <param name="existenceKeys">Existence keys.</param>
void RemoveDataSourceSpecificExistences(IEnumerable<string> existenceKeys)
{
foreach (var existenceKey in existenceKeys) {
if (ExistenceObjects.ContainsKey(existenceKey)) {
ExistenceObjects.Remove(existenceKey);
}
}
}
/// <summary>
/// Creates and sets up the DataTable with column information.
/// </summary>
/// <returns>A new DataTable, with Columns set up, ready to accept new rows.</returns>
/// <param name="feedFilePlan">The Plan for this Feed File; it contains all the
/// TransformMaps and other information necessary to set up the column headers in this
/// DataTable.
/// </param>
private DataTable SetUpDataTable (FeedFilePlan feedFilePlan)
{
var dt = new DataTable ();
dt.Columns.Add (IdString, typeof(Int32));
dt.Columns.Add (LoadNumberString, typeof(Int32));
dt.Columns.Add (DataSourceCodeString, typeof(string));
foreach (var map in feedFilePlan.TransformMaps) {
var t = typeof(String); // default
if (map.Type != null) {
switch (map.Type) {
case "int":
t = typeof(int);
break;
case "long":
t = typeof(long);
break;
case "bool":
t = typeof(bool);
break;
case "float":
t = typeof(float);
break;
case "double":
t = typeof(double);
break;
case "DateTime":
t = typeof(DateTime);
break;
}
}
dt.Columns.Add (map.DestCol, t);
}
return dt;
}
/// <summary>
/// Instantiates and builds the column definitions for the bad rows DataTable.
/// </summary>
/// <returns>The newly created datatable.</returns>
DataTable SetupBadOrWarnRowsDataTable ()
{
var dt = new DataTable ();
dt.Columns.Add (LoadNumberString, typeof(Int32));
dt.Columns.Add (DataSourceCodeString, typeof(string));
dt.Columns.Add (RowNumStr, typeof(Int32));
dt.Columns.Add (DestColumnStr, typeof(String));
dt.Columns.Add (ReasonStr, typeof(String));
dt.Columns.Add (ForeignIdStr, typeof(String));
dt.Columns.Add (RowDataStr, typeof(string));
return dt;
}
/// <summary>
/// Rows are processed in batches, and good and bad rows collected. This function
/// add a single bad row to a datatable which is comprised of all the bad rows for a
/// single batch.
/// </summary>
/// <param name="badRowDataTable">The data table to add to.</param>
/// <param name="dataSourceCode">The DataSourceCode.</param>
/// <param name="brex">The BadRowException that has contextual information.</param>
/// <param name="rowData">The raw parsed row data.</param>
void AddToBadRowsDataTable (DataTable badRowDataTable, string dataSourceCode,
BadRowException brex, IList<string> rowData)
{
AddToBadOrWarnRowsDataTable(badRowDataTable, dataSourceCode, brex.LoadNumber,
brex.RowNumber, brex.DestColumn, brex.Reason, brex.ForeignId,
rowData);
}
/// <summary>
/// Helper function for adding rows to data table that takes the individual
/// arguments. This makes it possible to do this without a BadRowException being
/// present, as in the case of LitmusTests.
/// </summary>
/// <param name="dataTable">The data table to add to.</param>
/// <param name="dataSourceCode">The DataSourceCode.</param>
/// <param name="loadNumber">The load number of the data.</param>
/// <param name="rowNumber">The row index.</param>
/// <param name="destinationColumn">The name of the destination column.</param>
/// <param name="reason">The reason it's a bad row.</param>
/// <param name="foreignId">The foreign id for the row.</param>
/// <param name="rowData">The raw parsed row data.</param>
private void AddToBadOrWarnRowsDataTable(DataTable dataTable,
string dataSourceCode, int loadNumber, int rowNumber, string destinationColumn,
string reason, string foreignId, IList<string> rowData)
{
var dr = dataTable.NewRow();
dr[LoadNumberString] = loadNumber;
dr[DataSourceCodeString] = dataSourceCode;
dr[RowNumStr] = rowNumber;
dr[DestColumnStr] = destinationColumn;
dr[ReasonStr] = reason ?? String.Empty;
dr[ForeignIdStr] = foreignId ?? String.Empty;
dr[RowDataStr] = FormXmlDocumentFromRowData(rowData);
dataTable.Rows.Add(dr);
}
/// <summary>
/// Helper function that adds all the warning rows for a given input row to the
/// WarnRows datatable.
/// </summary>
/// <param name="warnRowsDataTable">DataTable for WarnRows table.</param>
/// <param name="dataSourceCode">The DataSourceCode.</param>
/// <param name="loadNumber">The Load Number.</param>
/// <param name="rowNumber">The row index.</param>
/// <param name="destinationColumn">The name of the destination column.</param>
/// <param name="warnings">The List of Warnings.</param>
/// <param name="foreignId">The foreignId for the row.</param>
/// <param name="rowData">The raw parsed row data.</param>
private void AddToWarnRowsDataTable(DataTable warnRowsDataTable, string dataSourceCode,
int loadNumber, int rowNumber, string destinationColumn,
IList<string> warnings , string foreignId,
IList<string> rowData)
{
// Add one row for each warning. This means a single input row can generate
// multiple warning rows (which is right and proper).
foreach (var warning in warnings) {
AddToBadOrWarnRowsDataTable(warnRowsDataTable, dataSourceCode, loadNumber,
rowNumber, destinationColumn, warning, foreignId, rowData);
}
}
/// <summary>
/// Produces a simple xml object from the row Data. The reason to do it this way is
/// that the BadRows table has to support any feed, with any schema. Instead of using
/// a blob or nvarchar(max) column, the Xml data type is queryable.
/// </summary>
string FormXmlDocumentFromRowData (IList<string> rowData)
{
var builder = new StringBuilder ("<dataRow>");
for (var i = 1; i <= rowData.Count; i++) {
var dataValue = rowData[i - 1].Replace("]]>", String.Empty);
builder.AppendFormat ("<dataValue_{0}><![CDATA[{1}]]></dataValue_{0}>",
i, dataValue);
}
builder.Append ("</dataRow>");
return builder.ToString ();
}
/// <summary>
/// The DataSourcePlan has a set of PostProcessors, identified by fully-qualified
/// assembly name. If there is a readyToUseSubPlan, and it has postprocessors, it
/// will add those first.
/// <param name="readyToUseSubPlan">A ReadyToUsePlan (possibly null) they specify
/// processors to be fired first.</param>
/// </summary>
private void AcquirePostPostProcessors (IReadyToUseSubPlan readyToUseSubPlan)
{
PostProcessors = new List<IPostProcessor> ();
try {
// Get the processors from the ReadyToUseSubPlan first.
if (readyToUseSubPlan != null &&
readyToUseSubPlan.PostProcessorDescriptors != null) {
foreach (var postProcessorDescriptor in
readyToUseSubPlan.PostProcessorDescriptors) {
InstantiatePostProcessor(postProcessorDescriptor);
}
}
// Now get the ones from the DataSourcePlan.
if (Plan.PostProcessors != null) {
foreach (var postProcessorDescriptor in Plan.PostProcessors) {
InstantiatePostProcessor(postProcessorDescriptor);
}
}
} catch (Exception ex) {
throw new Exception (
String.Format ("AcquirePostPostProcessors - error {0}", ex.Message), ex);
}
}
/// <summary>
/// Instantiates a single PostProcessor.
/// </summary>
/// <param name="postProcessorDescriptor"></param>
/// <returns>Instantiated PostProcessor object.</returns>
private IPostProcessor InstantiatePostProcessor(
PostProcessorDescriptor postProcessorDescriptor)
{
var postProcessor = (IPostProcessor)
Activator.CreateInstance(Type.GetType(postProcessorDescriptor.Assembly));
// Propagate the plan-specified properties to the instance, and set the
// PhaseLogger to be the same as the enclosing FeedProcessor.
postProcessor.Properties = postProcessorDescriptor.Properties;
postProcessor.PhaseLogger = PhaseLogger;
PostProcessors.Add(postProcessor);
return postProcessor;
}
/// <summary>
/// Processes the post-row processor methods. These are methods that optionally run
/// subsequent to a row successfully processing, that generate some desired
/// side-effect.
/// </summary>
/// <param name="loadNumber">The load number.</param>
/// <param name="parsedInputRow">The raw row.</param>
/// <param name="transformedRow">The complete output row.</param>
/// <param name="plan">A FeedFilePlan with PostRowProcessorDescriptors.</param>
void ProcessPostRowProcessors(int loadNumber, IList<string> parsedInputRow,
IDictionary<string, string> transformedRow,FeedFilePlan plan)
{
if (plan.PostRowProcessorDescriptors == null) {
return;
}
foreach (var postRowProcessorDescriptor in plan.PostRowProcessorDescriptors) {
InvokePostRowProcessor(loadNumber, parsedInputRow, transformedRow,
postRowProcessorDescriptor);
}
}
/// <summary>
/// Processes the litmus tests.
/// </summary>
/// <returns>A reason for failing, on the first test that fails.</returns>
/// <param name="row">The raw row.</param>
/// <param name="plan">A FeedFilePlan with Litmus Test Descriptors.</param>
string ProcessLitmusTests(IList<string> row, FeedFilePlan plan)
{
foreach (var litmusTestDescriptor in plan.LitmusTestDescriptors) {
if (!PerformLitmusTest(row, litmusTestDescriptor)) {
return litmusTestDescriptor.Reason;
}
}
return String.Empty;
}
/// <summary>
/// Processes the warning tests. Warning Tests are litmus tests, the only difference
/// being that the handling of a failure is different. Warning tests cause the row
/// to be copied to the WarnRows table, but we still process the row.
/// </summary>
/// <returns>A list of warnings</returns>
/// <param name="row">The raw row.</param>
/// <param name="plan">A FeedFilePlan with Warning Test Descriptors.</param>
List<string> ProcessWarningTests(IList<string> row, FeedFilePlan plan)
{
var warnings = new List<String>();
if (plan.WarningTestDescriptors != null) {
foreach (var warnTestDesciptor in plan.WarningTestDescriptors) {
if (!PerformLitmusTest(row, warnTestDesciptor)) {
warnings.Add(warnTestDesciptor.Reason);
}
}
}
return warnings;
}
/// <summary>
/// This function is called for litmustest functions specified in the FeedFileMap.
/// </summary>
/// <param name="row">The raw data row.</param>
/// <param name="map">An IMethodMap that describes how to perform the Litmus Test.
/// </param>
/// <returns>True, if the row passed the test, false otherwise.</returns>
bool PerformLitmusTest(IList<string> row, IMethodMap map)
{
if (String.IsNullOrEmpty(map.MethodTag)) {
throw new Exception(
String.Format("TransformRow - have method {0}, but no methodTag",
map.Method));
}
if (!LitmusTestResolvers.ContainsKey(map.MethodTag)) {
throw new Exception(
String.Format("PerformLitmusTest - methodTag {0} for" +
" method {1} missing from map of LitmusTestResolvers - config error",
map.MethodTag, map.Method));
}
var args = ProcessingHelper.ParseMethodArguments(row, map, Lookups);
var method = LitmusTestResolvers[map.MethodTag].ResolveLitmusTest(map.Method);
try {
return method(Lookups, ExistenceObjects, args);
} catch (Exception ex) {
throw new Exception(
String.Format("PerformLitmusTest - transformation " +
"function {0} incorrectly threw an error {1} - this is a " +
"fatal bug in the litmus test function code",
map.Method, ex.Message));
}
}
/// <summary>
/// This function is called for PostRowProcessor methods specified in the FeedFileMap.
/// </summary>
/// <param name="loadNumber"></param>
/// <param name="row">The raw data row.</param>
/// <param name="rowInProgress">The completed output row.</param>
/// <param name="map">An IMethodMap that describes how to perform the PostRowProcessor.
/// </param>
void InvokePostRowProcessor(int loadNumber, IList<string> row,
IDictionary<string, string> rowInProgress, IMethodMap map)
{
if (String.IsNullOrEmpty(map.MethodTag)) {
throw new Exception(
String.Format("InvokePostRowProcessor - have method {0}, but no methodTag",
map.Method));
}
if (!PostRowProcessorResolvers.ContainsKey(map.MethodTag)) {
throw new Exception(
String.Format("InvokePostRowProcessor - methodTag {0} for" +
" method {1} missing from map of InvokePostRowProcessorResolvers - "
+ "config error",
map.MethodTag, map.Method));
}
var args = ProcessingHelper.ParseMethodArguments(row, map, Lookups);
var method = PostRowProcessorResolvers[map.MethodTag]
.ResolvePostRowProcessor(map.Method);
try {
method(loadNumber, Lookups, ExistenceObjects, rowInProgress, args);
} catch (Exception ex) {
throw new Exception(
String.Format("InvokePostRowProcessor - " +
"method {0} incorrectly threw an error {1} - this is a fatal bug in the " +
"postRowProcessor method code",
map.Method, ex.Message));
}
}
}
}
| |
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.38.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Admin Data Transfer API Version datatransfer_v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/admin-sdk/data-transfer/'>Admin Data Transfer API</a>
* <tr><th>API Version<td>datatransfer_v1
* <tr><th>API Rev<td>20160223 (418)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/admin-sdk/data-transfer/'>
* https://developers.google.com/admin-sdk/data-transfer/</a>
* <tr><th>Discovery Name<td>admin
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Admin Data Transfer API can be found at
* <a href='https://developers.google.com/admin-sdk/data-transfer/'>https://developers.google.com/admin-sdk/data-transfer/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Admin.DataTransfer.datatransfer_v1
{
/// <summary>The DataTransfer Service.</summary>
public class DataTransferService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "datatransfer_v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public DataTransferService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public DataTransferService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
applications = new ApplicationsResource(this);
transfers = new TransfersResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "admin"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/admin/datatransfer/v1/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "admin/datatransfer/v1/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch/admin/datatransfer_v1"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch/admin/datatransfer_v1"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Admin Data Transfer API.</summary>
public class Scope
{
/// <summary>View and manage data transfers between users in your organization</summary>
public static string AdminDatatransfer = "https://www.googleapis.com/auth/admin.datatransfer";
/// <summary>View data transfers between users in your organization</summary>
public static string AdminDatatransferReadonly = "https://www.googleapis.com/auth/admin.datatransfer.readonly";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Admin Data Transfer API.</summary>
public static class ScopeConstants
{
/// <summary>View and manage data transfers between users in your organization</summary>
public const string AdminDatatransfer = "https://www.googleapis.com/auth/admin.datatransfer";
/// <summary>View data transfers between users in your organization</summary>
public const string AdminDatatransferReadonly = "https://www.googleapis.com/auth/admin.datatransfer.readonly";
}
private readonly ApplicationsResource applications;
/// <summary>Gets the Applications resource.</summary>
public virtual ApplicationsResource Applications
{
get { return applications; }
}
private readonly TransfersResource transfers;
/// <summary>Gets the Transfers resource.</summary>
public virtual TransfersResource Transfers
{
get { return transfers; }
}
}
///<summary>A base abstract class for DataTransfer requests.</summary>
public abstract class DataTransferBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new DataTransferBaseServiceRequest instance.</summary>
protected DataTransferBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>An opaque string that represents a user for quota purposes. Must not exceed 40
/// characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Deprecated. Please use quotaUser instead.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes DataTransfer parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "applications" collection of methods.</summary>
public class ApplicationsResource
{
private const string Resource = "applications";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ApplicationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves information about an application for the given application ID.</summary>
/// <param name="applicationId">ID of the application resource to be retrieved.</param>
public virtual GetRequest Get(long applicationId)
{
return new GetRequest(service, applicationId);
}
/// <summary>Retrieves information about an application for the given application ID.</summary>
public class GetRequest : DataTransferBaseServiceRequest<Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.Application>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, long applicationId)
: base(service)
{
ApplicationId = applicationId;
InitParameters();
}
/// <summary>ID of the application resource to be retrieved.</summary>
[Google.Apis.Util.RequestParameterAttribute("applicationId", Google.Apis.Util.RequestParameterType.Path)]
public virtual long ApplicationId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "applications/{applicationId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"applicationId", new Google.Apis.Discovery.Parameter
{
Name = "applicationId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Lists the applications available for data transfer for a customer.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists the applications available for data transfer for a customer.</summary>
public class ListRequest : DataTransferBaseServiceRequest<Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.ApplicationsListResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Immutable ID of the Google Apps account.</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; set; }
/// <summary>Maximum number of results to return. Default is 100.</summary>
/// [minimum: 1]
/// [maximum: 500]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>Token to specify next page in the list.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "applications"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
/// <summary>The "transfers" collection of methods.</summary>
public class TransfersResource
{
private const string Resource = "transfers";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public TransfersResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves a data transfer request by its resource ID.</summary>
/// <param name="dataTransferId">ID of the resource to be retrieved. This is returned in the response from the insert
/// method.</param>
public virtual GetRequest Get(string dataTransferId)
{
return new GetRequest(service, dataTransferId);
}
/// <summary>Retrieves a data transfer request by its resource ID.</summary>
public class GetRequest : DataTransferBaseServiceRequest<Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.DataTransfer>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string dataTransferId)
: base(service)
{
DataTransferId = dataTransferId;
InitParameters();
}
/// <summary>ID of the resource to be retrieved. This is returned in the response from the insert
/// method.</summary>
[Google.Apis.Util.RequestParameterAttribute("dataTransferId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string DataTransferId { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "transfers/{dataTransferId}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"dataTransferId", new Google.Apis.Discovery.Parameter
{
Name = "dataTransferId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Inserts a data transfer request.</summary>
/// <param name="body">The body of the request.</param>
public virtual InsertRequest Insert(Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.DataTransfer body)
{
return new InsertRequest(service, body);
}
/// <summary>Inserts a data transfer request.</summary>
public class InsertRequest : DataTransferBaseServiceRequest<Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.DataTransfer>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.DataTransfer body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.DataTransfer Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "insert"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "transfers"; }
}
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Lists the transfers for a customer by source user, destination user, or status.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Lists the transfers for a customer by source user, destination user, or status.</summary>
public class ListRequest : DataTransferBaseServiceRequest<Google.Apis.Admin.DataTransfer.datatransfer_v1.Data.DataTransfersListResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Immutable ID of the Google Apps account.</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; set; }
/// <summary>Maximum number of results to return. Default is 100.</summary>
/// [minimum: 1]
/// [maximum: 500]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>Destination user's profile ID.</summary>
[Google.Apis.Util.RequestParameterAttribute("newOwnerUserId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string NewOwnerUserId { get; set; }
/// <summary>Source user's profile ID.</summary>
[Google.Apis.Util.RequestParameterAttribute("oldOwnerUserId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OldOwnerUserId { get; set; }
/// <summary>Token to specify the next page in the list.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Status of the transfer.</summary>
[Google.Apis.Util.RequestParameterAttribute("status", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Status { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "transfers"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"newOwnerUserId", new Google.Apis.Discovery.Parameter
{
Name = "newOwnerUserId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oldOwnerUserId", new Google.Apis.Discovery.Parameter
{
Name = "oldOwnerUserId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"status", new Google.Apis.Discovery.Parameter
{
Name = "status",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Admin.DataTransfer.datatransfer_v1.Data
{
/// <summary>The JSON template for an Application resource.</summary>
public class Application : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Etag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The application's ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual System.Nullable<long> Id { get; set; }
/// <summary>Identifies the resource as a DataTransfer Application Resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The application's name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The list of all possible transfer parameters for this application. These parameters can be used to
/// select the data of the user in this application to be transfered.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("transferParams")]
public virtual System.Collections.Generic.IList<ApplicationTransferParam> TransferParams { get; set; }
}
/// <summary>Template to map fields of ApplicationDataTransfer resource.</summary>
public class ApplicationDataTransfer : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The application's ID.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("applicationId")]
public virtual System.Nullable<long> ApplicationId { get; set; }
/// <summary>The transfer parameters for the application. These parameters are used to select the data which
/// will get transfered in context of this application.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("applicationTransferParams")]
public virtual System.Collections.Generic.IList<ApplicationTransferParam> ApplicationTransferParams { get; set; }
/// <summary>Current status of transfer for this application. (Read-only)</summary>
[Newtonsoft.Json.JsonPropertyAttribute("applicationTransferStatus")]
public virtual string ApplicationTransferStatus { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Template for application transfer parameters.</summary>
public class ApplicationTransferParam : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The type of the transfer parameter. eg: 'PRIVACY_LEVEL'</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>The value of the coressponding transfer parameter. eg: 'PRIVATE' or 'SHARED'</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual System.Collections.Generic.IList<string> Value { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>Template for a collection of Applications.</summary>
public class ApplicationsListResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of applications that support data transfer and are also installed for the customer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("applications")]
public virtual System.Collections.Generic.IList<Application> Applications { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>Identifies the resource as a collection of Applications.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Continuation token which will be used to specify next page in list API.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
/// <summary>The JSON template for a DataTransfer resource.</summary>
public class DataTransfer : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of per application data transfer resources. It contains data transfer details of the
/// applications associated with this transfer resource. Note that this list is also used to specify the
/// applications for which data transfer has to be done at the time of the transfer resource creation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("applicationDataTransfers")]
public virtual System.Collections.Generic.IList<ApplicationDataTransfer> ApplicationDataTransfers { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The transfer's ID (Read-only).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Identifies the resource as a DataTransfer request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>ID of the user to whom the data is being transfered.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("newOwnerUserId")]
public virtual string NewOwnerUserId { get; set; }
/// <summary>ID of the user whose data is being transfered.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("oldOwnerUserId")]
public virtual string OldOwnerUserId { get; set; }
/// <summary>Overall transfer status (Read-only).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("overallTransferStatusCode")]
public virtual string OverallTransferStatusCode { get; set; }
/// <summary>The time at which the data transfer was requested (Read-only).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("requestTime")]
public virtual string RequestTimeRaw { get; set; }
/// <summary><seealso cref="System.DateTime"/> representation of <see cref="RequestTimeRaw"/>.</summary>
[Newtonsoft.Json.JsonIgnore]
public virtual System.Nullable<System.DateTime> RequestTime
{
get
{
return Google.Apis.Util.Utilities.GetDateTimeFromString(RequestTimeRaw);
}
set
{
RequestTimeRaw = Google.Apis.Util.Utilities.GetStringFromDateTime(value);
}
}
}
/// <summary>Template for a collection of DataTransfer resources.</summary>
public class DataTransfersListResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of data transfer requests.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("dataTransfers")]
public virtual System.Collections.Generic.IList<DataTransfer> DataTransfers { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>Identifies the resource as a collection of data transfer requests.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Continuation token which will be used to specify next page in list API.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
}
| |
using UnityEngine;
using System.Collections;
namespace Xft
{
public class GlowPerObjEvent : CameraEffectEvent
{
public Shader ReplacementShader;
protected GameObject m_shaderCamera;
protected Camera ShaderCamera
{
get
{
if (m_shaderCamera == null)
{
m_shaderCamera = new GameObject("ShaderCamera", typeof(Camera));
m_shaderCamera.GetComponent<Camera>().enabled = false;
m_shaderCamera.hideFlags = HideFlags.HideAndDontSave;
}
return m_shaderCamera.GetComponent<Camera>();
}
}
protected RenderTexture TempRenderTex;
protected RenderTexture TempRenderGlow;
protected Color m_tint;
#region property
public Shader compositeShader;
Material m_CompositeMaterial = null;
protected Material compositeMaterial
{
get
{
if (m_CompositeMaterial == null)
{
m_CompositeMaterial = new Material(compositeShader);
m_CompositeMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_CompositeMaterial;
}
}
public Shader blurShader;
Material m_BlurMaterial = null;
protected Material blurMaterial
{
get
{
if (m_BlurMaterial == null)
{
m_BlurMaterial = new Material(blurShader);
m_BlurMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_BlurMaterial;
}
}
public Shader downsampleShader;
Material m_DownsampleMaterial = null;
protected Material downsampleMaterial
{
get
{
if (m_DownsampleMaterial == null)
{
m_DownsampleMaterial = new Material(downsampleShader);
m_DownsampleMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_DownsampleMaterial;
}
}
//final blend the temp render tecture and dest texture.
public Shader blendShader;
Material m_blendMaterial = null;
protected Material blendMaterial
{
get
{
if (m_blendMaterial == null)
{
m_blendMaterial = new Material(blendShader);
m_blendMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_blendMaterial;
}
}
#endregion
public GlowPerObjEvent(XftEventComponent owner)
: base(CameraEffectEvent.EType.GlowPerObj, owner)
{
ReplacementShader = owner.GlowPerObjReplacementShader;
blendShader = owner.GlowPerObjBlendShader;
downsampleShader = owner.GlowDownSampleShader;
compositeShader = owner.GlowCompositeShader;
blurShader = owner.GlowBlurShader;
}
#region verride functions
public override void Initialize()
{
base.Initialize();
//Note: In forward lightning path, the depth texture is not automatically generated.
if (MyCamera.depthTextureMode == DepthTextureMode.None)
MyCamera.depthTextureMode = DepthTextureMode.Depth;
}
public override bool CheckSupport()
{
bool ret = true;
if (!SystemInfo.supportsImageEffects)
{
ret = false;
}
if (!blurMaterial.shader.isSupported)
ret = false;
if (!compositeMaterial.shader.isSupported)
ret = false;
if (!downsampleMaterial.shader.isSupported)
ret = false;
return ret;
}
public override void OnPreRender()
{
PrepareRenderTex();
Camera cam = ShaderCamera;
cam.CopyFrom(MyCamera);
cam.backgroundColor = Color.black;
cam.clearFlags = CameraClearFlags.SolidColor;
cam.targetTexture = TempRenderTex;
//NOTE: MUST BE FORWARD!
cam.renderingPath = RenderingPath.Forward;
cam.RenderWithShader(ReplacementShader, "XftEffect");
}
public override void Update(float deltaTime)
{
m_elapsedTime += deltaTime;
float t = m_owner.ColorCurve.Evaluate(m_elapsedTime);
m_tint = Color.Lerp(m_owner.GlowColorStart, m_owner.GlowColorEnd, t);
}
public override void OnRenderImage(RenderTexture source, RenderTexture destination)
{
//only glow the particle "layer"
RenderGlow(TempRenderTex, TempRenderGlow);
blendMaterial.SetTexture("_GlowTex", TempRenderGlow);
//blendMaterial.SetTexture("_MainTex",source);
Graphics.Blit(source, destination, blendMaterial);
//Graphics.Blit (TempRenderGlow, destination);
ReleaseRenderTex();
}
#endregion
#region helper functions
void ReleaseRenderTex()
{
if (TempRenderGlow != null)
{
RenderTexture.ReleaseTemporary(TempRenderGlow);
TempRenderGlow = null;
}
if (TempRenderTex != null)
{
RenderTexture.ReleaseTemporary(TempRenderTex);
TempRenderTex = null;
}
}
void PrepareRenderTex()
{
if (TempRenderTex == null)
{
TempRenderTex = RenderTexture.GetTemporary((int)MyCamera.pixelWidth, (int)MyCamera.pixelHeight, 0);
}
if (TempRenderGlow == null)
{
TempRenderGlow = RenderTexture.GetTemporary((int)MyCamera.pixelWidth, (int)MyCamera.pixelHeight, 0);
}
}
void FourTapCone(RenderTexture source, RenderTexture dest, int iteration, float spread)
{
float off = 0.5f + iteration * spread;
Graphics.BlitMultiTap(source, dest, blurMaterial,
new Vector2(off, off),
new Vector2(-off, off),
new Vector2(off, -off),
new Vector2(-off, -off)
);
}
void DownSample4x(RenderTexture source, RenderTexture dest, Color tint)
{
downsampleMaterial.color = new Color(tint.r, tint.g, tint.b, tint.a / 4.0f);
Graphics.Blit(source, dest, downsampleMaterial);
}
void RenderGlow(RenderTexture source, RenderTexture destination)
{
float glowIntensity = m_owner.GlowIntensity;
int blurIterations = m_owner.GlowBlurIterations;
float blurSpread = m_owner.GlowBlurSpread;
// Clamp parameters to sane values
glowIntensity = Mathf.Clamp(glowIntensity, 0.0f, 10.0f);
blurIterations = Mathf.Clamp(blurIterations, 0, 30);
blurSpread = Mathf.Clamp(blurSpread, 0.5f, 1.0f);
RenderTexture buffer = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0);
RenderTexture buffer2 = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0);
// Copy source to the 4x4 smaller texture.
DownSample4x(source, buffer, m_tint);
// Blur the small texture
float extraBlurBoost = Mathf.Clamp01((glowIntensity - 1.0f) / 4.0f);
blurMaterial.color = new Color(1F, 1F, 1F, 0.25f + extraBlurBoost);
bool oddEven = true;
for (int i = 0; i < blurIterations; i++)
{
if (oddEven)
{
FourTapCone(buffer, buffer2, i, blurSpread);
buffer.DiscardContents();
}
else
{
FourTapCone(buffer2, buffer, i, blurSpread);
buffer2.DiscardContents();
}
oddEven = !oddEven;
}
Graphics.Blit(source, destination);
if (oddEven)
BlitGlow(buffer, destination, glowIntensity);
else
BlitGlow(buffer2, destination, glowIntensity);
RenderTexture.ReleaseTemporary(buffer);
RenderTexture.ReleaseTemporary(buffer2);
}
void BlitGlow(RenderTexture source, RenderTexture dest, float intensity)
{
compositeMaterial.color = new Color(1F, 1F, 1F, Mathf.Clamp01(intensity));
Graphics.Blit(source, dest, compositeMaterial);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using d60.Cirqus.Aggregates;
using d60.Cirqus.Commands;
using d60.Cirqus.Config;
using d60.Cirqus.Config.Configurers;
using d60.Cirqus.Events;
using d60.Cirqus.Extensions;
using d60.Cirqus.Numbers;
using d60.Cirqus.Serialization;
using d60.Cirqus.Testing.Internals;
using d60.Cirqus.Views;
using d60.Cirqus.Views.ViewManagers;
namespace d60.Cirqus.Testing
{
/// <summary>
/// Use the test context to carry out realistic testing of command processing, aggregate roots, and
/// event processing in view generation.
/// </summary>
public class TestContext : IDisposable
{
readonly IDomainEventSerializer _domainEventSerializer;
readonly IDomainTypeNameMapper _domainTypeNameMapper;
readonly IAggregateRootRepository _aggregateRootRepository;
readonly IEventDispatcher _eventDispatcher;
readonly ICommandMapper _testCommandMapper;
readonly InMemoryEventStore _eventStore;
DateTime _currentTime = DateTime.MinValue;
bool _initialized;
internal TestContext(InMemoryEventStore eventStore, IAggregateRootRepository aggregateRootRepository, IEventDispatcher eventDispatcher,
IDomainEventSerializer domainEventSerializer, ICommandMapper commandMapper, IDomainTypeNameMapper domainTypeNameMapper)
{
_eventStore = eventStore;
_aggregateRootRepository = aggregateRootRepository;
_eventDispatcher = eventDispatcher;
_domainEventSerializer = domainEventSerializer;
_testCommandMapper = commandMapper;
_domainTypeNameMapper = domainTypeNameMapper;
}
public static IOptionalConfiguration<TestContext> With()
{
return new TestContextConfigurationBuilder();
}
public static TestContext Create()
{
return With().Create();
}
internal event Action Disposed = delegate { };
internal bool Asynchronous { get; set; }
public TestContext AddViewManager(IViewManager viewManager)
{
WithEventDispatcherOfType<ViewManagerEventDispatcher>(x =>
{
x.AddViewManager(viewManager);
});
return this;
}
/// <summary>
/// Processes the specified command in a unit of work.
/// </summary>
public CommandProcessingResultWithEvents ProcessCommand(Command command)
{
using (var unitOfWork = BeginUnitOfWork())
{
var handler = _testCommandMapper.GetCommandAction(command);
handler(new DefaultCommandContext(unitOfWork.RealUnitOfWork, command.Meta), command);
var eventsToReturn = unitOfWork.EmittedEvents.ToList();
foreach (var e in eventsToReturn)
{
e.Meta.Merge(command.Meta);
}
unitOfWork.Commit();
var result = new CommandProcessingResultWithEvents(eventsToReturn);
if (!Asynchronous)
{
WaitForViewsToCatchUp();
}
return result;
}
}
/// <summary>
/// Creates a new unit of work similar to the one within which a command is processed.
/// </summary>
public TestUnitOfWork BeginUnitOfWork()
{
var unitOfWork = new TestUnitOfWork(_aggregateRootRepository, _eventStore, _eventDispatcher, _domainEventSerializer, _domainTypeNameMapper);
unitOfWork.Committed += () =>
{
if (!Asynchronous)
{
WaitForViewsToCatchUp();
}
};
return unitOfWork;
}
/// <summary>
/// Fixes the current time to the specified <see cref="fixedCurrentTime"/> which will cause emitted events to have that
/// time as their <see cref="DomainEvent.MetadataKeys.TimeUtc"/> header
/// </summary>
public void SetCurrentTime(DateTime fixedCurrentTime)
{
_currentTime = fixedCurrentTime;
}
/// <summary>
/// Gets the entire history of commited events from the event store
/// </summary>
public EventCollection History
{
get { return new EventCollection(_eventStore.Stream().Select(e => _domainEventSerializer.Deserialize(e))); }
}
/// <summary>
/// Hydrates and returns all aggregate roots from the entire history of the test context
/// </summary>
public IEnumerable<AggregateRoot> AggregateRoots
{
get
{
return _eventStore
.Select(e => e.GetAggregateRootId()).Distinct()
.Select(aggregateRootId =>
{
var firstEvent = _eventStore.Load(aggregateRootId).First();
var typeName = firstEvent.Meta[DomainEvent.MetadataKeys.Owner] ?? "";
var type = TryGetType(typeName);
if (type == null) return null;
var unitOfWork = new RealUnitOfWork(_aggregateRootRepository, _domainTypeNameMapper);
var parameters = new object[]
{
aggregateRootId,
unitOfWork,
long.MaxValue, // max global sequence number
false // createIfNotExists
};
try
{
var aggregateRoot = _aggregateRootRepository
.GetType()
.GetMethod("Get")
.MakeGenericMethod(type)
.Invoke(_aggregateRootRepository, parameters);
return (AggregateRoot)aggregateRoot;
}
catch (Exception exception)
{
throw new ApplicationException(string.Format("Could not hydrate aggregate root {0} with ID {1}!", type, aggregateRootId), exception);
}
})
.Where(aggregateRoot => aggregateRoot != null);
}
}
Type TryGetType(string typeName)
{
try
{
return _domainTypeNameMapper.GetType(typeName);
}
catch
{
return null;
}
}
/// <summary>
/// Saves the given domain event to the history - requires that the aggregate root ID has been added in the event's metadata under the <see cref="DomainEvent.MetadataKeys.AggregateRootId"/> key
/// </summary>
public CommandProcessingResultWithEvents Save(Type owner, DomainEvent domainEvent)
{
if (!domainEvent.Meta.ContainsKey(DomainEvent.MetadataKeys.AggregateRootId))
{
throw new InvalidOperationException(
string.Format(
"Cannot save domain event {0} because it does not have an aggregate root ID! Use the Save(id, event) overload or make sure that the '{1}' metadata key has been set",
domainEvent, DomainEvent.MetadataKeys.AggregateRootId));
}
return Save(domainEvent.GetAggregateRootId(), owner, domainEvent);
}
/// <summary>
/// Saves the given domain event to the history as if it was emitted by the specified aggregate root, immediately dispatching the event to the event dispatcher
/// </summary>
public CommandProcessingResultWithEvents Save<TAggregateRoot>(string aggregateRootId, params DomainEvent<TAggregateRoot>[] domainEvents) where TAggregateRoot : AggregateRoot
{
return Save(aggregateRootId, typeof(TAggregateRoot), domainEvents.ToArray<DomainEvent>());
}
/// <summary>
/// Saves the given domain events to the history as if they were emitted by the specified aggregate root, immediately dispatching the events to the event dispatcher
/// </summary>
public CommandProcessingResultWithEvents Save(string aggregateRootId, Type owner, params DomainEvent[] domainEvents)
{
foreach (var domainEvent in domainEvents)
{
SetMetadata(aggregateRootId, owner, domainEvent);
}
var eventData = domainEvents.Select(e => _domainEventSerializer.Serialize(e)).ToList();
_eventStore.Save(Guid.NewGuid(), eventData);
_eventDispatcher.Dispatch(_eventStore, domainEvents);
var result = new CommandProcessingResultWithEvents(domainEvents);
if (!Asynchronous)
{
WaitForViewsToCatchUp();
}
return result;
}
/// <summary>
/// Waits for all views to catch up with the entire history of events, timing out if that takes longer than 10 seconds
/// </summary>
public void WaitForViewsToCatchUp(int timeoutSeconds = 10)
{
var allGlobalSequenceNumbers = History.Select(h => h.GetGlobalSequenceNumber()).ToArray();
if (!allGlobalSequenceNumbers.Any()) return;
var result = CommandProcessingResult.WithNewPosition(allGlobalSequenceNumbers.Max());
WithEventDispatcherOfType<IAwaitableEventDispatcher>(x => x.WaitUntilProcessed(result, TimeSpan.FromSeconds(timeoutSeconds)).Wait());
}
/// <summary>
/// Waits for views managing the specified <see cref="TViewInstance"/> to catch up with the entire history of events, timing out if that takes longer than 10 seconds
/// </summary>
public void WaitForViewToCatchUp<TViewInstance>(int timeoutSeconds = 10) where TViewInstance : IViewInstance
{
var allGlobalSequenceNumbers = History.Select(h => h.GetGlobalSequenceNumber()).ToArray();
if (!allGlobalSequenceNumbers.Any()) return;
var result = CommandProcessingResult.WithNewPosition(allGlobalSequenceNumbers.Max());
WithEventDispatcherOfType<IAwaitableEventDispatcher>(x => x.WaitUntilProcessed<TViewInstance>(result, TimeSpan.FromSeconds(timeoutSeconds)).Wait());
}
public void Initialize()
{
if (!_initialized)
{
_eventDispatcher.Initialize(_eventStore, purgeExistingViews: true);
_initialized = true;
}
}
void SetMetadata(string aggregateRootId, Type owner, DomainEvent domainEvent)
{
var now = GetNow();
domainEvent.Meta[DomainEvent.MetadataKeys.Owner] = _domainTypeNameMapper.GetName(owner);
domainEvent.Meta[DomainEvent.MetadataKeys.AggregateRootId] = aggregateRootId;
domainEvent.Meta[DomainEvent.MetadataKeys.SequenceNumber] = _eventStore.GetNextSeqNo(aggregateRootId).ToString(Metadata.NumberCulture);
domainEvent.Meta[DomainEvent.MetadataKeys.Type] = _domainTypeNameMapper.GetName(domainEvent.GetType());
domainEvent.Meta[DomainEvent.MetadataKeys.TimeUtc] = now.ToString("u");
domainEvent.Meta.TakeFromAttributes(domainEvent.GetType());
domainEvent.Meta.TakeFromAttributes(owner);
EnsureSerializability(domainEvent);
}
void EnsureSerializability(DomainEvent domainEvent)
{
var firstSerialization = _domainEventSerializer.Serialize(domainEvent);
var secondSerialization = _domainEventSerializer.Serialize(
_domainEventSerializer.Deserialize(firstSerialization));
if (firstSerialization.IsSameAs(secondSerialization)) return;
throw new ArgumentException(string.Format(@"Could not properly roundtrip the following domain event: {0}
Result after first serialization:
{1}
Result after roundtripping:
{2}
Headers: {3}", domainEvent, firstSerialization, secondSerialization, domainEvent.Meta));
}
DateTime GetNow()
{
if (_currentTime == DateTime.MinValue)
{
return DateTime.UtcNow;
}
var timeToReturn = _currentTime.ToUniversalTime();
// simulate time progressing
_currentTime = _currentTime.AddTicks(1);
return timeToReturn;
}
void WithEventDispatcherOfType<T>(Action<T> action) where T: IEventDispatcher
{
if (!(_eventDispatcher is T)) return;
var viewManangerEventDispatcher = (T)_eventDispatcher;
action(viewManangerEventDispatcher);
}
bool _disposed;
~TestContext()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
Disposed();
}
_disposed = true;
}
}
}
| |
// /*
// * Licensed to the Apache Software Foundation (ASF) under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Collections;
using Apache.NMS.Util;
namespace Apache.NMS.Stomp.Protocol
{
/// <summary>
/// Reads / Writes an IPrimitveMap as XML compatible with XStream.
/// </summary>
public class XmlPrimitiveMapMarshaler : IPrimitiveMapMarshaler
{
private readonly Encoding encoder = new UTF8Encoding();
public XmlPrimitiveMapMarshaler()
{
}
public XmlPrimitiveMapMarshaler(Encoding encoder)
{
this.encoder = encoder;
}
public string Name
{
get{ return "jms-map-xml"; }
}
public byte[] Marshal(IPrimitiveMap map)
{
if(map == null)
{
return null;
}
StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.Encoding = this.encoder;
settings.NewLineHandling = NewLineHandling.None;
XmlWriter writer = XmlWriter.Create(builder, settings);
writer.WriteStartElement("map");
foreach(String entry in map.Keys)
{
writer.WriteStartElement("entry");
// Encode the Key <string>key</string>
writer.WriteElementString("string", entry);
Object value = map[entry];
// Encode the Value <${type}>value</${type}>
MarshalPrimitive(writer, value);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Close();
return this.encoder.GetBytes(builder.ToString());
}
public IPrimitiveMap Unmarshal(byte[] mapContent)
{
string xmlString = this.encoder.GetString(mapContent, 0, mapContent.Length);
PrimitiveMap result = new PrimitiveMap();
if (xmlString == null || xmlString == "")
{
return result;
}
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
settings.IgnoreProcessingInstructions = true;
XmlReader reader = XmlReader.Create(new StringReader(xmlString), settings);
reader.MoveToContent();
reader.ReadStartElement("map");
while(reader.Name == "entry")
{
reader.ReadStartElement();
string key = reader.ReadElementContentAsString("string", "");
Object value = null;
switch(reader.Name)
{
case "char":
value = Convert.ToChar(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "double":
value = Convert.ToDouble(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "float":
value = Convert.ToSingle(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "long":
value = Convert.ToInt64(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "int":
value = Convert.ToInt32(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "short":
value = Convert.ToInt16(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "byte":
value = (byte) Convert.ToInt16(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "boolean":
value = Convert.ToBoolean(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
case "byte-array":
value = Convert.FromBase64String(reader.ReadElementContentAsString());
reader.ReadEndElement();
break;
default:
value = reader.ReadElementContentAsString();
reader.ReadEndElement();
break;
};
// Now store the value into our new PrimitiveMap.
result[key] = value;
}
reader.Close();
return result;
}
private void MarshalPrimitive(XmlWriter writer, Object value)
{
if(value == null)
{
throw new NullReferenceException("PrimitiveMap values should not be Null");
}
else if(value is char)
{
writer.WriteElementString("char", value.ToString());
}
else if(value is bool)
{
writer.WriteElementString("boolean", value.ToString().ToLower());
}
else if(value is byte)
{
writer.WriteElementString("byte", ((Byte) value).ToString());
}
else if(value is short)
{
writer.WriteElementString("short", value.ToString());
}
else if(value is int)
{
writer.WriteElementString("int", value.ToString());
}
else if(value is long)
{
writer.WriteElementString("long", value.ToString());
}
else if(value is float)
{
writer.WriteElementString("float", value.ToString());
}
else if(value is double)
{
writer.WriteElementString("double", value.ToString());
}
else if(value is byte[])
{
writer.WriteElementString("byte-array", Convert.ToBase64String((byte[]) value));
}
else if(value is string)
{
writer.WriteElementString("string", (string) value);
}
else if(value is IDictionary)
{
Tracer.Debug("Can't Marshal a Dictionary");
throw new NotSupportedException("Can't marshal nested Maps in Stomp");
}
else if(value is IList)
{
Tracer.Debug("Can't Marshal a List");
throw new NotSupportedException("Can't marshal nested Maps in Stomp");
}
else
{
Console.WriteLine("Can't Marshal a something other than a Primitive Value.");
throw new Exception("Object is not a primitive: " + value);
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Store;
using Windows.Data.Xml.Dom;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Newtonsoft.Json;
using WinRTXamlToolkit.Tools;
using WB.SDK.Logging;
using WB.CraigslistApi;
using WB.Craigslist8X.Model;
using WB.Craigslist8X.View;
namespace WB.Craigslist8X
{
partial class App
{
public App()
{
InitializeComponent();
this.Resuming += AppResuming;
this.Suspending += OnSuspending;
this.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
DebugSettings.IsBindingTracingEnabled = false;
this.RequestedTheme = ApplicationTheme.Light;
}
async void OnResuming(object sender, object e)
{
await SavedSearches.Instance.LoadNotificationsAsync();
}
private async void BackgroundTimer_Tick(object sender, object e)
{
using (new MonitoredScope("Craigslist8X Background Tasks"))
{
await Craigslist8XData.SaveAsync();
await SavedSearches.Instance.LoadNotificationsAsync();
}
}
private async Task InitCraigslist8X()
{
using (new MonitoredScope("Initialize Craigslist8X"))
{
#if DEBUG
LicenseInfo = CurrentAppSimulator.LicenseInformation;
#else
LicenseInfo = CurrentApp.LicenseInformation;
#endif
bool loaded = await Craigslist8XData.LoadAsync();
// Load notification data every time we start the app because background task may have kicked in
await SavedSearches.Instance.LoadNotificationsAsync();
if (loaded)
{
// Hook up settings handlers
SettingsPane.GetForCurrentView().CommandsRequested += SettingsUI.SettingsUI_CommandsRequested;
if (this.BackgroundTimer == null)
{
this.BackgroundTimer = new BackgroundTimer();
this.BackgroundTimer.Interval = TimeSpan.FromSeconds(15);
this.BackgroundTimer.Tick += BackgroundTimer_Tick;
this.BackgroundTimer.IsEnabled = true;
this.BackgroundTimer.Start();
}
}
// Ensure we have a window to look at
if (MainPage.Instance == null)
{
Frame root = await EnsureNavigationFrame();
root.Navigate(typeof(MainPage), null);
DataTransferManager.GetForCurrentView().DataRequested += MainPage.Instance.MainPage_DataRequested;
}
}
}
protected async override void OnLaunched(LaunchActivatedEventArgs args)
{
using (new MonitoredScope("Launch Craigslist8X"))
{
await this.InitCraigslist8X();
try
{
if (!string.IsNullOrEmpty(args.Arguments))
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(args.Arguments);
XmlElement xe = doc.DocumentElement;
if (xe.NodeName == "SavedQuery")
{
await MainPage.Instance.ExecuteSavedSearches(null, Uri.UnescapeDataString(xe.GetAttribute("Name")));
}
}
catch
{
}
// It could have been a JSON argument instead of XML
dynamic argObject = JsonConvert.DeserializeObject(args.Arguments);
if (argObject.type == "toast")
{
var webUrl = argObject.clientUrl;
var uri = new Uri(webUrl.ToString());
await Windows.System.Launcher.LaunchUriAsync(uri);
}
}
}
catch (Exception ex)
{
Logger.LogMessage("Exception thrown launching app with the following arguments: {0}", args.Arguments);
Logger.LogException(ex);
}
}
}
protected async override void OnSearchActivated(SearchActivatedEventArgs args)
{
using (new MonitoredScope("Search Activate Craigslist8X"))
{
await this.InitCraigslist8X();
if (!CityManager.Instance.SearchCitiesDefined)
{
MessageDialog dlg = new MessageDialog("Please set the city you want to search and try again.", "Craigslist 8X");
await dlg.ShowAsync();
SettingsUI.ShowSearchSettings();
}
else
{
// As of this writing, this app has two actual pages. The MainPage and the ChooceCitiesPage. We need to ensure that
// we navigate to the MainPage.
Frame frame = await EnsureNavigationFrame();
frame.Content = MainPage.Instance;
Query template = new Query(CityManager.Instance.SearchCities.First(), CategoryManager.Instance.SearchCategory, args.QueryText);
template.HasImage = Settings.Instance.OnlyShowPostsPictures;
template.Type = Settings.Instance.OnlySearchTitles ? Query.QueryType.TitleOnly : Query.QueryType.EntirePost;
QueryBatch qb = QueryBatch.BuildQueryBatch(CityManager.Instance.SearchCities, template);
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High,
async () =>
{
await MainPage.Instance.ExecuteSearchQuery(null, qb);
});
}
}
}
protected async void AppResuming(object sender, object e)
{
await SavedSearches.Instance.LoadNotificationsAsync();
}
protected async void OnSuspending(object sender, SuspendingEventArgs e)
{
using (new MonitoredScope("Suspend Craigslist8X"))
{
SuspendingDeferral deferral = e.SuspendingOperation.GetDeferral();
await Craigslist8XData.SaveAsync();
deferral.Complete();
}
}
protected async void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Logger.LogException(e.Exception);
await Craigslist8XData.SaveAsync();
}
#region Static
public static async Task<Frame> EnsureNavigationFrame()
{
if (Window.Current.Content == null)
{
Window.Current.Content = new Frame();
}
else if (!(Window.Current.Content is Frame))
{
await Logger.AssertNotReached("Why is Window.Current.Content set to a non null type that is not a Frame?");
Window.Current.Content = new Frame();
}
Window.Current.Activate();
return (Frame)Window.Current.Content;
}
public static LicenseInformation LicenseInfo;
#endregion
#region Pro
internal const string Craigslist8XPRO = "Craigslist8XPRO";
public static bool IsPro
{
get
{
#if CRAIGSLIST8XPRO
return true;
#else
return LicenseInfo.ProductLicenses[Craigslist8XPRO].IsActive;
#endif
}
}
#endregion
private BackgroundTimer BackgroundTimer;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.IO;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
///<summary>
/// This is the object used by Runspace,pipeline,host to send data
/// to remote end. Transport layer owns breaking this into fragments
/// and sending to other end
///</summary>
internal class RemoteDataObject<T>
{
#region Private Members
private const int destinationOffset = 0;
private const int dataTypeOffset = 4;
private const int rsPoolIdOffset = 8;
private const int psIdOffset = 24;
private const int headerLength = 4 + 4 + 16 + 16;
private const int SessionMask = 0x00010000;
private const int RunspacePoolMask = 0x00021000;
private const int PowerShellMask = 0x00041000;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructs a RemoteDataObject from its
/// individual components.
/// </summary>
/// <param name="destination">
/// Destination this object is going to.
/// </param>
/// <param name="dataType">
/// Payload type this object represents.
/// </param>
/// <param name="runspacePoolId">
/// Runspace id this object belongs to.
/// </param>
/// <param name="powerShellId">
/// PowerShell (pipeline) id this object belongs to.
/// This may be null if the payload belongs to runspace.
/// </param>
/// <param name="data">
/// Actual payload.
/// </param>
protected RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
Destination = destination;
DataType = dataType;
RunspacePoolId = runspacePoolId;
PowerShellId = powerShellId;
Data = data;
}
#endregion Constructors
#region Properties
internal RemotingDestination Destination { get; }
/// <summary>
/// Gets the target (Runspace / Pipeline / Powershell / Host)
/// the payload belongs to.
/// </summary>
internal RemotingTargetInterface TargetInterface
{
get
{
int dt = (int)DataType;
// get the most used ones in the top.
if ((dt & PowerShellMask) == PowerShellMask)
{
return RemotingTargetInterface.PowerShell;
}
if ((dt & RunspacePoolMask) == RunspacePoolMask)
{
return RemotingTargetInterface.RunspacePool;
}
if ((dt & SessionMask) == SessionMask)
{
return RemotingTargetInterface.Session;
}
return RemotingTargetInterface.InvalidTargetInterface;
}
}
internal RemotingDataType DataType { get; }
internal Guid RunspacePoolId { get; }
internal Guid PowerShellId { get; }
internal T Data { get; }
#endregion Properties
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, data);
}
/// <summary>
/// Creates a RemoteDataObject by deserializing <paramref name="data"/>.
/// </summary>
/// <param name="serializedDataStream"></param>
/// <param name="defragmentor">
/// Defragmentor used to deserialize an object.
/// </param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(Stream serializedDataStream, Fragmentor defragmentor)
{
Dbg.Assert(serializedDataStream != null, "cannot construct a RemoteDataObject from null data");
Dbg.Assert(defragmentor != null, "defragmentor cannot be null.");
if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength)
{
PSRemotingTransportException e =
new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject,
RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject,
headerLength + FragmentedRemoteObject.HeaderLength);
throw e;
}
RemotingDestination destination = (RemotingDestination)DeserializeUInt(serializedDataStream);
RemotingDataType dataType = (RemotingDataType)DeserializeUInt(serializedDataStream);
Guid runspacePoolId = DeserializeGuid(serializedDataStream);
Guid powerShellId = DeserializeGuid(serializedDataStream);
object actualData = null;
if ((serializedDataStream.Length - headerLength) > 0)
{
actualData = defragmentor.DeserializeToPSObject(serializedDataStream);
}
T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T),
System.Globalization.CultureInfo.CurrentCulture);
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, deserializedObject);
}
#region Serialize / Deserialize
/// <summary>
/// Serializes the object into the stream specified. The serialization mechanism uses
/// UTF8 encoding to encode data.
/// </summary>
/// <param name="streamToWriteTo"></param>
/// <param name="fragmentor">
/// fragmentor used to serialize and fragment the object.
/// </param>
internal virtual void Serialize(Stream streamToWriteTo, Fragmentor fragmentor)
{
Dbg.Assert(streamToWriteTo != null, "Stream to write to cannot be null.");
Dbg.Assert(fragmentor != null, "Fragmentor cannot be null.");
SerializeHeader(streamToWriteTo);
if (Data != null)
{
fragmentor.SerializeToBytes(Data, streamToWriteTo);
}
return;
}
/// <summary>
/// Serializes only the header portion of the object. ie., runspaceId,
/// powerShellId, destination and dataType.
/// </summary>
/// <param name="streamToWriteTo">
/// place where the serialized data is stored into.
/// </param>
/// <returns></returns>
private void SerializeHeader(Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
// Serialize destination
SerializeUInt((uint)Destination, streamToWriteTo);
// Serialize data type
SerializeUInt((uint)DataType, streamToWriteTo);
// Serialize runspace guid
SerializeGuid(RunspacePoolId, streamToWriteTo);
// Serialize powershell guid
SerializeGuid(PowerShellId, streamToWriteTo);
return;
}
private void SerializeUInt(uint data, Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
byte[] result = new byte[4]; // size of int
int idx = 0;
result[idx++] = (byte)(data & 0xFF);
result[idx++] = (byte)((data >> 8) & 0xFF);
result[idx++] = (byte)((data >> (2 * 8)) & 0xFF);
result[idx++] = (byte)((data >> (3 * 8)) & 0xFF);
streamToWriteTo.Write(result, 0, 4);
}
private static uint DeserializeUInt(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 4, "Not enough data to get Int.");
uint result = 0;
result |= (((uint)(serializedDataStream.ReadByte())) & 0xFF);
result |= (((uint)(serializedDataStream.ReadByte() << 8)) & 0xFF00);
result |= (((uint)(serializedDataStream.ReadByte() << (2 * 8))) & 0xFF0000);
result |= (((uint)(serializedDataStream.ReadByte() << (3 * 8))) & 0xFF000000);
return result;
}
private void SerializeGuid(Guid guid, Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
byte[] guidArray = guid.ToByteArray();
streamToWriteTo.Write(guidArray, 0, guidArray.Length);
}
private static Guid DeserializeGuid(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 16, "Not enough data to get Guid.");
byte[] guidarray = new byte[16]; // Size of GUID.
for (int idx = 0; idx < 16; idx++)
{
guidarray[idx] = (byte)serializedDataStream.ReadByte();
}
return new Guid(guidarray);
}
#endregion
}
internal class RemoteDataObject : RemoteDataObject<object>
{
#region Constructors / Factory
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
private RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data) : base(destination, dataType, runspacePoolId, powerShellId, data)
{
}
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static new RemoteDataObject CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data)
{
return new RemoteDataObject(destination, dataType, runspacePoolId,
powerShellId, data);
}
#endregion Constructors
}
}
| |
/*
* RegExp.cs
*/
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Text;
using Core.Library;
namespace Core.Library.RE {
/**
* A regular expression. This class creates and holds an internal
* data structure representing a regular expression. It also
* allows creating matchers. This class is thread-safe. Multiple
* matchers may operate simultanously on the same regular
* expression.
*
*
*/
public class RegExp {
/**
* The base regular expression element.
*/
private Element element;
/**
* The regular expression pattern.
*/
private string pattern;
/**
* The character case ignore flag.
*/
private bool ignoreCase;
/**
* The current position in the pattern. This variable is used by
* the parsing methods.
*/
private int pos;
/**
* Creates a new case-sensitive regular expression.
*
* @param pattern the regular expression pattern
*
* @throws RegExpException if the regular expression couldn't be
* parsed correctly
*/
public RegExp(string pattern)
: this(pattern, false) {
}
/**
* Creates a new regular expression. The regular expression
* can be either case-sensitive or case-insensitive.
*
* @param pattern the regular expression pattern
* @param ignoreCase the character case ignore flag
*
* @throws RegExpException if the regular expression couldn't be
* parsed correctly
*
*
*/
public RegExp(string pattern, bool ignoreCase) {
this.pattern = pattern;
this.ignoreCase = ignoreCase;
this.pos = 0;
this.element = ParseExpr();
if (pos < pattern.Length) {
throw new RegExpException(
RegExpException.ErrorType.UNEXPECTED_CHARACTER,
pos,
pattern);
}
}
/**
* Creates a new matcher for the specified string.
*
* @param str the string to work with
*
* @return the regular expresion matcher
*/
public Matcher Matcher(string str) {
return Matcher(new ReaderBuffer(new StringReader(str)));
}
/**
* Creates a new matcher for the specified look-ahead
* character input stream.
*
* @param buffer the character input buffer
*
* @return the regular expresion matcher
*
*
*/
public Matcher Matcher(ReaderBuffer buffer) {
return new Matcher((Element) element.Clone(), buffer, ignoreCase);
}
/**
* Returns a string representation of the regular expression.
*
* @return a string representation of the regular expression
*/
public override string ToString() {
StringWriter str;
str = new StringWriter();
str.WriteLine("Regular Expression");
str.WriteLine(" Pattern: " + pattern);
str.Write(" Flags:");
if (ignoreCase) {
str.Write(" caseignore");
}
str.WriteLine();
str.WriteLine(" Compiled:");
element.PrintTo(str, " ");
return str.ToString();
}
/**
* Parses a regular expression. This method handles the Expr
* production in the grammar (see regexp.grammar).
*
* @return the element representing this expression
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseExpr() {
Element first;
Element second;
first = ParseTerm();
if (PeekChar(0) != '|') {
return first;
} else {
ReadChar('|');
second = ParseExpr();
return new AlternativeElement(first, second);
}
}
/**
* Parses a regular expression term. This method handles the
* Term production in the grammar (see regexp.grammar).
*
* @return the element representing this term
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseTerm() {
ArrayList list = new ArrayList();
list.Add(ParseFact());
while (true) {
switch (PeekChar(0)) {
case -1:
case ')':
case ']':
case '{':
case '}':
case '?':
case '+':
case '|':
return CombineElements(list);
default:
list.Add(ParseFact());
break;
}
}
}
/**
* Parses a regular expression factor. This method handles the
* Fact production in the grammar (see regexp.grammar).
*
* @return the element representing this factor
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseFact() {
Element elem;
elem = ParseAtom();
switch (PeekChar(0)) {
case '?':
case '*':
case '+':
case '{':
return ParseAtomModifier(elem);
default:
return elem;
}
}
/**
* Parses a regular expression atom. This method handles the
* Atom production in the grammar (see regexp.grammar).
*
* @return the element representing this atom
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseAtom() {
Element elem;
switch (PeekChar(0)) {
case '.':
ReadChar('.');
return CharacterSetElement.DOT;
case '(':
ReadChar('(');
elem = ParseExpr();
ReadChar(')');
return elem;
case '[':
ReadChar('[');
elem = ParseCharSet();
ReadChar(']');
return elem;
case -1:
case ')':
case ']':
case '{':
case '}':
case '?':
case '*':
case '+':
case '|':
throw new RegExpException(
RegExpException.ErrorType.UNEXPECTED_CHARACTER,
pos,
pattern);
default:
return ParseChar();
}
}
/**
* Parses a regular expression atom modifier. This method handles
* the AtomModifier production in the grammar (see regexp.grammar).
*
* @param elem the element to modify
*
* @return the modified element
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseAtomModifier(Element elem) {
int min = 0;
int max = -1;
RepeatElement.RepeatType type;
int firstPos;
// Read min and max
type = RepeatElement.RepeatType.GREEDY;
switch (ReadChar()) {
case '?':
min = 0;
max = 1;
break;
case '*':
min = 0;
max = -1;
break;
case '+':
min = 1;
max = -1;
break;
case '{':
firstPos = pos - 1;
min = ReadNumber();
max = min;
if (PeekChar(0) == ',') {
ReadChar(',');
max = -1;
if (PeekChar(0) != '}') {
max = ReadNumber();
}
}
ReadChar('}');
if (max == 0 || (max > 0 && min > max)) {
throw new RegExpException(
RegExpException.ErrorType.INVALID_REPEAT_COUNT,
firstPos,
pattern);
}
break;
default:
throw new RegExpException(
RegExpException.ErrorType.UNEXPECTED_CHARACTER,
pos - 1,
pattern);
}
// Read operator mode
if (PeekChar(0) == '?') {
ReadChar('?');
type = RepeatElement.RepeatType.RELUCTANT;
} else if (PeekChar(0) == '+') {
ReadChar('+');
type = RepeatElement.RepeatType.POSSESSIVE;
}
return new RepeatElement(elem, min, max, type);
}
/**
* Parses a regular expression character set. This method handles
* the contents of the '[...]' construct in a regular expression.
*
* @return the element representing this character set
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseCharSet() {
CharacterSetElement charset;
Element elem;
bool repeat = true;
char start;
char end;
if (PeekChar(0) == '^') {
ReadChar('^');
charset = new CharacterSetElement(true);
} else {
charset = new CharacterSetElement(false);
}
while (PeekChar(0) > 0 && repeat) {
start = (char) PeekChar(0);
switch (start) {
case ']':
repeat = false;
break;
case '\\':
elem = ParseEscapeChar();
if (elem is StringElement) {
charset.AddCharacters((StringElement) elem);
} else {
charset.AddCharacterSet((CharacterSetElement) elem);
}
break;
default:
ReadChar(start);
if (PeekChar(0) == '-'
&& PeekChar(1) > 0
&& PeekChar(1) != ']') {
ReadChar('-');
end = ReadChar();
charset.AddRange(FixChar(start), FixChar(end));
} else {
charset.AddCharacter(FixChar(start));
}
break;
}
}
return charset;
}
/**
* Parses a regular expression character. This method handles
* a single normal character in a regular expression.
*
* @return the element representing this character
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseChar() {
switch (PeekChar(0)) {
case '\\':
return ParseEscapeChar();
case '^':
case '$':
throw new RegExpException(
RegExpException.ErrorType.UNSUPPORTED_SPECIAL_CHARACTER,
pos,
pattern);
default:
return new StringElement(FixChar(ReadChar()));
}
}
/**
* Parses a regular expression character escape. This method
* handles a single character escape in a regular expression.
*
* @return the element representing this character escape
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private Element ParseEscapeChar() {
char c;
string str;
int value;
ReadChar('\\');
c = ReadChar();
switch (c) {
case '0':
c = ReadChar();
if (c < '0' || c > '3') {
throw new RegExpException(
RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
pos - 3,
pattern);
}
value = c - '0';
c = (char) PeekChar(0);
if ('0' <= c && c <= '7') {
value *= 8;
value += ReadChar() - '0';
c = (char) PeekChar(0);
if ('0' <= c && c <= '7') {
value *= 8;
value += ReadChar() - '0';
}
}
return new StringElement(FixChar((char) value));
case 'x':
str = ReadChar().ToString() +
ReadChar().ToString();
try {
value = Int32.Parse(str,
NumberStyles.AllowHexSpecifier);
return new StringElement(FixChar((char) value));
} catch (FormatException) {
throw new RegExpException(
RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
pos - str.Length - 2,
pattern);
}
case 'u':
str = ReadChar().ToString() +
ReadChar().ToString() +
ReadChar().ToString() +
ReadChar().ToString();
try {
value = Int32.Parse(str,
NumberStyles.AllowHexSpecifier);
return new StringElement(FixChar((char) value));
} catch (FormatException) {
throw new RegExpException(
RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
pos - str.Length - 2,
pattern);
}
case 't':
return new StringElement('\t');
case 'n':
return new StringElement('\n');
case 'r':
return new StringElement('\r');
case 'f':
return new StringElement('\f');
case 'a':
return new StringElement('\u0007');
case 'e':
return new StringElement('\u001B');
case 'd':
return CharacterSetElement.DIGIT;
case 'D':
return CharacterSetElement.NON_DIGIT;
case 's':
return CharacterSetElement.WHITESPACE;
case 'S':
return CharacterSetElement.NON_WHITESPACE;
case 'w':
return CharacterSetElement.WORD;
case 'W':
return CharacterSetElement.NON_WORD;
default:
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) {
throw new RegExpException(
RegExpException.ErrorType.UNSUPPORTED_ESCAPE_CHARACTER,
pos - 2,
pattern);
}
return new StringElement(FixChar(c));
}
}
/**
* Adjusts a character for inclusion in a string or character
* set element. For case-insensitive regular expressions, this
* transforms the character to lower-case.
*
* @param c the input character
*
* @return the adjusted character
*/
private char FixChar(char c) {
return ignoreCase ? Char.ToLower(c) : c;
}
/**
* Reads a number from the pattern. If the next character isn't a
* numeric character, an exception is thrown. This method reads
* several consecutive numeric characters.
*
* @return the numeric value read
*
* @throws RegExpException if an error was encountered in the
* pattern string
*/
private int ReadNumber() {
StringBuilder buf = new StringBuilder();
int c;
c = PeekChar(0);
while ('0' <= c && c <= '9') {
buf.Append(ReadChar());
c = PeekChar(0);
}
if (buf.Length <= 0) {
throw new RegExpException(
RegExpException.ErrorType.UNEXPECTED_CHARACTER,
pos,
pattern);
}
return Int32.Parse(buf.ToString());
}
/**
* Reads the next character in the pattern. If no next character
* exists, an exception is thrown.
*
* @return the character read
*
* @throws RegExpException if no next character was available in
* the pattern string
*/
private char ReadChar() {
int c = PeekChar(0);
if (c < 0) {
throw new RegExpException(
RegExpException.ErrorType.UNTERMINATED_PATTERN,
pos,
pattern);
} else {
pos++;
return (char) c;
}
}
/**
* Reads the next character in the pattern. If the character
* wasn't the specified one, an exception is thrown.
*
* @param c the character to read
*
* @return the character read
*
* @throws RegExpException if the character read didn't match the
* specified one, or if no next character was
* available in the pattern string
*/
private char ReadChar(char c) {
if (c != ReadChar()) {
throw new RegExpException(
RegExpException.ErrorType.UNEXPECTED_CHARACTER,
pos - 1,
pattern);
}
return c;
}
/**
* Returns a character that has not yet been read from the
* pattern. If the requested position is beyond the end of the
* pattern string, -1 is returned.
*
* @param count the preview position, from zero (0)
*
* @return the character found, or
* -1 if beyond the end of the pattern string
*/
private int PeekChar(int count) {
if (pos + count < pattern.Length) {
return pattern[pos + count];
} else {
return -1;
}
}
/**
* Combines a list of elements. This method takes care to always
* concatenate adjacent string elements into a single string
* element.
*
* @param list the list with elements
*
* @return the combined element
*/
private Element CombineElements(ArrayList list) {
Element prev;
Element elem;
string str;
int i;
// Concatenate string elements
prev = (Element) list[0];
for (i = 1; i < list.Count; i++) {
elem = (Element) list[i];
if (prev is StringElement
&& elem is StringElement) {
str = ((StringElement) prev).GetString() +
((StringElement) elem).GetString();
elem = new StringElement(str);
list.RemoveAt(i);
list[i - 1] = elem;
i--;
}
prev = elem;
}
// Combine all remaining elements
elem = (Element) list[list.Count - 1];
for (i = list.Count - 2; i >= 0; i--) {
prev = (Element) list[i];
elem = new CombineElement(prev, elem);
}
return elem;
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents an UpdateItem request.
/// </summary>
internal sealed class UpdateItemRequest : MultiResponseServiceRequest<UpdateItemResponse>
{
private List<Item> items = new List<Item>();
private FolderId savedItemsDestinationFolder;
private ConflictResolutionMode conflictResolutionMode;
private MessageDisposition? messageDisposition;
private SendInvitationsOrCancellationsMode? sendInvitationsOrCancellationsMode;
/// <summary>
/// Initializes a new instance of the <see cref="UpdateItemRequest"/> class.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="errorHandlingMode"> Indicates how errors should be handled.</param>
internal UpdateItemRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode)
: base(service, errorHandlingMode)
{
}
/// <summary>
/// Gets a value indicating whether the TimeZoneContext SOAP header should be eimitted.
/// </summary>
/// <value>
/// <c>true</c> if the time zone should be emitted; otherwise, <c>false</c>.
/// </value>
internal override bool EmitTimeZoneHeader
{
get
{
foreach (Item item in this.Items)
{
if (item.GetIsTimeZoneHeaderRequired(true /* isUpdateOpeartion */))
{
return true;
}
}
return false;
}
}
/// <summary>
/// Validates the request.
/// </summary>
internal override void Validate()
{
base.Validate();
EwsUtilities.ValidateParamCollection(this.Items, "Items");
for (int i = 0; i < this.Items.Count; i++)
{
if ((this.Items[i] == null) || this.Items[i].IsNew)
{
throw new ArgumentException(string.Format(Strings.ItemToUpdateCannotBeNullOrNew, i));
}
}
if (this.SavedItemsDestinationFolder != null)
{
this.SavedItemsDestinationFolder.Validate(this.Service.RequestedServerVersion);
}
// Validate each item.
foreach (Item item in this.Items)
{
item.Validate();
}
if (this.SuppressReadReceipts && this.Service.RequestedServerVersion < ExchangeVersion.Exchange2013)
{
throw new ServiceVersionException(
string.Format(
Strings.ParameterIncompatibleWithRequestVersion,
"SuppressReadReceipts",
ExchangeVersion.Exchange2013));
}
}
/// <summary>
/// Creates the service response.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="responseIndex">Index of the response.</param>
/// <returns>Response object.</returns>
internal override UpdateItemResponse CreateServiceResponse(ExchangeService service, int responseIndex)
{
return new UpdateItemResponse(this.Items[responseIndex]);
}
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetXmlElementName()
{
return XmlElementNames.UpdateItem;
}
/// <summary>
/// Gets the name of the response XML element.
/// </summary>
/// <returns>Xml element name.</returns>
internal override string GetResponseXmlElementName()
{
return XmlElementNames.UpdateItemResponse;
}
/// <summary>
/// Gets the name of the response message XML element.
/// </summary>
/// <returns>Xml element name.</returns>
internal override string GetResponseMessageXmlElementName()
{
return XmlElementNames.UpdateItemResponseMessage;
}
/// <summary>
/// Gets the expected response message count.
/// </summary>
/// <returns>Number of items in response.</returns>
internal override int GetExpectedResponseMessageCount()
{
return this.items.Count;
}
/// <summary>
/// Writes XML attributes.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteAttributesToXml(EwsServiceXmlWriter writer)
{
base.WriteAttributesToXml(writer);
if (this.MessageDisposition.HasValue)
{
writer.WriteAttributeValue(XmlAttributeNames.MessageDisposition, this.MessageDisposition);
}
if (this.SuppressReadReceipts)
{
writer.WriteAttributeValue(XmlAttributeNames.SuppressReadReceipts, true);
}
writer.WriteAttributeValue(XmlAttributeNames.ConflictResolution, this.ConflictResolutionMode);
if (this.SendInvitationsOrCancellationsMode.HasValue)
{
writer.WriteAttributeValue(
XmlAttributeNames.SendMeetingInvitationsOrCancellations,
this.SendInvitationsOrCancellationsMode.Value);
}
}
/// <summary>
/// Writes XML elements.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
if (this.SavedItemsDestinationFolder != null)
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SavedItemFolderId);
this.SavedItemsDestinationFolder.WriteToXml(writer);
writer.WriteEndElement();
}
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.ItemChanges);
foreach (Item item in this.items)
{
item.WriteToXmlForUpdate(writer);
}
writer.WriteEndElement();
}
/// <summary>
/// Gets the request version.
/// </summary>
/// <returns>Earliest Exchange version in which this request is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2007_SP1;
}
/// <summary>
/// Gets or sets the message disposition.
/// </summary>
/// <value>The message disposition.</value>
public MessageDisposition? MessageDisposition
{
get { return this.messageDisposition; }
set { this.messageDisposition = value; }
}
/// <summary>
/// Gets or sets the conflict resolution mode.
/// </summary>
/// <value>The conflict resolution mode.</value>
public ConflictResolutionMode ConflictResolutionMode
{
get { return this.conflictResolutionMode; }
set { this.conflictResolutionMode = value; }
}
/// <summary>
/// Gets or sets the send invitations or cancellations mode.
/// </summary>
/// <value>The send invitations or cancellations mode.</value>
public SendInvitationsOrCancellationsMode? SendInvitationsOrCancellationsMode
{
get { return this.sendInvitationsOrCancellationsMode; }
set { this.sendInvitationsOrCancellationsMode = value; }
}
/// <summary>
/// Gets or sets whether to suppress read receipts
/// </summary>
/// <value>Whether to suppress read receipts</value>
public bool SuppressReadReceipts
{
get;
set;
}
/// <summary>
/// Gets the items.
/// </summary>
/// <value>The items.</value>
public List<Item> Items
{
get { return this.items; }
}
/// <summary>
/// Gets or sets the saved items destination folder.
/// </summary>
/// <value>The saved items destination folder.</value>
public FolderId SavedItemsDestinationFolder
{
get { return this.savedItemsDestinationFolder; }
set { this.savedItemsDestinationFolder = value; }
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Internal.NetworkSenders
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using NLog.Internal.NetworkSenders;
using Xunit;
public class TcpNetworkSenderTests : NLogTestBase
{
[Fact]
public void TcpHappyPathTest()
{
foreach (bool async in new[] { false, true })
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
Async = async,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
mre.Reset();
for (int i = 1; i < 8; i *= 2)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions) exceptions.Add(ex);
});
}
sender.Close(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
}
mre.Set();
});
mre.WaitOne();
actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1);
Assert.True(actual.IndexOf("close") != -1);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
}
}
[Fact]
public void TcpProxyTest()
{
var sender = new TcpNetworkSender("tcp://foo:1234", AddressFamily.Unspecified);
var socket = sender.CreateSocket("foo", AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Assert.IsType<SocketProxy>(socket);
}
[Fact]
public void TcpConnectFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
ConnectFailure = 1,
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new List<Exception>();
var allSent = new ManualResetEvent(false);
for (int i = 1; i < 8; i++)
{
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (exceptions.Count == 7)
{
allSent.Set();
}
}
});
}
Assert.True(allSent.WaitOne(3000, false));
var mre = new ManualResetEvent(false);
sender.FlushAsync(ex => mre.Set());
mre.WaitOne(3000, false);
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("failed") != -1);
foreach (var ex in exceptions)
{
Assert.NotNull(ex);
}
}
[Fact]
public void TcpSendFailureTest()
{
var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified)
{
SendFailureIn = 3, // will cause failure on 3rd send
Async = true,
};
sender.Initialize();
byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog");
var exceptions = new Exception[9];
var writeFinished = new ManualResetEvent(false);
int remaining = exceptions.Length;
for (int i = 1; i < 10; i++)
{
int pos = i - 1;
sender.Send(
buffer, 0, i, ex =>
{
lock (exceptions)
{
exceptions[pos] = ex;
if (--remaining == 0)
{
writeFinished.Set();
}
}
});
}
var mre = new ManualResetEvent(false);
writeFinished.WaitOne();
sender.Close(ex => mre.Set());
mre.WaitOne();
var actual = sender.Log.ToString();
Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1);
Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1);
Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1);
Assert.True(actual.IndexOf("send async 0 1 'q'") != -1);
Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1);
Assert.True(actual.IndexOf("send async 0 3 'qui'") != -1);
Assert.True(actual.IndexOf("failed") != -1);
Assert.True(actual.IndexOf("close") != -1);
for (int i = 0; i < exceptions.Length; ++i)
{
if (i < 2)
{
Assert.Null(exceptions[i]);
}
else
{
Assert.NotNull(exceptions[i]);
}
}
}
internal class MyTcpNetworkSender : TcpNetworkSender
{
public StringWriter Log { get; set; }
public MyTcpNetworkSender(string url, AddressFamily addressFamily)
: base(url, addressFamily)
{
Log = new StringWriter();
}
protected internal override ISocket CreateSocket(string host, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
{
return new MockSocket(addressFamily, socketType, protocolType, this);
}
protected override EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily)
{
Log.WriteLine("Parse endpoint address {0} {1}", uri, addressFamily);
return new MockEndPoint(uri);
}
public int ConnectFailure { get; set; }
public bool Async { get; set; }
public int SendFailureIn { get; set; }
}
internal class MockSocket : ISocket
{
private readonly MyTcpNetworkSender sender;
private readonly StringWriter log;
private bool faulted;
public MockSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, MyTcpNetworkSender sender)
{
this.sender = sender;
log = sender.Log;
log.WriteLine("create socket {0} {1} {2}", addressFamily, socketType, protocolType);
}
public bool ConnectAsync(SocketAsyncEventArgs args)
{
log.WriteLine("connect async to {0}", args.RemoteEndPoint);
lock (this)
{
if (sender.ConnectFailure > 0)
{
sender.ConnectFailure--;
faulted = true;
args.SocketError = SocketError.SocketError;
log.WriteLine("failed");
}
}
return InvokeCallback(args);
}
private bool InvokeCallback(SocketAsyncEventArgs args)
{
lock (this)
{
var args2 = args as TcpNetworkSender.MySocketAsyncEventArgs;
if (sender.Async)
{
ThreadPool.QueueUserWorkItem(s =>
{
Thread.Sleep(10);
args2.RaiseCompleted();
});
return true;
}
else
{
return false;
}
}
}
public void Close()
{
lock (this)
{
log.WriteLine("close");
}
}
public bool SendAsync(SocketAsyncEventArgs args)
{
lock (this)
{
log.WriteLine("send async {0} {1} '{2}'", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count));
if (sender.SendFailureIn > 0)
{
sender.SendFailureIn--;
if (sender.SendFailureIn == 0)
{
faulted = true;
}
}
if (faulted)
{
log.WriteLine("failed");
args.SocketError = SocketError.SocketError;
}
}
return InvokeCallback(args);
}
public bool SendToAsync(SocketAsyncEventArgs args)
{
lock (this)
{
log.WriteLine("sendto async {0} {1} '{2}' {3}", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count), args.RemoteEndPoint);
return InvokeCallback(args);
}
}
}
internal class MockEndPoint : EndPoint
{
private readonly Uri uri;
public MockEndPoint(Uri uri)
{
this.uri = uri;
}
public override AddressFamily AddressFamily => (AddressFamily)10000;
public override string ToString()
{
return "{mock end point: " + uri + "}";
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowGroupBySpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Akka.IO;
using Akka.Streams.Dsl;
using Akka.Streams.Dsl.Internal;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Supervision;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Akka.Util;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowGroupBySpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public FlowGroupBySpec(ITestOutputHelper helper) : base(helper)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2);
Materializer = ActorMaterializer.Create(Sys, settings);
}
private sealed class StreamPuppet
{
private readonly TestSubscriber.ManualProbe<int> _probe;
private readonly ISubscription _subscription;
public StreamPuppet(IPublisher<int> p, TestKitBase kit)
{
_probe = kit.CreateManualSubscriberProbe<int>();
p.Subscribe(_probe);
_subscription = _probe.ExpectSubscription();
}
public void Request(int demand) => _subscription.Request(demand);
public void ExpectNext(int element) => _probe.ExpectNext(element);
public void ExpectNoMsg(TimeSpan max) => _probe.ExpectNoMsg(max);
public void ExpectComplete() => _probe.ExpectComplete();
public void ExpectError(Exception ex) => _probe.ExpectError().Should().Be(ex);
public void Cancel() => _subscription.Cancel();
}
private void WithSubstreamsSupport(int groupCount = 2, int elementCount = 6, int maxSubstream = -1,
Action<TestSubscriber.ManualProbe<Tuple<int, Source<int, NotUsed>>>, ISubscription, Func<int, Source<int, NotUsed>>> run = null)
{
var source = Source.From(Enumerable.Range(1, elementCount)).RunWith(Sink.AsPublisher<int>(false), Materializer);
var max = maxSubstream > 0 ? maxSubstream : groupCount;
var groupStream =
Source.FromPublisher(source)
.GroupBy(max, x => x % groupCount)
.Lift(x => x % groupCount)
.RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
var masterSubscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
groupStream.Subscribe(masterSubscriber);
var masterSubscription = masterSubscriber.ExpectSubscription();
run?.Invoke(masterSubscriber, masterSubscription, expectedKey =>
{
masterSubscription.Request(1);
var tuple = masterSubscriber.ExpectNext();
tuple.Item1.Should().Be(expectedKey);
return tuple.Item2;
});
}
private ByteString RandomByteString(int size)
{
var a = new byte[size];
ThreadLocalRandom.Current.NextBytes(a);
return ByteString.FromBytes(a);
}
[Fact]
public void GroupBy_must_work_in_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(2, run: (masterSubscriber, masterSubscription, getSubFlow) =>
{
var s1 = new StreamPuppet(getSubFlow(1).RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s1.Request(1);
s1.ExpectNext(1);
s1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
var s2 = new StreamPuppet(getSubFlow(0).RunWith(Sink.AsPublisher<int>(false), Materializer), this);
s2.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s2.Request(2);
s2.ExpectNext(2);
// Important to request here on the OTHER stream because the buffer space is exactly one without the fanout box
s1.Request(1);
s2.ExpectNext(4);
s2.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s1.ExpectNext(3);
s2.Request(1);
// Important to request here on the OTHER stream because the buffer space is exactly one without the fanout box
s1.Request(1);
s2.ExpectNext(6);
s2.ExpectComplete();
s1.ExpectNext(5);
s1.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void GroupBy_must_work_in_normal_user_scenario()
{
var source = Source.From(new[] { "Aaa", "Abb", "Bcc", "Cdd", "Cee" })
.GroupBy(3, s => s.Substring(0, 1))
.Grouped(10)
.MergeSubstreams()
.Grouped(10);
var task =
((Source<IEnumerable<IEnumerable<string>>, NotUsed>)source).RunWith(
Sink.First<IEnumerable<IEnumerable<string>>>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.OrderBy(e => e.First())
.ShouldBeEquivalentTo(new[] { new[] { "Aaa", "Abb" }, new[] { "Bcc" }, new[] { "Cdd", "Cee" } });
}
[Fact]
public void GroupBy_must_fail_when_key_function_returns_null()
{
var source = (Source<IEnumerable<string>, NotUsed>)Source.From(new[] { "Aaa", "Abb", "Bcc", "Cdd", "Cee" })
.GroupBy(3, s => s.StartsWith("A") ? null : s.Substring(0, 1))
.Grouped(10)
.MergeSubstreams();
var down = source.RunWith(this.SinkProbe<IEnumerable<string>>(), Materializer);
down.Request(1);
var ex = down.ExpectError();
ex.Message.Should().Contain("Key cannot be null");
ex.Should().BeOfType<ArgumentNullException>();
}
[Fact]
public void GroupBy_must_support_cancelling_substreams()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(2, run: (masterSubscriber, masterSubscription, getSubFlow) =>
{
new StreamPuppet(getSubFlow(1).RunWith(Sink.AsPublisher<int>(false), Materializer), this).Cancel();
var substream = new StreamPuppet(getSubFlow(0).RunWith(Sink.AsPublisher<int>(false), Materializer), this);
substream.Request(2);
substream.ExpectNext(2);
substream.ExpectNext(4);
substream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
substream.Request(2);
substream.ExpectNext(6);
substream.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void GroupBy_must_accept_cancellation_of_master_stream_when_not_consume_anything()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<int>();
var publisher =
Source.FromPublisher(publisherProbe)
.GroupBy(2, x => x % 2)
.Lift(x => x % 2)
.RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Cancel();
upstreamSubscription.ExpectCancellation();
}, Materializer);
}
[Fact]
public void GroupBy_must_work_with_empty_input_stream()
{
this.AssertAllStagesStopped(() =>
{
var publisher =
Source.From(new List<int>())
.GroupBy(2, x => x % 2)
.Lift(x => x % 2)
.RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
publisher.Subscribe(subscriber);
subscriber.ExpectSubscriptionAndComplete();
}, Materializer);
}
[Fact]
public void GroupBy_must_abort_onError_from_upstream()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<int>();
var publisher =
Source.FromPublisher(publisherProbe)
.GroupBy(2, x => x % 2)
.Lift(x => x % 2)
.RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Request(100);
var ex = new TestException("test");
upstreamSubscription.SendError(ex);
subscriber.ExpectError().Should().Be(ex);
}, Materializer);
}
[Fact]
public void GroupBy_must_abort_onError_from_upstream_when_substreams_are_running()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<int>();
var publisher =
Source.FromPublisher(publisherProbe)
.GroupBy(2, x => x % 2)
.Lift(x => x % 2)
.RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Request(100);
upstreamSubscription.SendNext(1);
var substream = subscriber.ExpectNext().Item2;
var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
substreamPuppet.Request(1);
substreamPuppet.ExpectNext(1);
var ex = new TestException("test");
upstreamSubscription.SendError(ex);
substreamPuppet.ExpectError(ex);
subscriber.ExpectError().Should().Be(ex);
}, Materializer);
}
[Fact]
public void GroupBy_must_fail_stream_when_GroupBy_function_throws()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<int>();
var ex = new TestException("test");
var publisher = Source.FromPublisher(publisherProbe).GroupBy(2, i =>
{
if (i == 2)
throw ex;
return i % 2;
})
.Lift(x => x % 2)
.RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Request(100);
upstreamSubscription.SendNext(1);
var substream = subscriber.ExpectNext().Item2;
var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
substreamPuppet.Request(1);
substreamPuppet.ExpectNext(1);
upstreamSubscription.SendNext(2);
subscriber.ExpectError().Should().Be(ex);
substreamPuppet.ExpectError(ex);
upstreamSubscription.ExpectCancellation();
}, Materializer);
}
[Fact]
public void GroupBy_must_resume_stream_when_GroupBy_function_throws()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<int>();
var ex = new TestException("test");
var publisher = Source.FromPublisher(publisherProbe).GroupBy(2, i =>
{
if (i == 2)
throw ex;
return i % 2;
})
.Lift(x => x % 2)
.WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.ResumingDecider))
.RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Request(100);
upstreamSubscription.SendNext(1);
var substream = subscriber.ExpectNext().Item2;
var substreamPuppet1 = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
substreamPuppet1.Request(10);
substreamPuppet1.ExpectNext(1);
upstreamSubscription.SendNext(2);
upstreamSubscription.SendNext(4);
var substream2 = subscriber.ExpectNext().Item2;
var substreamPuppet2 = new StreamPuppet(substream2.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
substreamPuppet2.Request(10);
substreamPuppet2.ExpectNext(4);
upstreamSubscription.SendNext(3);
substreamPuppet1.ExpectNext(3);
upstreamSubscription.SendNext(6);
substreamPuppet2.ExpectNext(6);
upstreamSubscription.SendComplete();
subscriber.ExpectComplete();
substreamPuppet1.ExpectComplete();
substreamPuppet2.ExpectComplete();
}, Materializer);
}
[Fact]
public void GroupBy_must_pass_along_early_cancellation()
{
this.AssertAllStagesStopped(() =>
{
var up = this.CreateManualPublisherProbe<int>();
var down = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
var flowSubscriber =
Source.AsSubscriber<int>()
.GroupBy(2, x => x % 2)
.Lift(x => x % 2)
.To(Sink.FromSubscriber(down)).Run(Materializer);
var downstream = down.ExpectSubscription();
downstream.Cancel();
up.Subscribe(flowSubscriber);
var upSub = up.ExpectSubscription();
upSub.ExpectCancellation();
}, Materializer);
}
[Fact]
public void GroupBy_must_fail_when_exceeding_maxSubstreams()
{
this.AssertAllStagesStopped(() =>
{
var f = Flow.Create<int>().GroupBy(1, x => x % 2).PrefixAndTail(0).MergeSubstreams();
var t = ((Flow<int, Tuple<IImmutableList<int>, Source<int, NotUsed>>, NotUsed>)f)
.RunWith(this.SourceProbe<int>(), this.SinkProbe<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(), Materializer);
var up = t.Item1;
var down = t.Item2;
down.Request(2);
up.SendNext(1);
var first = down.ExpectNext();
var s1 = new StreamPuppet(first.Item2.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
s1.Request(1);
s1.ExpectNext(1);
up.SendNext(2);
var ex = down.ExpectError();
ex.Message.Should().Contain("too many substreams");
s1.ExpectError(ex);
}, Materializer);
}
[Fact]
public void GroupBy_must_emit_subscribe_before_completed()
{
this.AssertAllStagesStopped(() =>
{
var source = (Source<Source<int, NotUsed>, NotUsed>)Source.Single(0).GroupBy(1, _ => "all")
.PrefixAndTail(0)
.Select(t => t.Item2)
.ConcatSubstream();
var futureGroupSource = source.RunWith(Sink.First<Source<int, NotUsed>>(), Materializer);
var publisher = futureGroupSource.AwaitResult().RunWith(Sink.AsPublisher<int>(false), Materializer);
var probe = this.CreateSubscriberProbe<int>();
publisher.Subscribe(probe);
var subscription = probe.ExpectSubscription();
subscription.Request(1);
probe.ExpectNext(0);
probe.ExpectComplete();
}, Materializer);
}
[Fact]
public void GroupBy_must_work_under_fuzzing_stress_test()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<ByteString>();
var subscriber = this.CreateManualSubscriberProbe<IEnumerable<byte>>();
var firstGroup = (Source<IEnumerable<byte>, NotUsed>)Source.FromPublisher(publisherProbe)
.GroupBy(256, element => element[0])
.Select(b => b.Reverse())
.MergeSubstreams();
var secondGroup = (Source<IEnumerable<byte>, NotUsed>)firstGroup.GroupBy(256, bytes => bytes.First())
.Select(b => b.Reverse())
.MergeSubstreams();
var publisher = secondGroup.RunWith(Sink.AsPublisher<IEnumerable<byte>>(false), Materializer);
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Request(300);
for (var i = 1; i <= 300; i++)
{
var byteString = RandomByteString(10);
upstreamSubscription.ExpectRequest();
upstreamSubscription.SendNext(byteString);
subscriber.ExpectNext().ShouldBeEquivalentTo(byteString);
}
upstreamSubscription.SendComplete();
}, Materializer);
}
[Fact]
public void GroupBy_must_Work_if_pull_is_exercised_from_both_substream_and_main()
{
this.AssertAllStagesStopped(() =>
{
var upstream = this.CreatePublisherProbe<int>();
var downstreamMaster = this.CreateSubscriberProbe<Source<int, NotUsed>>();
Source.FromPublisher(upstream)
.Via(new GroupBy<int, bool>(2, element => element == 0))
.RunWith(Sink.FromSubscriber(downstreamMaster), Materializer);
var substream = this.CreateSubscriberProbe<int>();
downstreamMaster.Request(1);
upstream.SendNext(1);
downstreamMaster.ExpectNext().RunWith(Sink.FromSubscriber(substream), Materializer);
// Read off first buffered element from subsource
substream.Request(1);
substream.ExpectNext(1);
// Both will attempt to pull upstream
substream.Request(1);
substream.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
downstreamMaster.Request(1);
downstreamMaster.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
// Cleanup, not part of the actual test
substream.Cancel();
downstreamMaster.Cancel();
upstream.SendComplete();
}, Materializer);
}
[Fact]
public void GroupBy_must_work_with_random_demand()
{
this.AssertAllStagesStopped(() =>
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(1, 1);
var materializer = Sys.Materializer(settings);
var props = new RandomDemandProperties
{
Kit = this
};
Enumerable.Range(0, 100)
.ToList()
.ForEach(_ => props.Probes.Add(new TaskCompletionSource<TestSubscriber.Probe<ByteString>>()));
var map = new Dictionary<int, SubFlowState>();
var publisherProbe = this.CreateManualPublisherProbe<ByteString>();
var probeShape = new SinkShape<ByteString>(new Inlet<ByteString>("ProbeSink.in"));
var probeSink = new ProbeSink(probeShape, props, Attributes.None);
Source.FromPublisher(publisherProbe)
.GroupBy(100, element => Math.Abs(element[0] % 100))
.To(new Sink<ByteString, TestSubscriber.Probe<ByteString>>(probeSink))
.Run(materializer);
var upstreamSubscription = publisherProbe.ExpectSubscription();
for (var i = 1; i <= 400; i++)
{
var byteString = RandomByteString(10);
var index = Math.Abs(byteString[0] % 100);
upstreamSubscription.ExpectRequest();
upstreamSubscription.SendNext(byteString);
if (map.TryGetValue(index, out var state))
{
if (state.FirstElement != null) //first element in subFlow
{
if (!state.HasDemand)
props.BlockingNextElement = byteString;
RandomDemand(map, props);
}
else if (state.HasDemand)
{
if (props.BlockingNextElement == null)
{
state.Probe.ExpectNext().ShouldBeEquivalentTo(byteString);
map[index] = new SubFlowState(state.Probe, false, null);
RandomDemand(map, props);
}
else
true.ShouldBeFalse("INVALID CASE");
}
else
{
props.BlockingNextElement = byteString;
RandomDemand(map, props);
}
}
else
{
var probe = props.Probes[props.ProbesReaderTop].Task.AwaitResult();
props.ProbesReaderTop++;
map[index] = new SubFlowState(probe, false, byteString);
//stream automatically requests next element
}
}
upstreamSubscription.SendComplete();
}, Materializer);
}
private sealed class SubFlowState
{
public SubFlowState(TestSubscriber.Probe<ByteString> probe, bool hasDemand, ByteString firstElement)
{
Probe = probe;
HasDemand = hasDemand;
FirstElement = firstElement;
}
public TestSubscriber.Probe<ByteString> Probe { get; }
public bool HasDemand { get; }
public ByteString FirstElement { get; }
}
private sealed class ProbeSink : SinkModule<ByteString, TestSubscriber.Probe<ByteString>>
{
private readonly RandomDemandProperties _properties;
public ProbeSink(SinkShape<ByteString> shape, RandomDemandProperties properties, Attributes attributes) : base(shape)
{
_properties = properties;
Attributes = attributes;
}
public override Attributes Attributes { get; }
public override IModule WithAttributes(Attributes attributes)
{
return new ProbeSink(AmendShape(attributes), _properties, attributes);
}
protected override SinkModule<ByteString, TestSubscriber.Probe<ByteString>> NewInstance(SinkShape<ByteString> shape)
{
return new ProbeSink(shape, _properties, Attributes);
}
public override object Create(MaterializationContext context, out TestSubscriber.Probe<ByteString> materializer)
{
var promise = _properties.Probes[_properties.ProbesWriterTop];
var probe = TestSubscriber.CreateSubscriberProbe<ByteString>(_properties.Kit);
promise.SetResult(probe);
_properties.ProbesWriterTop++;
materializer = probe;
return probe;
}
}
private sealed class RandomDemandProperties
{
public TestKitBase Kit { get; set; }
public int ProbesWriterTop { get; set; }
public int ProbesReaderTop { get; set; }
public List<TaskCompletionSource<TestSubscriber.Probe<ByteString>>> Probes { get; } =
new List<TaskCompletionSource<TestSubscriber.Probe<ByteString>>>(100);
public ByteString BlockingNextElement { get; set; }
}
private void RandomDemand(Dictionary<int, SubFlowState> map, RandomDemandProperties props)
{
while (true)
{
var nextIndex = ThreadLocalRandom.Current.Next(0, map.Count);
var key = map.Keys.ToArray()[nextIndex];
if (!map[key].HasDemand)
{
var state = map[key];
map[key] = new SubFlowState(state.Probe, true, state.FirstElement);
state.Probe.Request(1);
// need to verify elements that are first element in subFlow or is in nextElement buffer before
// pushing next element from upstream
if (state.FirstElement != null)
{
state.Probe.ExpectNext().ShouldBeEquivalentTo(state.FirstElement);
map[key] = new SubFlowState(state.Probe, false, null);
}
else if (props.BlockingNextElement != null && Math.Abs(props.BlockingNextElement[0] % 100) == key)
{
state.Probe.ExpectNext().ShouldBeEquivalentTo(props.BlockingNextElement);
props.BlockingNextElement = null;
map[key] = new SubFlowState(state.Probe, false, null);
}
else if (props.BlockingNextElement == null)
break;
}
}
}
}
}
| |
// 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.CodeDom.Compiler.CodeGenerator.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.CodeDom.Compiler
{
abstract public partial class CodeGenerator : ICodeGenerator
{
#region Methods and constructors
protected CodeGenerator()
{
}
protected virtual new void ContinueOnNewLine(string st)
{
Contract.Requires(this.Output != null);
}
protected abstract string CreateEscapedIdentifier(string value);
protected abstract string CreateValidIdentifier(string value);
protected abstract void GenerateArgumentReferenceExpression(System.CodeDom.CodeArgumentReferenceExpression e);
protected abstract void GenerateArrayCreateExpression(System.CodeDom.CodeArrayCreateExpression e);
protected abstract void GenerateArrayIndexerExpression(System.CodeDom.CodeArrayIndexerExpression e);
protected abstract void GenerateAssignStatement(System.CodeDom.CodeAssignStatement e);
protected abstract void GenerateAttachEventStatement(System.CodeDom.CodeAttachEventStatement e);
protected abstract void GenerateAttributeDeclarationsEnd(System.CodeDom.CodeAttributeDeclarationCollection attributes);
protected abstract void GenerateAttributeDeclarationsStart(System.CodeDom.CodeAttributeDeclarationCollection attributes);
protected abstract void GenerateBaseReferenceExpression(System.CodeDom.CodeBaseReferenceExpression e);
protected virtual new void GenerateBinaryOperatorExpression(System.CodeDom.CodeBinaryOperatorExpression e)
{
Contract.Requires(e != null);
Contract.Requires(this.Output != null);
}
protected abstract void GenerateCastExpression(System.CodeDom.CodeCastExpression e);
public virtual new void GenerateCodeFromMember(System.CodeDom.CodeTypeMember member, TextWriter writer, CodeGeneratorOptions options)
{
}
protected abstract void GenerateComment(System.CodeDom.CodeComment e);
protected virtual new void GenerateCommentStatement(System.CodeDom.CodeCommentStatement e)
{
Contract.Requires(e != null);
}
protected virtual new void GenerateCommentStatements(System.CodeDom.CodeCommentStatementCollection e)
{
Contract.Requires(e != null);
}
protected virtual new void GenerateCompileUnit(System.CodeDom.CodeCompileUnit e)
{
Contract.Requires(e != null);
}
protected virtual new void GenerateCompileUnitEnd(System.CodeDom.CodeCompileUnit e)
{
Contract.Requires(e != null);
}
protected virtual new void GenerateCompileUnitStart(System.CodeDom.CodeCompileUnit e)
{
Contract.Requires(e != null);
}
protected abstract void GenerateConditionStatement(System.CodeDom.CodeConditionStatement e);
protected abstract void GenerateConstructor(System.CodeDom.CodeConstructor e, System.CodeDom.CodeTypeDeclaration c);
protected virtual new void GenerateDecimalValue(Decimal d)
{
Contract.Requires(this.Output != null);
}
protected virtual new void GenerateDefaultValueExpression(System.CodeDom.CodeDefaultValueExpression e)
{
}
protected abstract void GenerateDelegateCreateExpression(System.CodeDom.CodeDelegateCreateExpression e);
protected abstract void GenerateDelegateInvokeExpression(System.CodeDom.CodeDelegateInvokeExpression e);
protected virtual new void GenerateDirectionExpression(System.CodeDom.CodeDirectionExpression e)
{
Contract.Requires(e != null);
}
protected virtual new void GenerateDirectives(System.CodeDom.CodeDirectiveCollection directives)
{
}
protected virtual new void GenerateDoubleValue(double d)
{
Contract.Requires(this.Output != null);
}
protected abstract void GenerateEntryPointMethod(System.CodeDom.CodeEntryPointMethod e, System.CodeDom.CodeTypeDeclaration c);
protected abstract void GenerateEvent(System.CodeDom.CodeMemberEvent e, System.CodeDom.CodeTypeDeclaration c);
protected abstract void GenerateEventReferenceExpression(System.CodeDom.CodeEventReferenceExpression e);
protected void GenerateExpression(System.CodeDom.CodeExpression e)
{
}
protected abstract void GenerateExpressionStatement(System.CodeDom.CodeExpressionStatement e);
protected abstract void GenerateField(System.CodeDom.CodeMemberField e);
protected abstract void GenerateFieldReferenceExpression(System.CodeDom.CodeFieldReferenceExpression e);
protected abstract void GenerateGotoStatement(System.CodeDom.CodeGotoStatement e);
protected abstract void GenerateIndexerExpression(System.CodeDom.CodeIndexerExpression e);
protected abstract void GenerateIterationStatement(System.CodeDom.CodeIterationStatement e);
protected abstract void GenerateLabeledStatement(System.CodeDom.CodeLabeledStatement e);
protected abstract void GenerateLinePragmaEnd(System.CodeDom.CodeLinePragma e);
protected abstract void GenerateLinePragmaStart(System.CodeDom.CodeLinePragma e);
protected abstract void GenerateMethod(System.CodeDom.CodeMemberMethod e, System.CodeDom.CodeTypeDeclaration c);
protected abstract void GenerateMethodInvokeExpression(System.CodeDom.CodeMethodInvokeExpression e);
protected abstract void GenerateMethodReferenceExpression(System.CodeDom.CodeMethodReferenceExpression e);
protected abstract void GenerateMethodReturnStatement(System.CodeDom.CodeMethodReturnStatement e);
protected virtual new void GenerateNamespace(System.CodeDom.CodeNamespace e)
{
Contract.Requires(e != null);
Contract.Requires(e.Comments != null);
}
protected abstract void GenerateNamespaceEnd(System.CodeDom.CodeNamespace e);
protected abstract void GenerateNamespaceImport(System.CodeDom.CodeNamespaceImport e);
protected void GenerateNamespaceImports(System.CodeDom.CodeNamespace e)
{
Contract.Requires(e != null);
Contract.Requires(e.Imports != null);
}
protected void GenerateNamespaces(System.CodeDom.CodeCompileUnit e)
{
Contract.Requires(e != null);
Contract.Requires(e.Namespaces != null);
}
protected abstract void GenerateNamespaceStart(System.CodeDom.CodeNamespace e);
protected abstract void GenerateObjectCreateExpression(System.CodeDom.CodeObjectCreateExpression e);
protected virtual new void GenerateParameterDeclarationExpression(System.CodeDom.CodeParameterDeclarationExpression e)
{
Contract.Requires(e != null);
}
protected virtual new void GeneratePrimitiveExpression(System.CodeDom.CodePrimitiveExpression e)
{
Contract.Requires(e != null);
}
protected abstract void GenerateProperty(System.CodeDom.CodeMemberProperty e, System.CodeDom.CodeTypeDeclaration c);
protected abstract void GeneratePropertyReferenceExpression(System.CodeDom.CodePropertyReferenceExpression e);
protected abstract void GeneratePropertySetValueReferenceExpression(System.CodeDom.CodePropertySetValueReferenceExpression e);
protected abstract void GenerateRemoveEventStatement(System.CodeDom.CodeRemoveEventStatement e);
protected virtual new void GenerateSingleFloatValue(float s)
{
Contract.Requires(this.Output != null);
}
protected virtual new void GenerateSnippetCompileUnit(System.CodeDom.CodeSnippetCompileUnit e)
{
Contract.Requires(e != null);
}
protected abstract void GenerateSnippetExpression(System.CodeDom.CodeSnippetExpression e);
protected abstract void GenerateSnippetMember(System.CodeDom.CodeSnippetTypeMember e);
protected virtual new void GenerateSnippetStatement(System.CodeDom.CodeSnippetStatement e)
{
Contract.Requires(e != null);
Contract.Requires(this.Output != null);
}
protected void GenerateStatement(System.CodeDom.CodeStatement e)
{
Contract.Requires(e != null);
}
protected void GenerateStatements(System.CodeDom.CodeStatementCollection stms)
{
Contract.Requires(stms != null);
}
protected abstract void GenerateThisReferenceExpression(System.CodeDom.CodeThisReferenceExpression e);
protected abstract void GenerateThrowExceptionStatement(System.CodeDom.CodeThrowExceptionStatement e);
protected abstract void GenerateTryCatchFinallyStatement(System.CodeDom.CodeTryCatchFinallyStatement e);
protected abstract void GenerateTypeConstructor(System.CodeDom.CodeTypeConstructor e);
protected abstract void GenerateTypeEnd(System.CodeDom.CodeTypeDeclaration e);
protected virtual new void GenerateTypeOfExpression(System.CodeDom.CodeTypeOfExpression e)
{
Contract.Requires(e != null);
Contract.Requires(this.Output != null);
}
protected virtual new void GenerateTypeReferenceExpression(System.CodeDom.CodeTypeReferenceExpression e)
{
Contract.Requires(e != null);
}
protected void GenerateTypes(System.CodeDom.CodeNamespace e)
{
Contract.Requires(e != null);
Contract.Requires(e.Types != null);
}
protected abstract void GenerateTypeStart(System.CodeDom.CodeTypeDeclaration e);
protected abstract void GenerateVariableDeclarationStatement(System.CodeDom.CodeVariableDeclarationStatement e);
protected abstract void GenerateVariableReferenceExpression(System.CodeDom.CodeVariableReferenceExpression e);
protected abstract string GetTypeOutput(System.CodeDom.CodeTypeReference value);
protected abstract bool IsValidIdentifier(string value);
public static bool IsValidLanguageIndependentIdentifier(string value)
{
Contract.Requires(value != null);
return default(bool);
}
protected virtual new void OutputAttributeArgument(System.CodeDom.CodeAttributeArgument arg)
{
Contract.Requires(arg != null);
}
protected virtual new void OutputAttributeDeclarations(System.CodeDom.CodeAttributeDeclarationCollection attributes)
{
Contract.Requires(attributes != null);
}
protected virtual new void OutputDirection(System.CodeDom.FieldDirection dir)
{
}
protected virtual new void OutputExpressionList(System.CodeDom.CodeExpressionCollection expressions, bool newlineBetweenItems)
{
Contract.Requires(expressions != null);
}
protected virtual new void OutputExpressionList(System.CodeDom.CodeExpressionCollection expressions)
{
Contract.Requires(expressions != null);
}
protected virtual new void OutputFieldScopeModifier(System.CodeDom.MemberAttributes attributes)
{
}
protected virtual new void OutputIdentifier(string ident)
{
Contract.Requires(this.Output != null);
}
protected virtual new void OutputMemberAccessModifier(System.CodeDom.MemberAttributes attributes)
{
}
protected virtual new void OutputMemberScopeModifier(System.CodeDom.MemberAttributes attributes)
{
}
protected virtual new void OutputOperator(System.CodeDom.CodeBinaryOperatorType op)
{
}
protected virtual new void OutputParameters(System.CodeDom.CodeParameterDeclarationExpressionCollection parameters)
{
Contract.Requires(parameters != null);
}
protected abstract void OutputType(System.CodeDom.CodeTypeReference typeRef);
protected virtual new void OutputTypeAttributes(System.Reflection.TypeAttributes attributes, bool isStruct, bool isEnum)
{
}
protected virtual new void OutputTypeNamePair(System.CodeDom.CodeTypeReference typeRef, string name)
{
}
protected abstract string QuoteSnippetString(string value);
protected abstract bool Supports(GeneratorSupport support);
string System.CodeDom.Compiler.ICodeGenerator.CreateEscapedIdentifier(string value)
{
return default(string);
}
string System.CodeDom.Compiler.ICodeGenerator.CreateValidIdentifier(string value)
{
return default(string);
}
void System.CodeDom.Compiler.ICodeGenerator.GenerateCodeFromCompileUnit(System.CodeDom.CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o)
{
}
void System.CodeDom.Compiler.ICodeGenerator.GenerateCodeFromExpression(System.CodeDom.CodeExpression e, TextWriter w, CodeGeneratorOptions o)
{
}
void System.CodeDom.Compiler.ICodeGenerator.GenerateCodeFromNamespace(System.CodeDom.CodeNamespace e, TextWriter w, CodeGeneratorOptions o)
{
}
void System.CodeDom.Compiler.ICodeGenerator.GenerateCodeFromStatement(System.CodeDom.CodeStatement e, TextWriter w, CodeGeneratorOptions o)
{
}
void System.CodeDom.Compiler.ICodeGenerator.GenerateCodeFromType(System.CodeDom.CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o)
{
}
string System.CodeDom.Compiler.ICodeGenerator.GetTypeOutput(System.CodeDom.CodeTypeReference type)
{
return default(string);
}
bool System.CodeDom.Compiler.ICodeGenerator.IsValidIdentifier(string value)
{
return default(bool);
}
bool System.CodeDom.Compiler.ICodeGenerator.Supports(GeneratorSupport support)
{
return default(bool);
}
void System.CodeDom.Compiler.ICodeGenerator.ValidateIdentifier(string value)
{
}
protected virtual new void ValidateIdentifier(string value)
{
}
public static void ValidateIdentifiers(System.CodeDom.CodeObject e)
{
}
#endregion
#region Properties and indexers
protected System.CodeDom.CodeTypeDeclaration CurrentClass
{
get
{
return default(System.CodeDom.CodeTypeDeclaration);
}
}
protected System.CodeDom.CodeTypeMember CurrentMember
{
get
{
return default(System.CodeDom.CodeTypeMember);
}
}
protected string CurrentMemberName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
protected string CurrentTypeName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
protected int Indent
{
get
{
return default(int);
}
set
{
}
}
protected bool IsCurrentClass
{
get
{
return default(bool);
}
}
protected bool IsCurrentDelegate
{
get
{
return default(bool);
}
}
protected bool IsCurrentEnum
{
get
{
return default(bool);
}
}
protected bool IsCurrentInterface
{
get
{
return default(bool);
}
}
protected bool IsCurrentStruct
{
get
{
return default(bool);
}
}
protected abstract string NullToken
{
get;
}
protected CodeGeneratorOptions Options
{
get
{
return default(CodeGeneratorOptions);
}
}
protected TextWriter Output
{
get
{
return default(TextWriter);
}
}
#endregion
}
}
| |
using Pathfinding;
using System.Collections.Generic;
namespace Pathfinding
{
/** Stores temporary node data for a single pathfinding request.
* Every node has one PathNode per thread used.
* It stores e.g G score, H score and other temporary variables needed
* for path calculation, but which are not part of the graph structure.
*
* \see Pathfinding.PathHandler
* \see https://en.wikipedia.org/wiki/A*_search_algorithm
*/
public class PathNode {
/** Reference to the actual graph node */
public GraphNode node;
/** Parent node in the search tree */
public PathNode parent;
/** The path request (in this thread, if multithreading is used) which last used this node */
public ushort pathID;
/** Bitpacked variable which stores several fields */
private uint flags;
/** Cost uses the first 28 bits */
private const uint CostMask = (1U << 28) - 1U;
/** Flag 1 is at bit 28 */
private const int Flag1Offset = 28;
private const uint Flag1Mask = (uint)(1 << Flag1Offset);
/** Flag 2 is at bit 29 */
private const int Flag2Offset = 29;
private const uint Flag2Mask = (uint)(1 << Flag2Offset);
public uint cost {
get {
return flags & CostMask;
}
set {
flags = (flags & ~CostMask) | value;
}
}
/** Use as temporary flag during pathfinding.
* Pathfinders (only) can use this during pathfinding to mark
* nodes. When done, this flag should be reverted to its default state (false) to
* avoid messing up other pathfinding requests.
*/
public bool flag1 {
get {
return (flags & Flag1Mask) != 0;
}
set {
flags = (flags & ~Flag1Mask) | (value ? Flag1Mask : 0U);
}
}
/** Use as temporary flag during pathfinding.
* Pathfinders (only) can use this during pathfinding to mark
* nodes. When done, this flag should be reverted to its default state (false) to
* avoid messing up other pathfinding requests.
*/
public bool flag2 {
get {
return (flags & Flag2Mask) != 0;
}
set {
flags = (flags & ~Flag2Mask) | (value ? Flag2Mask : 0U);
}
}
/** Backing field for the G score */
private uint g;
/** Backing field for the H score */
private uint h;
/** G score, cost to get to this node */
public uint G {get { return g;} set{g = value;}}
/** H score, estimated cost to get to to the target */
public uint H {get { return h;} set{h = value;}}
/** F score. H score + G score */
public uint F {get { return g+h;}}
}
/** Handles thread specific path data.
*/
public class PathHandler {
/** Current PathID.
* \see #PathID
*/
private ushort pathID;
public readonly int threadID;
public readonly int totalThreadCount;
/**
* Binary heap to keep track of nodes on the "Open list".
* \see https://en.wikipedia.org/wiki/A*_search_algorithm
*/
private BinaryHeapM heap = new BinaryHeapM(128);
/** ID for the path currently being calculated or last path that was calculated */
public ushort PathID {get { return pathID; }}
/** Push a node to the heap */
public void PushNode (PathNode node) {
heap.Add (node);
}
/** Pop the node with the lowest F score from the heap */
public PathNode PopNode () {
return heap.Remove ();
}
/** The internal heap.
* \note Most things can be accomplished with other methods on this class instead.
*
* \see PushNode
* \see PopNode
* \see HeapEmpty
*/
public BinaryHeapM GetHeap () {
return heap;
}
/** Rebuild the heap to account for changed node values.
* Some path types change the target for the H score in the middle of the path calculation,
* that requires rebuilding the heap to keep it correctly sorted.
*/
public void RebuildHeap () {
heap.Rebuild ();
}
/** True if the heap is empty */
public bool HeapEmpty () {
return heap.numberOfItems <= 0;
}
/** Log2 size of buckets.
* So 10 yields a real bucket size of 1024.
* Be careful with large values.
*/
const int BucketSizeLog2 = 10;
/** Real bucket size */
const int BucketSize = 1 << BucketSizeLog2;
const int BucketIndexMask = (1 << BucketSizeLog2)-1;
/** Array of buckets containing PathNodes */
public PathNode[][] nodes = new PathNode[0][];
private bool[] bucketNew = new bool[0];
private bool[] bucketCreated = new bool[0];
private Stack<PathNode[]> bucketCache = new Stack<PathNode[]> ();
private int filledBuckets;
/** StringBuilder that paths can use to build debug strings.
* Better for performance and memory usage to use a single StringBuilder instead of each path creating its own
*/
public readonly System.Text.StringBuilder DebugStringBuilder = new System.Text.StringBuilder();
public PathHandler (int threadID, int totalThreadCount ) {
this.threadID = threadID;
this.totalThreadCount = totalThreadCount;
}
public void InitializeForPath (Path p) {
pathID = p.pathID;
heap.Clear ();
}
/** Internal method to clean up node data */
public void DestroyNode (GraphNode node) {
PathNode pn = GetPathNode (node);
//Clean up reference to help GC
pn.node = null;
pn.parent = null;
}
/** Internal method to initialize node data */
public void InitializeNode (GraphNode node) {
//Get the index of the node
int ind = node.NodeIndex;
int bucketNumber = ind >> BucketSizeLog2;
int bucketIndex = ind & BucketIndexMask;
if (bucketNumber >= nodes.Length) {
// A resize is required
// At least increase the size to:
// Current size * 1.5
// Current size + 2 or
// bucketNumber+1
var newNodes = new PathNode[System.Math.Max (System.Math.Max (nodes.Length*3 / 2,bucketNumber+1), nodes.Length+2)][];
for (int i=0;i<nodes.Length;i++) newNodes[i] = nodes[i];
var newBucketNew = new bool[newNodes.Length];
for (int i=0;i<nodes.Length;i++) newBucketNew[i] = bucketNew[i];
var newBucketCreated = new bool[newNodes.Length];
for (int i=0;i<nodes.Length;i++) newBucketCreated[i] = bucketCreated[i];
nodes = newNodes;
bucketNew = newBucketNew;
bucketCreated = newBucketCreated;
}
if (nodes[bucketNumber] == null) {
PathNode[] ns;
if (bucketCache.Count > 0) {
ns = bucketCache.Pop();
} else {
ns = new PathNode[BucketSize];
for (int i=0;i<BucketSize;i++) ns[i] = new PathNode ();
}
nodes[bucketNumber] = ns;
if (!bucketCreated[bucketNumber]) {
bucketNew[bucketNumber] = true;
bucketCreated[bucketNumber] = true;
}
filledBuckets++;
}
PathNode pn = nodes[bucketNumber][bucketIndex];
pn.node = node;
}
public PathNode GetPathNode ( int nodeIndex ) {
return nodes[nodeIndex >> BucketSizeLog2][nodeIndex & BucketIndexMask];
}
/** Returns the PathNode corresponding to the specified node.
* The PathNode is specific to this PathHandler since multiple PathHandlers
* are used at the same time if multithreading is enabled.
*/
public PathNode GetPathNode ( GraphNode node ) {
// Get the index of the node
int ind = node.NodeIndex;
return nodes[ind >> BucketSizeLog2][ind & BucketIndexMask];
}
/** Set all nodes' pathIDs to 0.
* \see Pathfinding.PathNode.pathID
*/
public void ClearPathIDs () {
for (int i=0;i<nodes.Length;i++) {
PathNode[] ns = nodes[i];
if (ns != null) for (int j=0;j<BucketSize;j++) ns[j].pathID = 0;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.Messaging;
using Orleans.Runtime.Configuration;
using Orleans.SqlUtils;
namespace Orleans.Runtime.MembershipService
{
internal class SqlMembershipTable: IMembershipTable, IGatewayListProvider
{
private string deploymentId;
private TimeSpan maxStaleness;
private Logger logger;
private RelationalOrleansQueries orleansQueries;
public async Task InitializeMembershipTable(GlobalConfiguration config, bool tryInitTableVersion, Logger traceLogger)
{
logger = traceLogger;
deploymentId = config.DeploymentId;
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.InitializeMembershipTable called.");
//This initializes all of Orleans operational queries from the database using a well known view
//and assumes the database with appropriate defintions exists already.
orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString);
// even if I am not the one who created the table,
// try to insert an initial table version if it is not already there,
// so we always have a first table version row, before this silo starts working.
if(tryInitTableVersion)
{
var wasCreated = await InitTableAsync();
if(wasCreated)
{
logger.Info("Created new table version row.");
}
}
}
public async Task InitializeGatewayListProvider(ClientConfiguration config, Logger traceLogger)
{
logger = traceLogger;
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.InitializeGatewayListProvider called.");
deploymentId = config.DeploymentId;
maxStaleness = config.GatewayListRefreshPeriod;
orleansQueries = await RelationalOrleansQueries.CreateInstance(config.AdoInvariant, config.DataConnectionString);
}
public TimeSpan MaxStaleness
{
get { return maxStaleness; }
}
public bool IsUpdatable
{
get { return true; }
}
public async Task<IList<Uri>> GetGateways()
{
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.GetGateways called.");
try
{
return await orleansQueries.ActiveGatewaysAsync(deploymentId);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.Gateways failed {0}", ex);
throw;
}
}
public async Task<MembershipTableData> ReadRow(SiloAddress key)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("SqlMembershipTable.ReadRow called with key: {0}.", key));
try
{
return await orleansQueries.MembershipReadRowAsync(deploymentId, key);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.ReadRow failed: {0}", ex);
throw;
}
}
public async Task<MembershipTableData> ReadAll()
{
if (logger.IsVerbose3) logger.Verbose3("SqlMembershipTable.ReadAll called.");
try
{
return await orleansQueries.MembershipReadAllAsync(deploymentId);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.ReadAll failed: {0}", ex);
throw;
}
}
public async Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("SqlMembershipTable.InsertRow called with entry {0} and tableVersion {1}.", entry, tableVersion));
//The "tableVersion" parameter should always exist when inserting a row as Init should
//have been called and membership version created and read. This is an optimization to
//not to go through all the way to database to fail a conditional check on etag (which does
//exist for the sake of robustness) as mandated by Orleans membership protocol.
//Likewise, no update can be done without membership entry.
if (entry == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.InsertRow aborted due to null check. MembershipEntry is null.");
throw new ArgumentNullException("entry");
}
if (tableVersion == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.InsertRow aborted due to null check. TableVersion is null ");
throw new ArgumentNullException("tableVersion");
}
try
{
return await orleansQueries.InsertMembershipRowAsync(deploymentId, entry, tableVersion.VersionEtag);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.InsertRow failed: {0}", ex);
throw;
}
}
public async Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("IMembershipTable.UpdateRow called with entry {0}, etag {1} and tableVersion {2}.", entry, etag, tableVersion));
//The "tableVersion" parameter should always exist when updating a row as Init should
//have been called and membership version created and read. This is an optimization to
//not to go through all the way to database to fail a conditional check (which does
//exist for the sake of robustness) as mandated by Orleans membership protocol.
//Likewise, no update can be done without membership entry or an etag.
if (entry == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateRow aborted due to null check. MembershipEntry is null.");
throw new ArgumentNullException("entry");
}
if (tableVersion == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateRow aborted due to null check. TableVersion is null ");
throw new ArgumentNullException("tableVersion");
}
try
{
return await orleansQueries.UpdateMembershipRowAsync(deploymentId, entry, tableVersion.VersionEtag);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateRow failed: {0}", ex);
throw;
}
}
public async Task UpdateIAmAlive(MembershipEntry entry)
{
if(logger.IsVerbose3) logger.Verbose3(string.Format("IMembershipTable.UpdateIAmAlive called with entry {0}.", entry));
if (entry == null)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateIAmAlive aborted due to null check. MembershipEntry is null.");
throw new ArgumentNullException("entry");
}
try
{
await orleansQueries.UpdateIAmAliveTimeAsync(deploymentId, entry.SiloAddress, entry.IAmAliveTime);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.UpdateIAmAlive failed: {0}", ex);
throw;
}
}
public async Task DeleteMembershipTableEntries(string deploymentId)
{
if (logger.IsVerbose3) logger.Verbose3(string.Format("IMembershipTable.DeleteMembershipTableEntries called with deploymentId {0}.", deploymentId));
try
{
await orleansQueries.DeleteMembershipTableEntriesAsync(deploymentId);
}
catch(Exception ex)
{
if (logger.IsVerbose) logger.Verbose("SqlMembershipTable.DeleteMembershipTableEntries failed: {0}", ex);
throw;
}
}
private async Task<bool> InitTableAsync()
{
try
{
return await orleansQueries.InsertMembershipVersionRowAsync(deploymentId);
}
catch(Exception ex)
{
if(logger.IsVerbose2) logger.Verbose2("Insert silo membership version failed: {0}", ex.ToString());
throw;
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////
// Description: Data Access class for the table 'KelurahanDesa'
// Generated by LLBLGen v1.21.2003.712 Final on: 19 September 2006, 9:55:04
// Because the Base Class already implements IDispose, this class doesn't.
///////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace BkNet.DataAccess
{
/// <summary>
/// Purpose: Data Access class for the table 'KelurahanDesa'.
/// </summary>
public class KelurahanDesa : DBInteractionBase
{
#region Class Member Declarations
private SqlBoolean _published;
private SqlDateTime _createdDate, _modifiedDate;
private SqlInt32 _ordering, _createdBy, _id, _kecamatanId, _kecamatanIdOld, _modifiedBy;
private SqlString _nama, _kode, _kodePos, _keterangan;
#endregion
/// <summary>
/// Purpose: Class constructor.
/// </summary>
public KelurahanDesa()
{
// Nothing for now.
}
/// <summary>
/// Purpose: IsExist method. This method will check Exsisting data from database.
/// Addes By Ekitea On 19 September 2006
/// </summary>
/// <returns></returns>
public bool IsExist()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_IsExist]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanId));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@IsExist", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
int IsExist = int.Parse(cmdToExecute.Parameters["@IsExist"].Value.ToString());
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_IsExist' reported the ErrorCode: " + _errorCode);
}
return IsExist==1;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::IsExist::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Insert method. This method will insert one new row into the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>KecamatanId</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>KodePos. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Insert()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_Insert]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanId));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@KodePos", SqlDbType.VarChar, 5, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _kodePos));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 1, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 23, 3, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 23, 3, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_id = (SqlInt32)cmdToExecute.Parameters["@Id"].Value;
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_Insert' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::Insert::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method. This method will Update one existing row in the database.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// <LI>KecamatanId</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan. May be SqlString.Null</LI>
/// <LI>KodePos. May be SqlString.Null</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy. May be SqlInt32.Null</LI>
/// <LI>ModifiedDate. May be SqlDateTime.Null</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Update()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_Update]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanId));
cmdToExecute.Parameters.Add(new SqlParameter("@Kode", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _kode));
cmdToExecute.Parameters.Add(new SqlParameter("@Nama", SqlDbType.VarChar, 50, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, _nama));
cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan));
cmdToExecute.Parameters.Add(new SqlParameter("@KodePos", SqlDbType.VarChar, 5, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _kodePos));
cmdToExecute.Parameters.Add(new SqlParameter("@Published", SqlDbType.Bit, 1, ParameterDirection.Input, false, 1, 0, "", DataRowVersion.Proposed, _published));
cmdToExecute.Parameters.Add(new SqlParameter("@Ordering", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _ordering));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _createdBy));
cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, false, 23, 3, "", DataRowVersion.Proposed, _createdDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy));
cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 23, 3, "", DataRowVersion.Proposed, _modifiedDate));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_Update' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::Update::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Update method for updating one or more rows using the Foreign Key 'KecamatanId.
/// This method will Update one or more existing rows in the database. It will reset the field 'KecamatanId' in
/// all rows which have as value for this field the value as set in property 'KecamatanIdOld' to
/// the value as set in property 'KecamatanId'.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>KecamatanId</LI>
/// <LI>KecamatanIdOld</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public bool UpdateAllWKecamatanIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_UpdateAllWKecamatanIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanId));
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanIdOld", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanIdOld));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_UpdateAllWKecamatanIdLogic' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::UpdateAllWKecamatanIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method. This method will Delete one existing row in the database, based on the Primary Key.
/// </summary>
/// <returns>True if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override bool Delete()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_Delete]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_Delete' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::Delete::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Delete method for a foreign key. This method will Delete one or more rows from the database, based on the Foreign Key 'KecamatanId'
/// </summary>
/// <returns>True if succeeded, false otherwise. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>KecamatanId</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public bool DeleteAllWKecamatanIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_DeleteAllWKecamatanIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
_rowsAffected = cmdToExecute.ExecuteNonQuery();
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_DeleteAllWKecamatanIdLogic' reported the ErrorCode: " + _errorCode);
}
return true;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::DeleteAllWKecamatanIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
}
}
/// <summary>
/// Purpose: Select method. This method will Select one existing row from the database, based on the Primary Key.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>Id</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// <LI>Id</LI>
/// <LI>KecamatanId</LI>
/// <LI>Kode</LI>
/// <LI>Nama</LI>
/// <LI>Keterangan</LI>
/// <LI>KodePos</LI>
/// <LI>Published</LI>
/// <LI>Ordering</LI>
/// <LI>CreatedBy</LI>
/// <LI>CreatedDate</LI>
/// <LI>ModifiedBy</LI>
/// <LI>ModifiedDate</LI>
/// </UL>
/// Will fill all properties corresponding with a field in the table with the value of the row selected.
/// </remarks>
public override DataTable SelectOne()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_SelectOne]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("KelurahanDesa");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@Id", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _id));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_SelectOne' reported the ErrorCode: " + _errorCode);
}
if(toReturn.Rows.Count > 0)
{
_id = (Int32)toReturn.Rows[0]["Id"];
_kecamatanId = (Int32)toReturn.Rows[0]["KecamatanId"];
_kode = (string)toReturn.Rows[0]["Kode"];
_nama = (string)toReturn.Rows[0]["Nama"];
_keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"];
_kodePos = toReturn.Rows[0]["KodePos"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["KodePos"];
_published = (bool)toReturn.Rows[0]["Published"];
_ordering = (Int32)toReturn.Rows[0]["Ordering"];
_createdBy = (Int32)toReturn.Rows[0]["CreatedBy"];
_createdDate = (DateTime)toReturn.Rows[0]["CreatedDate"];
_modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"];
_modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"];
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::SelectOne::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: SelectAll method. This method will Select all rows from the table.
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public override DataTable SelectAll()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_SelectAll]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("KelurahanDesa");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_SelectAll' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::SelectAll::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'KecamatanId'
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>KecamatanId</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable SelectAllWKecamatanIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_SelectAllWKecamatanIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("KelurahanDesa");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_SelectAllWKecamatanIdLogic' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::SelectAllWKecamatanIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
/// <summary>
/// Purpose: GetListWKecamatanIdLogic method. This method will Select all rows from the table where is active.
/// Added by Ekitea On 19 September 2006
/// </summary>
/// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns>
/// <remarks>
/// Properties needed for this method:
/// <UL>
/// <LI>KecamatanId</LI>
/// </UL>
/// Properties set after a succesful call of this method:
/// <UL>
/// <LI>ErrorCode</LI>
/// </UL>
/// </remarks>
public DataTable GetListWKecamatanIdLogic()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "dbo.[KelurahanDesa_GetListWKecamatanIdLogic]";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataTable toReturn = new DataTable("KelurahanDesa");
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);
// Use base class' connection object
cmdToExecute.Connection = _mainConnection;
try
{
cmdToExecute.Parameters.Add(new SqlParameter("@KecamatanId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _kecamatanId));
cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode));
// Open connection.
_mainConnection.Open();
// Execute query.
adapter.Fill(toReturn);
_errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value;
if(_errorCode != (int)LLBLError.AllOk)
{
// Throw error.
throw new Exception("Stored Procedure 'KelurahanDesa_GetListWKecamatanIdLogic' reported the ErrorCode: " + _errorCode);
}
return toReturn;
}
catch(Exception ex)
{
// some error occured. Bubble it to caller and encapsulate Exception object
throw new Exception("KelurahanDesa::GetListWKecamatanIdLogic::Error occured.", ex);
}
finally
{
// Close connection.
_mainConnection.Close();
cmdToExecute.Dispose();
adapter.Dispose();
}
}
#region Class Property Declarations
public SqlInt32 Id
{
get
{
return _id;
}
set
{
SqlInt32 idTmp = (SqlInt32)value;
if(idTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Id", "Id can't be NULL");
}
_id = value;
}
}
public SqlInt32 KecamatanId
{
get
{
return _kecamatanId;
}
set
{
SqlInt32 kecamatanIdTmp = (SqlInt32)value;
if(kecamatanIdTmp.IsNull)
{
throw new ArgumentOutOfRangeException("KecamatanId", "KecamatanId can't be NULL");
}
_kecamatanId = value;
}
}
public SqlInt32 KecamatanIdOld
{
get
{
return _kecamatanIdOld;
}
set
{
SqlInt32 kecamatanIdOldTmp = (SqlInt32)value;
if(kecamatanIdOldTmp.IsNull)
{
throw new ArgumentOutOfRangeException("KecamatanIdOld", "KecamatanIdOld can't be NULL");
}
_kecamatanIdOld = value;
}
}
public SqlString Kode
{
get
{
return _kode;
}
set
{
SqlString kodeTmp = (SqlString)value;
if(kodeTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Kode", "Kode can't be NULL");
}
_kode = value;
}
}
public SqlString Nama
{
get
{
return _nama;
}
set
{
SqlString namaTmp = (SqlString)value;
if(namaTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Nama", "Nama can't be NULL");
}
_nama = value;
}
}
public SqlString Keterangan
{
get
{
return _keterangan;
}
set
{
_keterangan = value;
}
}
public SqlString KodePos
{
get
{
return _kodePos;
}
set
{
_kodePos = value;
}
}
public SqlBoolean Published
{
get
{
return _published;
}
set
{
SqlBoolean publishedTmp = (SqlBoolean)value;
if(publishedTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Published", "Published can't be NULL");
}
_published = value;
}
}
public SqlInt32 Ordering
{
get
{
return _ordering;
}
set
{
SqlInt32 orderingTmp = (SqlInt32)value;
if(orderingTmp.IsNull)
{
throw new ArgumentOutOfRangeException("Ordering", "Ordering can't be NULL");
}
_ordering = value;
}
}
public SqlInt32 CreatedBy
{
get
{
return _createdBy;
}
set
{
SqlInt32 createdByTmp = (SqlInt32)value;
if(createdByTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedBy", "CreatedBy can't be NULL");
}
_createdBy = value;
}
}
public SqlDateTime CreatedDate
{
get
{
return _createdDate;
}
set
{
SqlDateTime createdDateTmp = (SqlDateTime)value;
if(createdDateTmp.IsNull)
{
throw new ArgumentOutOfRangeException("CreatedDate", "CreatedDate can't be NULL");
}
_createdDate = value;
}
}
public SqlInt32 ModifiedBy
{
get
{
return _modifiedBy;
}
set
{
_modifiedBy = value;
}
}
public SqlDateTime ModifiedDate
{
get
{
return _modifiedDate;
}
set
{
_modifiedDate = value;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Signum.Utilities;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Data.Common;
using System.Globalization;
using Signum.Engine.Maps;
using Npgsql;
namespace Signum.Engine
{
public enum Spacing
{
Simple,
Double,
Triple
}
public abstract class SqlPreCommand
{
public abstract IEnumerable<SqlPreCommandSimple> Leaves();
public abstract SqlPreCommand Clone();
public abstract bool GoBefore { get; set; }
public abstract bool GoAfter { get; set; }
protected internal abstract int NumParameters { get; }
/// <summary>
/// For debugging purposes
/// </summary>
public string PlainSql()
{
StringBuilder sb = new StringBuilder();
this.PlainSql(sb);
return sb.ToString();
}
protected internal abstract void PlainSql(StringBuilder sb);
public override string ToString()
{
return this.PlainSql();
}
public static SqlPreCommand? Combine(Spacing spacing, params SqlPreCommand?[] sentences)
{
if (sentences.Contains(null))
sentences = sentences.NotNull().ToArray();
if (sentences.Length == 0)
return null;
if (sentences.Length == 1)
return sentences[0];
return new SqlPreCommandConcat(spacing, sentences as SqlPreCommand[]);
}
public abstract SqlPreCommand Replace(Regex regex, MatchEvaluator matchEvaluator);
}
public static class SqlPreCommandExtensions
{
public static SqlPreCommand? Combine(this IEnumerable<SqlPreCommand?> preCommands, Spacing spacing)
{
return SqlPreCommand.Combine(spacing, preCommands.ToArray());
}
public static SqlPreCommand PlainSqlCommand(this SqlPreCommand command)
{
return command.PlainSql().SplitNoEmpty("GO\r\n" )
.Select(s => new SqlPreCommandSimple(s))
.Combine(Spacing.Simple)!;
}
public static void OpenSqlFileRetry(this SqlPreCommand command)
{
SafeConsole.WriteLineColor(ConsoleColor.Yellow, "There are changes!");
var fileName = "Sync {0:dd-MM-yyyy HH_mm_ss}.sql".FormatWith(DateTime.Now);
Save(command, fileName);
SafeConsole.WriteLineColor(ConsoleColor.DarkYellow, command.PlainSql());
Console.WriteLine("Script saved in: " + Path.Combine(Directory.GetCurrentDirectory(), fileName));
var answer = SafeConsole.AskRetry("Open or run?", "open", "run", "exit");
if(answer == "open")
{
Thread.Sleep(1000);
Open(fileName);
if (SafeConsole.Ask("run now?"))
ExecuteRetry(fileName);
}
else if(answer == "run")
{
ExecuteRetry(fileName);
}
}
static void ExecuteRetry(string fileName)
{
retry:
try
{
var script = File.ReadAllText(fileName);
using (Transaction tr = Transaction.ForceNew(System.Data.IsolationLevel.Unspecified))
{
ExecuteScript("script", script);
tr.Commit();
}
}
catch (ExecuteSqlScriptException)
{
Console.WriteLine("The current script is in saved in: " + Path.Combine(Directory.GetCurrentDirectory(), fileName));
if (SafeConsole.Ask("retry?"))
goto retry;
}
}
public static int Timeout = 20 * 60;
public static void ExecuteScript(string title, string script)
{
using (Connector.CommandTimeoutScope(Timeout))
{
var regex = new Regex(@" *(GO|USE \w+|USE \[[^\]]+\]) *(\r?\n|$)", RegexOptions.IgnoreCase);
var parts = regex.Split(script);
var realParts = parts.Where(a => !string.IsNullOrWhiteSpace(a) && !regex.IsMatch(a)).ToArray();
int pos = 0;
try
{
for (pos = 0; pos < realParts.Length; pos++)
{
SafeConsole.WaitExecute("Executing {0} [{1}/{2}]".FormatWith(title, pos + 1, realParts.Length), () => Executor.ExecuteNonQuery(realParts[pos]));
}
}
catch (Exception ex)
{
var sqlE = ex as SqlException ?? ex.InnerException as SqlException;
var pgE = ex as PostgresException ?? ex.InnerException as PostgresException;
if (sqlE == null && pgE == null)
throw;
Console.WriteLine();
Console.WriteLine();
var list = script.Lines();
var lineNumer = (pgE?.Line?.ToInt() ?? sqlE!.LineNumber - 1) + pos + parts.Take(parts.IndexOf(realParts[pos])).Sum(a => a.Lines().Length);
SafeConsole.WriteLineColor(ConsoleColor.Red, "ERROR:");
var min = Math.Max(0, lineNumer - 20);
var max = Math.Min(list.Length - 1, lineNumer + 20);
if (min > 0)
Console.WriteLine("...");
for (int i = min; i <= max; i++)
{
Console.Write(i + ": ");
SafeConsole.WriteLineColor(i == lineNumer ? ConsoleColor.Red : ConsoleColor.DarkRed, list[i]);
}
if (max < list.Length - 1)
Console.WriteLine("...");
Console.WriteLine();
SafeConsole.WriteLineColor(ConsoleColor.DarkRed, ex.GetType().Name + " (Number {0}): ".FormatWith(pgE?.SqlState ?? sqlE?.Number.ToString()));
SafeConsole.WriteLineColor(ConsoleColor.Red, ex.Message);
if(ex.InnerException!=null)
{
SafeConsole.WriteLineColor(ConsoleColor.Red, ex.InnerException.Message);
foreach (var item in realParts[pos].Lines())
{
SafeConsole.WriteLineColor(ConsoleColor.Red, item);
}
}
Console.WriteLine();
throw new ExecuteSqlScriptException(ex.Message, ex);
}
}
}
private static void Open(string fileName)
{
new Process
{
StartInfo = new ProcessStartInfo(Path.Combine(Directory.GetCurrentDirectory(), fileName))
{
UseShellExecute = true
}
}.Start();
}
public static void Save(this SqlPreCommand command, string fileName)
{
string content = command.PlainSql();
File.WriteAllText(fileName, content, Encoding.Unicode);
}
}
[Serializable]
public class ExecuteSqlScriptException : Exception
{
public ExecuteSqlScriptException() { }
public ExecuteSqlScriptException(string message) : base(message) { }
public ExecuteSqlScriptException(string message, Exception inner) : base(message, inner) { }
protected ExecuteSqlScriptException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
public class SqlPreCommandSimple : SqlPreCommand
{
public override bool GoBefore { get; set; }
public override bool GoAfter { get; set; }
public string Sql { get; private set; }
public List<DbParameter>? Parameters { get; private set; }
public SqlPreCommandSimple(string sql)
{
this.Sql = sql;
}
public SqlPreCommandSimple(string sql, List<DbParameter>? parameters)
{
this.Sql = sql;
this.Parameters = parameters;
}
public void AlterSql(string sql)
{
this.Sql = sql;
}
public override IEnumerable<SqlPreCommandSimple> Leaves()
{
yield return this;
}
protected internal override int NumParameters
{
get { return Parameters?.Count ?? 0; }
}
static readonly Regex regex = new Regex(@"@[_\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nl}][_\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nl}\p{Nd}]*");
internal static string Encode(object? value)
{
if (value == null || value == DBNull.Value)
return "NULL";
if (value is string s)
return "\'" + s.Replace("'", "''") + "'";
if (value is char c)
return "\'" + c.ToString().Replace("'", "''") + "'";
if (value is Guid g)
return "\'" + g.ToString() + "'";
if (value is DateTime dt)
{
return Schema.Current.Settings.IsPostgres ?
"'{0}'".FormatWith(dt.ToString("yyyy-MM-dd hh:mm:ss.fff", CultureInfo.InvariantCulture)) :
"convert(datetime, '{0}', 126)".FormatWith(dt.ToString("yyyy-MM-ddThh:mm:ss.fff", CultureInfo.InvariantCulture));
}
if (value is TimeSpan ts)
{
var str = ts.ToString("g", CultureInfo.InvariantCulture);
return Schema.Current.Settings.IsPostgres ? str : "convert(time, '{0}')".FormatWith(str);
}
if (value is bool b)
{
if (Schema.Current.Settings.IsPostgres)
return b.ToString();
return (b ? 1 : 0).ToString();
}
if (Schema.Current.Settings.UdtSqlName.TryGetValue(value.GetType(), out var name))
return "CAST('{0}' AS {1})".FormatWith(value, name);
if (value.GetType().IsEnum)
return Convert.ToInt32(value).ToString();
if (value is byte[] bytes)
return "0x" + BitConverter.ToString(bytes).Replace("-", "");
if (value is IFormattable f)
return f.ToString(null, CultureInfo.InvariantCulture);
return value.ToString()!;
}
protected internal override void PlainSql(StringBuilder sb)
{
if (Parameters.IsNullOrEmpty())
sb.Append(Sql);
else
{
var dic = Parameters.ToDictionary(a => a.ParameterName, a => Encode(a.Value));
sb.Append(regex.Replace(Sql, m => dic.TryGetC(m.Value) ?? m.Value));
}
}
public string sp_executesql()
{
var pars = this.Parameters.EmptyIfNull();
var sqlBuilder = Connector.Current.SqlBuilder;
var parameterVars = pars.ToString(p => $"{p.ParameterName} {(p is SqlParameter sp ? sp.SqlDbType.ToString() : ((NpgsqlParameter)p).NpgsqlDbType.ToString())}{sqlBuilder.GetSizeScale(p.Size.DefaultToNull(), p.Scale.DefaultToNull())}", ", ");
var parameterValues = pars.ToString(p => Encode(p.Value), ",");
return $"EXEC sp_executesql N'{this.Sql}', N'{parameterVars}', {parameterValues}";
}
public override SqlPreCommand Clone()
{
return new SqlPreCommandSimple(Sql, Parameters?.Select(p => Connector.Current.CloneParameter(p)).ToList());
}
public SqlPreCommandSimple AddComment(string? comment)
{
if (comment.HasText())
{
int index = Sql.IndexOf("\r\n");
if (index == -1)
Sql = Sql + " -- " + comment;
else
Sql = Sql.Insert(index, " -- " + comment);
}
return this;
}
public SqlPreCommandSimple ReplaceFirstParameter(string? variableName)
{
if (variableName == null)
return this;
var first = Parameters!.FirstEx();
Sql = Regex.Replace(Sql, $@"(?<toReplace>{first.ParameterName})(\b|$)", variableName); //HACK
Parameters!.Remove(first);
return this;
}
public override SqlPreCommand Replace(Regex regex, MatchEvaluator matchEvaluator) => new SqlPreCommandSimple(regex.Replace(this.Sql, matchEvaluator), this.Parameters?.Select(p => Connector.Current.CloneParameter(p)).ToList())
{
GoAfter = GoAfter,
GoBefore = GoBefore,
};
}
public class SqlPreCommandConcat : SqlPreCommand
{
public Spacing Spacing { get; private set; }
public SqlPreCommand[] Commands { get; private set; }
public override bool GoBefore { get { return this.Commands.First().GoBefore; } set { this.Commands.First().GoBefore = true; } }
public override bool GoAfter { get { return this.Commands.Last().GoAfter; } set { this.Commands.Last().GoAfter = true; } }
internal SqlPreCommandConcat(Spacing spacing, SqlPreCommand[] commands)
{
this.Spacing = spacing;
this.Commands = commands;
}
public override IEnumerable<SqlPreCommandSimple> Leaves()
{
return Commands.SelectMany(c => c.Leaves());
}
static Dictionary<Spacing, string> separators = new Dictionary<Spacing, string>()
{
{Spacing.Simple, "\r\n"},
{Spacing.Double, "\r\n\r\n"},
{Spacing.Triple, "\r\n\r\n\r\n"},
};
protected internal override int NumParameters
{
get { return Commands.Sum(c => c.NumParameters); }
}
protected internal override void PlainSql(StringBuilder sb)
{
string sep = separators[Spacing];
bool borrar = false;
foreach (SqlPreCommand com in Commands)
{
var simple = com as SqlPreCommandSimple;
if (simple != null && simple.GoBefore)
sb.Append("GO\r\n");
com.PlainSql(sb);
if (simple != null && simple.GoAfter)
sb.Append("\r\nGO");
sb.Append(sep);
borrar = true;
}
if (borrar) sb.Remove(sb.Length - sep.Length, sep.Length);
}
public override SqlPreCommand Clone()
{
return new SqlPreCommandConcat(Spacing, Commands.Select(c => c.Clone()).ToArray());
}
public override SqlPreCommand Replace(Regex regex, MatchEvaluator matchEvaluator)
{
return new SqlPreCommandConcat(Spacing, Commands.Select(c => c.Replace(regex, matchEvaluator)).ToArray());
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// App Definition
///<para>SObject Name: AppDefinition</para>
///<para>Custom Object: False</para>
///</summary>
public class SfAppDefinition : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "AppDefinition"; }
}
///<summary>
/// App Definition ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Durable ID
/// <para>Name: DurableId</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "durableId")]
[Updateable(false), Createable(false)]
public string DurableId { get; set; }
///<summary>
/// Label
/// <para>Name: Label</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "label")]
[Updateable(false), Createable(false)]
public string Label { get; set; }
///<summary>
/// Master Label
/// <para>Name: MasterLabel</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "masterLabel")]
[Updateable(false), Createable(false)]
public string MasterLabel { get; set; }
///<summary>
/// Namespace Prefix
/// <para>Name: NamespacePrefix</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "namespacePrefix")]
[Updateable(false), Createable(false)]
public string NamespacePrefix { get; set; }
///<summary>
/// Developer Name
/// <para>Name: DeveloperName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "developerName")]
[Updateable(false), Createable(false)]
public string DeveloperName { get; set; }
///<summary>
/// Logo URL
/// <para>Name: LogoUrl</para>
/// <para>SF Type: url</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "logoUrl")]
[Updateable(false), Createable(false)]
public string LogoUrl { get; set; }
///<summary>
/// Description
/// <para>Name: Description</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "description")]
[Updateable(false), Createable(false)]
public string Description { get; set; }
///<summary>
/// UI Type
/// <para>Name: UiType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "uiType")]
[Updateable(false), Createable(false)]
public string UiType { get; set; }
///<summary>
/// Navigation Type
/// <para>Name: NavType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "navType")]
[Updateable(false), Createable(false)]
public string NavType { get; set; }
///<summary>
/// Utility Bar Name
/// <para>Name: UtilityBar</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "utilityBar")]
[Updateable(false), Createable(false)]
public string UtilityBar { get; set; }
///<summary>
/// Header Color
/// <para>Name: HeaderColor</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "headerColor")]
[Updateable(false), Createable(false)]
public string HeaderColor { get; set; }
///<summary>
/// Is Org Theme Overridden
/// <para>Name: IsOverrideOrgTheme</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isOverrideOrgTheme")]
[Updateable(false), Createable(false)]
public bool? IsOverrideOrgTheme { get; set; }
///<summary>
/// Is Small Form Factor Supported
/// <para>Name: IsSmallFormFactorSupported</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isSmallFormFactorSupported")]
[Updateable(false), Createable(false)]
public bool? IsSmallFormFactorSupported { get; set; }
///<summary>
/// Is Medium Form Factor Supported
/// <para>Name: IsMediumFormFactorSupported</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isMediumFormFactorSupported")]
[Updateable(false), Createable(false)]
public bool? IsMediumFormFactorSupported { get; set; }
///<summary>
/// Is Large Form Factor Supported
/// <para>Name: IsLargeFormFactorSupported</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isLargeFormFactorSupported")]
[Updateable(false), Createable(false)]
public bool? IsLargeFormFactorSupported { get; set; }
///<summary>
/// Is Navigation Menu Personalization Disabled
/// <para>Name: IsNavPersonalizationDisabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isNavPersonalizationDisabled")]
[Updateable(false), Createable(false)]
public bool? IsNavPersonalizationDisabled { get; set; }
///<summary>
/// Is Navigation Menu Automatically Create Temporary Tabs Disabled
/// <para>Name: IsNavAutoTempTabsDisabled</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isNavAutoTempTabsDisabled")]
[Updateable(false), Createable(false)]
public bool? IsNavAutoTempTabsDisabled { get; set; }
}
}
| |
using System;
using System.IO;
using System.Windows.Input;
using System.Windows.Ink;
namespace MS.Internal.Ink.InkSerializedFormat
{
/// <summary>
/// Summary description for MetricEnty.
/// </summary>
internal enum MetricEntryType
{
Optional = 0,
Must,
Never,
Custom,
}
// This is used while comparing two Metric Collections. This defines the relationship between
// two collections when one is superset of the other and can replace the other in the global
// list of collections
internal enum SetType
{
SubSet = 0,
SuperSet,
}
internal struct MetricEntryList
{
public KnownTagCache.KnownTagIndex Tag;
public StylusPointPropertyInfo PropertyMetrics;
public MetricEntryList (KnownTagCache.KnownTagIndex tag, StylusPointPropertyInfo prop)
{
Tag = tag;
PropertyMetrics = prop;
}
}
/// <summary>
/// This class holds the MetricEntries corresponding to a PacketProperty in the form of a link list
/// </summary>
internal class MetricEntry
{
//Maximum buffer size required to store the largest MetricEntry
private static int MAX_METRIC_DATA_BUFF = 24;
private KnownTagCache.KnownTagIndex _tag = 0;
private uint _size = 0;
private MetricEntry _next;
private byte[] _data = new Byte[MAX_METRIC_DATA_BUFF]; // We always allocate the max buffer needed to store the largest possible Metric Information blob
private static MetricEntryList[] _metricEntryOptional;
// helpers for Ink-local property metrics for X/Y coordiantes
public static StylusPointPropertyInfo DefaultXMetric = MetricEntry_Optional[0].PropertyMetrics;
public static StylusPointPropertyInfo DefaultYMetric = MetricEntry_Optional[1].PropertyMetrics;
/// <summary>
/// List of MetricEntry that may or may not appear in the serialized form depending on their default Metrics.
/// </summary>
public static MetricEntryList[] MetricEntry_Optional
{
get
{
if (_metricEntryOptional == null)
{
_metricEntryOptional = new MetricEntryList[] {
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.X, StylusPointPropertyInfoDefaults.X),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.Y, StylusPointPropertyInfoDefaults.Y),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.Z, StylusPointPropertyInfoDefaults.Z),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.NormalPressure, StylusPointPropertyInfoDefaults.NormalPressure),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.TangentPressure, StylusPointPropertyInfoDefaults.TangentPressure),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.ButtonPressure, StylusPointPropertyInfoDefaults.ButtonPressure),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.XTiltOrientation, StylusPointPropertyInfoDefaults.XTiltOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.YTiltOrientation, StylusPointPropertyInfoDefaults.YTiltOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.AzimuthOrientation, StylusPointPropertyInfoDefaults.AzimuthOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.AltitudeOrientation, StylusPointPropertyInfoDefaults.AltitudeOrientation),
new MetricEntryList (KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.TwistOrientation, StylusPointPropertyInfoDefaults.TwistOrientation)};
}
return _metricEntryOptional;
}
}
/// <summary>
/// List of MetricEntry whose Metric Information must appear in the serialized form and always written as they do not have proper default
/// </summary>
static KnownTagCache.KnownTagIndex[] MetricEntry_Must = new KnownTagCache.KnownTagIndex[]
{
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.PitchRotation),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.RollRotation),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.YawRotation),
};
/// <summary>
/// List of MetricEntry whose Metric information will never appear in the Serialized format and always ignored
/// </summary>
static KnownTagCache.KnownTagIndex[] MetricEntry_Never = new KnownTagCache.KnownTagIndex[]
{
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.PacketStatus),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.TimerTick),
(KnownTagCache.KnownTagIndex)((uint)KnownIdCache.KnownGuidBaseIndex + (uint)KnownIdCache.OriginalISFIdIndex.SerialNumber),
};
/// <summary>
/// Default StylusPointPropertyInfo for any property
/// </summary>
static StylusPointPropertyInfo DefaultPropertyMetrics = StylusPointPropertyInfoDefaults.DefaultValue;
/// <summary>
/// Gets or sets the Tag associated with this entry
/// </summary>
public KnownTagCache.KnownTagIndex Tag
{
get
{
return _tag;
}
set
{
_tag = value;
}
}
/// <summary>
/// Gets the size associated with this entry
/// </summary>
public uint Size
{
get
{
return _size;
}
}
/// <summary>
/// Gets or Sets the data associated with this metric entry
/// </summary>
public byte[] Data
{
get
{
return _data;
}
set
{
byte [] data = (byte[])value;
if( data.Length > MAX_METRIC_DATA_BUFF )
_size = (uint)MAX_METRIC_DATA_BUFF;
else
_size = (uint)data.Length;
for( int i = 0; i < (int)_size; i++ )
_data[i] = data[i];
}
}
/// <summary>
/// Compares a metricEntry object with this one and returns true or false
/// </summary>
/// <param name="metricEntry"></param>
/// <returns></returns>
public bool Compare(MetricEntry metricEntry)
{
if( Tag != metricEntry.Tag )
return false;
if( Size != metricEntry.Size )
return false;
for( int i = 0; i < Size; i++ )
{
if( Data[i] != metricEntry.Data[i] )
return false;
}
return true;
}
/// <summary>
/// Gets/Sets the next entry in the list
/// </summary>
public MetricEntry Next
{
get
{
return _next;
}
set
{
_next = value;
}
}
/// <summary>
/// Constructro
/// </summary>
public MetricEntry()
{
}
/// <summary>
/// Adds an entry in the list
/// </summary>
/// <param name="next"></param>
public void Add(MetricEntry next)
{
if( null == _next )
{
_next = next;
return;
}
MetricEntry prev = _next;
while( null != prev.Next )
{
prev = prev.Next;
}
prev.Next = next;
}
/// <summary>
/// Initializes a MetricEntry based on StylusPointPropertyInfo and default StylusPointPropertyInfo for the property
/// </summary>
/// <param name="originalInfo"></param>
/// <param name="defaultInfo"></param>
/// <returns></returns>
public void Initialize(StylusPointPropertyInfo originalInfo, StylusPointPropertyInfo defaultInfo)
{
_size = 0;
using (MemoryStream strm = new MemoryStream(_data))
{
if (!DoubleUtil.AreClose(originalInfo.Resolution, defaultInfo.Resolution))
{
// First min value
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
// Max value
_size += SerializationHelper.SignEncode(strm, originalInfo.Maximum);
// Units
_size += SerializationHelper.Encode(strm, (uint)originalInfo.Unit);
// resolution
using (BinaryWriter bw = new BinaryWriter(strm))
{
bw.Write(originalInfo.Resolution);
_size += 4; // sizeof(float)
}
}
else if (originalInfo.Unit != defaultInfo.Unit)
{
// First min value
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
// Max value
_size += SerializationHelper.SignEncode(strm, originalInfo.Maximum);
// Units
_size += SerializationHelper.Encode(strm, (uint)originalInfo.Unit);
}
else if (originalInfo.Maximum != defaultInfo.Maximum)
{
// First min value
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
// Max value
_size += SerializationHelper.SignEncode(strm, originalInfo.Maximum);
}
else if (originalInfo.Minimum != defaultInfo.Minimum)
{
_size += SerializationHelper.SignEncode(strm, originalInfo.Minimum);
}
}
}
/// <summary>
/// Creates a metric entry based on a PropertyInfo and Tag and returns the Metric Entry Type created
/// </summary>
/// <param name="propertyInfo"></param>
/// <param name="tag"></param>
/// <returns></returns>
public MetricEntryType CreateMetricEntry(StylusPointPropertyInfo propertyInfo, KnownTagCache.KnownTagIndex tag)
{
// First create the default Metric entry based on the property and type of metric entry and then use that to initialize the
// metric entry data.
uint index = 0;
Tag = tag;
MetricEntryType type;
if( IsValidMetricEntry(propertyInfo, Tag, out type, out index) )
{
switch(type)
{
case MetricEntryType.Optional:
{
Initialize(propertyInfo, MetricEntry_Optional[index].PropertyMetrics);
break;
}
case MetricEntryType.Must :
case MetricEntryType.Custom:
Initialize(propertyInfo, DefaultPropertyMetrics);
break;
default:
throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("MetricEntryType was persisted with Never flag which should never happen"));
}
}
return type;
}
/// <summary>
/// This function checks if this packet property results in a valid metric entry. This will be a valid entry if
/// 1. it is a custom property, 2. Does not belong to the global list of gaMetricEntry_Never, 3. Belongs to the
/// global list of gaMetricEntry_Must and 4. Belongs to global list of gaMetricEntry_Optional and at least one of
/// its metric values is different from the corresponding default.
/// </summary>
/// <param name="propertyInfo"></param>
/// <param name="tag"></param>
/// <param name="metricEntryType"></param>
/// <param name="index"></param>
/// <returns></returns>
static bool IsValidMetricEntry(StylusPointPropertyInfo propertyInfo, KnownTagCache.KnownTagIndex tag, out MetricEntryType metricEntryType, out uint index)
{
index = 0;
// If this is a custom property, check if all the Metric values are null or not. If they are then this is not a
// valid metric entry
if (tag >= (KnownTagCache.KnownTagIndex)KnownIdCache.CustomGuidBaseIndex)
{
metricEntryType = MetricEntryType.Custom;
if( Int32.MinValue == propertyInfo.Minimum &&
Int32.MaxValue == propertyInfo.Maximum &&
StylusPointPropertyUnit.None == propertyInfo.Unit &&
DoubleUtil.AreClose(1.0, propertyInfo.Resolution) )
return false;
else
return true;
}
else
{
int ul;
// First find the property in the gaMetricEntry_Never. If it belongs to this list,
// we will never write the metric table for this prop. So return FALSE;
for( ul = 0; ul < MetricEntry_Never.Length ; ul++ )
{
if( MetricEntry_Never[ul] == tag )
{
metricEntryType = MetricEntryType.Never;
return false;
}
}
// Then search the property in the gaMetricEntry_Must list. If it belongs to this list,
// we must always write the metric table for this prop. So return TRUE;
for( ul = 0; ul<MetricEntry_Must.Length; ul++ )
{
if( MetricEntry_Must[ul] == tag )
{
metricEntryType = MetricEntryType.Must;
if( propertyInfo.Minimum == DefaultPropertyMetrics.Minimum &&
propertyInfo.Maximum == DefaultPropertyMetrics.Maximum &&
propertyInfo.Unit == DefaultPropertyMetrics.Unit &&
DoubleUtil.AreClose(propertyInfo.Resolution, DefaultPropertyMetrics.Resolution ))
return false;
else
return true;
}
}
// Now seach it in the gaMetricEntry_Optional list. If it is there, check the metric values
// agianst the default values and if there is any non default value, return TRUE;
for( ul = 0; ul<MetricEntry_Optional.Length; ul++ )
{
if( ((MetricEntryList)MetricEntry_Optional[ul]).Tag == tag )
{
metricEntryType = MetricEntryType.Optional;
if( propertyInfo.Minimum == MetricEntry_Optional[ul].PropertyMetrics.Minimum &&
propertyInfo.Maximum == MetricEntry_Optional[ul].PropertyMetrics.Maximum &&
propertyInfo.Unit == MetricEntry_Optional[ul].PropertyMetrics.Unit &&
DoubleUtil.AreClose(propertyInfo.Resolution, MetricEntry_Optional[ul].PropertyMetrics.Resolution) )
return false;
else
{
index = (uint)ul;
return true;
}
}
}
// it is not found in any of the list. Force to write all metric entries for the property.
metricEntryType = MetricEntryType.Must;
return true;
}
}
}
/// <summary>
/// CMetricBlock owns CMetricEntry which is created based on the Packet Description of the stroke. It also
/// stores the pointer of the next Block. This is not used in the context of a stroke but is used in the
/// context of WispInk. Wispink forms a linked list based on the CMetricBlocks of all the strokes.
/// </summary>
internal class MetricBlock
{
private MetricEntry _Entry;
private uint _Count;
private uint _size;
/// <summary>
/// Constructor
/// </summary>
public MetricBlock()
{
}
/// <summary>
/// Gets the MetricEntry list associated with this instance
/// </summary>
/// <returns></returns>
public MetricEntry GetMetricEntryList()
{
return _Entry;
}
/// <summary>
/// Gets the count of MetricEntry for this instance
/// </summary>
public uint MetricEntryCount
{
get
{
return _Count;
}
}
// Returns the size required to serialize this instance
public uint Size
{
get
{
return (_size + SerializationHelper.VarSize(_size));
}
}
/// <summary>
/// Adds a new metric entry in the existing list of metric entries
/// </summary>
/// <param name="newEntry"></param>
/// <returns></returns>
public void AddMetricEntry(MetricEntry newEntry)
{
if (null == newEntry)
{
throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("MetricEntry cannot be null"));
}
if( null == _Entry )
_Entry = newEntry;
else
_Entry.Add(newEntry); // tack on at the end
_Count ++;
_size += newEntry.Size + SerializationHelper.VarSize(newEntry.Size) + SerializationHelper.VarSize((uint)newEntry.Tag);
}
/// <summary>
/// Adds a new metric entry in the existing list of metric entries
/// </summary>
/// <param name="property"></param>
/// <param name="tag"></param>
/// <returns></returns>
public MetricEntryType AddMetricEntry(StylusPointPropertyInfo property, KnownTagCache.KnownTagIndex tag)
{
// Create a new metric entry based on the packet information passed.
MetricEntry entry = new MetricEntry();
MetricEntryType type = entry.CreateMetricEntry(property, tag);
// Don't add this entry to the global list if size is 0, means default metric values!
if( 0 == entry.Size )
{
return type;
}
MetricEntry start = _Entry;
if( null == start )
{
_Entry = entry;
}
else // tack on data at the end, want to keep x,y at the beginning
{
while(start.Next != null)
{
start = start.Next;
}
start.Next = entry;
}
_Count++;
_size += entry.Size + SerializationHelper.VarSize(entry.Size) + SerializationHelper.VarSize((uint)_Entry.Tag);
return type;
}
/// <summary>
/// This function Packs the data in the buffer provided. The
/// function is being called during the save loop and caller
/// must call GetSize for the block before calling this function.
/// The buffer must be preallocated and buffer size must be at
/// least the size of the block.
/// On return cbBuffer contains the size of the data written.
/// Called only by BuildMetricTable funtion
/// </summary>
/// <param name="strm"></param>
/// <returns></returns>
public uint Pack(Stream strm)
{
// Write the size of the Block at the begining of the buffer.
// But first check the validity of the buffer & its size
uint cbWrite = 0;
// First write the size of the block
cbWrite = SerializationHelper.Encode(strm, _size);
// Now write each entry for the block
MetricEntry entry = _Entry;
while( null != entry )
{
cbWrite += SerializationHelper.Encode(strm, (uint)entry.Tag);
cbWrite += SerializationHelper.Encode(strm, entry.Size);
strm.Write(entry.Data, 0, (int)entry.Size);
cbWrite += entry.Size;
entry = entry.Next;
}
return cbWrite;
}
//
//
/// <summary>
/// This function compares pMetricColl with the current one. If pMetricColl has more entries apart from the one
/// in the current list with which some of its entries are identical, setType is set as SUPERSET.
/// </summary>
/// <param name="metricColl"></param>
/// <param name="setType"></param>
/// <returns></returns>
public bool CompareMetricBlock( MetricBlock metricColl, ref SetType setType)
{
if( null == metricColl )
return false;
// if both have null entry, implies default metric Block for both of them
// and it already exists in the list. Return TRUE
// If only one of the blocks is empty, return FALSE - they cannot be merged
// because the other block may have customized GUID_X or GUID_Y.
if (null == GetMetricEntryList())
return (metricColl.GetMetricEntryList() == null);
if (null == metricColl.GetMetricEntryList())
return false;
// Else compare the entries
bool fTagFound = false;
uint cbLhs = this.MetricEntryCount; // No of entries in this block
uint cbRhs = metricColl.MetricEntryCount; // No of entries in the block to be compared
MetricEntry outside, inside;
if( metricColl.MetricEntryCount <= MetricEntryCount )
{
outside = metricColl.GetMetricEntryList();
inside = GetMetricEntryList();
}
else
{
inside = metricColl.GetMetricEntryList();
outside = GetMetricEntryList();
setType = SetType.SuperSet;
}
// For each entry in metricColl, search for the same in this Block.
// If it is found, continue with the next entry of smaller Block.
while( null != outside )
{
fTagFound = false;
// Always start at the begining of the larger block
MetricEntry temp = inside;
while( null != temp )
{
if( outside.Compare(temp) )
{
fTagFound = true;
break;
}
else
temp = temp.Next;
}
if( !fTagFound )
return false;
// Found the entry; Continue with the next entry in the outside block
outside = outside.Next;
}
return true;
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using WOSI.CallButler.Data.DataProviders;
using System.Diagnostics;
using System.Xml;
using WOSI.CallButler.ManagementInterface;
namespace CallButler.Service.Services
{
internal class LogEntryEventArgs : EventArgs
{
public LogLevel Level;
public string Message;
public bool IsError = false;
public LogEntryEventArgs(LogLevel level, string message, bool isError)
{
this.Level = level;
this.Message = message;
this.IsError = isError;
}
}
class LoggingService
{
private static TextWriter logWriter = null;
private static int logStartDay = -1;
private static EventLog eventLog = null;
public static event EventHandler<LogEntryEventArgs> NewLogEntry;
static LoggingService()
{
try
{
CreateLogStorage(Properties.Settings.Default.LogStorage);
Properties.Settings.Default.SettingChanging += new System.Configuration.SettingChangingEventHandler(Default_SettingChanging);
}
catch { }
}
static void Default_SettingChanging(object sender, System.Configuration.SettingChangingEventArgs e)
{
try
{
if (e.SettingName == "LogStorage")
{
CreateLogStorage((LogStorage)e.NewValue);
}
}
catch { }
}
public static void AddLogEntry(LogLevel level, string message, bool isError)
{
try
{
Trace.WriteLine("Level : " + level + ", " + message);
// Only write log entries if they are at or below the current level
if (Properties.Settings.Default.LogStorage != LogStorage.None && level <= Properties.Settings.Default.LoggingLevel)
{
switch (Properties.Settings.Default.LogStorage)
{
case LogStorage.File:
{
logWriter.Write("[" + DateTime.Now.ToString() + "] ");
if (isError)
logWriter.Write("**ERROR** ");
logWriter.WriteLine(message);
logWriter.Flush();
break;
}
case LogStorage.SystemEventLog:
{
if (isError)
eventLog.WriteEntry(message, EventLogEntryType.Error);
else
eventLog.WriteEntry(message, System.Diagnostics.EventLogEntryType.Information);
break;
}
}
}
// Raise our event
WOSI.Utilities.EventUtils.FireAsyncEvent(NewLogEntry, null, new LogEntryEventArgs(level, message, isError));
}
catch { }
}
private static void CreateLogStorage(LogStorage logStorage)
{
if (logStorage == LogStorage.File)
{
// Create a new log file for every day
if (logStartDay != DateTime.Now.DayOfYear)
{
// Close the existing log file writer if it's open
if (logWriter != null)
{
logWriter.Close();
logWriter = null;
logStartDay = -1;
}
string logDirectory = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.LogDirectory);
if (!Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
string logFilename = logDirectory + "\\" + DateTime.Today.ToString("MM-dd-yyyy") + ".log";
// Check to see if the log already exists
logWriter = (TextWriter)new StreamWriter(logFilename, true, Encoding.UTF8);
logStartDay = DateTime.Now.DayOfYear;
}
}
else if (logStorage == LogStorage.SystemEventLog)
{
if (logWriter != null)
{
logWriter.Close();
logWriter = null;
logStartDay = -1;
}
if (eventLog == null)
{
if (!EventLog.SourceExists(Services.PrivateLabelService.ReplaceProductName("CallButler Log")))
{
EventLog.CreateEventSource(Services.PrivateLabelService.ReplaceProductName("CallButler Log"), Services.PrivateLabelService.ReplaceProductName("CallButler Log"));
}
// Create an EventLog instance and assign its source.
eventLog = new EventLog();
eventLog.Source = Services.PrivateLabelService.ReplaceProductName("CallButler Log");
eventLog.Log = Services.PrivateLabelService.ReplaceProductName("CallButler Log");
}
}
else
{
if (logWriter != null)
{
logWriter.Close();
logWriter = null;
logStartDay = -1;
}
if (eventLog != null)
{
eventLog.Close();
eventLog.Dispose();
eventLog = null;
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Drawables.Cards;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Overlays;
using osuTK;
using APIUser = osu.Game.Online.API.Requests.Responses.APIUser;
namespace osu.Game.Tests.Visual.Beatmaps
{
public class TestSceneBeatmapCard : OsuTestScene
{
/// <summary>
/// All cards on this scene use a common online ID to ensure that map download, preview tracks, etc. can be tested manually with online sources.
/// </summary>
private const int online_id = 163112;
private DummyAPIAccess dummyAPI => (DummyAPIAccess)API;
private APIBeatmapSet[] testCases;
[Resolved]
private BeatmapManager beatmaps { get; set; }
#region Test case generation
[BackgroundDependencyLoader]
private void load()
{
var normal = CreateAPIBeatmapSet(Ruleset.Value);
normal.HasVideo = true;
normal.HasStoryboard = true;
var withStatistics = CreateAPIBeatmapSet(Ruleset.Value);
withStatistics.Title = withStatistics.TitleUnicode = "play favourite stats";
withStatistics.Status = BeatmapOnlineStatus.Approved;
withStatistics.FavouriteCount = 284_239;
withStatistics.PlayCount = 999_001;
withStatistics.Ranked = DateTimeOffset.Now.AddDays(-45);
withStatistics.HypeStatus = new BeatmapSetHypeStatus
{
Current = 34,
Required = 5
};
withStatistics.NominationStatus = new BeatmapSetNominationStatus
{
Current = 1,
Required = 2
};
var undownloadable = getUndownloadableBeatmapSet();
undownloadable.LastUpdated = DateTimeOffset.Now.AddYears(-1);
var someDifficulties = getManyDifficultiesBeatmapSet(11);
someDifficulties.Title = someDifficulties.TitleUnicode = "favourited";
someDifficulties.Title = someDifficulties.TitleUnicode = "some difficulties";
someDifficulties.Status = BeatmapOnlineStatus.Qualified;
someDifficulties.HasFavourited = true;
someDifficulties.FavouriteCount = 1;
someDifficulties.NominationStatus = new BeatmapSetNominationStatus
{
Current = 2,
Required = 2
};
var manyDifficulties = getManyDifficultiesBeatmapSet(100);
manyDifficulties.Status = BeatmapOnlineStatus.Pending;
var explicitMap = CreateAPIBeatmapSet(Ruleset.Value);
explicitMap.Title = someDifficulties.TitleUnicode = "explicit beatmap";
explicitMap.HasExplicitContent = true;
var featuredMap = CreateAPIBeatmapSet(Ruleset.Value);
featuredMap.Title = someDifficulties.TitleUnicode = "featured artist beatmap";
featuredMap.TrackId = 1;
var explicitFeaturedMap = CreateAPIBeatmapSet(Ruleset.Value);
explicitFeaturedMap.Title = someDifficulties.TitleUnicode = "explicit featured artist";
explicitFeaturedMap.HasExplicitContent = true;
explicitFeaturedMap.TrackId = 2;
var longName = CreateAPIBeatmapSet(Ruleset.Value);
longName.Title = longName.TitleUnicode = "this track has an incredibly and implausibly long title";
longName.Artist = longName.ArtistUnicode = "and this artist! who would have thunk it. it's really such a long name.";
longName.HasExplicitContent = true;
longName.TrackId = 444;
testCases = new[]
{
normal,
withStatistics,
undownloadable,
someDifficulties,
manyDifficulties,
explicitMap,
featuredMap,
explicitFeaturedMap,
longName
};
foreach (var testCase in testCases)
testCase.OnlineID = online_id;
}
private APIBeatmapSet getUndownloadableBeatmapSet() => new APIBeatmapSet
{
OnlineID = 123,
Title = "undownloadable beatmap",
Artist = "test",
Source = "more tests",
Author = new APIUser
{
Username = "BanchoBot",
Id = 3,
},
Availability = new BeatmapSetOnlineAvailability
{
DownloadDisabled = true,
},
Preview = @"https://b.ppy.sh/preview/12345.mp3",
PlayCount = 123,
FavouriteCount = 456,
BPM = 111,
HasVideo = true,
HasStoryboard = true,
Covers = new BeatmapSetOnlineCovers(),
Beatmaps = new[]
{
new APIBeatmap
{
RulesetID = Ruleset.Value.OnlineID,
DifficultyName = "Test",
StarRating = 6.42,
}
}
};
private static APIBeatmapSet getManyDifficultiesBeatmapSet(int count)
{
var beatmaps = new List<APIBeatmap>();
for (int i = 0; i < count; i++)
{
beatmaps.Add(new APIBeatmap
{
RulesetID = i % 4,
StarRating = 2 + i % 4 * 2,
});
}
return new APIBeatmapSet
{
OnlineID = 1,
Title = "many difficulties beatmap",
Artist = "test",
Author = new APIUser
{
Username = "BanchoBot",
Id = 3,
},
HasVideo = true,
HasStoryboard = true,
Covers = new BeatmapSetOnlineCovers(),
Beatmaps = beatmaps.ToArray(),
};
}
#endregion
[SetUpSteps]
public void SetUpSteps()
{
AddStep("register request handling", () => dummyAPI.HandleRequest = request =>
{
if (!(request is PostBeatmapFavouriteRequest))
return false;
request.TriggerSuccess();
return true;
});
ensureSoleilyRemoved();
}
private void ensureSoleilyRemoved()
{
AddUntilStep("ensure manager loaded", () => beatmaps != null);
AddStep("remove map", () =>
{
var beatmap = beatmaps.QueryBeatmapSet(b => b.OnlineID == online_id);
if (beatmap != null) beatmaps.Delete(beatmap);
});
}
private Drawable createContent(OverlayColourScheme colourScheme, Func<APIBeatmapSet, Drawable> creationFunc)
{
var colourProvider = new OverlayColourProvider(colourScheme);
return new DependencyProvidingContainer
{
RelativeSizeAxes = Axes.Both,
CachedDependencies = new (Type, object)[]
{
(typeof(OverlayColourProvider), colourProvider)
},
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background5
},
new BasicScrollContainer
{
RelativeSizeAxes = Axes.Both,
Child = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Full,
Padding = new MarginPadding(10),
Spacing = new Vector2(10),
ChildrenEnumerable = testCases.Select(creationFunc)
}
}
}
};
}
private void createTestCase(Func<APIBeatmapSet, Drawable> creationFunc)
{
foreach (var scheme in Enum.GetValues(typeof(OverlayColourScheme)).Cast<OverlayColourScheme>())
AddStep($"set {scheme} scheme", () => Child = createContent(scheme, creationFunc));
}
[Test]
public void TestNormal() => createTestCase(beatmapSetInfo => new BeatmapCard(beatmapSetInfo));
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// ItemDigitalItem
/// </summary>
[DataContract]
public partial class ItemDigitalItem : IEquatable<ItemDigitalItem>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ItemDigitalItem" /> class.
/// </summary>
/// <param name="creationDts">File creation date.</param>
/// <param name="description">Description of the digital item.</param>
/// <param name="fileSize">File size.</param>
/// <param name="mimeType">Mime type associated with the file.</param>
/// <param name="originalFilename">Original filename.</param>
public ItemDigitalItem(string creationDts = default(string), string description = default(string), long? fileSize = default(long?), string mimeType = default(string), string originalFilename = default(string))
{
this.CreationDts = creationDts;
this.Description = description;
this.FileSize = fileSize;
this.MimeType = mimeType;
this.OriginalFilename = originalFilename;
}
/// <summary>
/// File creation date
/// </summary>
/// <value>File creation date</value>
[DataMember(Name="creation_dts", EmitDefaultValue=false)]
public string CreationDts { get; set; }
/// <summary>
/// Description of the digital item
/// </summary>
/// <value>Description of the digital item</value>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// File size
/// </summary>
/// <value>File size</value>
[DataMember(Name="file_size", EmitDefaultValue=false)]
public long? FileSize { get; set; }
/// <summary>
/// Mime type associated with the file
/// </summary>
/// <value>Mime type associated with the file</value>
[DataMember(Name="mime_type", EmitDefaultValue=false)]
public string MimeType { get; set; }
/// <summary>
/// Original filename
/// </summary>
/// <value>Original filename</value>
[DataMember(Name="original_filename", EmitDefaultValue=false)]
public string OriginalFilename { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ItemDigitalItem {\n");
sb.Append(" CreationDts: ").Append(CreationDts).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" FileSize: ").Append(FileSize).Append("\n");
sb.Append(" MimeType: ").Append(MimeType).Append("\n");
sb.Append(" OriginalFilename: ").Append(OriginalFilename).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ItemDigitalItem);
}
/// <summary>
/// Returns true if ItemDigitalItem instances are equal
/// </summary>
/// <param name="input">Instance of ItemDigitalItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ItemDigitalItem input)
{
if (input == null)
return false;
return
(
this.CreationDts == input.CreationDts ||
(this.CreationDts != null &&
this.CreationDts.Equals(input.CreationDts))
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.FileSize == input.FileSize ||
(this.FileSize != null &&
this.FileSize.Equals(input.FileSize))
) &&
(
this.MimeType == input.MimeType ||
(this.MimeType != null &&
this.MimeType.Equals(input.MimeType))
) &&
(
this.OriginalFilename == input.OriginalFilename ||
(this.OriginalFilename != null &&
this.OriginalFilename.Equals(input.OriginalFilename))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.CreationDts != null)
hashCode = hashCode * 59 + this.CreationDts.GetHashCode();
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
if (this.FileSize != null)
hashCode = hashCode * 59 + this.FileSize.GetHashCode();
if (this.MimeType != null)
hashCode = hashCode * 59 + this.MimeType.GetHashCode();
if (this.OriginalFilename != null)
hashCode = hashCode * 59 + this.OriginalFilename.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// Description (string) maxLength
if(this.Description != null && this.Description.Length > 200)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Description, length must be less than 200.", new [] { "Description" });
}
// MimeType (string) maxLength
if(this.MimeType != null && this.MimeType.Length > 100)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for MimeType, length must be less than 100.", new [] { "MimeType" });
}
// OriginalFilename (string) maxLength
if(this.OriginalFilename != null && this.OriginalFilename.Length > 250)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for OriginalFilename, length must be less than 250.", new [] { "OriginalFilename" });
}
yield break;
}
}
}
| |
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Elasticsearch.Client
{
public partial class ElasticsearchClient
{
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulateGet(Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulateGetAsync(Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulateGet(byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulateGetAsync(byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulateGetString(string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulateGetStringAsync(string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulatePost(Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulatePostAsync(Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulatePost(byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulatePostAsync(byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulatePostString(string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulatePostStringAsync(string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = "/_ingest/pipeline/_simulate";
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulateGet(string id, Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulateGetAsync(string id, Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulateGet(string id, byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulateGetAsync(string id, byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulateGetString(string id, string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulateGetStringAsync(string id, string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("GET", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulatePost(string id, Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulatePostAsync(string id, Stream body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulatePost(string id, byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulatePostAsync(string id, byte[] body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage IngestSimulatePostString(string id, string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest.html"/></summary>
///<param name="id">Pipeline ID</param>
///<param name="body">The simulate definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> IngestSimulatePostStringAsync(string id, string body, Func<IngestSimulateParameters, IngestSimulateParameters> options = null)
{
var uri = string.Format("/_ingest/pipeline/{0}/_simulate", id);
if (options != null)
{
uri = options.Invoke(new IngestSimulateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
}
}
| |
//+-----------------------------------------------------------------------
//
// Microsoft Windows Client Platform
// Copyright (C) Microsoft Corporation, 2002
//
// File: FamilyMap.cs
//
// Contents: FontFamilyMap implementation
//
// Spec: http://team/sites/Avalon/Specs/Fonts.htm
//
// Created: 5-25-2003 Worachai Chaoweeraprasit (wchao)
//
//------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security;
using System.Globalization;
using System.ComponentModel;
using System.Windows.Markup;
using MS.Internal.FontFace;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Media
{
/// <summary>
/// Defines which FontFamily to use for a specified set of Unicode code points and
/// a specified language. The FontFamilyMap also specifies a scale factor, allowing the
/// target FontFamily size to be adjusted to better match the size of other fonts
/// used in the composite font family.
/// </summary>
public class FontFamilyMap
{
private Range[] _ranges;
private XmlLanguage _language;
private double _scaleInEm;
private string _targetFamilyName;
internal const int LastUnicodeScalar = 0x10ffff;
private static readonly Range[] _defaultRanges = new Range[] { new Range(0, LastUnicodeScalar) };
internal static readonly FontFamilyMap Default = new FontFamilyMap(
0,
LastUnicodeScalar,
null, // any language
null, // Target
1.0 // Scale
);
/// <summary>
/// Construct a default family map object
/// </summary>
public FontFamilyMap()
: this(
0,
LastUnicodeScalar,
null, // any language
null, // Target
1.0 // Scale
)
{}
/// <summary>
/// Construct a Family map object
/// </summary>
/// <param name="firstChar">first character</param>
/// <param name="lastChar">last character</param>
/// <param name="language">language</param>
/// <param name="targetFamilyName">target family name</param>
/// <param name="scaleInEm">font scale in EM</param>
internal FontFamilyMap(
int firstChar,
int lastChar,
XmlLanguage language,
string targetFamilyName,
double scaleInEm
)
{
if (firstChar == 0 && lastChar == LastUnicodeScalar)
_ranges = _defaultRanges;
else
_ranges = new Range[]{ new Range(firstChar, lastChar) };
_language = language;
_scaleInEm = scaleInEm;
_targetFamilyName = targetFamilyName;
}
/// <summary>
/// String of Unicode ranges as a list of 'FirstCode-LastCode' separated by comma
/// e.g. "0000-00ff,00e0-00ef"
/// </summary>
[DesignerSerializationOptions(DesignerSerializationOptions.SerializeAsAttribute)]
public string Unicode
{
set
{
if (value == null)
throw new ArgumentNullException("value");
_ranges = ParseUnicodeRanges(value);
}
get
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < _ranges.Length; ++i)
{
if (i != 0) sb.Append(',');
sb.AppendFormat(NumberFormatInfo.InvariantInfo, "{0:x4}-{1:x4}", _ranges[i].First, _ranges[i].Last);
}
return sb.ToString();
}
}
/// <summary>
/// Target font family name in which the ranges map to
/// </summary>
[DesignerSerializationOptions(DesignerSerializationOptions.SerializeAsAttribute)]
public string Target
{
get
{
return _targetFamilyName;
}
set
{
_targetFamilyName = value;
}
}
/// <summary>
/// Font scaling factor relative to EM
/// </summary>
public double Scale
{
get
{
return _scaleInEm;
}
set
{
CompositeFontParser.VerifyPositiveMultiplierOfEm("Scale", ref value);
_scaleInEm = value;
}
}
/// <summary>
/// Language to which the FontFamilyMap applies.
/// </summary>
/// <remarks>
/// This property can be a specific language if the FontFamilyMap applies to just that
/// language, a neutral language if it applies to a group of related languages, or
/// the empty string if it applies to any language. The default value is the empty string.
/// </remarks>
public XmlLanguage Language
{
get
{
return _language;
}
set
{
_language = (value == XmlLanguage.Empty) ? null : value;
_language = value;
}
}
/// <summary>
/// Indicates whether the FontFamilyMap is a simple one such as produced
/// by common cases like "Tahoma,Verdana".
/// </summary>
/// <remarks>
/// A simple family map matches all code points for all languages
/// with no scaling. In other words, all properties except Target
/// have default values.
/// </remarks>
internal bool IsSimpleFamilyMap
{
get
{
return _language == null &&
_scaleInEm == 1.0 &&
_ranges == _defaultRanges;
}
}
internal static bool MatchLanguage(XmlLanguage familyMapLanguage, XmlLanguage language)
{
// If there is no family map langue, the family map applies to any language.
if (familyMapLanguage == null)
{
return true;
}
if (language != null)
{
return familyMapLanguage.RangeIncludes(language);
}
return false;
}
internal static bool MatchCulture(XmlLanguage familyMapLanguage, CultureInfo culture)
{
// If there is no family map langue, the family map applies to any language.
if (familyMapLanguage == null)
{
return true;
}
if (culture != null)
{
return familyMapLanguage.RangeIncludes(culture);
}
return false;
}
internal Range[] Ranges
{
get { return _ranges; }
}
private static void ThrowInvalidUnicodeRange()
{
throw new FormatException(SR.Get(SRID.CompositeFontInvalidUnicodeRange));
}
private static Range[] ParseUnicodeRanges(string unicodeRanges)
{
List<Range> ranges = new List<Range>(3);
int index = 0;
while (index < unicodeRanges.Length)
{
int firstNum;
if (!ParseHexNumber(unicodeRanges, ref index, out firstNum))
{
ThrowInvalidUnicodeRange();
}
int lastNum = firstNum;
if (index < unicodeRanges.Length)
{
if (unicodeRanges[index] == '?')
{
do
{
firstNum = firstNum * 16;
lastNum = lastNum * 16 + 0x0F;
index++;
} while (
index < unicodeRanges.Length &&
unicodeRanges[index] == '?' &&
lastNum <= LastUnicodeScalar);
}
else if (unicodeRanges[index] == '-')
{
index++; // pass '-' character
if (!ParseHexNumber(unicodeRanges, ref index, out lastNum))
{
ThrowInvalidUnicodeRange();
}
}
}
if (firstNum > lastNum ||
lastNum > LastUnicodeScalar ||
(index<unicodeRanges.Length && unicodeRanges[index] !=','))
{
ThrowInvalidUnicodeRange();
}
ranges.Add(new Range(firstNum, lastNum));
index++; // ranges seperator comma
}
return ranges.ToArray();
}
/// <summary>
/// helper method to convert a string (written as hex number) into number.
/// </summary>
internal static bool ParseHexNumber(string numString, ref int index, out int number)
{
while (index<numString.Length && numString[index] == ' ')
{
index++;
}
int startIndex = index;
number = 0;
while (index < numString.Length)
{
int n = (int) numString[index];
if (n >= (int)'0' && n <= (int)'9')
{
number = (number * 0x10) + (n - ((int)'0'));
index++;
}
else
{
n |= 0x20; // [A-F] --> [a-f]
if (n >= (int)'a' && n <= (int)'f')
{
number = (number * 0x10) + (n - ((int)'a' - 10));
index++;
}
else
{
break;
}
}
}
bool retValue = index > startIndex;
while (index < numString.Length && numString[index] == ' ')
{
index++;
}
return retValue;
}
internal bool InRange(int ch)
{
for(int i = 0; i < _ranges.Length; i++)
{
Range r = _ranges[i];
if(r.InRange(ch))
return true;
}
return false;
}
/// <summary>
/// Unicode range
/// </summary>
internal class Range
{
private int _first;
private uint _delta;
internal Range(
int first,
int last
)
{
Debug.Assert(first <= last);
_first = first;
_delta = (uint)(last - _first); // used in range testing
}
internal bool InRange(int ch)
{
// clever code from Word meaning: "ch >= _first && ch <= _last",
// this is done with one test and branch.
return (uint)(ch - _first) <= _delta;
}
internal int First
{
get { return _first; }
}
internal int Last
{
get { return _first + (int) _delta; }
}
internal uint Delta
{
get { return _delta; }
}
}
}
}
| |
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Data;
using NServiceKit.Common.Utils;
using NServiceKit.DataAnnotations;
using NServiceKit.Common;
using System.Reflection;
using NServiceKit.OrmLite;
using NServiceKit.OrmLite.Firebird;
namespace TestExpressions
{
/// <summary>An author.</summary>
public class Author{
/// <summary>Initializes a new instance of the TestExpressions.Author class.</summary>
public Author(){}
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
[Alias("AuthorID")]
public Int32 Id { get; set;}
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
[Index(Unique = true)]
[StringLength(40)]
public string Name { get; set;}
/// <summary>Gets or sets the Date/Time of the birthday.</summary>
/// <value>The birthday.</value>
public DateTime Birthday { get; set;}
/// <summary>Gets or sets the Date/Time of the last activity.</summary>
/// <value>The last activity.</value>
public DateTime ? LastActivity { get; set;}
/// <summary>Gets or sets the earnings.</summary>
/// <value>The earnings.</value>
public Decimal? Earnings { get; set;}
/// <summary>Gets or sets a value indicating whether the active.</summary>
/// <value>true if active, false if not.</value>
public bool Active { get; set; }
/// <summary>Gets or sets the city.</summary>
/// <value>The city.</value>
[StringLength(80)]
[Alias("JobCity")]
public string City { get; set;}
/// <summary>Gets or sets the comments.</summary>
/// <value>The comments.</value>
[StringLength(80)]
[Alias("Comment")]
public string Comments { get; set;}
/// <summary>Gets or sets the rate.</summary>
/// <value>The rate.</value>
public Int16 Rate{ get; set;}
}
/// <summary>A main class.</summary>
class MainClass
{
/// <summary>Main entry-point for this application.</summary>
/// <param name="args">Array of command-line argument strings.</param>
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
OrmLiteConfig.DialectProvider = new FirebirdOrmLiteDialectProvider();
SqlExpressionVisitor<Author> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>();
using (IDbConnection db =
"User=SYSDBA;Password=masterkey;Database=employee.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;".OpenDbConnection())
{
db.DropTable<Author>();
db.CreateTable<Author>();
db.DeleteAll<Author>();
List<Author> authors = new List<Author>();
authors.Add(new Author(){Name="Demis Bellot",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 99.9m,Comments="CSharp books", Rate=10, City="London"});
authors.Add(new Author(){Name="Angel Colmenares",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 50.0m,Comments="CSharp books", Rate=5, City="Bogota"});
authors.Add(new Author(){Name="Adam Witco",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 80.0m,Comments="Math Books", Rate=9, City="London"});
authors.Add(new Author(){Name="Claudia Espinel",Birthday= DateTime.Today.AddYears(-23),Active=true,Earnings= 60.0m,Comments="Cooking books", Rate=10, City="Bogota"});
authors.Add(new Author(){Name="Libardo Pajaro",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 80.0m,Comments="CSharp books", Rate=9, City="Bogota"});
authors.Add(new Author(){Name="Jorge Garzon",Birthday= DateTime.Today.AddYears(-28),Active=true,Earnings= 70.0m,Comments="CSharp books", Rate=9, City="Bogota"});
authors.Add(new Author(){Name="Alejandro Isaza",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 70.0m,Comments="Java books", Rate=0, City="Bogota"});
authors.Add(new Author(){Name="Wilmer Agamez",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 30.0m,Comments="Java books", Rate=0, City="Cartagena"});
authors.Add(new Author(){Name="Rodger Contreras",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 90.0m,Comments="CSharp books", Rate=8, City="Cartagena"});
authors.Add(new Author(){Name="Chuck Benedict",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.5m,Comments="CSharp books", Rate=8, City="London"});
authors.Add(new Author(){Name="James Benedict II",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.5m,Comments="Java books", Rate=5, City="Berlin"});
authors.Add(new Author(){Name="Ethan Brown",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 45.0m,Comments="CSharp books", Rate=5, City="Madrid"});
authors.Add(new Author(){Name="Xavi Garzon",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 75.0m,Comments="CSharp books", Rate=9, City="Madrid"});
authors.Add(new Author(){Name="Luis garzon",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.0m,Comments="CSharp books", Rate=10, City="Mexico"});
db.InsertAll(authors);
// lets start !
// select authors born 20 year ago
int year = DateTime.Today.AddYears(-20).Year;
int expected=5;
ev.Where(rn=> rn.Birthday>=new DateTime(year, 1,1) && rn.Birthday<=new DateTime(year, 12,31));
List<Author> result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
result = db.Select<Author>(qry => qry.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31)));
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count);
result = db.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31));
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count);
// select authors from London, Berlin and Madrid : 6
expected=6;
//Sql.In can take params object[]
ev.Where(rn=> Sql.In( rn.City, new object[]{"London", "Madrid", "Berlin"}) );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors from Bogota and Cartagena : 7
expected=7;
//... or Sql.In can take IList<Object>
List<Object> cities= new List<Object>();
cities.Add("Bogota");
cities.Add("Cartagena");
ev.Where(rn => Sql.In(rn.City, cities ));
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name starts with A
expected=3;
ev.Where(rn=> rn.Name.StartsWith("A") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name ends with Garzon o GARZON o garzon ( no case sensitive )
expected=3;
ev.Where(rn=> rn.Name.ToUpper().EndsWith("GARZON") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name ends with garzon ( no case sensitive )
expected=3;
ev.Where(rn=> rn.Name.EndsWith("garzon") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name contains Benedict
expected=2;
ev.Where(rn=> rn.Name.Contains("Benedict") );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors with Earnings <= 50
expected=3;
ev.Where(rn=> rn.Earnings<=50 );
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors with Rate = 10 and city=Mexio
expected=1;
ev.Where(rn=> rn.Rate==10 && rn.City=="Mexico");
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// enough selecting, lets update;
// set Active=false where rate =0
expected=2;
ev.Where(rn=> rn.Rate==0 ).Update(rn=> rn.Active);
var rows = db.UpdateOnly( new Author(){ Active=false }, ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// insert values only in Id, Name, Birthday, Rate and Active fields
expected=4;
ev.Insert(rn =>new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate} );
db.InsertOnly( new Author(){Active=false, Rate=0, Name="Victor Grozny", Birthday=DateTime.Today.AddYears(-18) }, ev);
db.InsertOnly( new Author(){Active=false, Rate=0, Name="Ivan Chorny", Birthday=DateTime.Today.AddYears(-19) }, ev);
ev.Where(rn=> !rn.Active);
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
//update comment for City == null
expected=2;
ev.Where( rn => rn.City==null ).Update(rn=> rn.Comments);
rows=db.UpdateOnly(new Author(){Comments="No comments"}, ev);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// delete where City is null
expected=2;
rows = db.Delete( ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// lets select all records ordered by Rate Descending and Name Ascending
expected=14;
ev.Where().OrderBy(rn=> new{ at=Sql.Desc(rn.Rate), rn.Name }); // clear where condition
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
Console.WriteLine(ev.OrderByExpression);
var author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel", author.Name, "Claudia Espinel"==author.Name);
// select only first 5 rows ....
expected=5;
ev.Limit(5); // note: order is the same as in the last sentence
result=db.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// lets select only Name and City (name will be "UPPERCASED" )
ev.Select(rn=> new { at= Sql.As( rn.Name.ToUpper(), "Name" ), rn.City} );
Console.WriteLine(ev.SelectExpression);
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper()==author.Name);
//paging :
ev.Limit(0,4);// first page, page size=4;
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper()==author.Name);
ev.Limit(4,4);// second page
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon".ToUpper(), author.Name, "Jorge Garzon".ToUpper()==author.Name);
ev.Limit(8,4);// third page
result=db.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Rodger Contreras".ToUpper(), author.Name, "Rodger Contreras".ToUpper()==author.Name);
// select distinct..
ev.Limit(); // clear limit
ev.SelectDistinct(r=>r.City);
expected=6;
result=db.Select(ev);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
Console.ReadLine();
Console.WriteLine("Press Enter to continue");
}
Console.WriteLine ("This is The End my friend!");
}
}
}
| |
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.ClientTesting;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Google.Cloud.PubSub.V1.Snippets
{
[SnippetOutputCollector]
[Collection(nameof(PubsubSnippetFixture))]
public class SubscriberServiceApiClientSnippets
{
private readonly PubsubSnippetFixture _fixture;
public SubscriberServiceApiClientSnippets(PubsubSnippetFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void Overview()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
string subscriptionId = _fixture.CreateSubscriptionId();
// Sample: Overview
// First create a topic.
PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
TopicName topicName = new TopicName(projectId, topicId);
publisher.CreateTopic(topicName);
// Subscribe to the topic.
SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
// Publish a message to the topic.
PubsubMessage message = new PubsubMessage
{
// The data is any arbitrary ByteString. Here, we're using text.
Data = ByteString.CopyFromUtf8("Hello, Pubsub"),
// The attributes provide metadata in a string-to-string dictionary.
Attributes =
{
{ "description", "Simple text message" }
}
};
publisher.Publish(topicName, new[] { message });
// Pull messages from the subscription. This will wait for some time if no new messages have been
// published yet.
PullResponse response = subscriber.Pull(subscriptionName, maxMessages: 10);
foreach (ReceivedMessage received in response.ReceivedMessages)
{
PubsubMessage msg = received.Message;
Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
}
// Acknowledge that we've received the messages. If we don't do this within 60 seconds (as specified
// when we created the subscription) we'll receive the messages again when we next pull.
subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId));
// Tidy up by deleting the subscription and the topic.
subscriber.DeleteSubscription(subscriptionName);
publisher.DeleteTopic(topicName);
// End sample
Assert.Equal(1, response.ReceivedMessages.Count);
Assert.Equal("Hello, Pubsub", response.ReceivedMessages[0].Message.Data.ToStringUtf8());
Assert.Equal("Simple text message", response.ReceivedMessages[0].Message.Attributes["description"]);
}
[Fact]
public async Task SimpleOverview()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
string subscriptionId = _fixture.CreateSubscriptionId();
// Sample: SimpleOverview
// First create a topic.
PublisherServiceApiClient publisherService = await PublisherServiceApiClient.CreateAsync();
TopicName topicName = new TopicName(projectId, topicId);
publisherService.CreateTopic(topicName);
// Subscribe to the topic.
SubscriberServiceApiClient subscriberService = await SubscriberServiceApiClient.CreateAsync();
SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
// Publish a message to the topic using PublisherClient.
PublisherClient publisher = await PublisherClient.CreateAsync(topicName);
// PublishAsync() has various overloads. Here we're using the string overload.
string messageId = await publisher.PublishAsync("Hello, Pubsub");
// PublisherClient instance should be shutdown after use.
// The TimeSpan specifies for how long to attempt to publish locally queued messages.
await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));
// Pull messages from the subscription using SubscriberClient.
SubscriberClient subscriber = await SubscriberClient.CreateAsync(subscriptionName);
List<PubsubMessage> receivedMessages = new List<PubsubMessage>();
// Start the subscriber listening for messages.
await subscriber.StartAsync((msg, cancellationToken) =>
{
receivedMessages.Add(msg);
Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
// Stop this subscriber after one message is received.
// This is non-blocking, and the returned Task may be awaited.
subscriber.StopAsync(TimeSpan.FromSeconds(15));
// Return Reply.Ack to indicate this message has been handled.
return Task.FromResult(SubscriberClient.Reply.Ack);
});
// Tidy up by deleting the subscription and the topic.
subscriberService.DeleteSubscription(subscriptionName);
publisherService.DeleteTopic(topicName);
// End sample
Assert.Equal(1, receivedMessages.Count);
Assert.Equal("Hello, Pubsub", receivedMessages[0].Data.ToStringUtf8());
}
[Fact]
public void ListSubscriptions()
{
string projectId = _fixture.ProjectId;
// Snippet: ListSubscriptions(ProjectName,*,*,*)
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();
ProjectName projectName = new ProjectName(projectId);
foreach (Subscription subscription in client.ListSubscriptions(projectName))
{
Console.WriteLine($"{subscription.Name} subscribed to {subscription.Topic}");
}
// End snippet
}
[Fact]
public async Task ListSubscriptionsAsync()
{
string projectId = _fixture.ProjectId;
// Snippet: ListSubscriptionsAsync(ProjectName,*,*,*)
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();
ProjectName projectName = new ProjectName(projectId);
IAsyncEnumerable<Subscription> subscriptions = client.ListSubscriptionsAsync(projectName);
await subscriptions.ForEachAsync(subscription =>
{
Console.WriteLine($"{subscription.Name} subscribed to {subscription.Topic}");
});
// End snippet
}
[Fact]
public void CreateSubscription()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
string subscriptionId = _fixture.CreateSubscriptionId();
PublisherServiceApiClient.Create().CreateTopic(new TopicName(projectId, topicId));
// Snippet: CreateSubscription(SubscriptionName,*,*,*,*)
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
TopicName topicName = new TopicName(projectId, topicId);
Subscription subscription = client.CreateSubscription(
subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 30);
Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}");
// End snippet
}
[Fact]
public async Task CreateSubscriptionAsync()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
string subscriptionId = _fixture.CreateSubscriptionId();
PublisherServiceApiClient.Create().CreateTopic(new TopicName(projectId, topicId));
// Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CallSettings)
// Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CancellationToken)
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
TopicName topicName = new TopicName(projectId, topicId);
Subscription subscription = await client.CreateSubscriptionAsync(
subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 30);
Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}");
// End snippet
}
[Fact]
public void Pull()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
string subscriptionId = _fixture.CreateSubscriptionId();
PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
TopicName topicName = new TopicName(projectId, topicId);
publisher.CreateTopic(topicName);
PubsubMessage newMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8("Simple text") };
SubscriberServiceApiClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60);
publisher.Publish(topicName, new[] { newMessage });
// Snippet: Pull(SubscriptionName,*,*,*)
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
PullResponse pullResponse = client.Pull(subscriptionName, maxMessages: 100);
foreach (ReceivedMessage message in pullResponse.ReceivedMessages)
{
// Messages can contain any data. We'll assume that we know this
// topic publishes UTF-8-encoded text.
Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
}
// Acknowledge the messages after pulling them, so we don't pull them
// a second time later. The ackDeadlineSeconds parameter specified when
// the subscription is created determines how quickly you need to acknowledge
// successfully-pulled messages before they will be redelivered.
var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);
client.Acknowledge(subscriptionName, ackIds);
// End snippet
}
[Fact]
public async Task PullAsync()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
string subscriptionId = _fixture.CreateSubscriptionId();
PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
TopicName topicName = new TopicName(projectId, topicId);
publisher.CreateTopic(topicName);
PubsubMessage newMessage = new PubsubMessage { Data = ByteString.CopyFromUtf8("Simple text") };
SubscriberServiceApiClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60);
publisher.Publish(topicName, new[] { newMessage });
// Snippet: PullAsync(SubscriptionName,*,*,CallSettings)
// Additional: PullAsync(SubscriptionName,*,*,CancellationToken)
SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
PullResponse pullResponse = await client.PullAsync(subscriptionName, maxMessages: 100);
foreach (ReceivedMessage message in pullResponse.ReceivedMessages)
{
// Messages can contain any data. We'll assume that we know this
// topic publishes UTF-8-encoded text.
Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
}
// Acknowledge the messages after pulling them, so we don't pull them
// a second time later. The ackDeadlineSeconds parameter specified when
// the subscription is created determines how quickly you need to acknowledge
// successfully-pulled messages before they will be redelivered.
var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);
await client.AcknowledgeAsync(subscriptionName, ackIds);
// End snippet
}
[Fact]
public async Task StreamingPull()
{
string projectId = _fixture.ProjectId;
string topicId = _fixture.CreateTopicId();
string subscriptionId = _fixture.CreateSubscriptionId();
// Snippet: StreamingPull(*, *)
PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
TopicName topicName = new TopicName(projectId, topicId);
publisher.CreateTopic(topicName);
SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
subscriber.CreateSubscription(subscriptionName, topicName, null, 60);
// If we don't see all the messages we expect in 10 seconds, we'll cancel the call.
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10));
CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token);
SubscriberServiceApiClient.StreamingPullStream stream = subscriber.StreamingPull(callSettings);
// The first request must include the subscription name and the stream ack deadline
await stream.WriteAsync(new StreamingPullRequest { SubscriptionAsSubscriptionName = subscriptionName, StreamAckDeadlineSeconds = 20 });
Task pullingTask = Task.Run(async () =>
{
int messagesSeen = 0;
AsyncResponseStream<StreamingPullResponse> responseStream = stream.GetResponseStream();
// Handle responses as we see them.
while (await responseStream.MoveNextAsync())
{
StreamingPullResponse response = responseStream.Current;
Console.WriteLine("Received streaming response");
foreach (ReceivedMessage message in response.ReceivedMessages)
{
// Messages can contain any data. We'll assume that we know this
// topic publishes UTF-8-encoded text.
Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
}
// Acknowledge the messages we've just seen
await stream.WriteAsync(new StreamingPullRequest { AckIds = { response.ReceivedMessages.Select(rm => rm.AckId) } });
// If we've seen all the messages we expect, we can complete the streaming call,
// and our next MoveNext call will return false.
messagesSeen += response.ReceivedMessages.Count;
if (messagesSeen == 3)
{
await stream.WriteCompleteAsync();
}
}
});
publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 1") } });
publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 2") } });
publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 3") } });
await pullingTask;
// End snippet
}
[Fact]
public void Emulator()
{
// Sample: Emulator
SubscriberServiceApiClient subscriber = new SubscriberServiceApiClientBuilder
{
EmulatorDetection = EmulatorDetection.EmulatorOrProduction
}.Build();
// End sample
}
}
}
| |
using BDSA2017.Lecture07.Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Moq;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace BDSA2017.Lecture07.Models.Tests
{
public class CharacterRepositoryTests
{
[Fact]
public async Task CreateAsync_given_character_adds_it()
{
var entity = default(Character);
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.Add(It.IsAny<Character>())).Callback<Character>(t => entity = t);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
ActorId = 1,
Name = "Name",
Species = "Species",
Planet = "Planet"
};
await repository.CreateAsync(character);
}
Assert.Equal(1, entity.ActorId);
Assert.Equal("Name", entity.Name);
Assert.Equal("Species", entity.Species);
Assert.Equal("Planet", entity.Planet);
}
[Fact]
public async Task Create_given_character_calls_SaveChangesAsync()
{
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.Add(It.IsAny<Character>()));
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
Name = "Name",
Species = "Species",
};
await repository.CreateAsync(character);
}
context.Verify(c => c.SaveChangesAsync(default(CancellationToken)));
}
[Fact]
public async Task Create_given_character_returns_new_Id()
{
var entity = default(Character);
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.Add(It.IsAny<Character>()))
.Callback<Character>(t => entity = t);
context.Setup(c => c.SaveChangesAsync(default(CancellationToken)))
.Returns(Task.FromResult(0))
.Callback(() => entity.Id = 42);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
Name = "Name",
Species = "Species",
};
var id = await repository.CreateAsync(character);
Assert.Equal(42, id);
}
}
[Fact]
public async Task Find_given_non_existing_id_returns_null()
{
var builder = new DbContextOptionsBuilder<FuturamaContext>()
.UseInMemoryDatabase(nameof(Find_given_non_existing_id_returns_null));
using (var context = new FuturamaContext(builder.Options))
using (var repository = new CharacterRepository(context))
{
var character = await repository.FindAsync(42);
Assert.Null(character);
}
}
[Fact]
public async Task Find_given_existing_id_returns_mapped_CharacterDTO()
{
using (var connection = new SqliteConnection("DataSource=:memory:"))
{
connection.Open();
var builder = new DbContextOptionsBuilder<FuturamaContext>()
.UseSqlite(connection);
var context = new FuturamaContext(builder.Options);
await context.Database.EnsureCreatedAsync();
var entity = new Character
{
Name = "Name",
Species = "Species",
Planet = "Planet",
Actor = new Actor { Name = "Actor" },
Episodes = new[] { new EpisodeCharacter { Episode = new Episode { Title = "Episode 1" } }, new EpisodeCharacter { Episode = new Episode { Title = "Episode 2" } } }
};
context.Characters.Add(entity);
await context.SaveChangesAsync();
var id = entity.Id;
using (var repository = new CharacterRepository(context))
{
var character = await repository.FindAsync(id);
Assert.Equal("Name", character.Name);
Assert.Equal("Species", character.Species);
Assert.Equal("Planet", character.Planet);
Assert.Equal("Actor", character.ActorName);
Assert.Equal(2, character.NumberOfEpisodes);
}
}
}
[Fact]
public async Task Read_returns_mapped_CharacterDTO()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var builder = new DbContextOptionsBuilder<FuturamaContext>()
.UseSqlite(connection);
var context = new FuturamaContext(builder.Options);
context.Database.EnsureCreated();
var entity = new Character
{
Name = "Name",
Species = "Species",
Planet = "Planet",
Actor = new Actor { Name = "Actor" },
Episodes = new[] { new EpisodeCharacter { Episode = new Episode { Title = "Episode 1" } }, new EpisodeCharacter { Episode = new Episode { Title = "Episode 2" } } }
};
context.Characters.Add(entity);
await context.SaveChangesAsync();
var id = entity.Id;
using (var repository = new CharacterRepository(context))
{
var characters = await repository.Read().ToListAsync();
var character = characters.Single();
Assert.Equal("Name", character.Name);
Assert.Equal("Species", character.Species);
Assert.Equal("Planet", character.Planet);
Assert.Equal("Actor", character.ActorName);
Assert.Equal(2, character.NumberOfEpisodes);
}
}
[Fact]
public async Task UpdateAsync_given_existing_character_Updates_properties()
{
var context = new Mock<IFuturamaContext>();
var entity = new Character { Id = 42 };
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(entity);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
Id = 42,
ActorId = 12,
Name = "Name",
Species = "Species",
Planet = "Planet"
};
await repository.UpdateAsync(character);
}
Assert.Equal(12, entity.ActorId);
Assert.Equal("Name", entity.Name);
Assert.Equal("Species", entity.Species);
Assert.Equal("Planet", entity.Planet);
}
[Fact]
public async Task Update_given_existing_character_calls_SaveChangesAsync()
{
var context = new Mock<IFuturamaContext>();
var entity = new Character { Id = 42 };
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(entity);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
await repository.UpdateAsync(character);
}
context.Verify(c => c.SaveChangesAsync(default(CancellationToken)));
}
[Fact]
public async Task Update_given_existing_character_returns_true()
{
var context = new Mock<IFuturamaContext>();
var entity = new Character { Id = 42 };
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(entity);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
var result = await repository.UpdateAsync(character);
Assert.True(result);
}
}
[Fact]
public async Task Update_given_non_existing_character_returns_false()
{
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
var result = await repository.UpdateAsync(character);
Assert.False(result);
}
}
[Fact]
public async Task Update_given_non_existing_character_does_not_SaveChangesAsync()
{
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
await repository.UpdateAsync(character);
}
context.Verify(c => c.SaveChangesAsync(default(CancellationToken)), Times.Never);
}
[Fact]
public async Task Delete_given_existing_character_removes_it()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(character);
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.Characters.Remove(character));
}
[Fact]
public async Task Delete_given_existing_character_calls_SaveChangesAsync()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(character);
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.SaveChangesAsync(default(CancellationToken)));
}
[Fact]
public async Task Delete_given_non_existing_character_does_not_remove_it()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.Characters.Remove(character), Times.Never);
}
[Fact]
public async Task Delete_given_non_existing_character_does_not_call_SaveChangesAsync()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.SaveChangesAsync(default(CancellationToken)), Times.Never);
}
[Fact]
public void Dispose_disposes_context()
{
var mock = new Mock<IFuturamaContext>();
using (var repository = new CharacterRepository(mock.Object))
{
}
mock.Verify(m => m.Dispose());
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using Microsoft.PythonTools.DkmDebugger;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
// This file contains the various event objects that are sent to the debugger from the sample engine via IDebugEventCallback2::Event.
// These are used in EngineCallback.cs.
// The events are how the engine tells the debugger about what is happening in the debuggee process.
// There are three base classe the other events derive from: AD7AsynchronousEvent, AD7StoppingEvent, and AD7SynchronousEvent. These
// each implement the IDebugEvent2.GetAttributes method for the type of event they represent.
// Most events sent the debugger are asynchronous events.
namespace Microsoft.PythonTools.Debugger.DebugEngine {
#region Event base classes
class AD7AsynchronousEvent : IDebugEvent2 {
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes) {
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7StoppingEvent : IDebugEvent2 {
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_ASYNC_STOP;
int IDebugEvent2.GetAttributes(out uint eventAttributes) {
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
class AD7SynchronousEvent : IDebugEvent2 {
public const uint Attributes = (uint)enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS;
int IDebugEvent2.GetAttributes(out uint eventAttributes) {
eventAttributes = Attributes;
return VSConstants.S_OK;
}
}
#endregion
// The debug engine (DE) sends this interface to the session debug manager (SDM) when an instance of the DE is created.
sealed class AD7EngineCreateEvent : AD7AsynchronousEvent, IDebugEngineCreateEvent2 {
public const string IID = "FE5B734C-759D-4E59-AB04-F103343BDD06";
private IDebugEngine2 m_engine;
AD7EngineCreateEvent(AD7Engine engine) {
m_engine = engine;
}
public static void Send(AD7Engine engine) {
AD7EngineCreateEvent eventObject = new AD7EngineCreateEvent(engine);
engine.Send(eventObject, IID, null, null);
}
int IDebugEngineCreateEvent2.GetEngine(out IDebugEngine2 engine) {
engine = m_engine;
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
sealed class AD7ProgramCreateEvent : AD7AsynchronousEvent, IDebugProgramCreateEvent2 {
public const string IID = "96CD11EE-ECD4-4E89-957E-B5D496FC4139";
internal static void Send(AD7Engine engine) {
AD7ProgramCreateEvent eventObject = new AD7ProgramCreateEvent();
engine.Send(eventObject, IID, null);
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is attached to.
sealed class AD7ExpressionEvaluationCompleteEvent : AD7AsynchronousEvent, IDebugExpressionEvaluationCompleteEvent2 {
public const string IID = "C0E13A85-238A-4800-8315-D947C960A843";
private readonly IDebugExpression2 _expression;
private readonly IDebugProperty2 _property;
public AD7ExpressionEvaluationCompleteEvent(IDebugExpression2 expression, IDebugProperty2 property) {
this._expression = expression;
this._property = property;
}
#region IDebugExpressionEvaluationCompleteEvent2 Members
public int GetExpression(out IDebugExpression2 ppExpr) {
ppExpr = _expression;
return VSConstants.S_OK;
}
public int GetResult(out IDebugProperty2 ppResult) {
ppResult = _property;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a module is loaded or unloaded.
sealed class AD7ModuleLoadEvent : AD7AsynchronousEvent, IDebugModuleLoadEvent2 {
public const string IID = "989DB083-0D7C-40D1-A9D9-921BF611A4B2";
readonly AD7Module m_module;
readonly bool m_fLoad;
public AD7ModuleLoadEvent(AD7Module module, bool fLoad) {
m_module = module;
m_fLoad = fLoad;
}
int IDebugModuleLoadEvent2.GetModule(out IDebugModule2 module, ref string debugMessage, ref int fIsLoad) {
module = m_module;
if (m_fLoad) {
debugMessage = null; //String.Concat("Loaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 1;
} else {
debugMessage = null; // String.Concat("Unloaded '", m_module.DebuggedModule.Name, "'");
fIsLoad = 0;
}
return VSConstants.S_OK;
}
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program has run to completion
// or is otherwise destroyed.
sealed class AD7ProgramDestroyEvent : AD7SynchronousEvent, IDebugProgramDestroyEvent2 {
public const string IID = "E147E9E3-6440-4073-A7B7-A65592C714B5";
readonly uint m_exitCode;
public AD7ProgramDestroyEvent(uint exitCode) {
m_exitCode = exitCode;
}
#region IDebugProgramDestroyEvent2 Members
int IDebugProgramDestroyEvent2.GetExitCode(out uint exitCode) {
exitCode = m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread is created in a program being debugged.
sealed class AD7ThreadCreateEvent : AD7AsynchronousEvent, IDebugThreadCreateEvent2 {
public const string IID = "2090CCFC-70C5-491D-A5E8-BAD2DD9EE3EA";
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a thread has exited.
sealed class AD7ThreadDestroyEvent : AD7AsynchronousEvent, IDebugThreadDestroyEvent2 {
public const string IID = "2C3B7532-A36F-4A6E-9072-49BE649B8541";
readonly uint m_exitCode;
public AD7ThreadDestroyEvent(uint exitCode) {
m_exitCode = exitCode;
}
#region IDebugThreadDestroyEvent2 Members
int IDebugThreadDestroyEvent2.GetExitCode(out uint exitCode) {
exitCode = m_exitCode;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent by the debug engine (DE) to the session debug manager (SDM) when a program is loaded, but before any code is executed.
sealed class AD7LoadCompleteEvent : AD7StoppingEvent, IDebugLoadCompleteEvent2 {
public const string IID = "B1844850-1349-45D4-9F12-495212F5EB0B";
public AD7LoadCompleteEvent() {
}
internal static void Send(AD7Engine engine) {
var eventObject = new AD7LoadCompleteEvent();
engine.Send(eventObject, IID, null);
}
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
sealed class AD7AsyncBreakCompleteEvent : AD7StoppingEvent, IDebugBreakEvent2 {
public const string IID = "c7405d1d-e24b-44e0-b707-d8a5a4e1641b";
}
// This interface tells the session debug manager (SDM) that an asynchronous break has been successfully completed.
sealed class AD7SteppingCompleteEvent : AD7StoppingEvent, IDebugStepCompleteEvent2 {
public const string IID = "0F7F24C1-74D9-4EA6-A3EA-7EDB2D81441D";
}
// This interface is sent when a pending breakpoint has been bound in the debuggee.
sealed class AD7BreakpointBoundEvent : AD7AsynchronousEvent, IDebugBreakpointBoundEvent2 {
public const string IID = "1dddb704-cf99-4b8a-b746-dabb01dd13a0";
private AD7PendingBreakpoint m_pendingBreakpoint;
private AD7BoundBreakpoint m_boundBreakpoint;
public AD7BreakpointBoundEvent(AD7PendingBreakpoint pendingBreakpoint, AD7BoundBreakpoint boundBreakpoint) {
m_pendingBreakpoint = pendingBreakpoint;
m_boundBreakpoint = boundBreakpoint;
}
#region IDebugBreakpointBoundEvent2 Members
int IDebugBreakpointBoundEvent2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) {
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[1];
boundBreakpoints[0] = m_boundBreakpoint;
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
return VSConstants.S_OK;
}
int IDebugBreakpointBoundEvent2.GetPendingBreakpoint(out IDebugPendingBreakpoint2 ppPendingBP) {
ppPendingBP = m_pendingBreakpoint;
return VSConstants.S_OK;
}
#endregion
}
// This interface is sent when the entry point has been hit.
sealed class AD7EntryPointEvent : AD7StoppingEvent, IDebugEntryPointEvent2 {
public const string IID = "e8414a3e-1642-48ec-829e-5f4040e16da9";
}
// This Event is sent when a breakpoint is hit in the debuggee
sealed class AD7BreakpointEvent : AD7StoppingEvent, IDebugBreakpointEvent2 {
public const string IID = "501C1E21-C557-48B8-BA30-A1EAB0BC4A74";
IEnumDebugBoundBreakpoints2 m_boundBreakpoints;
public AD7BreakpointEvent(IEnumDebugBoundBreakpoints2 boundBreakpoints) {
m_boundBreakpoints = boundBreakpoints;
}
#region IDebugBreakpointEvent2 Members
int IDebugBreakpointEvent2.EnumBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) {
ppEnum = m_boundBreakpoints;
return VSConstants.S_OK;
}
#endregion
}
sealed class AD7DebugOutputStringEvent2 : AD7AsynchronousEvent, IDebugOutputStringEvent2 {
public const string IID = "569C4BB1-7B82-46FC-AE28-4536DDAD753E";
private readonly string _output;
public AD7DebugOutputStringEvent2(string output) {
_output = output;
}
#region IDebugOutputStringEvent2 Members
public int GetString(out string pbstrString) {
pbstrString = _output;
return VSConstants.S_OK;
}
#endregion
}
sealed class AD7CustomEvent : IDebugEvent2, IDebugCustomEvent110 {
public const string IID = "2615D9BC-1948-4D21-81EE-7A963F20CF59";
private readonly VsComponentMessage _message;
public AD7CustomEvent(VsComponentMessage message) {
_message = message;
}
public AD7CustomEvent(VsPackageMessage message, object param1 = null, object param2 = null)
: this(new VsComponentMessage { MessageCode = (uint)message, Parameter1 = param1, Parameter2 = param2 }) {
}
int IDebugEvent2.GetAttributes(out uint eventAttributes) {
eventAttributes = (uint)(enum_EVENTATTRIBUTES.EVENT_SYNCHRONOUS | enum_EVENTATTRIBUTES.EVENT_IMMEDIATE);
return VSConstants.S_OK;
}
int IDebugCustomEvent110.GetCustomEventInfo(out Guid guidVSService, VsComponentMessage[] message) {
guidVSService = Guids.CustomDebuggerEventHandlerGuid;
message[0] = _message;
return VSConstants.S_OK;
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI81;
using NUnit.Framework;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI81
{
/// <summary>
/// C_GenerateKey and C_GenerateKeyPair tests.
/// </summary>
[TestFixture()]
public class _19_GenerateKeyAndKeyPairTest
{
/// <summary>
/// C_GenerateKey test.
/// </summary>
[Test()]
public void _01_GenerateKeyTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs81);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
ulong slotId = Helpers.GetUsableSlot(pkcs11);
ulong session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare attribute template of new key
CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[4];
template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY);
template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3);
template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN);
// Generate key
ulong keyId = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_GenerateKey(session, ref mechanism, template, Convert.ToUInt64(template.Length), ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < template.Length; i++)
{
UnmanagedMemory.Free(ref template[i].value);
template[i].valueLen = 0;
}
// Do something interesting with generated key
// Destroy object
rv = pkcs11.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_GenerateKeyPair test.
/// </summary>
[Test()]
public void _02_GenerateKeyPairTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs81);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
ulong slotId = Helpers.GetUsableSlot(pkcs11);
ulong session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
byte[] ckaId = new byte[20];
rv = pkcs11.C_GenerateRandom(session, ckaId, Convert.ToUInt64(ckaId.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare attribute template of new public key
CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10];
pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false);
pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true);
pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true);
pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true);
pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true);
pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024);
pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 });
// Prepare attribute template of new private key
CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9];
privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true);
privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true);
privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName);
privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId);
privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true);
privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true);
privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true);
privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true);
privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true);
// Specify key generation mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);
// Generate key pair
ulong pubKeyId = CK.CK_INVALID_HANDLE;
ulong privKeyId = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, Convert.ToUInt64(pubKeyTemplate.Length), privKeyTemplate, Convert.ToUInt64(privKeyTemplate.Length), ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// In LowLevelAPI we have to free unmanaged memory taken by attributes
for (int i = 0; i < privKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref privKeyTemplate[i].value);
privKeyTemplate[i].valueLen = 0;
}
for (int i = 0; i < pubKeyTemplate.Length; i++)
{
UnmanagedMemory.Free(ref pubKeyTemplate[i].value);
pubKeyTemplate[i].valueLen = 0;
}
// Do something interesting with generated key pair
// Destroy object
rv = pkcs11.C_DestroyObject(session, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_DestroyObject(session, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Security.Cryptography.X509Certificates
{
public partial class X509CertificateCollection : ICollection, IEnumerable, IList
{
private readonly List<X509Certificate> _list;
public X509CertificateCollection()
{
_list = new List<X509Certificate>();
}
public X509CertificateCollection(X509Certificate[] value)
: this()
{
AddRange(value);
}
public X509CertificateCollection(X509CertificateCollection value)
: this()
{
AddRange(value);
}
public int Count
{
get { return _list.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return NonGenericList.SyncRoot; }
}
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
object IList.this[int index]
{
get
{
return NonGenericList[index];
}
set
{
if (value == null)
throw new ArgumentNullException("value");
NonGenericList[index] = value;
}
}
public X509Certificate this[int index]
{
get
{
return _list[index];
}
set
{
if (value == null)
throw new ArgumentNullException("value");
_list[index] = value;
}
}
public int Add(X509Certificate value)
{
if (value == null)
throw new ArgumentNullException("value");
int index = _list.Count;
_list.Add(value);
return index;
}
public void AddRange(X509Certificate[] value)
{
if (value == null)
throw new ArgumentNullException("value");
for (int i = 0; i < value.Length; i++)
{
Add(value[i]);
}
}
public void AddRange(X509CertificateCollection value)
{
if (value == null)
throw new ArgumentNullException("value");
for (int i = 0; i < value.Count; i++)
{
Add(value[i]);
}
}
public void Clear()
{
_list.Clear();
}
public bool Contains(X509Certificate value)
{
return _list.Contains(value);
}
public void CopyTo(X509Certificate[] array, int index)
{
_list.CopyTo(array, index);
}
public X509CertificateEnumerator GetEnumerator()
{
return new X509CertificateEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override int GetHashCode()
{
int hashCode = 0;
foreach (X509Certificate cert in _list)
{
hashCode += cert.GetHashCode();
}
return hashCode;
}
public int IndexOf(X509Certificate value)
{
return _list.IndexOf(value);
}
public void Insert(int index, X509Certificate value)
{
if (value == null)
throw new ArgumentNullException("value");
_list.Insert(index, value);
}
public void Remove(X509Certificate value)
{
if (value == null)
throw new ArgumentNullException("value");
bool removed = _list.Remove(value);
// This throws on full framework, so it will also throw here.
if (!removed)
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
}
public void RemoveAt(int index)
{
_list.RemoveAt(index);
}
void ICollection.CopyTo(Array array, int index)
{
NonGenericList.CopyTo(array, index);
}
int IList.Add(object value)
{
if (value == null)
throw new ArgumentNullException("value");
return NonGenericList.Add(value);
}
bool IList.Contains(object value)
{
return NonGenericList.Contains(value);
}
int IList.IndexOf(object value)
{
return NonGenericList.IndexOf(value);
}
void IList.Insert(int index, object value)
{
if (value == null)
throw new ArgumentNullException("value");
NonGenericList.Insert(index, value);
}
void IList.Remove(object value)
{
if (value == null)
throw new ArgumentNullException("value");
// On full framework this method throws when removing an item that
// is not present in the collection, and that behavior needs to be
// preserved.
//
// Since that behavior is not provided by the IList.Remove exposed
// via the NonGenericList property, this method can't just defer
// like the rest of the IList explicit implementations do.
//
// The List<T> which backs this collection will guard against any
// objects which are not X509Certificiate-or-derived, and we've
// already checked whether value itself was null. Therefore we
// know that any (value as X509Certificate) which becomes null
// could not have been in our collection, and when not null we
// have a rich object reference and can defer to the other Remove
// method on this class.
X509Certificate cert = value as X509Certificate;
if (cert == null)
{
throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
Remove(cert);
}
private IList NonGenericList
{
get { return _list; }
}
internal void GetEnumerator(out List<X509Certificate>.Enumerator enumerator)
{
enumerator = _list.GetEnumerator();
}
}
}
| |
using System.Drawing;
using pol = Anycmd.Xacml.Policy;
namespace Anycmd.Xacml.ControlCenter.CustomControls
{
/// <summary>
/// Summary description for PolicySet.
/// </summary>
public class PolicySet : BaseControl
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtDescription;
private System.Windows.Forms.GroupBox grpDefaults;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtPolicySetId;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox cmbPolicyCombiningAlgorithm;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtXPathVersion;
private pol.PolicySetElementReadWrite _policySet;
private System.Windows.Forms.Button btnApply;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Creates a new control that points to the policy set element specified.
/// </summary>
/// <param name="policySet"></param>
public PolicySet( pol.PolicySetElementReadWrite policySet )
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
_policySet = policySet;
LoadingData = true;
cmbPolicyCombiningAlgorithm.Items.Add( Consts.Schema1.PolicyCombiningAlgorithms.DenyOverrides );
cmbPolicyCombiningAlgorithm.Items.Add( Consts.Schema1.PolicyCombiningAlgorithms.PermitOverrides );
cmbPolicyCombiningAlgorithm.Items.Add( Consts.Schema1.PolicyCombiningAlgorithms.FirstApplicable );
cmbPolicyCombiningAlgorithm.Items.Add( Consts.Schema1.PolicyCombiningAlgorithms.OnlyOneApplicable );
txtDescription.Text = _policySet.Description;
txtPolicySetId.Text = _policySet.Id;
txtXPathVersion.Text = _policySet.XPathVersion;
cmbPolicyCombiningAlgorithm.SelectedText = _policySet.PolicyCombiningAlgorithm;
txtDescription.DataBindings.Add( "Text", _policySet, "Description" );
txtPolicySetId.DataBindings.Add( "Text", _policySet, "Id" );
if(_policySet.XPathVersion != null)
txtXPathVersion.DataBindings.Add( "Text", _policySet, "XPathVersion" );
cmbPolicyCombiningAlgorithm.DataBindings.Add( "SelectedValue", policySet, "PolicyCombiningAlgorithm" );
LoadingData = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.txtDescription = new System.Windows.Forms.TextBox();
this.grpDefaults = new System.Windows.Forms.GroupBox();
this.txtXPathVersion = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtPolicySetId = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.cmbPolicyCombiningAlgorithm = new System.Windows.Forms.ComboBox();
this.btnApply = new System.Windows.Forms.Button();
this.grpDefaults.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.TabIndex = 0;
this.label1.Text = "Description:";
//
// txtDescription
//
this.txtDescription.Location = new System.Drawing.Point(80, 8);
this.txtDescription.Multiline = true;
this.txtDescription.Name = "txtDescription";
this.txtDescription.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtDescription.Size = new System.Drawing.Size(504, 64);
this.txtDescription.TabIndex = 1;
this.txtDescription.Text = "";
this.txtDescription.TextChanged += TextBox_TextChanged;
//
// grpDefaults
//
this.grpDefaults.Controls.Add(this.txtXPathVersion);
this.grpDefaults.Controls.Add(this.label4);
this.grpDefaults.Location = new System.Drawing.Point(8, 144);
this.grpDefaults.Name = "grpDefaults";
this.grpDefaults.Size = new System.Drawing.Size(576, 56);
this.grpDefaults.TabIndex = 2;
this.grpDefaults.TabStop = false;
this.grpDefaults.Text = "PolicySet Defaults";
//
// txtXPathVersion
//
this.txtXPathVersion.Location = new System.Drawing.Point(80, 24);
this.txtXPathVersion.Name = "txtXPathVersion";
this.txtXPathVersion.Size = new System.Drawing.Size(488, 20);
this.txtXPathVersion.TabIndex = 1;
this.txtXPathVersion.Text = "";
this.txtXPathVersion.TextChanged += TextBox_TextChanged;
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 24);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(176, 23);
this.label4.TabIndex = 0;
this.label4.Text = "XPath version:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 80);
this.label2.Name = "label2";
this.label2.TabIndex = 0;
this.label2.Text = "PolicySet Id:";
//
// txtPolicySetId
//
this.txtPolicySetId.Location = new System.Drawing.Point(80, 80);
this.txtPolicySetId.Name = "txtPolicySetId";
this.txtPolicySetId.Size = new System.Drawing.Size(504, 20);
this.txtPolicySetId.TabIndex = 1;
this.txtPolicySetId.Text = "";
this.txtPolicySetId.TextChanged += TextBox_TextChanged;
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 112);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(176, 23);
this.label3.TabIndex = 0;
this.label3.Text = "Policy Combining Algorithm:";
//
// cmbPolicyCombiningAlgorithm
//
this.cmbPolicyCombiningAlgorithm.Location = new System.Drawing.Point(152, 112);
this.cmbPolicyCombiningAlgorithm.Name = "cmbPolicyCombiningAlgorithm";
this.cmbPolicyCombiningAlgorithm.Size = new System.Drawing.Size(432, 21);
this.cmbPolicyCombiningAlgorithm.TabIndex = 3;
this.cmbPolicyCombiningAlgorithm.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
//
// button1
//
this.btnApply.Location = new System.Drawing.Point(248, 208);
this.btnApply.Name = "btnApply";
this.btnApply.TabIndex = 4;
this.btnApply.Text = "Apply";
this.btnApply.Click += new System.EventHandler(this.button1_Click);
//
// PolicySet
//
this.Controls.Add(this.btnApply);
this.Controls.Add(this.cmbPolicyCombiningAlgorithm);
this.Controls.Add(this.grpDefaults);
this.Controls.Add(this.txtDescription);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtPolicySetId);
this.Controls.Add(this.label2);
this.Controls.Add(this.label3);
this.Name = "PolicySet";
this.Size = new System.Drawing.Size(592, 232);
this.grpDefaults.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void button1_Click(object sender, System.EventArgs e)
{
_policySet.Description = txtDescription.Text;
_policySet.Id = txtPolicySetId.Text;
_policySet.XPathVersion = txtXPathVersion.Text;
_policySet.PolicyCombiningAlgorithm = cmbPolicyCombiningAlgorithm.SelectedText;
ModifiedValue = false;
txtDescription.BackColor = Color.White;
txtPolicySetId.BackColor = Color.White;
txtXPathVersion.BackColor = Color.White;
cmbPolicyCombiningAlgorithm.BackColor = Color.White;
}
/// <summary>
///
/// </summary>
public pol.PolicySetElementReadWrite PolicySetElement
{
get{ return _policySet; }
}
}
}
| |
// 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 gcdv = Google.Cloud.Dataplex.V1;
using sys = System;
namespace Google.Cloud.Dataplex.V1
{
/// <summary>Resource name for the <c>Entity</c> resource.</summary>
public sealed partial class EntityName : gax::IResourceName, sys::IEquatable<EntityName>
{
/// <summary>The possible contents of <see cref="EntityName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</c>.
/// </summary>
ProjectLocationLakeZoneEntity = 1,
}
private static gax::PathTemplate s_projectLocationLakeZoneEntity = new gax::PathTemplate("projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}");
/// <summary>Creates a <see cref="EntityName"/> 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="EntityName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static EntityName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new EntityName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="EntityName"/> with the pattern
/// <c>projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="EntityName"/> constructed from the provided ids.</returns>
public static EntityName FromProjectLocationLakeZoneEntity(string projectId, string locationId, string lakeId, string zoneId, string entityId) =>
new EntityName(ResourceNameType.ProjectLocationLakeZoneEntity, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), entityId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityId, nameof(entityId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="EntityName"/> with pattern
/// <c>projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="EntityName"/> with pattern
/// <c>projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string lakeId, string zoneId, string entityId) =>
FormatProjectLocationLakeZoneEntity(projectId, locationId, lakeId, zoneId, entityId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="EntityName"/> with pattern
/// <c>projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="EntityName"/> with pattern
/// <c>projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</c>.
/// </returns>
public static string FormatProjectLocationLakeZoneEntity(string projectId, string locationId, string lakeId, string zoneId, string entityId) =>
s_projectLocationLakeZoneEntity.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entityId, nameof(entityId)));
/// <summary>Parses the given resource name string into a new <see cref="EntityName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="entityName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="EntityName"/> if successful.</returns>
public static EntityName Parse(string entityName) => Parse(entityName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="EntityName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="entityName">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="EntityName"/> if successful.</returns>
public static EntityName Parse(string entityName, bool allowUnparsed) =>
TryParse(entityName, allowUnparsed, out EntityName 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="EntityName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="entityName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="EntityName"/>, 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 entityName, out EntityName result) => TryParse(entityName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="EntityName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="entityName">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="EntityName"/>, 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 entityName, bool allowUnparsed, out EntityName result)
{
gax::GaxPreconditions.CheckNotNull(entityName, nameof(entityName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationLakeZoneEntity.TryParseName(entityName, out resourceName))
{
result = FromProjectLocationLakeZoneEntity(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(entityName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private EntityName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string entityId = null, string lakeId = null, string locationId = null, string projectId = null, string zoneId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
EntityId = entityId;
LakeId = lakeId;
LocationId = locationId;
ProjectId = projectId;
ZoneId = zoneId;
}
/// <summary>
/// Constructs a new instance of a <see cref="EntityName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
public EntityName(string projectId, string locationId, string lakeId, string zoneId, string entityId) : this(ResourceNameType.ProjectLocationLakeZoneEntity, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), entityId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityId, nameof(entityId)))
{
}
/// <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>Entity</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string EntityId { get; }
/// <summary>
/// The <c>Lake</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LakeId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Zone</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ZoneId { 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.ProjectLocationLakeZoneEntity: return s_projectLocationLakeZoneEntity.Expand(ProjectId, LocationId, LakeId, ZoneId, EntityId);
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 EntityName);
/// <inheritdoc/>
public bool Equals(EntityName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(EntityName a, EntityName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(EntityName a, EntityName b) => !(a == b);
}
/// <summary>Resource name for the <c>Partition</c> resource.</summary>
public sealed partial class PartitionName : gax::IResourceName, sys::IEquatable<PartitionName>
{
/// <summary>The possible contents of <see cref="PartitionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>
/// projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</c>
/// .
/// </summary>
ProjectLocationLakeZoneEntityPartition = 1,
}
private static gax::PathTemplate s_projectLocationLakeZoneEntityPartition = new gax::PathTemplate("projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}");
/// <summary>Creates a <see cref="PartitionName"/> 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="PartitionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static PartitionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new PartitionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="PartitionName"/> with the pattern
/// <c>
/// projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="partitionId">The <c>Partition</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="PartitionName"/> constructed from the provided ids.</returns>
public static PartitionName FromProjectLocationLakeZoneEntityPartition(string projectId, string locationId, string lakeId, string zoneId, string entityId, string partitionId) =>
new PartitionName(ResourceNameType.ProjectLocationLakeZoneEntityPartition, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), entityId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityId, nameof(entityId)), partitionId: gax::GaxPreconditions.CheckNotNullOrEmpty(partitionId, nameof(partitionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PartitionName"/> with pattern
/// <c>
/// projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="partitionId">The <c>Partition</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PartitionName"/> with pattern
/// <c>
/// projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</c>
/// .
/// </returns>
public static string Format(string projectId, string locationId, string lakeId, string zoneId, string entityId, string partitionId) =>
FormatProjectLocationLakeZoneEntityPartition(projectId, locationId, lakeId, zoneId, entityId, partitionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="PartitionName"/> with pattern
/// <c>
/// projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="partitionId">The <c>Partition</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="PartitionName"/> with pattern
/// <c>
/// projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</c>
/// .
/// </returns>
public static string FormatProjectLocationLakeZoneEntityPartition(string projectId, string locationId, string lakeId, string zoneId, string entityId, string partitionId) =>
s_projectLocationLakeZoneEntityPartition.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entityId, nameof(entityId)), gax::GaxPreconditions.CheckNotNullOrEmpty(partitionId, nameof(partitionId)));
/// <summary>Parses the given resource name string into a new <see cref="PartitionName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="partitionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="PartitionName"/> if successful.</returns>
public static PartitionName Parse(string partitionName) => Parse(partitionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="PartitionName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="partitionName">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="PartitionName"/> if successful.</returns>
public static PartitionName Parse(string partitionName, bool allowUnparsed) =>
TryParse(partitionName, allowUnparsed, out PartitionName 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="PartitionName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="partitionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="PartitionName"/>, 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 partitionName, out PartitionName result) => TryParse(partitionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="PartitionName"/> 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}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="partitionName">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="PartitionName"/>, 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 partitionName, bool allowUnparsed, out PartitionName result)
{
gax::GaxPreconditions.CheckNotNull(partitionName, nameof(partitionName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationLakeZoneEntityPartition.TryParseName(partitionName, out resourceName))
{
result = FromProjectLocationLakeZoneEntityPartition(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4], resourceName[5]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(partitionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private PartitionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string entityId = null, string lakeId = null, string locationId = null, string partitionId = null, string projectId = null, string zoneId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
EntityId = entityId;
LakeId = lakeId;
LocationId = locationId;
PartitionId = partitionId;
ProjectId = projectId;
ZoneId = zoneId;
}
/// <summary>
/// Constructs a new instance of a <see cref="PartitionName"/> class from the component parts of pattern
/// <c>
/// projects/{project}/locations/{location}/lakes/{lake}/zones/{zone}/entities/{entity}/partitions/{partition}</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="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="zoneId">The <c>Zone</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="entityId">The <c>Entity</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="partitionId">The <c>Partition</c> ID. Must not be <c>null</c> or empty.</param>
public PartitionName(string projectId, string locationId, string lakeId, string zoneId, string entityId, string partitionId) : this(ResourceNameType.ProjectLocationLakeZoneEntityPartition, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), zoneId: gax::GaxPreconditions.CheckNotNullOrEmpty(zoneId, nameof(zoneId)), entityId: gax::GaxPreconditions.CheckNotNullOrEmpty(entityId, nameof(entityId)), partitionId: gax::GaxPreconditions.CheckNotNullOrEmpty(partitionId, nameof(partitionId)))
{
}
/// <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>Entity</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string EntityId { get; }
/// <summary>
/// The <c>Lake</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LakeId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Partition</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string PartitionId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Zone</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ZoneId { 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.ProjectLocationLakeZoneEntityPartition: return s_projectLocationLakeZoneEntityPartition.Expand(ProjectId, LocationId, LakeId, ZoneId, EntityId, PartitionId);
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 PartitionName);
/// <inheritdoc/>
public bool Equals(PartitionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(PartitionName a, PartitionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(PartitionName a, PartitionName b) => !(a == b);
}
public partial class CreateEntityRequest
{
/// <summary><see cref="ZoneName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public ZoneName ParentAsZoneName
{
get => string.IsNullOrEmpty(Parent) ? null : ZoneName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteEntityRequest
{
/// <summary>
/// <see cref="gcdv::EntityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::EntityName EntityName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::EntityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListEntitiesRequest
{
/// <summary><see cref="ZoneName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public ZoneName ParentAsZoneName
{
get => string.IsNullOrEmpty(Parent) ? null : ZoneName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetEntityRequest
{
/// <summary>
/// <see cref="gcdv::EntityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::EntityName EntityName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::EntityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListPartitionsRequest
{
/// <summary><see cref="EntityName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public EntityName ParentAsEntityName
{
get => string.IsNullOrEmpty(Parent) ? null : EntityName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class CreatePartitionRequest
{
/// <summary><see cref="EntityName"/>-typed view over the <see cref="Parent"/> resource name property.</summary>
public EntityName ParentAsEntityName
{
get => string.IsNullOrEmpty(Parent) ? null : EntityName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeletePartitionRequest
{
/// <summary>
/// <see cref="gcdv::PartitionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::PartitionName PartitionName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::PartitionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetPartitionRequest
{
/// <summary>
/// <see cref="gcdv::PartitionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::PartitionName PartitionName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::PartitionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Entity
{
/// <summary>
/// <see cref="gcdv::EntityName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::EntityName EntityName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::EntityName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Partition
{
/// <summary>
/// <see cref="gcdv::PartitionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::PartitionName PartitionName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::PartitionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// DependentPhoneNumberResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Api.V2010.Account.Address
{
public class DependentPhoneNumberResource : Resource
{
public sealed class AddressRequirementEnum : StringEnum
{
private AddressRequirementEnum(string value) : base(value) {}
public AddressRequirementEnum() {}
public static implicit operator AddressRequirementEnum(string value)
{
return new AddressRequirementEnum(value);
}
public static readonly AddressRequirementEnum None = new AddressRequirementEnum("none");
public static readonly AddressRequirementEnum Any = new AddressRequirementEnum("any");
public static readonly AddressRequirementEnum Local = new AddressRequirementEnum("local");
public static readonly AddressRequirementEnum Foreign = new AddressRequirementEnum("foreign");
}
public sealed class EmergencyStatusEnum : StringEnum
{
private EmergencyStatusEnum(string value) : base(value) {}
public EmergencyStatusEnum() {}
public static implicit operator EmergencyStatusEnum(string value)
{
return new EmergencyStatusEnum(value);
}
public static readonly EmergencyStatusEnum Active = new EmergencyStatusEnum("Active");
public static readonly EmergencyStatusEnum Inactive = new EmergencyStatusEnum("Inactive");
}
private static Request BuildReadRequest(ReadDependentPhoneNumberOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Addresses/" + options.PathAddressSid + "/DependentPhoneNumbers.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read DependentPhoneNumber parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of DependentPhoneNumber </returns>
public static ResourceSet<DependentPhoneNumberResource> Read(ReadDependentPhoneNumberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<DependentPhoneNumberResource>.FromJson("dependent_phone_numbers", response.Content);
return new ResourceSet<DependentPhoneNumberResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read DependentPhoneNumber parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of DependentPhoneNumber </returns>
public static async System.Threading.Tasks.Task<ResourceSet<DependentPhoneNumberResource>> ReadAsync(ReadDependentPhoneNumberOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<DependentPhoneNumberResource>.FromJson("dependent_phone_numbers", response.Content);
return new ResourceSet<DependentPhoneNumberResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathAddressSid"> The SID of the Address resource associated with the phone number </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of DependentPhoneNumber </returns>
public static ResourceSet<DependentPhoneNumberResource> Read(string pathAddressSid,
string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadDependentPhoneNumberOptions(pathAddressSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathAddressSid"> The SID of the Address resource associated with the phone number </param>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of DependentPhoneNumber </returns>
public static async System.Threading.Tasks.Task<ResourceSet<DependentPhoneNumberResource>> ReadAsync(string pathAddressSid,
string pathAccountSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadDependentPhoneNumberOptions(pathAddressSid){PathAccountSid = pathAccountSid, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<DependentPhoneNumberResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<DependentPhoneNumberResource>.FromJson("dependent_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<DependentPhoneNumberResource> NextPage(Page<DependentPhoneNumberResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<DependentPhoneNumberResource>.FromJson("dependent_phone_numbers", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<DependentPhoneNumberResource> PreviousPage(Page<DependentPhoneNumberResource> page,
ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<DependentPhoneNumberResource>.FromJson("dependent_phone_numbers", response.Content);
}
/// <summary>
/// Converts a JSON string into a DependentPhoneNumberResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> DependentPhoneNumberResource object represented by the provided JSON </returns>
public static DependentPhoneNumberResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<DependentPhoneNumberResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
[JsonProperty("friendly_name")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber FriendlyName { get; private set; }
/// <summary>
/// The phone number in E.164 format
/// </summary>
[JsonProperty("phone_number")]
[JsonConverter(typeof(PhoneNumberConverter))]
public Types.PhoneNumber PhoneNumber { get; private set; }
/// <summary>
/// The URL we call when the phone number receives a call
/// </summary>
[JsonProperty("voice_url")]
public Uri VoiceUrl { get; private set; }
/// <summary>
/// The HTTP method used with the voice_url
/// </summary>
[JsonProperty("voice_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod VoiceMethod { get; private set; }
/// <summary>
/// The HTTP method used with voice_fallback_url
/// </summary>
[JsonProperty("voice_fallback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod VoiceFallbackMethod { get; private set; }
/// <summary>
/// The URL we call when an error occurs in TwiML
/// </summary>
[JsonProperty("voice_fallback_url")]
public Uri VoiceFallbackUrl { get; private set; }
/// <summary>
/// Whether to lookup the caller's name
/// </summary>
[JsonProperty("voice_caller_id_lookup")]
public bool? VoiceCallerIdLookup { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The RFC 2822 date and time in GMT that the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The HTTP method used with sms_fallback_url
/// </summary>
[JsonProperty("sms_fallback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod SmsFallbackMethod { get; private set; }
/// <summary>
/// The URL that we call when an error occurs while retrieving or executing the TwiML
/// </summary>
[JsonProperty("sms_fallback_url")]
public Uri SmsFallbackUrl { get; private set; }
/// <summary>
/// The HTTP method to use with sms_url
/// </summary>
[JsonProperty("sms_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod SmsMethod { get; private set; }
/// <summary>
/// The URL we call when the phone number receives an incoming SMS message
/// </summary>
[JsonProperty("sms_url")]
public Uri SmsUrl { get; private set; }
/// <summary>
/// Whether the phone number requires an Address registered with Twilio
/// </summary>
[JsonProperty("address_requirements")]
[JsonConverter(typeof(StringEnumConverter))]
public DependentPhoneNumberResource.AddressRequirementEnum AddressRequirements { get; private set; }
/// <summary>
/// Indicate if a phone can receive calls or messages
/// </summary>
[JsonProperty("capabilities")]
public object Capabilities { get; private set; }
/// <summary>
/// The URL to send status information to your application
/// </summary>
[JsonProperty("status_callback")]
public Uri StatusCallback { get; private set; }
/// <summary>
/// The HTTP method we use to call status_callback
/// </summary>
[JsonProperty("status_callback_method")]
[JsonConverter(typeof(HttpMethodConverter))]
public Twilio.Http.HttpMethod StatusCallbackMethod { get; private set; }
/// <summary>
/// The API version used to start a new TwiML session
/// </summary>
[JsonProperty("api_version")]
public string ApiVersion { get; private set; }
/// <summary>
/// The SID of the application that handles SMS messages sent to the phone number
/// </summary>
[JsonProperty("sms_application_sid")]
public string SmsApplicationSid { get; private set; }
/// <summary>
/// The SID of the application that handles calls to the phone number
/// </summary>
[JsonProperty("voice_application_sid")]
public string VoiceApplicationSid { get; private set; }
/// <summary>
/// The SID of the Trunk that handles calls to the phone number
/// </summary>
[JsonProperty("trunk_sid")]
public string TrunkSid { get; private set; }
/// <summary>
/// Whether the phone number is enabled for emergency calling
/// </summary>
[JsonProperty("emergency_status")]
[JsonConverter(typeof(StringEnumConverter))]
public DependentPhoneNumberResource.EmergencyStatusEnum EmergencyStatus { get; private set; }
/// <summary>
/// The emergency address configuration to use for emergency calling
/// </summary>
[JsonProperty("emergency_address_sid")]
public string EmergencyAddressSid { get; private set; }
/// <summary>
/// The URI of the resource, relative to `https://api.twilio.com`
/// </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
private DependentPhoneNumberResource()
{
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole, Rob Prouse
//
// 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.Linq;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData;
using NUnit.TestUtilities;
#if ASYNC
using System.Threading.Tasks;
#endif
#if NET40
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.Framework.Assertions
{
[TestFixture]
public class WarningTests
{
[TestCase(nameof(WarningFixture.WarnUnless_Passes_Boolean))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_Boolean))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanWithMessageAndArgs))]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambda))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambda))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambdaWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambdaWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambdaWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambdaWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambdaWithWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambdaWithWithMessageStringFunc))]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraint))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraint))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraintWithMessageAndArgs))]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraint))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraint))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraintWithMessageStringFunc))]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraint))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraint))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessageAndArgs))]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessageStringFunc))]
#endif
#if ASYNC
[TestCase(nameof(WarningFixture.WarnUnless_Passes_Async))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_Async))]
#endif
public void WarningPasses(string methodName)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
Assert.That(result.ResultState, Is.EqualTo(ResultState.Success));
Assert.That(result.AssertCount, Is.EqualTo(1), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(0), "There should be no AssertionResults");
}
[TestCase(nameof(WarningFixture.WarnUnless_Fails_Boolean), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_Boolean), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanWithMessageAndArgs), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanWithMessageAndArgs), "got 5")]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanWithMessageStringFunc), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanWithMessageStringFunc), "got 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambda), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambda), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambdaWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambdaWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambdaWithMessageAndArgs), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambdaWithMessageAndArgs), "got 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambdaWithMessageStringFunc), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambdaWithMessageStringFunc), "got 5")]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraintWithMessageAndArgs), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraintWithMessageAndArgs), "Should be 5")]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraintWithMessageStringFunc), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraintWithMessageStringFunc), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraintWithMessageAndArgs), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraintWithMessageAndArgs), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraintWithMessageStringFunc), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraintWithMessageStringFunc), "Should be 5")]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraintWithMessageAndArgs), "Should be 4")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessageAndArgs), "Should be 4")]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraintWithMessageStringFunc), "Should be 4")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessageStringFunc), "Should be 4")]
#endif
#if ASYNC
[TestCase(nameof(WarningFixture.WarnUnless_Fails_Async), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_Async), null)]
#endif
public void WarningFails(string methodName, string expectedMessage)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
Assert.That(result.ResultState, Is.EqualTo(ResultState.Warning));
Assert.That(result.AssertCount, Is.EqualTo(1), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(1), "Incorrect number of AssertionResults");
Assert.That(result.AssertionResults[0].Status, Is.EqualTo(AssertionStatus.Warning));
Assert.That(result.AssertionResults[0].Message, Is.Not.Null, "Assertion Message should not be null");
Assert.That(result.Message, Is.Not.Null, "Result Message should not be null");
Assert.That(result.Message, Contains.Substring(result.AssertionResults[0].Message), "Result message should contain assertion message");
Assert.That(result.AssertionResults[0].StackTrace, Does.Contain("WarningFixture"));
Assert.That(result.AssertionResults[0].StackTrace.Split(new char[] { '\n' }).Length, Is.LessThan(3));
if (expectedMessage != null)
{
Assert.That(result.Message, Does.Contain(expectedMessage));
Assert.That(result.AssertionResults[0].Message, Does.Contain(expectedMessage));
}
}
[TestCase(typeof(WarningInSetUpPasses), nameof(WarningInSetUpPasses.WarningPassesInTest), 2, 0)]
[TestCase(typeof(WarningInSetUpPasses), nameof(WarningInSetUpPasses.WarningFailsInTest), 2, 1)]
[TestCase(typeof(WarningInSetUpPasses), nameof(WarningInSetUpPasses.ThreeWarningsFailInTest), 4, 3)]
[TestCase(typeof(WarningInSetUpFails), nameof(WarningInSetUpFails.WarningPassesInTest), 2, 1)]
[TestCase(typeof(WarningInSetUpFails), nameof(WarningInSetUpFails.WarningFailsInTest), 2, 2)]
[TestCase(typeof(WarningInSetUpFails), nameof(WarningInSetUpFails.ThreeWarningsFailInTest), 4, 4)]
[TestCase(typeof(WarningInTearDownPasses), nameof(WarningInTearDownPasses.WarningPassesInTest), 2, 0)]
[TestCase(typeof(WarningInTearDownPasses), nameof(WarningInTearDownPasses.WarningFailsInTest), 2, 1)]
[TestCase(typeof(WarningInTearDownPasses), nameof(WarningInTearDownPasses.ThreeWarningsFailInTest), 4, 3)]
[TestCase(typeof(WarningInTearDownFails), nameof(WarningInTearDownFails.WarningPassesInTest), 2, 1)]
[TestCase(typeof(WarningInTearDownFails), nameof(WarningInTearDownFails.WarningFailsInTest), 2, 2)]
[TestCase(typeof(WarningInTearDownFails), nameof(WarningInTearDownFails.ThreeWarningsFailInTest), 4, 4)]
public void WarningUsedInSetUpOrTearDown(Type fixtureType, string methodName, int expectedAsserts, int expectedWarnings)
{
var result = TestBuilder.RunTestCase(fixtureType, methodName);
Assert.That(result.ResultState, Is.EqualTo(expectedWarnings == 0 ? ResultState.Success : ResultState.Warning));
Assert.That(result.AssertCount, Is.EqualTo(expectedAsserts), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(expectedWarnings), $"There should be {expectedWarnings} AssertionResults");
}
#if !NET20
[Test]
public void PassingAssertion_DoesNotCallExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
using (new TestExecutionContext.IsolatedContext())
Warn.Unless(0 + 1 == 1, getExceptionMessage);
// Assert
Assert.That(!funcWasCalled, "The getExceptionMessage function was called when it should not have been.");
}
[Test]
public void FailingWarning_CallsExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
using (new TestExecutionContext.IsolatedContext())
Warn.Unless(1 + 1 == 1, getExceptionMessage);
// Assert
Assert.That(funcWasCalled, "The getExceptionMessage function was not called when it should have been.");
}
#endif
#if ASYNC
[Test]
public void WarnUnless_Async_Error()
{
#if !NET40
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Warn.Unless(async () => await ThrowExceptionGenericTask(), Is.EqualTo(1)));
#if !NET40
Assert.That(exception.StackTrace, Does.Contain("ThrowExceptionGenericTask"));
#endif
}
[Test]
public void WarnIf_Async_Error()
{
#if !NET40
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Warn.If(async () => await ThrowExceptionGenericTask(), Is.Not.EqualTo(1)));
#if !NET40
Assert.That(exception.StackTrace, Does.Contain("ThrowExceptionGenericTask"));
#endif
}
private static Task<int> One()
{
return Task.Run(() => 1);
}
private static async Task<int> ThrowExceptionGenericTask()
{
await One();
throw new InvalidOperationException();
}
#endif
// We decided to trim ExecutionContext and below because ten lines per warning adds up
// and makes it hard to read build logs.
// See https://github.com/nunit/nunit/pull/2431#issuecomment-328404432.
[TestCase(nameof(WarningFixture.WarningSynchronous), 1)]
[TestCase(nameof(WarningFixture.WarningInThreadStart), 2)]
#if !PLATFORM_DETECTION
[TestCase(nameof(WarningFixture.WarningInBeginInvoke), 4)]
#else
[TestCase(nameof(WarningFixture.WarningInBeginInvoke), 4, ExcludePlatform = "mono", Reason = "Warning has no effect inside BeginInvoke on Mono")]
#endif
[TestCase(nameof(WarningFixture.WarningInThreadPoolQueueUserWorkItem), 2)]
#if ASYNC
[TestCase(nameof(WarningFixture.WarningInTaskRun), 4)]
[TestCase(nameof(WarningFixture.WarningAfterAwaitTaskDelay), 5)]
#endif
public static void StackTracesAreFiltered(string methodName, int maxLineCount)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
if (result.FailCount != 0 && result.Message.StartsWith(typeof(PlatformNotSupportedException).FullName))
{
return; // BeginInvoke causes PlatformNotSupportedException on .NET Core
}
if (result.AssertionResults.Count != 1 || result.AssertionResults[0].Status != AssertionStatus.Warning)
{
Assert.Fail("Expected a single warning assertion. Message: " + result.Message);
}
var warningStackTrace = result.AssertionResults[0].StackTrace;
var lines = warningStackTrace.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (maxLineCount < lines.Length)
{
Assert.Fail(
$"Expected the number of lines to be no more than {maxLineCount}, but it was {lines.Length}:" + Environment.NewLine
+ Environment.NewLine
+ string.Concat(lines.Select((line, i) => $" {i + 1}. {line.Trim()}" + Environment.NewLine).ToArray())
+ "(end)");
// ^ Most of that is to differentiate it from the current method's stack trace
// reported directly underneath at the same level of indentation.
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.Runtime.Loader
{
public abstract class AssemblyLoadContext
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool OverrideDefaultAssemblyLoadContextForCurrentDomain(IntPtr ptrNativeAssemblyLoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromAssemblyName(IntPtr ptrNativeAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
protected AssemblyLoadContext()
{
// Initialize the ALC representing non-TPA LoadContext
InitializeLoadContext(false);
}
internal AssemblyLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the ALC representing TPA LoadContext
InitializeLoadContext(fRepresentsTPALoadContext);
}
void InitializeLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
GCHandle gchALC = GCHandle.Alloc(this);
IntPtr ptrALC = GCHandle.ToIntPtr(gchALC);
m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC, fRepresentsTPALoadContext);
// Initialize event handlers to be null by default
Resolving = null;
Unloading = null;
// Since unloading an AssemblyLoadContext is not yet implemented, this is a temporary solution to raise the
// Unloading event on process exit. Register for the current AppDomain's ProcessExit event, and the handler will in
// turn raise the Unloading event.
AppContext.Unloading += OnAppContextUnloading;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies);
public static Assembly[] GetLoadedAssemblies()
{
Assembly[] assemblies = null;
GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies));
return assemblies;
}
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
public Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
if (PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
}
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException(nameof(nativeImagePath));
}
if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath));
}
if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
}
// Basic validation has succeeded - lets try to load the NI image.
// Ask LoadFile to load the specified assembly in the DefaultContext
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
int iAssemblyStreamLength = (int)assembly.Length;
int iSymbolLength = 0;
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[] arrSymbols = null;
if (assemblySymbols != null)
{
iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
RuntimeAssembly loadedAssembly = null;
unsafe
{
fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
{
LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
}
return loadedAssembly;
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected abstract Assembly Load(AssemblyName assemblyName);
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.ResolveUsingLoad(assemblyName);
}
// This method is invoked by the VM to resolve an assembly reference using the Resolving event
// after trying assembly resolution via Load override and TPA load context without success.
private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
// Invoke the AssemblyResolve event callbacks if wired up
return context.ResolveUsingEvent(assemblyName);
}
private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName)
{
Assembly resolvedAssembly = null;
Func<AssemblyLoadContext, AssemblyName, Assembly> assemblyResolveHandler = Resolving;
if (assemblyResolveHandler != null)
{
// Loop through the event subscribers and return the first non-null Assembly instance
Delegate [] arrSubscribers = assemblyResolveHandler.GetInvocationList();
for(int i = 0; i < arrSubscribers.Length; i++)
{
resolvedAssembly = ((Func<AssemblyLoadContext, AssemblyName, Assembly>)arrSubscribers[i])(this, assemblyName);
if (resolvedAssembly != null)
{
break;
}
}
}
return resolvedAssembly;
}
private Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string requestedSimpleName)
{
// Get the name of the loaded assembly
string loadedSimpleName = null;
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly;
if (rtLoadedAssembly != null)
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
// The simple names should match at the very least
if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)))
throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch"));
return assembly;
}
private Assembly ResolveUsingLoad(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
Assembly assembly = Load(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
return assembly;
}
private Assembly ResolveUsingEvent(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
// Invoke the AssemblyResolve event callbacks if wired up
Assembly assembly = GetFirstResolvedAssembly(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
// Since attempt to resolve the assembly via Resolving event is the last option,
// throw an exception if we do not find any assembly.
if (assembly == null)
{
throw new FileNotFoundException(Environment.GetResourceString("IO.FileLoad"), simpleName);
}
return assembly;
}
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
Assembly loadedAssembly = Assembly.Load(assemblyName, m_pNativeAssemblyLoadContext);
return loadedAssembly;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InternalLoadUnmanagedDllFromPath(string unmanagedDllPath);
// This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a
// platform-independent way. The DLL is loaded with default load flags.
protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath)
{
if (unmanagedDllPath == null)
{
throw new ArgumentNullException(nameof(unmanagedDllPath));
}
if (unmanagedDllPath.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(unmanagedDllPath));
}
if (PathInternal.IsPartiallyQualified(unmanagedDllPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(unmanagedDllPath));
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName)
{
//defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadUnmanagedDll(unmanagedDllName);
}
public static AssemblyLoadContext Default
{
get
{
if (s_DefaultAssemblyLoadContext == null)
{
// Try to initialize the default assembly load context with apppath one if we are allowed to
if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain())
{
// Synchronize access to initializing Default ALC
lock(s_initLock)
{
if (s_DefaultAssemblyLoadContext == null)
{
s_DefaultAssemblyLoadContext = new AppPathAssemblyLoadContext();
}
}
}
}
return s_DefaultAssemblyLoadContext;
}
}
// This will be used to set the AssemblyLoadContext for DefaultContext, for the AppDomain,
// by a host. Once set, the runtime will invoke the LoadFromAssemblyName method against it to perform
// assembly loads for the DefaultContext.
//
// This method will throw if the Default AssemblyLoadContext is already set or the Binding model is already locked.
public static void InitializeDefaultContext(AssemblyLoadContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Try to override the default assembly load context
if (!AssemblyLoadContext.OverrideDefaultAssemblyLoadContextForCurrentDomain(context.m_pNativeAssemblyLoadContext))
{
throw new InvalidOperationException(Environment.GetResourceString("AppDomain_BindingModelIsLocked"));
}
// Update the managed side as well.
s_DefaultAssemblyLoadContext = context;
}
// This call opens and closes the file, but does not add the
// assembly to the domain.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern AssemblyName nGetFileInformation(String s);
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
string fullPath = Path.GetFullPath(assemblyPath);
return nGetFileInformation(fullPath);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly);
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext GetLoadContext(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
AssemblyLoadContext loadContextForAssembly = null;
RuntimeAssembly rtAsm = assembly as RuntimeAssembly;
// We only support looking up load context for runtime assemblies.
if (rtAsm != null)
{
IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly(rtAsm);
if (ptrAssemblyLoadContext == IntPtr.Zero)
{
// If the load context is returned null, then the assembly was bound using the TPA binder
// and we shall return reference to the active "Default" binder - which could be the TPA binder
// or an overridden CLRPrivBinderAssemblyLoadContext instance.
loadContextForAssembly = AssemblyLoadContext.Default;
}
else
{
loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target);
}
}
return loadContextForAssembly;
}
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
InternalSetProfileRoot(directoryPath);
}
// Start profile optimization for the specified profile name.
public void StartProfileOptimization(string profile)
{
InternalStartProfile(profile, m_pNativeAssemblyLoadContext);
}
private void OnAppContextUnloading(object sender, EventArgs e)
{
var unloading = Unloading;
if (unloading != null)
{
unloading(this);
}
}
public event Func<AssemblyLoadContext, AssemblyName, Assembly> Resolving;
public event Action<AssemblyLoadContext> Unloading;
// Contains the reference to VM's representation of the AssemblyLoadContext
private IntPtr m_pNativeAssemblyLoadContext;
// Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is
// specified by the host. By having the field as a static, we are
// making it an AppDomain-wide field.
private static volatile AssemblyLoadContext s_DefaultAssemblyLoadContext;
// Synchronization primitive for controlling initialization of Default load context
private static readonly object s_initLock = new Object();
// Occurs when an Assembly is loaded
public static event AssemblyLoadEventHandler AssemblyLoad
{
add { AppDomain.CurrentDomain.AssemblyLoad += value; }
remove { AppDomain.CurrentDomain.AssemblyLoad -= value; }
}
// Occurs when resolution of type fails
public static event ResolveEventHandler TypeResolve
{
add { AppDomain.CurrentDomain.TypeResolve += value; }
remove { AppDomain.CurrentDomain.TypeResolve -= value; }
}
// Occurs when resolution of resource fails
public static event ResolveEventHandler ResourceResolve
{
add { AppDomain.CurrentDomain.ResourceResolve += value; }
remove { AppDomain.CurrentDomain.ResourceResolve -= value; }
}
// Occurs when resolution of assembly fails
// This event is fired after resolve events of AssemblyLoadContext fails
public static event ResolveEventHandler AssemblyResolve
{
add { AppDomain.CurrentDomain.AssemblyResolve += value; }
remove { AppDomain.CurrentDomain.AssemblyResolve -= value; }
}
}
class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(true)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
// We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here.
// Returning null will result in the AssemblyResolve event subscribers to be invoked to help resolve the assembly.
return null;
}
}
internal class IndividualAssemblyLoadContext : AssemblyLoadContext
{
internal IndividualAssemblyLoadContext() : base(false)
{
}
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog.Targets
{
using System.ComponentModel;
using System.Messaging;
using System.Text;
using Config;
using Layouts;
/// <summary>
/// Writes log message to the specified message queue handled by MSMQ.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/MessageQueue-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/MSMQ/Simple/NLog.config" />
/// <p>
/// You can use a single target to write to multiple queues (similar to writing to multiple files with the File target).
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/MSMQ/Multiple/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule.
/// More configuration options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/MSMQ/Simple/Example.cs" />
/// </example>
[Target("MSMQ")]
public class MessageQueueTarget : TargetWithLayout
{
private MessagePriority messagePriority = MessagePriority.Normal;
/// <summary>
/// Initializes a new instance of the <see cref="MessageQueueTarget"/> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public MessageQueueTarget()
{
MessageQueueProxy = new MessageQueueProxy();
Label = "NLog";
Encoding = Encoding.UTF8;
CheckIfQueueExists = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="MessageQueueTarget"/> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public MessageQueueTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the name of the queue to write to.
/// </summary>
/// <remarks>
/// To write to a private queue on a local machine use <c>.\private$\QueueName</c>.
/// For other available queue names, consult MSMQ documentation.
/// </remarks>
/// <docgen category='Queue Options' order='10' />
[RequiredParameter]
public Layout Queue { get; set; }
/// <summary>
/// Gets or sets the label to associate with each message.
/// </summary>
/// <remarks>
/// By default no label is associated.
/// </remarks>
/// <docgen category='Queue Options' order='10' />
[DefaultValue("NLog")]
public Layout Label { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to create the queue if it doesn't exists.
/// </summary>
/// <docgen category='Queue Options' order='10' />
[DefaultValue(false)]
public bool CreateQueueIfNotExists { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use recoverable messages (with guaranteed delivery).
/// </summary>
/// <docgen category='Queue Options' order='10' />
[DefaultValue(false)]
public bool Recoverable { get; set; }
/// <summary>
/// Gets or sets the encoding to be used when writing text to the queue.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use the XML format when serializing message.
/// This will also disable creating queues.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue(false)]
public bool UseXmlEncoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to check if a queue exists before writing to it.
/// </summary>
/// <docgen category='Layout Options' order='11' />
[DefaultValue(true)]
public bool CheckIfQueueExists { get; set; }
internal MessageQueueProxy MessageQueueProxy { get; set; }
/// <summary>
/// Writes the specified logging event to a queue specified in the Queue
/// parameter.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
if (Queue == null)
{
return;
}
var queue = Queue.Render(logEvent);
if (CheckIfQueueExists)
{
if (!IsFormatNameSyntax(queue) && !MessageQueueProxy.Exists(queue))
{
if (CreateQueueIfNotExists)
{
MessageQueueProxy.Create(queue);
}
else
{
return;
}
}
}
var msg = PrepareMessage(logEvent);
MessageQueueProxy.Send(queue, msg);
}
/// <summary>
/// Prepares a message to be sent to the message queue.
/// </summary>
/// <param name="logEvent">The log event to be used when calculating label and text to be written.</param>
/// <returns>The message to be sent.</returns>
/// <remarks>
/// You may override this method in inheriting classes
/// to provide services like encryption or message
/// authentication.
/// </remarks>
protected virtual Message PrepareMessage(LogEventInfo logEvent)
{
var msg = new Message();
if (Label != null)
{
msg.Label = Label.Render(logEvent);
}
msg.Recoverable = Recoverable;
msg.Priority = messagePriority;
if (UseXmlEncoding)
{
msg.Body = Layout.Render(logEvent);
}
else
{
var dataBytes = Encoding.GetBytes(Layout.Render(logEvent));
msg.BodyStream.Write(dataBytes, 0, dataBytes.Length);
}
return msg;
}
private static bool IsFormatNameSyntax(string queue)
{
return queue.ToLowerInvariant().IndexOf('=') != -1;
}
}
internal class MessageQueueProxy
{
public virtual bool Exists(string queue)
{
return MessageQueue.Exists(queue);
}
public virtual void Create(string queue)
{
MessageQueue.Create(queue);
}
public virtual void Send(string queue, Message message)
{
if (message == null)
{
return;
}
using (var mq = new MessageQueue(queue))
{
mq.Send(message);
}
}
}
}
#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.
/******************************************************************************
* 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 SubtractByte()
{
var test = new SimpleBinaryOpTest__SubtractByte();
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__SubtractByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[ElementCount];
private static Byte[] _data2 = new Byte[ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte> _dataTable;
static SimpleBinaryOpTest__SubtractByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__SubtractByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte>(_data1, _data2, new Byte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Subtract(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Subtract(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_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.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__SubtractByte();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Subtract(_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<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, 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 = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if ((byte)(left[0] - right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((byte)(left[i] - right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Byte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace ToolGood.Algorithm.LitJson
{
internal class Lexer
{
#region Fields
private delegate bool StateHandler(FsmContext ctx);
private static readonly int[] fsm_return_table;
private static readonly StateHandler[] fsm_handler_table;
private bool allow_comments;
private bool allow_single_quoted_strings;
private bool end_of_input;
private readonly FsmContext fsm_context;
private int input_buffer;
private int input_char;
private readonly TextReader reader;
private int state;
private readonly StringBuilder string_buffer;
private string string_value;
private int token;
private int unichar;
#endregion
#region Properties
public bool EndOfInput { get { return end_of_input; } }
public int Token { get { return token; } }
public string StringValue { get { return string_value; } }
#endregion
#region Constructors
static Lexer()
{
PopulateFsmTables(out fsm_handler_table, out fsm_return_table);
}
public Lexer(TextReader reader)
{
allow_comments = true;
allow_single_quoted_strings = true;
input_buffer = 0;
string_buffer = new StringBuilder(128);
state = 1;
end_of_input = false;
this.reader = reader;
fsm_context = new FsmContext();
fsm_context.L = this;
}
#endregion
#region Static Methods
private static int HexValue(int digit)
{
switch (digit) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return digit - '0';
}
}
private static void PopulateFsmTables(out StateHandler[] fsm_handler_table, out int[] fsm_return_table)
{
// See section A.1. of the manual for details of the finite state machine.
fsm_handler_table = new StateHandler[28] {
State1,
State2,
State3,
State4,
State5,
State6,
State7,
State8,
State9,
State10,
State11,
State12,
State13,
State14,
State15,
State16,
State17,
State18,
State19,
State20,
State21,
State22,
State23,
State24,
State25,
State26,
State27,
State28
};
fsm_return_table = new int[28] {
(int) ParserToken.Char,
0,
(int) ParserToken.Number,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
(int) ParserToken.Number,
0,
0,
(int) ParserToken.True,
0,
0,
0,
(int) ParserToken.False,
0,
0,
(int) ParserToken.Null,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
(int) ParserToken.CharSeq,
(int) ParserToken.Char,
0,
0,
0,
0
};
}
private static char ProcessEscChar(int esc_char)
{
switch (esc_char) {
case '"':
case '\'':
case '\\':
case '/': return Convert.ToChar(esc_char);
case 'n': return '\n';
case 't': return '\t';
case 'r': return '\r';
case 'b': return '\b';
case 'f': return '\f';
default: return '?';
}
}
private static bool State1(FsmContext ctx)
{
while (ctx.L.GetChar()) {
if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r')
continue;
if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '"':
ctx.NextState = 19;
ctx.Return = true;
return true;
case ',':
case ':':
case '[':
case ']':
case '{':
case '}':
ctx.NextState = 1;
ctx.Return = true;
return true;
case '-':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 2;
return true;
case '0':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 4;
return true;
case 'f':
ctx.NextState = 12;
return true;
case 'n':
ctx.NextState = 16;
return true;
case 't':
ctx.NextState = 9;
return true;
case '\'':
if (!ctx.L.allow_single_quoted_strings) return false;
ctx.L.input_char = '"';
ctx.NextState = 23;
ctx.Return = true;
return true;
case '/':
if (!ctx.L.allow_comments) return false;
ctx.NextState = 25;
return true;
default:
return false;
}
}
return true;
}
private static bool State2(FsmContext ctx)
{
ctx.L.GetChar();
if (ctx.L.input_char >= '1' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 3;
return true;
}
switch (ctx.L.input_char) {
case '0':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 4;
return true;
default:
return false;
}
}
private static bool State3(FsmContext ctx)
{
while (ctx.L.GetChar()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append((char)ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' ||
ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State4(FsmContext ctx)
{
ctx.L.GetChar();
if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 1;
return true;
case '.':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 5;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
private static bool State5(FsmContext ctx)
{
ctx.L.GetChar();
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 6;
return true;
}
return false;
}
private static bool State6(FsmContext ctx)
{
while (ctx.L.GetChar()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append((char)ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 1;
return true;
case 'e':
case 'E':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 7;
return true;
default:
return false;
}
}
return true;
}
private static bool State7(FsmContext ctx)
{
ctx.L.GetChar();
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 8;
return true;
}
switch (ctx.L.input_char) {
case '+':
case '-':
ctx.L.string_buffer.Append((char)ctx.L.input_char);
ctx.NextState = 8;
return true;
default:
return false;
}
}
private static bool State8(FsmContext ctx)
{
while (ctx.L.GetChar()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9') {
ctx.L.string_buffer.Append((char)ctx.L.input_char);
continue;
}
if (ctx.L.input_char == ' ' || ctx.L.input_char >= '\t' && ctx.L.input_char <= '\r') {
ctx.Return = true;
ctx.NextState = 1;
return true;
}
switch (ctx.L.input_char) {
case ',':
case ']':
case '}':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
return true;
}
private static bool State9(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'r':
ctx.NextState = 10;
return true;
default:
return false;
}
}
private static bool State10(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 11;
return true;
default:
return false;
}
}
private static bool State11(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State12(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'a':
ctx.NextState = 13;
return true;
default:
return false;
}
}
private static bool State13(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 14;
return true;
default:
return false;
}
}
private static bool State14(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 's':
ctx.NextState = 15;
return true;
default:
return false;
}
}
private static bool State15(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'e':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State16(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 17;
return true;
default:
return false;
}
}
private static bool State17(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'l':
ctx.NextState = 18;
return true;
default:
return false;
}
}
private static bool State18(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'l':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State19(FsmContext ctx)
{
while (ctx.L.GetChar()) {
switch (ctx.L.input_char) {
case '"':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 20;
return true;
case '\\':
ctx.StateStack = 19;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append((char)ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State20(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case '"':
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State21(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case 'u':
ctx.NextState = 22;
return true;
case '"':
case '\'':
case '/':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
ctx.L.string_buffer.Append(ProcessEscChar(ctx.L.input_char));
ctx.NextState = ctx.StateStack;
return true;
default:
return false;
}
}
private static bool State22(FsmContext ctx)
{
int counter = 0;
int mult = 4096;
ctx.L.unichar = 0;
while (ctx.L.GetChar()) {
if (ctx.L.input_char >= '0' && ctx.L.input_char <= '9' || ctx.L.input_char >= 'A' && ctx.L.input_char <= 'F' || ctx.L.input_char >= 'a' && ctx.L.input_char <= 'f') {
ctx.L.unichar += HexValue(ctx.L.input_char) * mult;
counter++;
mult /= 16;
if (counter == 4) {
ctx.L.string_buffer.Append(Convert.ToChar(ctx.L.unichar));
ctx.NextState = ctx.StateStack;
return true;
}
continue;
}
return false;
}
return true;
}
private static bool State23(FsmContext ctx)
{
while (ctx.L.GetChar()) {
switch (ctx.L.input_char) {
case '\'':
ctx.L.UngetChar();
ctx.Return = true;
ctx.NextState = 24;
return true;
case '\\':
ctx.StateStack = 23;
ctx.NextState = 21;
return true;
default:
ctx.L.string_buffer.Append((char)ctx.L.input_char);
continue;
}
}
return true;
}
private static bool State24(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case '\'':
ctx.L.input_char = '"';
ctx.Return = true;
ctx.NextState = 1;
return true;
default:
return false;
}
}
private static bool State25(FsmContext ctx)
{
ctx.L.GetChar();
switch (ctx.L.input_char) {
case '*':
ctx.NextState = 27;
return true;
case '/':
ctx.NextState = 26;
return true;
default:
return false;
}
}
private static bool State26(FsmContext ctx)
{
while (ctx.L.GetChar()) {
if (ctx.L.input_char == '\n') {
ctx.NextState = 1;
return true;
}
}
return true;
}
private static bool State27(FsmContext ctx)
{
while (ctx.L.GetChar()) {
if (ctx.L.input_char == '*') {
ctx.NextState = 28;
return true;
}
}
return true;
}
private static bool State28(FsmContext ctx)
{
while (ctx.L.GetChar()) {
if (ctx.L.input_char == '*') continue;
if (ctx.L.input_char == '/') {
ctx.NextState = 1;
return true;
}
ctx.NextState = 27;
return true;
}
return true;
}
#endregion
private bool GetChar()
{
if ((input_char = NextChar()) != -1) return true;
end_of_input = true;
return false;
}
private int NextChar()
{
if (input_buffer != 0) {
int tmp = input_buffer;
input_buffer = 0;
return tmp;
}
return reader.Read();
}
public bool NextToken()
{
StateHandler handler;
fsm_context.Return = false;
while (true) {
handler = fsm_handler_table[state - 1];
if (!handler(fsm_context)) throw new JsonException(input_char);
if (end_of_input) return false;
if (fsm_context.Return) {
string_value = string_buffer.ToString();
string_buffer.Remove(0, string_buffer.Length);
token = fsm_return_table[state - 1];
if (token == (int)ParserToken.Char) token = input_char;
state = fsm_context.NextState;
return true;
}
state = fsm_context.NextState;
}
}
private void UngetChar()
{
input_buffer = input_char;
}
}
}
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <kintaro@think-in-co.de>
*/
using System;
namespace Pictor.VertexSource
{
public interface ICurve : IVertexSource
{
};
public static class Curves
{
//--------------------------------------------ECurveApproximationMethod
public enum ECurveApproximationMethod
{
Inc,
Div
};
public static double curve_distance_epsilon = 1e-30;
public static double curve_collinearity_epsilon = 1e-30;
public static double curve_angle_tolerance_epsilon = 0.01;
public enum curve_recursion_limit_e { curve_recursion_limit = 32 };
//-------------------------------------------------------catrom_to_bezier
public static Curve4Points catrom_to_bezier(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
// Trans. matrix Catmull-Rom to Bezier
//
// 0 1 0 0
// -1/6 1 1/6 0
// 0 1/6 1 -1/6
// 0 0 1 0
//
return new Curve4Points(
x2,
y2,
(-x1 + 6 * x2 + x3) / 6,
(-y1 + 6 * y2 + y3) / 6,
(x2 + 6 * x3 - x4) / 6,
(y2 + 6 * y3 - y4) / 6,
x3,
y3);
}
//-----------------------------------------------------------------------
public static Curve4Points
catrom_to_bezier(Curve4Points cp)
{
return catrom_to_bezier(cp[0], cp[1], cp[2], cp[3],
cp[4], cp[5], cp[6], cp[7]);
}
//-----------------------------------------------------ubspline_to_bezier
public static Curve4Points ubspline_to_bezier(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
// Trans. matrix Uniform BSpline to Bezier
//
// 1/6 4/6 1/6 0
// 0 4/6 2/6 0
// 0 2/6 4/6 0
// 0 1/6 4/6 1/6
//
return new Curve4Points(
(x1 + 4 * x2 + x3) / 6,
(y1 + 4 * y2 + y3) / 6,
(4 * x2 + 2 * x3) / 6,
(4 * y2 + 2 * y3) / 6,
(2 * x2 + 4 * x3) / 6,
(2 * y2 + 4 * y3) / 6,
(x2 + 4 * x3 + x4) / 6,
(y2 + 4 * y3 + y4) / 6);
}
//-----------------------------------------------------------------------
public static Curve4Points
ubspline_to_bezier(Curve4Points cp)
{
return ubspline_to_bezier(cp[0], cp[1], cp[2], cp[3],
cp[4], cp[5], cp[6], cp[7]);
}
//------------------------------------------------------hermite_to_bezier
public static Curve4Points hermite_to_bezier(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
// Trans. matrix Hermite to Bezier
//
// 1 0 0 0
// 1 0 1/3 0
// 0 1 0 -1/3
// 0 1 0 0
//
return new Curve4Points(
x1,
y1,
(3 * x1 + x3) / 3,
(3 * y1 + y3) / 3,
(3 * x2 - x4) / 3,
(3 * y2 - y4) / 3,
x2,
y2);
}
//-----------------------------------------------------------------------
public static Curve4Points
hermite_to_bezier(Curve4Points cp)
{
return hermite_to_bezier(cp[0], cp[1], cp[2], cp[3],
cp[4], cp[5], cp[6], cp[7]);
}
};
// See Implementation agg_curves.cpp
//--------------------------------------------------------------Curve3Inc
public sealed class Curve3Inc
{
private int m_num_steps;
private int m_step;
private double m_scale;
private double m_start_x;
private double m_start_y;
private double m_end_x;
private double m_end_y;
private double m_fx;
private double m_fy;
private double m_dfx;
private double m_dfy;
private double m_ddfx;
private double m_ddfy;
private double m_saved_fx;
private double m_saved_fy;
private double m_saved_dfx;
private double m_saved_dfy;
public Curve3Inc()
{
m_num_steps = (0);
m_step = (0);
m_scale = (1.0);
}
public Curve3Inc(double x1, double y1,
double x2, double y2,
double x3, double y3)
{
m_num_steps = (0);
m_step = (0);
m_scale = (1.0);
init(x1, y1, x2, y2, x3, y3);
}
public void reset()
{
m_num_steps = 0; m_step = -1;
}
public void init(double x1, double y1,
double x2, double y2,
double x3, double y3)
{
m_start_x = x1;
m_start_y = y1;
m_end_x = x3;
m_end_y = y3;
double dx1 = x2 - x1;
double dy1 = y2 - y1;
double dx2 = x3 - x2;
double dy2 = y3 - y2;
double len = Math.Sqrt(dx1 * dx1 + dy1 * dy1) + Math.Sqrt(dx2 * dx2 + dy2 * dy2);
m_num_steps = (int)Basics.UnsignedRound(len * 0.25 * m_scale);
if (m_num_steps < 4)
{
m_num_steps = 4;
}
double subdivide_step = 1.0 / m_num_steps;
double subdivide_step2 = subdivide_step * subdivide_step;
double tmpx = (x1 - x2 * 2.0 + x3) * subdivide_step2;
double tmpy = (y1 - y2 * 2.0 + y3) * subdivide_step2;
m_saved_fx = m_fx = x1;
m_saved_fy = m_fy = y1;
m_saved_dfx = m_dfx = tmpx + (x2 - x1) * (2.0 * subdivide_step);
m_saved_dfy = m_dfy = tmpy + (y2 - y1) * (2.0 * subdivide_step);
m_ddfx = tmpx * 2.0;
m_ddfy = tmpy * 2.0;
m_step = m_num_steps;
}
public void approximation_method(Curves.ECurveApproximationMethod method)
{
}
public Curves.ECurveApproximationMethod approximation_method()
{
return Curves.ECurveApproximationMethod.Inc;
}
public void approximation_scale(double s)
{
m_scale = s;
}
public double approximation_scale()
{
return m_scale;
}
public void angle_tolerance(double angle)
{
}
public double angle_tolerance()
{
return 0.0;
}
public void cusp_limit(double limit)
{
}
public double cusp_limit()
{
return 0.0;
}
public void rewind(uint path_id)
{
if (m_num_steps == 0)
{
m_step = -1;
return;
}
m_step = m_num_steps;
m_fx = m_saved_fx;
m_fy = m_saved_fy;
m_dfx = m_saved_dfx;
m_dfy = m_saved_dfy;
}
public uint vertex(out double x, out double y)
{
if (m_step < 0)
{
x = 0;
y = 0;
return (uint)Path.EPathCommands.Stop;
}
if (m_step == m_num_steps)
{
x = m_start_x;
y = m_start_y;
--m_step;
return (uint)Path.EPathCommands.MoveTo;
}
if (m_step == 0)
{
x = m_end_x;
y = m_end_y;
--m_step;
return (uint)Path.EPathCommands.LineTo;
}
m_fx += m_dfx;
m_fy += m_dfy;
m_dfx += m_ddfx;
m_dfy += m_ddfy;
x = m_fx;
y = m_fy;
--m_step;
return (uint)Path.EPathCommands.LineTo;
}
};
//-------------------------------------------------------------Curve3Div
public sealed class Curve3Div
{
private double m_approximation_scale;
private double m_distance_tolerance_square;
private double m_angle_tolerance;
private uint m_count;
private VectorPOD<PointD> m_points;
public Curve3Div()
{
m_points = new VectorPOD<PointD>();
m_approximation_scale = (1.0);
m_angle_tolerance = (0.0);
m_count = (0);
}
public Curve3Div(double x1, double y1,
double x2, double y2,
double x3, double y3)
{
m_approximation_scale = (1.0);
m_angle_tolerance = (0.0);
m_count = (0);
init(x1, y1, x2, y2, x3, y3);
}
public void reset()
{
m_points.RemoveAll(); m_count = 0;
}
public void init(double x1, double y1,
double x2, double y2,
double x3, double y3)
{
m_points.RemoveAll();
m_distance_tolerance_square = 0.5 / m_approximation_scale;
m_distance_tolerance_square *= m_distance_tolerance_square;
bezier(x1, y1, x2, y2, x3, y3);
m_count = 0;
}
public void approximation_method(Curves.ECurveApproximationMethod method)
{
}
public Curves.ECurveApproximationMethod approximation_method()
{
return Curves.ECurveApproximationMethod.Div;
}
public void approximation_scale(double s)
{
m_approximation_scale = s;
}
public double approximation_scale()
{
return m_approximation_scale;
}
public void angle_tolerance(double a)
{
m_angle_tolerance = a;
}
public double angle_tolerance()
{
return m_angle_tolerance;
}
public void cusp_limit(double limit)
{
}
public double cusp_limit()
{
return 0.0;
}
public void rewind(uint idx)
{
m_count = 0;
}
public uint vertex(out double x, out double y)
{
if (m_count >= m_points.Size())
{
x = 0;
y = 0;
return (uint)Path.EPathCommands.Stop;
}
PointD p = m_points[m_count++];
x = p.x;
y = p.y;
return (m_count == 1) ? (uint)Path.EPathCommands.MoveTo : (uint)Path.EPathCommands.LineTo;
}
private void bezier(double x1, double y1,
double x2, double y2,
double x3, double y3)
{
m_points.Add(new PointD(x1, y1));
recursive_bezier(x1, y1, x2, y2, x3, y3, 0);
m_points.Add(new PointD(x3, y3));
}
private void recursive_bezier(double x1, double y1,
double x2, double y2,
double x3, double y3,
uint level)
{
if (level > (uint)Curves.curve_recursion_limit_e.curve_recursion_limit)
{
return;
}
// Calculate all the mid-points of the Line segments
//----------------------
double x12 = (x1 + x2) / 2;
double y12 = (y1 + y2) / 2;
double x23 = (x2 + x3) / 2;
double y23 = (y2 + y3) / 2;
double x123 = (x12 + x23) / 2;
double y123 = (y12 + y23) / 2;
double dx = x3 - x1;
double dy = y3 - y1;
double d = Math.Abs(((x2 - x3) * dy - (y2 - y3) * dx));
double da;
if (d > Curves.curve_collinearity_epsilon)
{
// Regular case
//-----------------
if (d * d <= m_distance_tolerance_square * (dx * dx + dy * dy))
{
// If the curvature doesn't exceed the distance_tolerance Value
// we tend to finish subdivisions.
//----------------------
if (m_angle_tolerance < Curves.curve_angle_tolerance_epsilon)
{
m_points.Add(new PointD(x123, y123));
return;
}
// Angle & Cusp Condition
//----------------------
da = Math.Abs(Math.Atan2(y3 - y2, x3 - x2) - Math.Atan2(y2 - y1, x2 - x1));
if (da >= Math.PI) da = 2 * Math.PI - da;
if (da < m_angle_tolerance)
{
// Finally we can stop the recursion
//----------------------
m_points.Add(new PointD(x123, y123));
return;
}
}
}
else
{
// Collinear case
//------------------
da = dx * dx + dy * dy;
if (da == 0)
{
d = PictorMath.CalculateSquaredDistance(x1, y1, x2, y2);
}
else
{
d = ((x2 - x1) * dx + (y2 - y1) * dy) / da;
if (d > 0 && d < 1)
{
// Simple collinear case, 1---2---3
// We can leave just two endpoints
return;
}
if (d <= 0) d = PictorMath.CalculateSquaredDistance(x2, y2, x1, y1);
else if (d >= 1) d = PictorMath.CalculateSquaredDistance(x2, y2, x3, y3);
else d = PictorMath.CalculateSquaredDistance(x2, y2, x1 + d * dx, y1 + d * dy);
}
if (d < m_distance_tolerance_square)
{
m_points.Add(new PointD(x2, y2));
return;
}
}
// Continue subdivision
//----------------------
recursive_bezier(x1, y1, x12, y12, x123, y123, level + 1);
recursive_bezier(x123, y123, x23, y23, x3, y3, level + 1);
}
};
//-------------------------------------------------------------Curve4Points
public sealed class Curve4Points
{
private double[] cp = new double[8];
public Curve4Points()
{
}
public Curve4Points(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
cp[0] = x1; cp[1] = y1; cp[2] = x2; cp[3] = y2;
cp[4] = x3; cp[5] = y3; cp[6] = x4; cp[7] = y4;
}
public void init(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
cp[0] = x1; cp[1] = y1; cp[2] = x2; cp[3] = y2;
cp[4] = x3; cp[5] = y3; cp[6] = x4; cp[7] = y4;
}
public double this[int i]
{
get
{
return cp[i];
}
}
//double operator [] (uint i){ return cp[i]; }
//double& operator [] (uint i) { return cp[i]; }
};
//-------------------------------------------------------------Curve4Inc
public sealed class Curve4Inc
{
private int m_num_steps;
private int m_step;
private double m_scale;
private double m_start_x;
private double m_start_y;
private double m_end_x;
private double m_end_y;
private double m_fx;
private double m_fy;
private double m_dfx;
private double m_dfy;
private double m_ddfx;
private double m_ddfy;
private double m_dddfx;
private double m_dddfy;
private double m_saved_fx;
private double m_saved_fy;
private double m_saved_dfx;
private double m_saved_dfy;
private double m_saved_ddfx;
private double m_saved_ddfy;
public Curve4Inc()
{
m_num_steps = (0);
m_step = (0);
m_scale = (1.0);
}
public Curve4Inc(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
m_num_steps = (0);
m_step = (0);
m_scale = (1.0);
init(x1, y1, x2, y2, x3, y3, x4, y4);
}
public Curve4Inc(Curve4Points cp)
{
m_num_steps = (0);
m_step = (0);
m_scale = (1.0);
init(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]);
}
public void Reset()
{
m_num_steps = 0; m_step = -1;
}
public void init(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
m_start_x = x1;
m_start_y = y1;
m_end_x = x4;
m_end_y = y4;
double dx1 = x2 - x1;
double dy1 = y2 - y1;
double dx2 = x3 - x2;
double dy2 = y3 - y2;
double dx3 = x4 - x3;
double dy3 = y4 - y3;
double len = (Math.Sqrt(dx1 * dx1 + dy1 * dy1) +
Math.Sqrt(dx2 * dx2 + dy2 * dy2) +
Math.Sqrt(dx3 * dx3 + dy3 * dy3)) * 0.25 * m_scale;
m_num_steps = (int)Basics.UnsignedRound(len);
if (m_num_steps < 4)
{
m_num_steps = 4;
}
double subdivide_step = 1.0 / m_num_steps;
double subdivide_step2 = subdivide_step * subdivide_step;
double subdivide_step3 = subdivide_step * subdivide_step * subdivide_step;
double pre1 = 3.0 * subdivide_step;
double pre2 = 3.0 * subdivide_step2;
double pre4 = 6.0 * subdivide_step2;
double pre5 = 6.0 * subdivide_step3;
double tmp1x = x1 - x2 * 2.0 + x3;
double tmp1y = y1 - y2 * 2.0 + y3;
double tmp2x = (x2 - x3) * 3.0 - x1 + x4;
double tmp2y = (y2 - y3) * 3.0 - y1 + y4;
m_saved_fx = m_fx = x1;
m_saved_fy = m_fy = y1;
m_saved_dfx = m_dfx = (x2 - x1) * pre1 + tmp1x * pre2 + tmp2x * subdivide_step3;
m_saved_dfy = m_dfy = (y2 - y1) * pre1 + tmp1y * pre2 + tmp2y * subdivide_step3;
m_saved_ddfx = m_ddfx = tmp1x * pre4 + tmp2x * pre5;
m_saved_ddfy = m_ddfy = tmp1y * pre4 + tmp2y * pre5;
m_dddfx = tmp2x * pre5;
m_dddfy = tmp2y * pre5;
m_step = m_num_steps;
}
public void init(Curve4Points cp)
{
init(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]);
}
public void approximation_method(Curves.ECurveApproximationMethod method)
{
}
public Curves.ECurveApproximationMethod approximation_method()
{
return Curves.ECurveApproximationMethod.Inc;
}
public void approximation_scale(double s)
{
m_scale = s;
}
public double approximation_scale()
{
return m_scale;
}
public void angle_tolerance(double angle)
{
}
public double angle_tolerance()
{
return 0.0;
}
public void cusp_limit(double limit)
{
}
public double cusp_limit()
{
return 0.0;
}
public void rewind(uint path_id)
{
if (m_num_steps == 0)
{
m_step = -1;
return;
}
m_step = m_num_steps;
m_fx = m_saved_fx;
m_fy = m_saved_fy;
m_dfx = m_saved_dfx;
m_dfy = m_saved_dfy;
m_ddfx = m_saved_ddfx;
m_ddfy = m_saved_ddfy;
}
public uint vertex(out double x, out double y)
{
if (m_step < 0)
{
x = 0;
y = 0;
return (uint)Path.EPathCommands.Stop;
}
if (m_step == m_num_steps)
{
x = m_start_x;
y = m_start_y;
--m_step;
return (uint)Path.EPathCommands.MoveTo;
}
if (m_step == 0)
{
x = m_end_x;
y = m_end_y;
--m_step;
return (uint)Path.EPathCommands.LineTo;
}
m_fx += m_dfx;
m_fy += m_dfy;
m_dfx += m_ddfx;
m_dfy += m_ddfy;
m_ddfx += m_dddfx;
m_ddfy += m_dddfy;
x = m_fx;
y = m_fy;
--m_step;
return (uint)Path.EPathCommands.LineTo;
}
};
//-------------------------------------------------------------Curve4Div
public sealed class Curve4Div
{
private double m_approximation_scale;
private double m_distance_tolerance_square;
private double m_angle_tolerance;
private double m_cusp_limit;
private uint m_count;
private VectorPOD<PointD> m_points;
public Curve4Div()
{
m_points = new VectorPOD<PointD>();
m_approximation_scale = (1.0);
m_angle_tolerance = (0.0);
m_cusp_limit = (0.0);
m_count = (0);
}
public Curve4Div(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
m_approximation_scale = (1.0);
m_angle_tolerance = (0.0);
m_cusp_limit = (0.0);
m_count = (0);
init(x1, y1, x2, y2, x3, y3, x4, y4);
}
public Curve4Div(Curve4Points cp)
{
m_approximation_scale = (1.0);
m_angle_tolerance = (0.0);
m_count = (0);
init(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]);
}
public void Reset()
{
m_points.RemoveAll(); m_count = 0;
}
public void init(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
m_points.RemoveAll();
m_distance_tolerance_square = 0.5 / m_approximation_scale;
m_distance_tolerance_square *= m_distance_tolerance_square;
bezier(x1, y1, x2, y2, x3, y3, x4, y4);
m_count = 0;
}
public void init(Curve4Points cp)
{
init(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]);
}
public void approximation_method(Curves.ECurveApproximationMethod method)
{
}
public Curves.ECurveApproximationMethod approximation_method()
{
return Curves.ECurveApproximationMethod.Div;
}
public void approximation_scale(double s)
{
m_approximation_scale = s;
}
public double approximation_scale()
{
return m_approximation_scale;
}
public void angle_tolerance(double a)
{
m_angle_tolerance = a;
}
public double angle_tolerance()
{
return m_angle_tolerance;
}
public void cusp_limit(double v)
{
m_cusp_limit = (v == 0.0) ? 0.0 : Math.PI - v;
}
public double cusp_limit()
{
return (m_cusp_limit == 0.0) ? 0.0 : Math.PI - m_cusp_limit;
}
public void rewind(uint idx)
{
m_count = 0;
}
public uint vertex(out double x, out double y)
{
if (m_count >= m_points.Size())
{
x = 0;
y = 0;
return (uint)Path.EPathCommands.Stop;
}
PointD p = m_points[m_count++];
x = p.x;
y = p.y;
return (m_count == 1) ? (uint)Path.EPathCommands.MoveTo : (uint)Path.EPathCommands.LineTo;
}
private void bezier(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
m_points.Add(new PointD(x1, y1));
recursive_bezier(x1, y1, x2, y2, x3, y3, x4, y4, 0);
m_points.Add(new PointD(x4, y4));
}
private void recursive_bezier(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4,
uint level)
{
if (level > (uint)Curves.curve_recursion_limit_e.curve_recursion_limit)
{
return;
}
// Calculate all the mid-points of the Line segments
//----------------------
double x12 = (x1 + x2) / 2;
double y12 = (y1 + y2) / 2;
double x23 = (x2 + x3) / 2;
double y23 = (y2 + y3) / 2;
double x34 = (x3 + x4) / 2;
double y34 = (y3 + y4) / 2;
double x123 = (x12 + x23) / 2;
double y123 = (y12 + y23) / 2;
double x234 = (x23 + x34) / 2;
double y234 = (y23 + y34) / 2;
double x1234 = (x123 + x234) / 2;
double y1234 = (y123 + y234) / 2;
// Try to approximate the full cubic curve by a single straight Line
//------------------
double dx = x4 - x1;
double dy = y4 - y1;
double d2 = Math.Abs(((x2 - x4) * dy - (y2 - y4) * dx));
double d3 = Math.Abs(((x3 - x4) * dy - (y3 - y4) * dx));
double da1, da2, k;
int SwitchCase = 0;
if (d2 > Curves.curve_collinearity_epsilon)
{
SwitchCase = 2;
}
if (d3 > Curves.curve_collinearity_epsilon)
{
SwitchCase++;
}
switch (SwitchCase)
{
case 0:
// All collinear OR p1==p4
//----------------------
k = dx * dx + dy * dy;
if (k == 0)
{
d2 = PictorMath.CalculateSquaredDistance(x1, y1, x2, y2);
d3 = PictorMath.CalculateSquaredDistance(x4, y4, x3, y3);
}
else
{
k = 1 / k;
da1 = x2 - x1;
da2 = y2 - y1;
d2 = k * (da1 * dx + da2 * dy);
da1 = x3 - x1;
da2 = y3 - y1;
d3 = k * (da1 * dx + da2 * dy);
if (d2 > 0 && d2 < 1 && d3 > 0 && d3 < 1)
{
// Simple collinear case, 1---2---3---4
// We can leave just two endpoints
return;
}
if (d2 <= 0) d2 = PictorMath.CalculateSquaredDistance(x2, y2, x1, y1);
else if (d2 >= 1) d2 = PictorMath.CalculateSquaredDistance(x2, y2, x4, y4);
else d2 = PictorMath.CalculateSquaredDistance(x2, y2, x1 + d2 * dx, y1 + d2 * dy);
if (d3 <= 0) d3 = PictorMath.CalculateSquaredDistance(x3, y3, x1, y1);
else if (d3 >= 1) d3 = PictorMath.CalculateSquaredDistance(x3, y3, x4, y4);
else d3 = PictorMath.CalculateSquaredDistance(x3, y3, x1 + d3 * dx, y1 + d3 * dy);
}
if (d2 > d3)
{
if (d2 < m_distance_tolerance_square)
{
m_points.Add(new PointD(x2, y2));
return;
}
}
else
{
if (d3 < m_distance_tolerance_square)
{
m_points.Add(new PointD(x3, y3));
return;
}
}
break;
case 1:
// p1,p2,p4 are collinear, p3 is significant
//----------------------
if (d3 * d3 <= m_distance_tolerance_square * (dx * dx + dy * dy))
{
if (m_angle_tolerance < Curves.curve_angle_tolerance_epsilon)
{
m_points.Add(new PointD(x23, y23));
return;
}
// Angle Condition
//----------------------
da1 = Math.Abs(Math.Atan2(y4 - y3, x4 - x3) - Math.Atan2(y3 - y2, x3 - x2));
if (da1 >= Math.PI) da1 = 2 * Math.PI - da1;
if (da1 < m_angle_tolerance)
{
m_points.Add(new PointD(x2, y2));
m_points.Add(new PointD(x3, y3));
return;
}
if (m_cusp_limit != 0.0)
{
if (da1 > m_cusp_limit)
{
m_points.Add(new PointD(x3, y3));
return;
}
}
}
break;
case 2:
// p1,p3,p4 are collinear, p2 is significant
//----------------------
if (d2 * d2 <= m_distance_tolerance_square * (dx * dx + dy * dy))
{
if (m_angle_tolerance < Curves.curve_angle_tolerance_epsilon)
{
m_points.Add(new PointD(x23, y23));
return;
}
// Angle Condition
//----------------------
da1 = Math.Abs(Math.Atan2(y3 - y2, x3 - x2) - Math.Atan2(y2 - y1, x2 - x1));
if (da1 >= Math.PI) da1 = 2 * Math.PI - da1;
if (da1 < m_angle_tolerance)
{
m_points.Add(new PointD(x2, y2));
m_points.Add(new PointD(x3, y3));
return;
}
if (m_cusp_limit != 0.0)
{
if (da1 > m_cusp_limit)
{
m_points.Add(new PointD(x2, y2));
return;
}
}
}
break;
case 3:
// Regular case
//-----------------
if ((d2 + d3) * (d2 + d3) <= m_distance_tolerance_square * (dx * dx + dy * dy))
{
// If the curvature doesn't exceed the distance_tolerance Value
// we tend to finish subdivisions.
//----------------------
if (m_angle_tolerance < Curves.curve_angle_tolerance_epsilon)
{
m_points.Add(new PointD(x23, y23));
return;
}
// Angle & Cusp Condition
//----------------------
k = Math.Atan2(y3 - y2, x3 - x2);
da1 = Math.Abs(k - Math.Atan2(y2 - y1, x2 - x1));
da2 = Math.Abs(Math.Atan2(y4 - y3, x4 - x3) - k);
if (da1 >= Math.PI) da1 = 2 * Math.PI - da1;
if (da2 >= Math.PI) da2 = 2 * Math.PI - da2;
if (da1 + da2 < m_angle_tolerance)
{
// Finally we can stop the recursion
//----------------------
m_points.Add(new PointD(x23, y23));
return;
}
if (m_cusp_limit != 0.0)
{
if (da1 > m_cusp_limit)
{
m_points.Add(new PointD(x2, y2));
return;
}
if (da2 > m_cusp_limit)
{
m_points.Add(new PointD(x3, y3));
return;
}
}
}
break;
}
// Continue subdivision
//----------------------
recursive_bezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1);
recursive_bezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1);
}
};
//-----------------------------------------------------------------Curve3
public sealed class Curve3 : ICurve
{
private Curve3Inc m_curve_inc;
private Curve3Div m_curve_div;
private Curves.ECurveApproximationMethod m_approximation_method;
public Curve3()
{
m_curve_inc = new Curve3Inc();
m_curve_div = new Curve3Div();
m_approximation_method = Curves.ECurveApproximationMethod.Div;
}
public Curve3(double x1, double y1,
double x2, double y2,
double x3, double y3)
: base()
{
m_approximation_method = Curves.ECurveApproximationMethod.Div;
init(x1, y1, x2, y2, x3, y3);
}
public void reset()
{
m_curve_inc.reset();
m_curve_div.reset();
}
public void init(double x1, double y1,
double x2, double y2,
double x3, double y3)
{
if (m_approximation_method == Curves.ECurveApproximationMethod.Inc)
{
m_curve_inc.init(x1, y1, x2, y2, x3, y3);
}
else
{
m_curve_div.init(x1, y1, x2, y2, x3, y3);
}
}
public void ApproximationMethod(Curves.ECurveApproximationMethod v)
{
m_approximation_method = v;
}
public Curves.ECurveApproximationMethod ApproximationMethod()
{
return m_approximation_method;
}
public double ApproximationScale
{
get { return m_curve_inc.approximation_scale(); }
set
{
m_curve_inc.approximation_scale(value);
m_curve_div.approximation_scale(value);
}
}
public double AngleTolerance
{
get { return m_curve_div.angle_tolerance(); }
set { m_curve_div.angle_tolerance(value); }
}
public double CuspLimit
{
get
{
return m_curve_div.cusp_limit();
}
set
{
m_curve_div.cusp_limit(value);
}
}
public void Rewind(uint path_id)
{
if (m_approximation_method == Curves.ECurveApproximationMethod.Inc)
{
m_curve_inc.rewind(path_id);
}
else
{
m_curve_div.rewind(path_id);
}
}
public uint Vertex(out double x, out double y)
{
if (m_approximation_method == Curves.ECurveApproximationMethod.Inc)
{
return m_curve_inc.vertex(out x, out y);
}
return m_curve_div.vertex(out x, out y);
}
};
//-----------------------------------------------------------------Curve4
public sealed class Curve4 : ICurve
{
private Curve4Inc m_curve_inc;
private Curve4Div m_curve_div;
private Curves.ECurveApproximationMethod m_approximation_method;
public Curve4()
{
m_curve_inc = new Curve4Inc();
m_curve_div = new Curve4Div();
m_approximation_method = Curves.ECurveApproximationMethod.Div;
}
public Curve4(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
: base()
{
m_approximation_method = Curves.ECurveApproximationMethod.Div;
Init(x1, y1, x2, y2, x3, y3, x4, y4);
}
public Curve4(Curve4Points cp)
{
m_approximation_method = Curves.ECurveApproximationMethod.Div;
Init(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]);
}
public void Reset()
{
m_curve_inc.Reset();
m_curve_div.Reset();
}
public void Init(double x1, double y1,
double x2, double y2,
double x3, double y3,
double x4, double y4)
{
if (m_approximation_method == Curves.ECurveApproximationMethod.Inc)
{
m_curve_inc.init(x1, y1, x2, y2, x3, y3, x4, y4);
}
else
{
m_curve_div.init(x1, y1, x2, y2, x3, y3, x4, y4);
}
}
public void Init(Curve4Points cp)
{
Init(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5], cp[6], cp[7]);
}
public void ApproximationMethod(Curves.ECurveApproximationMethod v)
{
m_approximation_method = v;
}
public Curves.ECurveApproximationMethod ApproximationMethod()
{
return m_approximation_method;
}
public double ApproximationScale
{
get { return m_curve_inc.approximation_scale(); }
set
{
m_curve_inc.approximation_scale(value);
m_curve_div.approximation_scale(value);
}
}
public void AngleTolerance(double v)
{
m_curve_div.angle_tolerance(v);
}
public double AngleTolerance()
{
return m_curve_div.angle_tolerance();
}
public double CuspLimit
{
get
{
return m_curve_div.cusp_limit();
}
set
{
m_curve_div.cusp_limit(value);
}
}
public void Rewind(uint path_id)
{
if (m_approximation_method == Curves.ECurveApproximationMethod.Inc)
{
m_curve_inc.rewind(path_id);
}
else
{
m_curve_div.rewind(path_id);
}
}
public uint Vertex(out double x, out double y)
{
if (m_approximation_method == Curves.ECurveApproximationMethod.Inc)
{
return m_curve_inc.vertex(out x, out y);
}
return m_curve_div.vertex(out x, out y);
}
};
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Reflection.Metadata.Ecma335
{
public static class CodedIndex
{
private static int ToCodedIndex(this int rowId, HasCustomAttribute tag) => (rowId << (int)HasCustomAttribute.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasConstant tag) => (rowId << (int)HasConstant.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, CustomAttributeType tag) => (rowId << (int)CustomAttributeType.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasDeclSecurity tag) => (rowId << (int)HasDeclSecurity.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasFieldMarshal tag) => (rowId << (int)HasFieldMarshal.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasSemantics tag) => (rowId << (int)HasSemantics.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, Implementation tag) => (rowId << (int)Implementation.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, MemberForwarded tag) => (rowId << (int)MemberForwarded.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, MemberRefParent tag) => (rowId << (int)MemberRefParent.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, MethodDefOrRef tag) => (rowId << (int)MethodDefOrRef.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, ResolutionScope tag) => (rowId << (int)ResolutionScope.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, TypeDefOrRefOrSpec tag) => (rowId << (int)TypeDefOrRefOrSpec.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, TypeOrMethodDef tag) => (rowId << (int)TypeOrMethodDef.__bits) | (int)tag;
private static int ToCodedIndex(this int rowId, HasCustomDebugInformation tag) => (rowId << (int)HasCustomDebugInformation.__bits) | (int)tag;
public static int ToHasCustomAttribute(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasCustomAttributeTag(handle.Kind));
public static int ToHasConstant(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasConstantTag(handle.Kind));
public static int ToCustomAttributeType(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToCustomAttributeTypeTag(handle.Kind));
public static int ToHasDeclSecurity(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasDeclSecurityTag(handle.Kind));
public static int ToHasFieldMarshal(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasFieldMarshalTag(handle.Kind));
public static int ToHasSemantics(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasSemanticsTag(handle.Kind));
public static int ToImplementation(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToImplementationTag(handle.Kind));
public static int ToMemberForwarded(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMemberForwardedTag(handle.Kind));
public static int ToMemberRefParent(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMemberRefParentTag(handle.Kind));
public static int ToMethodDefOrRef(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToMethodDefOrRefTag(handle.Kind));
public static int ToResolutionScope(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToResolutionScopeTag(handle.Kind));
public static int ToTypeDefOrRefOrSpec(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToTypeDefOrRefOrSpecTag(handle.Kind));
public static int ToTypeOrMethodDef(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToTypeOrMethodDefTag(handle.Kind));
public static int ToHasCustomDebugInformation(EntityHandle handle) => MetadataTokens.GetRowNumber(handle).ToCodedIndex(ToHasCustomDebugInformationTag(handle.Kind));
private enum HasCustomAttribute
{
MethodDef = 0,
Field = 1,
TypeRef = 2,
TypeDef = 3,
Param = 4,
InterfaceImpl = 5,
MemberRef = 6,
Module = 7,
DeclSecurity = 8,
Property = 9,
Event = 10,
StandAloneSig = 11,
ModuleRef = 12,
TypeSpec = 13,
Assembly = 14,
AssemblyRef = 15,
File = 16,
ExportedType = 17,
ManifestResource = 18,
GenericParam = 19,
GenericParamConstraint = 20,
MethodSpec = 21,
__bits = 5
}
private static Exception UnexpectedHandleKind(HandleKind kind)
{
return new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
}
private static HasCustomAttribute ToHasCustomAttributeTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return HasCustomAttribute.MethodDef;
case HandleKind.FieldDefinition: return HasCustomAttribute.Field;
case HandleKind.TypeReference: return HasCustomAttribute.TypeRef;
case HandleKind.TypeDefinition: return HasCustomAttribute.TypeDef;
case HandleKind.Parameter: return HasCustomAttribute.Param;
case HandleKind.InterfaceImplementation: return HasCustomAttribute.InterfaceImpl;
case HandleKind.MemberReference: return HasCustomAttribute.MemberRef;
case HandleKind.ModuleDefinition: return HasCustomAttribute.Module;
case HandleKind.DeclarativeSecurityAttribute: return HasCustomAttribute.DeclSecurity;
case HandleKind.PropertyDefinition: return HasCustomAttribute.Property;
case HandleKind.EventDefinition: return HasCustomAttribute.Event;
case HandleKind.StandaloneSignature: return HasCustomAttribute.StandAloneSig;
case HandleKind.ModuleReference: return HasCustomAttribute.ModuleRef;
case HandleKind.TypeSpecification: return HasCustomAttribute.TypeSpec;
case HandleKind.AssemblyDefinition: return HasCustomAttribute.Assembly;
case HandleKind.AssemblyReference: return HasCustomAttribute.AssemblyRef;
case HandleKind.AssemblyFile: return HasCustomAttribute.File;
case HandleKind.ExportedType: return HasCustomAttribute.ExportedType;
case HandleKind.ManifestResource: return HasCustomAttribute.ManifestResource;
case HandleKind.GenericParameter: return HasCustomAttribute.GenericParam;
case HandleKind.GenericParameterConstraint: return HasCustomAttribute.GenericParamConstraint;
case HandleKind.MethodSpecification: return HasCustomAttribute.MethodSpec;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasConstant
{
Field = 0,
Param = 1,
Property = 2,
__bits = 2,
__mask = (1 << __bits) - 1
}
private static HasConstant ToHasConstantTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.FieldDefinition: return HasConstant.Field;
case HandleKind.Parameter: return HasConstant.Param;
case HandleKind.PropertyDefinition: return HasConstant.Property;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum CustomAttributeType
{
MethodDef = 2,
MemberRef = 3,
__bits = 3
}
private static CustomAttributeType ToCustomAttributeTypeTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return CustomAttributeType.MethodDef;
case HandleKind.MemberReference: return CustomAttributeType.MemberRef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasDeclSecurity
{
TypeDef = 0,
MethodDef = 1,
Assembly = 2,
__bits = 2,
__mask = (1 << __bits) - 1
}
private static HasDeclSecurity ToHasDeclSecurityTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return HasDeclSecurity.TypeDef;
case HandleKind.MethodDefinition: return HasDeclSecurity.MethodDef;
case HandleKind.AssemblyDefinition: return HasDeclSecurity.Assembly;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasFieldMarshal
{
Field = 0,
Param = 1,
__bits = 1,
__mask = (1 << __bits) - 1
}
private static HasFieldMarshal ToHasFieldMarshalTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.FieldDefinition: return HasFieldMarshal.Field;
case HandleKind.Parameter: return HasFieldMarshal.Param;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasSemantics
{
Event = 0,
Property = 1,
__bits = 1
}
private static HasSemantics ToHasSemanticsTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.EventDefinition: return HasSemantics.Event;
case HandleKind.PropertyDefinition: return HasSemantics.Property;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum Implementation
{
File = 0,
AssemblyRef = 1,
ExportedType = 2,
__bits = 2
}
private static Implementation ToImplementationTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.AssemblyFile: return Implementation.File;
case HandleKind.AssemblyReference: return Implementation.AssemblyRef;
case HandleKind.ExportedType: return Implementation.ExportedType;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum MemberForwarded
{
Field = 0,
MethodDef = 1,
__bits = 1
}
private static MemberForwarded ToMemberForwardedTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.FieldDefinition: return MemberForwarded.Field;
case HandleKind.MethodDefinition: return MemberForwarded.MethodDef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum MemberRefParent
{
TypeDef = 0,
TypeRef = 1,
ModuleRef = 2,
MethodDef = 3,
TypeSpec = 4,
__bits = 3
}
private static MemberRefParent ToMemberRefParentTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return MemberRefParent.TypeDef;
case HandleKind.TypeReference: return MemberRefParent.TypeRef;
case HandleKind.ModuleReference: return MemberRefParent.ModuleRef;
case HandleKind.MethodDefinition: return MemberRefParent.MethodDef;
case HandleKind.TypeSpecification: return MemberRefParent.TypeSpec;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum MethodDefOrRef
{
MethodDef = 0,
MemberRef = 1,
__bits = 1
}
private static MethodDefOrRef ToMethodDefOrRefTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return MethodDefOrRef.MethodDef;
case HandleKind.MemberReference: return MethodDefOrRef.MemberRef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum ResolutionScope
{
Module = 0,
ModuleRef = 1,
AssemblyRef = 2,
TypeRef = 3,
__bits = 2
}
private static ResolutionScope ToResolutionScopeTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.ModuleDefinition: return ResolutionScope.Module;
case HandleKind.ModuleReference: return ResolutionScope.ModuleRef;
case HandleKind.AssemblyReference: return ResolutionScope.AssemblyRef;
case HandleKind.TypeReference: return ResolutionScope.TypeRef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum TypeDefOrRefOrSpec
{
TypeDef = 0,
TypeRef = 1,
TypeSpec = 2,
__bits = 2
}
private static TypeDefOrRefOrSpec ToTypeDefOrRefOrSpecTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return TypeDefOrRefOrSpec.TypeDef;
case HandleKind.TypeReference: return TypeDefOrRefOrSpec.TypeRef;
case HandleKind.TypeSpecification: return TypeDefOrRefOrSpec.TypeSpec;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum TypeOrMethodDef
{
TypeDef = 0,
MethodDef = 1,
__bits = 1
}
private static TypeOrMethodDef ToTypeOrMethodDefTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.TypeDefinition: return TypeOrMethodDef.TypeDef;
case HandleKind.MethodDefinition: return TypeOrMethodDef.MethodDef;
default:
throw UnexpectedHandleKind(kind);
}
}
private enum HasCustomDebugInformation
{
MethodDef = 0,
Field = 1,
TypeRef = 2,
TypeDef = 3,
Param = 4,
InterfaceImpl = 5,
MemberRef = 6,
Module = 7,
DeclSecurity = 8,
Property = 9,
Event = 10,
StandAloneSig = 11,
ModuleRef = 12,
TypeSpec = 13,
Assembly = 14,
AssemblyRef = 15,
File = 16,
ExportedType = 17,
ManifestResource = 18,
GenericParam = 19,
GenericParamConstraint = 20,
MethodSpec = 21,
Document = 22,
LocalScope = 23,
LocalVariable = 24,
LocalConstant = 25,
ImportScope = 26,
__bits = 5
}
private static HasCustomDebugInformation ToHasCustomDebugInformationTag(HandleKind kind)
{
switch (kind)
{
case HandleKind.MethodDefinition: return HasCustomDebugInformation.MethodDef;
case HandleKind.FieldDefinition: return HasCustomDebugInformation.Field;
case HandleKind.TypeReference: return HasCustomDebugInformation.TypeRef;
case HandleKind.TypeDefinition: return HasCustomDebugInformation.TypeDef;
case HandleKind.Parameter: return HasCustomDebugInformation.Param;
case HandleKind.InterfaceImplementation: return HasCustomDebugInformation.InterfaceImpl;
case HandleKind.MemberReference: return HasCustomDebugInformation.MemberRef;
case HandleKind.ModuleDefinition: return HasCustomDebugInformation.Module;
case HandleKind.DeclarativeSecurityAttribute: return HasCustomDebugInformation.DeclSecurity;
case HandleKind.PropertyDefinition: return HasCustomDebugInformation.Property;
case HandleKind.EventDefinition: return HasCustomDebugInformation.Event;
case HandleKind.StandaloneSignature: return HasCustomDebugInformation.StandAloneSig;
case HandleKind.ModuleReference: return HasCustomDebugInformation.ModuleRef;
case HandleKind.TypeSpecification: return HasCustomDebugInformation.TypeSpec;
case HandleKind.AssemblyDefinition: return HasCustomDebugInformation.Assembly;
case HandleKind.AssemblyReference: return HasCustomDebugInformation.AssemblyRef;
case HandleKind.AssemblyFile: return HasCustomDebugInformation.File;
case HandleKind.ExportedType: return HasCustomDebugInformation.ExportedType;
case HandleKind.ManifestResource: return HasCustomDebugInformation.ManifestResource;
case HandleKind.GenericParameter: return HasCustomDebugInformation.GenericParam;
case HandleKind.GenericParameterConstraint: return HasCustomDebugInformation.GenericParamConstraint;
case HandleKind.MethodSpecification: return HasCustomDebugInformation.MethodSpec;
case HandleKind.Document: return HasCustomDebugInformation.Document;
case HandleKind.LocalScope: return HasCustomDebugInformation.LocalScope;
case HandleKind.LocalVariable: return HasCustomDebugInformation.LocalVariable;
case HandleKind.LocalConstant: return HasCustomDebugInformation.LocalConstant;
case HandleKind.ImportScope: return HasCustomDebugInformation.ImportScope;
default:
throw UnexpectedHandleKind(kind);
}
}
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using FluentAssertions;
using NBitcoin;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Features.RPC;
using Stratis.Bitcoin.Features.Wallet;
using Stratis.Bitcoin.Features.Wallet.Interfaces;
using Stratis.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers;
using Stratis.Bitcoin.Networks;
using Stratis.Bitcoin.Tests.Common;
using Xunit;
namespace Stratis.Bitcoin.IntegrationTests.RPC
{
/// <summary>
/// Stratis test fixture for RPC tests.
/// </summary>
public class RpcTestFixtureStratis : RpcTestFixtureBase
{
/// <inheritdoc />
protected override void InitializeFixture()
{
this.Builder = NodeBuilder.Create(this);
this.Node = this.Builder.CreateStratisPowNode(new BitcoinRegTest()).Start();
this.RpcClient = this.Node.CreateRPCClient();
this.NetworkPeerClient = this.Node.CreateNetworkPeerClient();
this.NetworkPeerClient.VersionHandshakeAsync().GetAwaiter().GetResult();
// Move a wallet file to the right folder and restart the wallet manager to take it into account.
this.InitializeTestWallet(this.Node.FullNode.DataFolder.WalletPath);
var walletManager = this.Node.FullNode.NodeService<IWalletManager>() as WalletManager;
walletManager.Start();
}
}
public class RpcTests : IClassFixture<RpcTestFixtureStratis>
{
private readonly RpcTestFixtureStratis rpcTestFixture;
public RpcTests(RpcTestFixtureStratis RpcTestFixture)
{
this.rpcTestFixture = RpcTestFixture;
}
/// <summary>
/// Tests whether the RPC method "addnode" adds a network peer to the connection manager.
/// </summary>
[Fact]
public void CanAddNodeToConnectionManager()
{
var connectionManager = this.rpcTestFixture.Node.FullNode.NodeService<IConnectionManager>();
Assert.Empty(connectionManager.ConnectionSettings.AddNode);
IPAddress ipAddress = IPAddress.Parse("::ffff:192.168.0.1");
var endpoint = new IPEndPoint(ipAddress, 80);
this.rpcTestFixture.RpcClient.AddNode(endpoint);
Assert.Single(connectionManager.ConnectionSettings.AddNode);
}
[Fact]
public void CheckRPCFailures()
{
uint256 hash = this.rpcTestFixture.RpcClient.GetBestBlockHash();
Assert.Equal(hash, KnownNetworks.RegTest.GetGenesis().GetHash());
RPCClient oldClient = this.rpcTestFixture.RpcClient;
var client = new RPCClient("abc:def", this.rpcTestFixture.RpcClient.Address, this.rpcTestFixture.RpcClient.Network);
try
{
client.GetBestBlockHash();
Assert.True(false, "should throw");
}
catch (Exception ex)
{
Assert.Contains("401", ex.Message);
}
client = oldClient;
try
{
client.SendCommand("addnode", "regreg", "addr");
Assert.True(false, "should throw");
}
catch (RPCException ex)
{
Assert.Equal(RPCErrorCode.RPC_INTERNAL_ERROR, ex.RPCCode);
}
}
[Fact]
public void InvalidCommandSendRPCException()
{
var ex = Assert.Throws<RPCException>(() => this.rpcTestFixture.RpcClient.SendCommand("donotexist"));
Assert.True(ex.RPCCode == RPCErrorCode.RPC_METHOD_NOT_FOUND);
}
[Fact]
public void CanSendCommand()
{
RPCResponse response = this.rpcTestFixture.RpcClient.SendCommand(RPCOperations.getinfo);
Assert.NotNull(response.Result);
}
[Fact]
public void CanGetRawMemPool()
{
uint256[] ids = this.rpcTestFixture.RpcClient.GetRawMempool();
Assert.NotNull(ids);
}
[Fact]
public void CanGetBlockCount()
{
int blockCount = this.rpcTestFixture.RpcClient.GetBlockCountAsync().Result;
Assert.Equal(0, blockCount);
}
[Fact]
public void CanGetStratisPeersInfo()
{
PeerInfo[] peers = this.rpcTestFixture.RpcClient.GetStratisPeersInfoAsync().Result;
Assert.NotEmpty(peers);
}
/// <summary>
/// Tests RPC get genesis block hash.
/// </summary>
[Fact]
public void CanGetGenesisBlockHashFromRPC()
{
RPCResponse response = this.rpcTestFixture.RpcClient.SendCommand(RPCOperations.getblockhash, 0);
string actualGenesis = (string)response.Result;
Assert.Equal(KnownNetworks.RegTest.GetGenesis().GetHash().ToString(), actualGenesis);
}
/// <summary>
/// Tests RPC getbestblockhash.
/// </summary>
[Fact]
public void CanGetGetBestBlockHashFromRPC()
{
uint256 expected = this.rpcTestFixture.Node.FullNode.ChainIndexer.Tip.Header.GetHash();
uint256 response = this.rpcTestFixture.RpcClient.GetBestBlockHash();
Assert.Equal(expected, response);
}
/// <summary>
/// Tests RPC getblockheader.
/// </summary>
[Fact]
public void CanGetBlockHeaderFromRPC()
{
uint256 hash = this.rpcTestFixture.RpcClient.GetBlockHash(0);
BlockHeader expectedHeader = this.rpcTestFixture.Node.FullNode.ChainIndexer?.GetHeader(hash)?.Header;
BlockHeader actualHeader = this.rpcTestFixture.RpcClient.GetBlockHeader(0);
// Assert block header fields match.
Assert.Equal(expectedHeader.Version, actualHeader.Version);
Assert.Equal(expectedHeader.HashPrevBlock, actualHeader.HashPrevBlock);
Assert.Equal(expectedHeader.HashMerkleRoot, actualHeader.HashMerkleRoot);
Assert.Equal(expectedHeader.Time, actualHeader.Time);
Assert.Equal(expectedHeader.Bits, actualHeader.Bits);
Assert.Equal(expectedHeader.Nonce, actualHeader.Nonce);
// Assert header hash matches genesis hash.
Assert.Equal(KnownNetworks.RegTest.GenesisHash, actualHeader.GetHash());
}
/// <summary>
/// Tests whether the RPC method "getpeersinfo" can be called and returns a non-empty result.
/// </summary>
[Fact]
public void CanGetPeersInfo()
{
PeerInfo[] peers = this.rpcTestFixture.RpcClient.GetPeersInfo();
Assert.NotEmpty(peers);
}
/// <summary>
/// Tests whether the RPC method "getpeersinfo" can be called and returns a string result suitable for console output.
/// We are also testing whether all arguments can be passed as strings.
/// </summary>
[Fact]
public void CanGetPeersInfoByStringArgs()
{
string resp = this.rpcTestFixture.RpcClient.SendCommand("getpeerinfo").ResultString;
Assert.StartsWith("[" + Environment.NewLine + " {" + Environment.NewLine + " \"id\": 0," + Environment.NewLine + " \"addr\": \"[", resp);
}
/// <summary>
/// Tests whether the RPC method "getblockhash" can be called and returns the expected string result suitable for console output.
/// We are also testing whether all arguments can be passed as strings.
/// </summary>
[Fact]
public void CanGetBlockHashByStringArgs()
{
string resp = this.rpcTestFixture.RpcClient.SendCommand("getblockhash", "0").ResultString;
Assert.Equal("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206", resp);
}
/// <summary>
/// Tests whether the RPC method "generate" can be called and returns a string result suitable for console output.
/// We are also testing whether all arguments can be passed as strings.
/// </summary>
[Fact]
public void CanGenerateByStringArgs()
{
string resp = this.rpcTestFixture.RpcClient.SendCommand("generate", "1").ResultString;
Assert.StartsWith("[" + Environment.NewLine + " \"", resp);
}
/// <summary>
/// Tests that RPC method 'SendRawTransaction' can be called with a new transaction.
/// </summary>
[Fact]
public void SendRawTransaction()
{
var tx = new Transaction();
tx.Outputs.Add(new TxOut(Money.Coins(1.0m), new Key()));
this.rpcTestFixture.RpcClient.SendRawTransaction(tx);
}
/// <summary>
/// Tests that RPC method 'GetNewAddress' can be called and returns an address.
/// </summary>
[Fact]
public void GetNewAddress()
{
// Try creating with default parameters.
BitcoinAddress address = this.rpcTestFixture.RpcClient.GetNewAddress();
Assert.NotNull(address);
// Try creating with optional parameters.
address = BitcoinAddress.Create(this.rpcTestFixture.RpcClient.SendCommand(RPCOperations.getnewaddress, new[] { string.Empty, "legacy" }).ResultString, this.rpcTestFixture.RpcClient.Network);
Assert.NotNull(address);
}
[Fact]
public void TestGetNewAddressWithUnsupportedAddressTypeThrowsRpcException()
{
Assert.Throws<RPCException>(() => this.rpcTestFixture.RpcClient.SendCommand(RPCOperations.getnewaddress, new[] { string.Empty, "bech32" }));
}
[Fact]
public void TestGetNewAddressWithAccountParameterThrowsRpcException()
{
Assert.Throws<RPCException>(() => this.rpcTestFixture.RpcClient.SendCommand(RPCOperations.getnewaddress, new[] { "account1", "legacy" }));
}
[Fact]
public async Task TestRpcBatchAsync()
{
var rpcBatch = this.rpcTestFixture.RpcClient.PrepareBatch();
var rpc1 = rpcBatch.SendCommandAsync("getpeerinfo");
var rpc2 = rpcBatch.SendCommandAsync("getrawmempool");
await rpcBatch.SendBatchAsync();
var response1 = await rpc1;
var response1AsString = response1.ResultString;
Assert.False(string.IsNullOrEmpty(response1AsString));
var response2 = await rpc2;
var response2AsString = response2.ResultString;
Assert.False(string.IsNullOrEmpty(response2AsString));
}
[Fact]
public async Task TestRpcBatchWithUnknownMethodsReturnsArrayAsync()
{
var rpcBatch = this.rpcTestFixture.RpcClient.PrepareBatch();
var unknownRpc = rpcBatch.SendCommandAsync("unknownmethod", "random");
var address = new Key().ScriptPubKey.WitHash.ScriptPubKey.GetDestinationAddress(rpcBatch.Network);
var knownRpc = rpcBatch.SendCommandAsync("validateaddress",address.ToString());
await rpcBatch.SendBatchAsync();
Func<Task> unknownRpcMethod = async () => { await unknownRpc; };
unknownRpcMethod.Should().Throw<RPCException>().Which.RPCCode.Should().Be(RPCErrorCode.RPC_METHOD_NOT_FOUND);
var knownRpcResponse = await knownRpc;
var knownRpcResponseAsString = knownRpcResponse.ResultString;
Assert.False(string.IsNullOrEmpty(knownRpcResponseAsString));
}
// TODO: implement the RPC methods used below
//[Fact]
//public void RawTransactionIsConformsToRPC()
//{
// var tx = Transaction.Load("01000000ac55a957010000000000000000000000000000000000000000000000000000000000000000ffffffff0401320103ffffffff010084d717000000001976a9143ac0dad2ad42e35fcd745d7511d47c24ad6580b588ac00000000", network: this.rpcTestFixture.Node.FullNode.Network);
// Transaction tx2 = this.rpcTestFixture.RpcClient.GetRawTransaction(uint256.Parse("65a26bc20b0351aebf05829daefa8f7db2f800623439f3c114257c91447f1518"));
// Assert.Equal(tx.GetHash(), tx2.GetHash());
//}
//[Fact]
//public void CanDecodeRawTransaction()
//{
// var tx = this.rpcTestFixture.Node.FullNode.Network.GetGenesis().Transactions[0];
// var tx2 = this.rpcTestFixture.RpcClient.DecodeRawTransaction(tx.ToBytes());
// Assert.True(JToken.DeepEquals(tx.ToString(RawFormat.Satoshi), tx2.ToString(RawFormat.Satoshi)));
//}
//[Fact]
//public void CanEstimateFeeRate()
//{
// Assert.Throws<NoEstimationException>(() => this.rpcTestFixture.RpcClient.EstimateFeeRate(1));
//}
//[Fact]
//public void TryEstimateFeeRate()
//{
// Assert.Null(this.rpcTestFixture.RpcClient.TryEstimateFeeRate(1));
//}
//[Fact]
//public void CanAddNodes()
//{
// using (var builder = NodeBuilder.Create(this))
// {
// CoreNode nodeA = builder.CreateStratisPosNode();
// CoreNode nodeB = builder.CreateStratisPosNode();
// builder.StartAll();
// RPCClient rpc = nodeA.CreateRPCClient();
// rpc.RemoveNode(nodeA.Endpoint);
// rpc.AddNode(nodeB.Endpoint);
// Thread.Sleep(500);
// AddedNodeInfo[] info = rpc.GetAddedNodeInfo(true);
// Assert.NotNull(info);
// Assert.NotEmpty(info);
// //For some reason this one does not pass anymore in 0.13.1.
// //Assert.Equal(nodeB.Endpoint, info.First().Addresses.First().Address);
// AddedNodeInfo oneInfo = rpc.GetAddedNodeInfo(true, nodeB.Endpoint);
// Assert.NotNull(oneInfo);
// Assert.True(oneInfo.AddedNode.ToString() == nodeB.Endpoint.ToString());
// oneInfo = rpc.GetAddedNodeInfo(true, nodeA.Endpoint);
// Assert.Null(oneInfo);
// //rpc.RemoveNode(nodeB.Endpoint);
// //Thread.Sleep(500);
// //info = rpc.GetAddedNodeInfo(true);
// //Assert.Equal(0, info.Count());
// }
//}
//[Fact]
//public void CanGetPrivateKeysFromAccount()
//{
// string accountName = "account";
// Key key = new Key();
// this.rpcTestFixture.RpcClient.ImportAddress(key.PubKey.GetAddress(StratisNetworks.StratisMain), accountName, false);
// BitcoinAddress address = this.rpcTestFixture.RpcClient.GetAccountAddress(accountName);
// BitcoinSecret secret = this.rpcTestFixture.RpcClient.DumpPrivKey(address);
// BitcoinSecret secret2 = this.rpcTestFixture.RpcClient.GetAccountSecret(accountName);
// Assert.Equal(secret.ToString(), secret2.ToString());
// Assert.Equal(address.ToString(), secret.GetAddress().ToString());
//}
//[Fact]
//public void CanGetPrivateKeysFromAccount()
//{
// string accountName = "account";
// Key key = new Key();
// this.rpcTestFixture.RpcClient.ImportAddress(key.PubKey.GetAddress(StratisNetworks.StratisMain), accountName, false);
// BitcoinAddress address = this.rpcTestFixture.RpcClient.GetAccountAddress(accountName);
// BitcoinSecret secret = this.rpcTestFixture.RpcClient.DumpPrivKey(address);
// BitcoinSecret secret2 = this.rpcTestFixture.RpcClient.GetAccountSecret(accountName);
// Assert.Equal(secret.ToString(), secret2.ToString());
// Assert.Equal(address.ToString(), secret.GetAddress().ToString());
//}
//[Fact]
//public void CanBackupWallet()
//{
// var buildOutputDir = Path.GetDirectoryName(".");
// var filePath = Path.Combine(buildOutputDir, "wallet_backup.dat");
// try
// {
// this.rpcTestFixture.RpcClient.BackupWallet(filePath);
// Assert.True(File.Exists(filePath));
// }
// finally
// {
// if (File.Exists(filePath))
// File.Delete(filePath);
// }
//}
//[Fact]
//public void CanEstimatePriority()
//{
// var priority = this.rpcTestFixture.RpcClient.EstimatePriority(10);
// Assert.True(priority > 0 || priority == -1);
//}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.FlowAnalysis.Analysis.PropertySetAnalysis;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis;
using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.NetCore.Analyzers.Security.Helpers;
namespace Microsoft.NetCore.Analyzers.Security
{
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotInstallRootCert : DiagnosticAnalyzer
{
internal static DiagnosticDescriptor DefinitelyInstallRootCertRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5380",
typeof(MicrosoftNetCoreAnalyzersResources),
nameof(MicrosoftNetCoreAnalyzersResources.DefinitelyInstallRootCert),
nameof(MicrosoftNetCoreAnalyzersResources.DefinitelyInstallRootCertMessage),
RuleLevel.Disabled,
isPortedFxCopRule: false,
isDataflowRule: true,
isReportedAtCompilationEnd: true,
descriptionResourceStringName: nameof(MicrosoftNetCoreAnalyzersResources.DoNotInstallRootCertDescription));
internal static DiagnosticDescriptor MaybeInstallRootCertRule = SecurityHelpers.CreateDiagnosticDescriptor(
"CA5381",
typeof(MicrosoftNetCoreAnalyzersResources),
nameof(MicrosoftNetCoreAnalyzersResources.MaybeInstallRootCert),
nameof(MicrosoftNetCoreAnalyzersResources.MaybeInstallRootCertMessage),
RuleLevel.Disabled,
isPortedFxCopRule: false,
isDataflowRule: true,
isReportedAtCompilationEnd: true,
descriptionResourceStringName: nameof(MicrosoftNetCoreAnalyzersResources.DoNotInstallRootCertDescription));
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(
DefinitelyInstallRootCertRule,
MaybeInstallRootCertRule);
private static readonly PropertyMapperCollection PropertyMappers = new(
new PropertyMapper(
"...dummy name", // There isn't *really* a property for what we're tracking; just the constructor argument.
(PointsToAbstractValue v) => PropertySetAbstractValueKind.Unknown));
private static HazardousUsageEvaluationResult HazardousUsageCallback(IMethodSymbol methodSymbol, PropertySetAbstractValue propertySetAbstractValue)
{
return (propertySetAbstractValue[0]) switch
{
PropertySetAbstractValueKind.Flagged => HazardousUsageEvaluationResult.Flagged,
PropertySetAbstractValueKind.MaybeFlagged => HazardousUsageEvaluationResult.MaybeFlagged,
_ => HazardousUsageEvaluationResult.Unflagged,
};
}
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
// Security analyzer - analyze and report diagnostics on generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
HazardousUsageEvaluatorCollection hazardousUsageEvaluators = new HazardousUsageEvaluatorCollection(
new HazardousUsageEvaluator("Add", HazardousUsageCallback));
context.RegisterCompilationStartAction(
(CompilationStartAnalysisContext compilationStartAnalysisContext) =>
{
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilationStartAnalysisContext.Compilation);
if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyX509CertificatesX509Store, out var x509TypeSymbol))
{
return;
}
if (!wellKnownTypeProvider.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyX509CertificatesStoreName, out var storeNameTypeSymbol))
{
return;
}
// If X509Store is initialized with Root store, then that instance is flagged.
var constructorMapper = new ConstructorMapper(
(IMethodSymbol constructorMethod, IReadOnlyList<ValueContentAbstractValue> argumentValueContentAbstractValues,
IReadOnlyList<PointsToAbstractValue> argumentPointsToAbstractValues) =>
{
var kind = PropertySetAbstractValueKind.Unflagged;
if (!constructorMethod.Parameters.IsEmpty)
{
if (constructorMethod.Parameters[0].Type.Equals(storeNameTypeSymbol))
{
kind = PropertySetCallbacks.EvaluateLiteralValues(argumentValueContentAbstractValues[0], o => o != null && o.Equals(6));
}
else if (constructorMethod.Parameters[0].Type.SpecialType == SpecialType.System_String)
{
kind = PropertySetCallbacks.EvaluateLiteralValues(
argumentValueContentAbstractValues[0],
s => s != null && string.Equals(s.ToString(), "root", StringComparison.OrdinalIgnoreCase));
}
}
return PropertySetAbstractValue.GetInstance(kind);
});
var rootOperationsNeedingAnalysis = PooledHashSet<(IOperation, ISymbol)>.GetInstance();
compilationStartAnalysisContext.RegisterOperationBlockStartAction(
(OperationBlockStartAnalysisContext operationBlockStartAnalysisContext) =>
{
var owningSymbol = operationBlockStartAnalysisContext.OwningSymbol;
// TODO: Handle case when exactly one of the below rules is configured to skip analysis.
if (operationBlockStartAnalysisContext.Options.IsConfiguredToSkipAnalysis(DefinitelyInstallRootCertRule,
owningSymbol, operationBlockStartAnalysisContext.Compilation, operationBlockStartAnalysisContext.CancellationToken) &&
operationBlockStartAnalysisContext.Options.IsConfiguredToSkipAnalysis(MaybeInstallRootCertRule,
owningSymbol, operationBlockStartAnalysisContext.Compilation, operationBlockStartAnalysisContext.CancellationToken))
{
return;
}
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var invocationOperation = (IInvocationOperation)operationAnalysisContext.Operation;
if (x509TypeSymbol.Equals(invocationOperation.Instance?.Type) &&
invocationOperation.TargetMethod.Name == "Add")
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((invocationOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Invocation);
operationBlockStartAnalysisContext.RegisterOperationAction(
(OperationAnalysisContext operationAnalysisContext) =>
{
var argumentOperation = (IArgumentOperation)operationAnalysisContext.Operation;
if (x509TypeSymbol.Equals(argumentOperation.Parameter.Type))
{
lock (rootOperationsNeedingAnalysis)
{
rootOperationsNeedingAnalysis.Add((argumentOperation.GetRoot(), operationAnalysisContext.ContainingSymbol));
}
}
},
OperationKind.Argument);
});
compilationStartAnalysisContext.RegisterCompilationEndAction(
(CompilationAnalysisContext compilationAnalysisContext) =>
{
PooledDictionary<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult>? allResults = null;
try
{
lock (rootOperationsNeedingAnalysis)
{
if (!rootOperationsNeedingAnalysis.Any())
{
return;
}
allResults = PropertySetAnalysis.BatchGetOrComputeHazardousUsages(
compilationAnalysisContext.Compilation,
rootOperationsNeedingAnalysis,
compilationAnalysisContext.Options,
WellKnownTypeNames.SystemSecurityCryptographyX509CertificatesX509Store,
constructorMapper,
PropertyMappers,
hazardousUsageEvaluators,
InterproceduralAnalysisConfiguration.Create(
compilationAnalysisContext.Options,
SupportedDiagnostics,
rootOperationsNeedingAnalysis.First().Item1,
compilationAnalysisContext.Compilation,
defaultInterproceduralAnalysisKind: InterproceduralAnalysisKind.ContextSensitive,
cancellationToken: compilationAnalysisContext.CancellationToken));
}
if (allResults == null)
{
return;
}
foreach (KeyValuePair<(Location Location, IMethodSymbol? Method), HazardousUsageEvaluationResult> kvp
in allResults)
{
DiagnosticDescriptor descriptor;
switch (kvp.Value)
{
case HazardousUsageEvaluationResult.Flagged:
descriptor = DefinitelyInstallRootCertRule;
break;
case HazardousUsageEvaluationResult.MaybeFlagged:
descriptor = MaybeInstallRootCertRule;
break;
default:
Debug.Fail($"Unhandled result value {kvp.Value}");
continue;
}
RoslynDebug.Assert(kvp.Key.Method != null); // HazardousUsageEvaluations only for invocations.
compilationAnalysisContext.ReportDiagnostic(
Diagnostic.Create(
descriptor,
kvp.Key.Location,
kvp.Key.Method.ToDisplayString(
SymbolDisplayFormat.MinimallyQualifiedFormat)));
}
}
finally
{
rootOperationsNeedingAnalysis.Free(compilationAnalysisContext.CancellationToken);
allResults?.Free(compilationAnalysisContext.CancellationToken);
}
});
});
}
}
}
| |
using System;
using System.Data;
using FileHelpers.Dynamic;
using NUnit.Framework;
namespace FileHelpers.Tests.Dynamic
{
[TestFixture]
public class DelimitedClassBuilderTests
{
private FileHelperEngine mEngine;
[Test]
[Category("Dynamic")]
public void FullClassBuilding()
{
var cb = new DelimitedClassBuilder("Customers", ",");
cb.IgnoreFirstLines = 1;
cb.IgnoreEmptyLines = true;
cb.AddField("Field1", typeof(DateTime));
cb.LastField.TrimMode = TrimMode.Both;
cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted;
cb.LastField.FieldNullValue = DateTime.Today;
cb.AddField("Field2", typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
cb.AddField("Field3", typeof(int));
mEngine = new FileHelperEngine(cb.CreateRecordClass());
DataTable dt = mEngine.ReadFileAsDT(TestCommon.GetPath("Good", "Test2.txt"));
Assert.AreEqual(4, dt.Rows.Count);
Assert.AreEqual(4, mEngine.TotalRecords);
Assert.AreEqual(0, mEngine.ErrorManager.ErrorCount);
Assert.AreEqual("Field1", dt.Columns[0].ColumnName);
Assert.AreEqual("Field2", dt.Columns[1].ColumnName);
Assert.AreEqual("Field3", dt.Columns[2].ColumnName);
Assert.AreEqual("Hola", dt.Rows[0][1]);
Assert.AreEqual(DateTime.Today, dt.Rows[2][0]);
}
[Test]
[Category("Dynamic")]
public void TestingNameAndTypes()
{
var cb = new DelimitedClassBuilder("Customers", ",");
cb.IgnoreFirstLines = 1;
cb.IgnoreEmptyLines = true;
cb.AddField("Field1", typeof (DateTime));
cb.LastField.TrimMode = TrimMode.Both;
cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted;
cb.LastField.FieldNullValue = DateTime.Today;
cb.AddField("Field2", typeof (string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
cb.AddField("Field3", typeof (int));
mEngine = new FileHelperEngine(cb.CreateRecordClass());
DataTable dt = mEngine.ReadFileAsDT(TestCommon.GetPath("Good", "Test2.txt"));
Assert.AreEqual("Field1", dt.Columns[0].ColumnName);
Assert.AreEqual(typeof (DateTime), dt.Columns[0].DataType);
Assert.AreEqual("Field2", dt.Columns[1].ColumnName);
Assert.AreEqual(typeof (string), dt.Columns[1].DataType);
Assert.AreEqual("Field3", dt.Columns[2].ColumnName);
Assert.AreEqual(typeof (int), dt.Columns[2].DataType);
}
[Test]
public void SaveLoadXmlFileDelimited()
{
var cb = new DelimitedClassBuilder("Customers", ",");
cb.IgnoreFirstLines = 1;
cb.IgnoreEmptyLines = true;
cb.AddField("Field1", typeof(DateTime));
cb.LastField.TrimMode = TrimMode.Both;
cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted;
cb.LastField.FieldNullValue = DateTime.Today;
cb.AddField("FieldTwo", typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
cb.AddField("Field333", typeof(int));
cb.SaveToXml(@"dynamic.xml");
var loaded = (DelimitedClassBuilder)ClassBuilder.LoadFromXml(@"dynamic.xml");
Assert.AreEqual("Field1", loaded.FieldByIndex(0).FieldName);
Assert.AreEqual("FieldTwo", loaded.FieldByIndex(1).FieldName);
Assert.AreEqual("Field333", loaded.FieldByIndex(2).FieldName);
Assert.AreEqual("System.DateTime", loaded.FieldByIndex(0).FieldType);
Assert.AreEqual("System.String", loaded.FieldByIndex(1).FieldType);
Assert.AreEqual("System.Int32", loaded.FieldByIndex(2).FieldType);
Assert.AreEqual(QuoteMode.AlwaysQuoted, loaded.FieldByIndex(0).QuoteMode);
Assert.AreEqual(false, loaded.FieldByIndex(0).FieldQuoted);
Assert.AreEqual('"', loaded.FieldByIndex(1).QuoteChar);
Assert.AreEqual(true, loaded.FieldByIndex(1).FieldQuoted);
}
[Test]
[Category("Dynamic")]
public void SaveLoadXmlFileDelimited2()
{
var cb = new DelimitedClassBuilder("Customers", ",");
cb.IgnoreFirstLines = 1;
cb.IgnoreEmptyLines = true;
cb.AddField("Field1", typeof(DateTime));
cb.LastField.TrimMode = TrimMode.Both;
cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted;
cb.LastField.FieldNullValue = DateTime.Today;
cb.AddField("FieldTwo", typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
cb.AddField("Field333", typeof(int));
cb.SaveToXml(@"dynamic.xml");
mEngine = new FileHelperEngine(ClassBuilder.ClassFromXmlFile("dynamic.xml"));
Assert.AreEqual("Customers", mEngine.RecordType.Name);
Assert.AreEqual(3, mEngine.RecordType.GetFields().Length);
Assert.AreEqual("Field1", mEngine.RecordType.GetFields()[0].Name);
}
[Test]
public void SaveLoadXmlOptions()
{
var cbOrig = new DelimitedClassBuilder("Customers", ",");
cbOrig.AddField("Field1", typeof(DateTime));
cbOrig.AddField("FieldTwo", typeof(string));
cbOrig.RecordCondition.Condition = RecordCondition.ExcludeIfMatchRegex;
cbOrig.RecordCondition.Selector = @"\w*";
cbOrig.IgnoreCommentedLines.CommentMarker = "//";
cbOrig.IgnoreCommentedLines.InAnyPlace = false;
cbOrig.IgnoreEmptyLines = true;
cbOrig.IgnoreFirstLines = 123;
cbOrig.IgnoreLastLines = 456;
cbOrig.SealedClass = false;
cbOrig.SaveToXml(@"dynamic.xml");
cbOrig.SaveToXml(@"dynamic.xml");
ClassBuilder cb2 = ClassBuilder.LoadFromXml("dynamic.xml");
Assert.AreEqual("Customers", cb2.ClassName);
Assert.AreEqual(2, cb2.FieldCount);
Assert.AreEqual("Field1", cb2.Fields[0].FieldName);
Assert.AreEqual(RecordCondition.ExcludeIfMatchRegex, cb2.RecordCondition.Condition);
Assert.AreEqual(@"\w*", cb2.RecordCondition.Selector);
Assert.AreEqual("//", cb2.IgnoreCommentedLines.CommentMarker);
Assert.AreEqual(false, cb2.IgnoreCommentedLines.InAnyPlace);
Assert.AreEqual(false, cb2.SealedClass);
Assert.AreEqual(true, cb2.IgnoreEmptyLines);
Assert.AreEqual(123, cb2.IgnoreFirstLines);
Assert.AreEqual(456, cb2.IgnoreLastLines);
}
[Test]
public void SaveLoadXmlOptionsString()
{
var cbOrig = new DelimitedClassBuilder("Customers", ",");
cbOrig.AddField("Field1", typeof(DateTime));
cbOrig.AddField("FieldTwo", typeof(string));
cbOrig.RecordCondition.Condition = RecordCondition.ExcludeIfMatchRegex;
cbOrig.RecordCondition.Selector = @"\w*";
cbOrig.IgnoreCommentedLines.CommentMarker = "//";
cbOrig.IgnoreCommentedLines.InAnyPlace = false;
cbOrig.IgnoreEmptyLines = true;
cbOrig.IgnoreFirstLines = 123;
cbOrig.IgnoreLastLines = 456;
cbOrig.SealedClass = false;
string xml = cbOrig.SaveToXmlString();
ClassBuilder cb2 = ClassBuilder.LoadFromXmlString(xml);
Assert.AreEqual("Customers", cb2.ClassName);
Assert.AreEqual(2, cb2.FieldCount);
Assert.AreEqual("Field1", cb2.Fields[0].FieldName);
Assert.AreEqual(RecordCondition.ExcludeIfMatchRegex, cb2.RecordCondition.Condition);
Assert.AreEqual(@"\w*", cb2.RecordCondition.Selector);
Assert.AreEqual("//", cb2.IgnoreCommentedLines.CommentMarker);
Assert.AreEqual(false, cb2.IgnoreCommentedLines.InAnyPlace);
Assert.AreEqual(false, cb2.SealedClass);
Assert.AreEqual(true, cb2.IgnoreEmptyLines);
Assert.AreEqual(123, cb2.IgnoreFirstLines);
Assert.AreEqual(456, cb2.IgnoreLastLines);
}
public class MyCustomConverter : ConverterBase
{
public override object StringToField(string from)
{
if (from == "NaN")
return null;
else
return Convert.ToInt32(Int32.Parse(from));
}
public override string FieldToString(object fieldValue)
{
if (fieldValue == null)
return "NaN";
else
return fieldValue.ToString();
}
}
[Test]
[Category("Dynamic")]
public void ReadAsDataTableWithCustomConverter()
{
var fields = new[] {
"FirstName",
"LastName",
"StreetNumber",
"StreetAddress",
"Unit",
"City",
"State",
};
var cb = new DelimitedClassBuilder("ImportContact", ",");
// Add assembly reference
cb.AdditionalReferences.Add(typeof(MyCustomConverter).Assembly);
foreach (var f in fields)
{
cb.AddField(f, typeof(string));
cb.LastField.TrimMode = TrimMode.Both;
cb.LastField.FieldQuoted = false;
}
cb.AddField("Zip", typeof(int?));
cb.LastField.Converter.TypeName = "FileHelpers.Tests.Dynamic.DelimitedClassBuilderTests.MyCustomConverter";
mEngine = new FileHelperEngine(cb.CreateRecordClass());
string source = "Alex & Jen,Bouquet,1815,Bell Rd,, Batavia,OH,45103" + Environment.NewLine +
"Mark & Lisa K ,Arlinghaus,1817,Bell Rd,, Batavia,OH,NaN" + Environment.NewLine +
"Ed & Karen S ,Craycraft,1819,Bell Rd,, Batavia,OH,45103" + Environment.NewLine;
var contactData = mEngine.ReadString(source);
Assert.AreEqual(3, contactData.Length);
var zip = mEngine.RecordType.GetFields()[7];
Assert.AreEqual("Zip", zip.Name);
Assert.IsNull(zip.GetValue(contactData[1]));
Assert.AreEqual((decimal)45103, zip.GetValue(contactData[2]));
}
[Test]
[Category("Dynamic")]
public void LoopingFields()
{
var cb = new DelimitedClassBuilder("MyClass", ",");
string[] lst = { "fieldOne", "fieldTwo", "fieldThree" };
for (int i = 0; i < lst.Length; i++)
cb.AddField(lst[i], typeof(string));
mEngine = new FileHelperEngine(cb.CreateRecordClass());
}
[Test]
public void GotchClassName1()
{
new DelimitedClassBuilder(" MyClass", ",");
}
[Test]
public void GotchClassName2()
{
new DelimitedClassBuilder(" MyClass ", ",");
}
[Test]
public void GotchClassName3()
{
new DelimitedClassBuilder("MyClass ", ",");
}
[Test]
public void GotchClassName4()
{
new DelimitedClassBuilder("_MyClass2", ",");
}
[Test]
public void BadClassName1()
{
Assert.Throws<FileHelpersException>(()
=> new DelimitedClassBuilder("2yClass", ","));
}
[Test]
public void BadClassName2()
{
Assert.Throws<FileHelpersException>(()
=> new DelimitedClassBuilder("My Class", ","));
}
[Test]
public void BadClassName3()
{
Assert.Throws<FileHelpersException>(()
=> new DelimitedClassBuilder("", ","));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Schema
{
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlRoot("schema", Namespace = XmlSchema.Namespace)]
public class XmlSchema : XmlSchemaObject
{
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Namespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public const string Namespace = XmlReservedNs.NsXs;
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.InstanceNamespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public const string InstanceNamespace = XmlReservedNs.NsXsi;
private XmlSchemaForm _attributeFormDefault = XmlSchemaForm.None;
private XmlSchemaForm _elementFormDefault = XmlSchemaForm.None;
private XmlSchemaDerivationMethod _blockDefault = XmlSchemaDerivationMethod.None;
private XmlSchemaDerivationMethod _finalDefault = XmlSchemaDerivationMethod.None;
private string _targetNs;
private string _version;
private XmlSchemaObjectCollection _includes = new XmlSchemaObjectCollection();
private XmlSchemaObjectCollection _items = new XmlSchemaObjectCollection();
private string _id;
private XmlAttribute[] _moreAttributes;
// compiled info
private bool _isCompiled = false;
private bool _isCompiledBySet = false;
private bool _isPreprocessed = false;
private bool _isRedefined = false;
private int _errorCount = 0;
private XmlSchemaObjectTable _attributes;
private XmlSchemaObjectTable _attributeGroups = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _elements = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _types = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _groups = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _notations = new XmlSchemaObjectTable();
private XmlSchemaObjectTable _identityConstraints = new XmlSchemaObjectTable();
private static int s_globalIdCounter = -1;
private ArrayList _importedSchemas;
private ArrayList _importedNamespaces;
private int _schemaId = -1; //Not added to a set
private Uri _baseUri;
private bool _isChameleon;
private Hashtable _ids = new Hashtable();
private XmlDocument _document;
private XmlNameTable _nameTable;
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.XmlSchema"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchema() { }
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchema Read(TextReader reader, ValidationEventHandler validationEventHandler)
{
return Read(new XmlTextReader(reader), validationEventHandler);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchema Read(Stream stream, ValidationEventHandler validationEventHandler)
{
return Read(new XmlTextReader(stream), validationEventHandler);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchema Read(XmlReader reader, ValidationEventHandler validationEventHandler)
{
XmlNameTable nameTable = reader.NameTable;
Parser parser = new Parser(SchemaType.XSD, nameTable, new SchemaNames(nameTable), validationEventHandler);
try
{
parser.Parse(reader, null);
}
catch (XmlSchemaException e)
{
if (validationEventHandler != null)
{
validationEventHandler(null, new ValidationEventArgs(e));
}
else
{
throw;
}
return null;
}
return parser.XmlSchema;
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(Stream stream)
{
Write(stream, null);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(Stream stream, XmlNamespaceManager namespaceManager)
{
XmlTextWriter xmlWriter = new XmlTextWriter(stream, null);
xmlWriter.Formatting = Formatting.Indented;
Write(xmlWriter, namespaceManager);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(TextWriter writer)
{
Write(writer, null);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(TextWriter writer, XmlNamespaceManager namespaceManager)
{
XmlTextWriter xmlWriter = new XmlTextWriter(writer);
xmlWriter.Formatting = Formatting.Indented;
Write(xmlWriter, namespaceManager);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(XmlWriter writer)
{
Write(writer, null);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager)
{
XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema));
XmlSerializerNamespaces ns;
if (namespaceManager != null)
{
ns = new XmlSerializerNamespaces();
bool ignoreXS = false;
if (this.Namespaces != null)
{ //User may have set both nsManager and Namespaces property on the XmlSchema object
ignoreXS = this.Namespaces.Namespaces.ContainsKey("xs") || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs);
}
if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null &&
namespaceManager.LookupNamespace("xs") == null)
{
ns.Add("xs", XmlReservedNs.NsXs);
}
foreach (string prefix in namespaceManager)
{
if (prefix != "xml" && prefix != "xmlns")
{
ns.Add(prefix, namespaceManager.LookupNamespace(prefix));
}
}
}
else if (this.Namespaces != null && this.Namespaces.Count > 0)
{
Dictionary<string, string> serializerNS = this.Namespaces.Namespaces;
if (!serializerNS.ContainsKey("xs") && !serializerNS.ContainsValue(XmlReservedNs.NsXs))
{ //Prefix xs not defined AND schema namespace not already mapped to a prefix
serializerNS.Add("xs", XmlReservedNs.NsXs);
}
ns = this.Namespaces;
}
else
{
ns = new XmlSerializerNamespaces();
ns.Add("xs", XmlSchema.Namespace);
if (_targetNs != null && _targetNs.Length != 0)
{
ns.Add("tns", _targetNs);
}
}
serializer.Serialize(writer, this, ns);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compile"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")]
public void Compile(ValidationEventHandler validationEventHandler)
{
SchemaInfo sInfo = new SchemaInfo();
sInfo.SchemaType = SchemaType.XSD;
CompileSchema(null, null, sInfo, null, validationEventHandler, NameTable, false);
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compileq"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")]
public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver)
{
SchemaInfo sInfo = new SchemaInfo();
sInfo.SchemaType = SchemaType.XSD;
CompileSchema(null, resolver, sInfo, null, validationEventHandler, NameTable, false);
}
#pragma warning disable 618
internal bool CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, string ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, bool CompileContentModel)
{
//Need to lock here to prevent multi-threading problems when same schema is added to set and compiled
lock (this)
{
//Preprocessing
SchemaCollectionPreprocessor prep = new SchemaCollectionPreprocessor(nameTable, null, validationEventHandler);
prep.XmlResolver = resolver;
if (!prep.Execute(this, ns, true, xsc))
{
return false;
}
//Compilation
SchemaCollectionCompiler compiler = new SchemaCollectionCompiler(nameTable, validationEventHandler);
_isCompiled = compiler.Execute(this, schemaInfo, CompileContentModel);
this.SetIsCompiled(_isCompiled);
return _isCompiled;
}
}
#pragma warning restore 618
internal void CompileSchemaInSet(XmlNameTable nameTable, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings)
{
Debug.Assert(_isPreprocessed);
Compiler setCompiler = new Compiler(nameTable, eventHandler, null, compilationSettings);
setCompiler.Prepare(this, true);
_isCompiledBySet = setCompiler.Compile();
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeFormDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("attributeFormDefault"), DefaultValue(XmlSchemaForm.None)]
public XmlSchemaForm AttributeFormDefault
{
get { return _attributeFormDefault; }
set { _attributeFormDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.BlockDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("blockDefault"), DefaultValue(XmlSchemaDerivationMethod.None)]
public XmlSchemaDerivationMethod BlockDefault
{
get { return _blockDefault; }
set { _blockDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.FinalDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("finalDefault"), DefaultValue(XmlSchemaDerivationMethod.None)]
public XmlSchemaDerivationMethod FinalDefault
{
get { return _finalDefault; }
set { _finalDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.ElementFormDefault"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("elementFormDefault"), DefaultValue(XmlSchemaForm.None)]
public XmlSchemaForm ElementFormDefault
{
get { return _elementFormDefault; }
set { _elementFormDefault = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.TargetNamespace"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("targetNamespace", DataType = "anyURI")]
public string TargetNamespace
{
get { return _targetNs; }
set { _targetNs = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Version"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("version", DataType = "token")]
public string Version
{
get { return _version; }
set { _version = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Includes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlElement("include", typeof(XmlSchemaInclude)),
XmlElement("import", typeof(XmlSchemaImport)),
XmlElement("redefine", typeof(XmlSchemaRedefine))]
public XmlSchemaObjectCollection Includes
{
get { return _includes; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Items"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlElement("annotation", typeof(XmlSchemaAnnotation)),
XmlElement("attribute", typeof(XmlSchemaAttribute)),
XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroup)),
XmlElement("complexType", typeof(XmlSchemaComplexType)),
XmlElement("simpleType", typeof(XmlSchemaSimpleType)),
XmlElement("element", typeof(XmlSchemaElement)),
XmlElement("group", typeof(XmlSchemaGroup)),
XmlElement("notation", typeof(XmlSchemaNotation))]
public XmlSchemaObjectCollection Items
{
get { return _items; }
}
// Compiled info
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.IsCompiled"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public bool IsCompiled
{
get
{
return _isCompiled || _isCompiledBySet;
}
}
[XmlIgnore]
internal bool IsCompiledBySet
{
get { return _isCompiledBySet; }
set { _isCompiledBySet = value; }
}
[XmlIgnore]
internal bool IsPreprocessed
{
get { return _isPreprocessed; }
set { _isPreprocessed = value; }
}
[XmlIgnore]
internal bool IsRedefined
{
get { return _isRedefined; }
set { _isRedefined = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Attributes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Attributes
{
get
{
if (_attributes == null)
{
_attributes = new XmlSchemaObjectTable();
}
return _attributes;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeGroups"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable AttributeGroups
{
get
{
if (_attributeGroups == null)
{
_attributeGroups = new XmlSchemaObjectTable();
}
return _attributeGroups;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.SchemaTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable SchemaTypes
{
get
{
if (_types == null)
{
_types = new XmlSchemaObjectTable();
}
return _types;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Elements"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Elements
{
get
{
if (_elements == null)
{
_elements = new XmlSchemaObjectTable();
}
return _elements;
}
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Id"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("id", DataType = "ID")]
public string Id
{
get { return _id; }
set { _id = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.UnhandledAttributes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAnyAttribute]
public XmlAttribute[] UnhandledAttributes
{
get { return _moreAttributes; }
set { _moreAttributes = value; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Groups"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Groups
{
get { return _groups; }
}
/// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Notations"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaObjectTable Notations
{
get { return _notations; }
}
[XmlIgnore]
internal XmlSchemaObjectTable IdentityConstraints
{
get { return _identityConstraints; }
}
[XmlIgnore]
internal Uri BaseUri
{
get { return _baseUri; }
set
{
_baseUri = value;
}
}
[XmlIgnore]
// Please be careful with this property. Since it lazy initialized and its value depends on a global state
// if it gets called on multiple schemas in a different order the schemas will end up with different IDs
// Unfortunately the IDs are used to sort the schemas in the schema set and thus changing the IDs might change
// the order which would be a breaking change!!
// Simply put if you are planning to add or remove a call to this getter you need to be extra carefull
// or better don't do it at all.
internal int SchemaId
{
get
{
if (_schemaId == -1)
{
_schemaId = Interlocked.Increment(ref s_globalIdCounter);
}
return _schemaId;
}
}
[XmlIgnore]
internal bool IsChameleon
{
get { return _isChameleon; }
set { _isChameleon = value; }
}
[XmlIgnore]
internal Hashtable Ids
{
get { return _ids; }
}
[XmlIgnore]
internal XmlDocument Document
{
get { if (_document == null) _document = new XmlDocument(); return _document; }
}
[XmlIgnore]
internal int ErrorCount
{
get { return _errorCount; }
set { _errorCount = value; }
}
internal new XmlSchema Clone()
{
XmlSchema that = new XmlSchema();
that._attributeFormDefault = _attributeFormDefault;
that._elementFormDefault = _elementFormDefault;
that._blockDefault = _blockDefault;
that._finalDefault = _finalDefault;
that._targetNs = _targetNs;
that._version = _version;
that._includes = _includes;
that.Namespaces = this.Namespaces;
that._items = _items;
that.BaseUri = this.BaseUri;
SchemaCollectionCompiler.Cleanup(that);
return that;
}
internal XmlSchema DeepClone()
{
XmlSchema that = new XmlSchema();
that._attributeFormDefault = _attributeFormDefault;
that._elementFormDefault = _elementFormDefault;
that._blockDefault = _blockDefault;
that._finalDefault = _finalDefault;
that._targetNs = _targetNs;
that._version = _version;
that._isPreprocessed = _isPreprocessed;
//that.IsProcessing = this.IsProcessing; //Not sure if this is needed
//Clone its Items
for (int i = 0; i < _items.Count; ++i)
{
XmlSchemaObject newItem;
XmlSchemaComplexType complexType;
XmlSchemaElement element;
XmlSchemaGroup group;
if ((complexType = _items[i] as XmlSchemaComplexType) != null)
{
newItem = complexType.Clone(this);
}
else if ((element = _items[i] as XmlSchemaElement) != null)
{
newItem = element.Clone(this);
}
else if ((group = _items[i] as XmlSchemaGroup) != null)
{
newItem = group.Clone(this);
}
else
{
newItem = _items[i].Clone();
}
that.Items.Add(newItem);
}
//Clone Includes
for (int i = 0; i < _includes.Count; ++i)
{
XmlSchemaExternal newInclude = (XmlSchemaExternal)_includes[i].Clone();
that.Includes.Add(newInclude);
}
that.Namespaces = this.Namespaces;
//that.includes = this.includes; //Need to verify this is OK for redefines
that.BaseUri = this.BaseUri;
return that;
}
[XmlIgnore]
internal override string IdAttribute
{
get { return Id; }
set { Id = value; }
}
internal void SetIsCompiled(bool isCompiled)
{
_isCompiled = isCompiled;
}
internal override void SetUnhandledAttributes(XmlAttribute[] moreAttributes)
{
_moreAttributes = moreAttributes;
}
internal override void AddAnnotation(XmlSchemaAnnotation annotation)
{
_items.Add(annotation);
}
internal XmlNameTable NameTable
{
get { if (_nameTable == null) _nameTable = new System.Xml.NameTable(); return _nameTable; }
}
internal ArrayList ImportedSchemas
{
get
{
if (_importedSchemas == null)
{
_importedSchemas = new ArrayList();
}
return _importedSchemas;
}
}
internal ArrayList ImportedNamespaces
{
get
{
if (_importedNamespaces == null)
{
_importedNamespaces = new ArrayList();
}
return _importedNamespaces;
}
}
internal void GetExternalSchemasList(IList extList, XmlSchema schema)
{
Debug.Assert(extList != null && schema != null);
if (extList.Contains(schema))
{
return;
}
extList.Add(schema);
for (int i = 0; i < schema.Includes.Count; ++i)
{
XmlSchemaExternal ext = (XmlSchemaExternal)schema.Includes[i];
if (ext.Schema != null)
{
GetExternalSchemasList(extList, ext.Schema);
}
}
}
#if TRUST_COMPILE_STATE
internal void AddCompiledInfo(SchemaInfo schemaInfo) {
XmlQualifiedName itemName;
foreach (XmlSchemaElement element in elements.Values) {
itemName = element.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
if (schemaInfo.ElementDecls[itemName] == null) {
schemaInfo.ElementDecls.Add(itemName, element.ElementDecl);
}
}
foreach (XmlSchemaAttribute attribute in attributes.Values) {
itemName = attribute.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
if (schemaInfo.ElementDecls[itemName] == null) {
schemaInfo.AttributeDecls.Add(itemName, attribute.AttDef);
}
}
foreach (XmlSchemaType type in types.Values) {
itemName = type.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
XmlSchemaComplexType complexType = type as XmlSchemaComplexType;
if ((complexType == null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] == null) {
schemaInfo.ElementDeclsByType.Add(itemName, type.ElementDecl);
}
}
foreach (XmlSchemaNotation notation in notations.Values) {
itemName = notation.QualifiedName;
schemaInfo.TargetNamespaces[itemName.Namespace] = true;
SchemaNotation no = new SchemaNotation(itemName);
no.SystemLiteral = notation.System;
no.Pubid = notation.Public;
if (schemaInfo.Notations[itemName.Name] == null) {
schemaInfo.Notations.Add(itemName.Name, no);
}
}
}
#endif//TRUST_COMPILE_STATE
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Routing
{
public class ControllerActionEndpointDataSourceTest : ActionEndpointDataSourceBaseTest
{
[Fact]
public void Endpoints_Ignores_NonController()
{
// Arrange
var actions = new List<ActionDescriptor>
{
new ActionDescriptor
{
AttributeRouteInfo = new AttributeRouteInfo()
{
Template = "/test",
},
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Test" },
{ "controller", "Test" },
},
},
};
var mockDescriptorProvider = new Mock<IActionDescriptorCollectionProvider>();
mockDescriptorProvider.Setup(m => m.ActionDescriptors).Returns(new ActionDescriptorCollection(actions, 0));
var dataSource = (ControllerActionEndpointDataSource)CreateDataSource(mockDescriptorProvider.Object);
// Act
var endpoints = dataSource.Endpoints;
// Assert
Assert.Empty(endpoints);
}
[Fact]
public void Endpoints_MultipledActions_MultipleRoutes()
{
// Arrange
var actions = new List<ActionDescriptor>
{
new ControllerActionDescriptor
{
AttributeRouteInfo = new AttributeRouteInfo()
{
Template = "/test",
Name = "Test",
},
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Test" },
{ "controller", "Test" },
},
},
new ControllerActionDescriptor
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Index" },
{ "controller", "Home" },
},
}
};
var mockDescriptorProvider = new Mock<IActionDescriptorCollectionProvider>();
mockDescriptorProvider
.Setup(m => m.ActionDescriptors)
.Returns(new ActionDescriptorCollection(actions, 0));
var dataSource = (ControllerActionEndpointDataSource)CreateDataSource(mockDescriptorProvider.Object);
dataSource.AddRoute("1", "/1/{controller}/{action}/{id?}", null, null, null);
dataSource.AddRoute("2", "/2/{controller}/{action}/{id?}", null, null, null);
// Act
var endpoints = dataSource.Endpoints;
// Assert
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => !SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
});
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("1", e.Metadata.GetMetadata<IRouteNameMetadata>().RouteName);
Assert.Equal("1", e.Metadata.GetMetadata<IEndpointNameMetadata>().EndpointName);
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("2", e.Metadata.GetMetadata<IRouteNameMetadata>().RouteName);
Assert.Equal("2", e.Metadata.GetMetadata<IEndpointNameMetadata>().EndpointName);
},
e =>
{
Assert.Equal("/test", e.RoutePattern.RawText);
Assert.Same(actions[0], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Test", e.Metadata.GetMetadata<IRouteNameMetadata>().RouteName);
Assert.Equal("Test", e.Metadata.GetMetadata<IEndpointNameMetadata>().EndpointName);
});
}
[Fact]
public void Endpoints_AppliesConventions()
{
// Arrange
var actions = new List<ActionDescriptor>
{
new ControllerActionDescriptor
{
AttributeRouteInfo = new AttributeRouteInfo()
{
Template = "/test",
},
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Test" },
{ "controller", "Test" },
},
},
new ControllerActionDescriptor
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Index" },
{ "controller", "Home" },
},
}
};
var mockDescriptorProvider = new Mock<IActionDescriptorCollectionProvider>();
mockDescriptorProvider.Setup(m => m.ActionDescriptors).Returns(new ActionDescriptorCollection(actions, 0));
var dataSource = (ControllerActionEndpointDataSource)CreateDataSource(mockDescriptorProvider.Object);
dataSource.AddRoute("1", "/1/{controller}/{action}/{id?}", null, null, null);
dataSource.AddRoute("2", "/2/{controller}/{action}/{id?}", null, null, null);
dataSource.DefaultBuilder.Add((b) =>
{
b.Metadata.Add("Hi there");
});
// Act
var endpoints = dataSource.Endpoints;
// Assert
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => !SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Hi there", e.Metadata.GetMetadata<string>());
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Hi there", e.Metadata.GetMetadata<string>());
});
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Hi there", e.Metadata.GetMetadata<string>());
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Hi there", e.Metadata.GetMetadata<string>());
},
e =>
{
Assert.Equal("/test", e.RoutePattern.RawText);
Assert.Same(actions[0], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Hi there", e.Metadata.GetMetadata<string>());
});
}
[Fact]
public void Endpoints_AppliesConventions_CanOverideEndpointName()
{
// Arrange
var actions = new List<ActionDescriptor>
{
new ControllerActionDescriptor
{
AttributeRouteInfo = new AttributeRouteInfo()
{
Template = "/test",
Name = "Test",
},
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Test" },
{ "controller", "Test" },
},
},
new ControllerActionDescriptor
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Index" },
{ "controller", "Home" },
},
}
};
var mockDescriptorProvider = new Mock<IActionDescriptorCollectionProvider>();
mockDescriptorProvider
.Setup(m => m.ActionDescriptors)
.Returns(new ActionDescriptorCollection(actions, 0));
var dataSource = (ControllerActionEndpointDataSource)CreateDataSource(mockDescriptorProvider.Object);
dataSource.AddRoute("1", "/1/{controller}/{action}/{id?}", null, null, null);
dataSource.AddRoute("2", "/2/{controller}/{action}/{id?}", null, null, null);
dataSource.DefaultBuilder.Add(b =>
{
if (b.Metadata.OfType<ActionDescriptor>().FirstOrDefault()?.AttributeRouteInfo != null)
{
b.Metadata.Add(new EndpointNameMetadata("NewName"));
}
});
// Act
var endpoints = dataSource.Endpoints;
// Assert
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => !SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
});
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("1", e.Metadata.GetMetadata<IRouteNameMetadata>().RouteName);
Assert.Equal("1", e.Metadata.GetMetadata<IEndpointNameMetadata>().EndpointName);
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("2", e.Metadata.GetMetadata<IRouteNameMetadata>().RouteName);
Assert.Equal("2", e.Metadata.GetMetadata<IEndpointNameMetadata>().EndpointName);
},
e =>
{
Assert.Equal("/test", e.RoutePattern.RawText);
Assert.Same(actions[0], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Test", e.Metadata.GetMetadata<IRouteNameMetadata>().RouteName);
Assert.Equal("NewName", e.Metadata.GetMetadata<IEndpointNameMetadata>().EndpointName);
});
}
[Fact]
public void Endpoints_AppliesConventions_RouteSpecificMetadata()
{
// Arrange
var actions = new List<ActionDescriptor>
{
new ControllerActionDescriptor
{
AttributeRouteInfo = new AttributeRouteInfo()
{
Template = "/test",
},
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Test" },
{ "controller", "Test" },
},
},
new ControllerActionDescriptor
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "action", "Index" },
{ "controller", "Home" },
},
}
};
var mockDescriptorProvider = new Mock<IActionDescriptorCollectionProvider>();
mockDescriptorProvider.Setup(m => m.ActionDescriptors).Returns(new ActionDescriptorCollection(actions, 0));
var dataSource = (ControllerActionEndpointDataSource)CreateDataSource(mockDescriptorProvider.Object);
dataSource.AddRoute("1", "/1/{controller}/{action}/{id?}", null, null, null).Add(b => b.Metadata.Add("A"));
dataSource.AddRoute("2", "/2/{controller}/{action}/{id?}", null, null, null).Add(b => b.Metadata.Add("B"));
dataSource.DefaultBuilder.Add((b) =>
{
b.Metadata.Add("Hi there");
});
// Act
var endpoints = dataSource.Endpoints;
// Assert
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => !SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal(new[] { "Hi there", "A" }, e.Metadata.GetOrderedMetadata<string>());
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Same(actions[1], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal(new[] { "Hi there", "B" }, e.Metadata.GetOrderedMetadata<string>());
});
Assert.Collection(
endpoints.OfType<RouteEndpoint>().Where(e => SupportsLinkGeneration(e)).OrderBy(e => e.RoutePattern.RawText),
e =>
{
Assert.Equal("/1/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal(new[] { "Hi there", "A" }, e.Metadata.GetOrderedMetadata<string>());
},
e =>
{
Assert.Equal("/2/{controller}/{action}/{id?}", e.RoutePattern.RawText);
Assert.Null(e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal(new[] { "Hi there", "B" }, e.Metadata.GetOrderedMetadata<string>());
},
e =>
{
Assert.Equal("/test", e.RoutePattern.RawText);
Assert.Same(actions[0], e.Metadata.GetMetadata<ActionDescriptor>());
Assert.Equal("Hi there", e.Metadata.GetMetadata<string>());
});
}
private static bool SupportsLinkGeneration(RouteEndpoint endpoint)
{
return !(endpoint.Metadata.GetMetadata<ISuppressLinkGenerationMetadata>()?.SuppressLinkGeneration == true);
}
private protected override ActionEndpointDataSourceBase CreateDataSource(IActionDescriptorCollectionProvider actions, ActionEndpointFactory endpointFactory)
{
return new ControllerActionEndpointDataSource(
new ControllerActionEndpointDataSourceIdProvider(),
actions,
endpointFactory,
new OrderedEndpointsSequenceProvider());
}
protected override ActionDescriptor CreateActionDescriptor(
object values,
string pattern = null,
IList<object> metadata = null)
{
var action = new ControllerActionDescriptor();
foreach (var kvp in new RouteValueDictionary(values))
{
action.RouteValues[kvp.Key] = kvp.Value?.ToString();
}
if (!string.IsNullOrEmpty(pattern))
{
action.AttributeRouteInfo = new AttributeRouteInfo
{
Name = "test",
Template = pattern,
};
}
action.EndpointMetadata = metadata;
return action;
}
}
}
| |
// 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 AndNotInt32()
{
var test = new SimpleBinaryOpTest__AndNotInt32();
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__AndNotInt32
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Int32);
private static Int32[] _data1 = new Int32[ElementCount];
private static Int32[] _data2 = new Int32[ElementCount];
private static Vector256<Int32> _clsVar1;
private static Vector256<Int32> _clsVar2;
private Vector256<Int32> _fld1;
private Vector256<Int32> _fld2;
private SimpleBinaryOpTest__DataTable<Int32> _dataTable;
static SimpleBinaryOpTest__AndNotInt32()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AndNotInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int32>(_data1, _data2, new Int32[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.AndNot(
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.AndNot(
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.AndNot(
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int32>), typeof(Vector256<Int32>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr);
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndNotInt32();
var result = Avx2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int32> left, Vector256<Int32> right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[ElementCount];
Int32[] inArray2 = new Int32[ElementCount];
Int32[] outArray = new Int32[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[ElementCount];
Int32[] inArray2 = new Int32[ElementCount];
Int32[] outArray = new Int32[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
if ((int)(~left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((int)(~left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<Int32>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// This file contains Weapon and Ammo Class/"namespace" helper methods as well
// as hooks into the inventory system. These functions are not attached to a
// specific C++ class or datablock, but define a set of methods which are part
// of dynamic namespaces "class". The Items include these namespaces into their
// scope using the ItemData and ItemImageData "className" variable.
// ----------------------------------------------------------------------------
// All ShapeBase images are mounted into one of 8 slots on a shape. This weapon
// system assumes all primary weapons are mounted into this specified slot:
$WeaponSlot = 0;
// ----------------------------------------------------------------------------
// Weapon Order
// ----------------------------------------------------------------------------
// This is a simple means of handling easy adding & removal of weapons to the
// cycleWeapon function and still maintain a constant cycle order.
function WeaponOrder(%weapon, %slot)
{
if ($lastWeaponOrderSlot $= "")
$lastWeaponOrderSlot = -1;
// the order# slot to name index
$weaponOrderIndex[%slot] = %weapon;
// the weaponName to order# slot index
$weaponNameIndex[%weapon] = %slot;
// the last slot in the array
$lastWeaponOrderSlot++;
}
// Now create the Index/array by passing a name and order# for each weapon.
// NOTE: the first weapon needs to be 0.
WeaponOrder(SoldierGun, 0);
WeaponOrder(RocketLauncher, 1);
//-----------------------------------------------------------------------------
// Weapon Class
//-----------------------------------------------------------------------------
function Weapon::onUse(%data, %obj)
{
// Default behavior for all weapons is to mount it into the object's weapon
// slot, which is currently assumed to be slot 0
if (%obj.getMountedImage($WeaponSlot) != %data.image.getId())
{
serverPlay3D(WeaponUseSound, %obj.getTransform());
%obj.mountImage(%data.image, $WeaponSlot);
if (%obj.client)
{
if (%data.description !$= "")
messageClient(%obj.client, 'MsgWeaponUsed', '\c0%1 selected.', %data.description);
else
messageClient(%obj.client, 'MsgWeaponUsed', '\c0Weapon selected');
}
}
}
function Weapon::onPickup(%this, %obj, %shape, %amount)
{
// The parent Item method performs the actual pickup.
// For player's we automatically use the weapon if the
// player does not already have one in hand.
if (Parent::onPickup(%this, %obj, %shape, %amount))
{
serverPlay3D(WeaponPickupSound, %shape.getTransform());
if (%shape.getClassName() $= "Player" && %shape.getMountedImage($WeaponSlot) == 0)
%shape.use(%this);
}
}
function Weapon::onInventory(%this, %obj, %amount)
{
// Weapon inventory has changed, make sure there are no weapons
// of this type mounted if there are none left in inventory.
if (!%amount && (%slot = %obj.getMountSlot(%this.image)) != -1)
%obj.unmountImage(%slot);
}
//-----------------------------------------------------------------------------
// Weapon Image Class
//-----------------------------------------------------------------------------
function WeaponImage::onMount(%this, %obj, %slot)
{
// Images assume a false ammo state on load. We need to
// set the state according to the current inventory.
if(%this.ammo !$= "")
{
if (%obj.getInventory(%this.ammo))
{
%obj.setImageAmmo(%slot, true);
%currentAmmo = %obj.getInventory(%this.ammo);
}
else
%currentAmmo = 0;
%obj.client.RefreshWeaponHud(%currentAmmo, %this.item.previewImage, %this.item.reticle, %this.item.zoomReticle);
}
}
function WeaponImage::onUnmount(%this, %obj, %slot)
{
%obj.client.RefreshWeaponHud(0, "", "");
}
// ----------------------------------------------------------------------------
// A "generic" weaponimage onFire handler for most weapons. Can be overridden
// with an appropriate namespace method for any weapon that requires a custom
// firing solution.
// projectileSpread is a dynamic property declared in the weaponImage datablock
// for those weapons in which bullet skew is desired. Must be greater than 0,
// otherwise the projectile goes straight ahead as normal. lower values give
// greater accuracy, higher values increase the spread pattern.
// ----------------------------------------------------------------------------
function WeaponImage::onFire(%this, %obj, %slot)
{
//echo("\c4WeaponImage::onFire( "@%this.getName()@", "@%obj.client.nameBase@", "@%slot@" )");
// Decrement inventory ammo. The image's ammo state is updated
// automatically by the ammo inventory hooks.
if ( !%this.infiniteAmmo )
%obj.decInventory(%this.ammo, 1);
if (%this.projectileSpread)
{
// We'll need to "skew" this projectile a little bit. We start by
// getting the straight ahead aiming point of the gun
%vec = %obj.getMuzzleVector(%slot);
// Then we'll create a spread matrix by randomly generating x, y, and z
// points in a circle
for(%i = 0; %i < 3; %i++)
%matrix = %matrix @ (getRandom() - 0.5) * 2 * 3.1415926 * %this.projectileSpread @ " ";
%mat = MatrixCreateFromEuler(%matrix);
// Which we'll use to alter the projectile's initial vector with
%muzzleVector = MatrixMulVector(%mat, %vec);
}
else
{
// Weapon projectile doesn't have a spread factor so we fire it using
// the straight ahead aiming point of the gun
%muzzleVector = %obj.getMuzzleVector(%slot);
}
// Get the player's velocity, we'll then add it to that of the projectile
%objectVelocity = %obj.getVelocity();
%muzzleVelocity = VectorAdd(
VectorScale(%muzzleVector, %this.projectile.muzzleVelocity),
VectorScale(%objectVelocity, %this.projectile.velInheritFactor));
// Create the projectile object
%p = new (%this.projectileType)()
{
dataBlock = %this.projectile;
initialVelocity = %muzzleVelocity;
initialPosition = %obj.getMuzzlePoint(%slot);
sourceObject = %obj;
sourceSlot = %slot;
client = %obj.client;
};
MissionCleanup.add(%p);
return %p;
}
// ----------------------------------------------------------------------------
// A "generic" weaponimage onAltFire handler for most weapons. Can be
// overridden with an appropriate namespace method for any weapon that requires
// a custom firing solution.
// ----------------------------------------------------------------------------
function WeaponImage::onAltFire(%this, %obj, %slot)
{
//echo("\c4WeaponImage::onAltFire("@%this.getName()@", "@%obj.client.nameBase@", "@%slot@")");
// Decrement inventory ammo. The image's ammo state is updated
// automatically by the ammo inventory hooks.
%obj.decInventory(%this.ammo, 1);
if (%this.altProjectileSpread)
{
// We'll need to "skew" this projectile a little bit. We start by
// getting the straight ahead aiming point of the gun
%vec = %obj.getMuzzleVector(%slot);
// Then we'll create a spread matrix by randomly generating x, y, and z
// points in a circle
for(%i = 0; %i < 3; %i++)
%matrix = %matrix @ (getRandom() - 0.5) * 2 * 3.1415926 * %this.altProjectileSpread @ " ";
%mat = MatrixCreateFromEuler(%matrix);
// Which we'll use to alter the projectile's initial vector with
%muzzleVector = MatrixMulVector(%mat, %vec);
}
else
{
// Weapon projectile doesn't have a spread factor so we fire it using
// the straight ahead aiming point of the gun.
%muzzleVector = %obj.getMuzzleVector(%slot);
}
// Get the player's velocity, we'll then add it to that of the projectile
%objectVelocity = %obj.getVelocity();
%muzzleVelocity = VectorAdd(
VectorScale(%muzzleVector, %this.altProjectile.muzzleVelocity),
VectorScale(%objectVelocity, %this.altProjectile.velInheritFactor));
// Create the projectile object
%p = new (%this.projectileType)()
{
dataBlock = %this.altProjectile;
initialVelocity = %muzzleVelocity;
initialPosition = %obj.getMuzzlePoint(%slot);
sourceObject = %obj;
sourceSlot = %slot;
client = %obj.client;
};
MissionCleanup.add(%p);
return %p;
}
// ----------------------------------------------------------------------------
// A "generic" weaponimage onWetFire handler for most weapons. Can be
// overridden with an appropriate namespace method for any weapon that requires
// a custom firing solution.
// ----------------------------------------------------------------------------
function WeaponImage::onWetFire(%this, %obj, %slot)
{
//echo("\c4WeaponImage::onWetFire("@%this.getName()@", "@%obj.client.nameBase@", "@%slot@")");
// Decrement inventory ammo. The image's ammo state is updated
// automatically by the ammo inventory hooks.
%obj.decInventory(%this.ammo, 1);
if (%this.wetProjectileSpread)
{
// We'll need to "skew" this projectile a little bit. We start by
// getting the straight ahead aiming point of the gun
%vec = %obj.getMuzzleVector(%slot);
// Then we'll create a spread matrix by randomly generating x, y, and z
// points in a circle
for(%i = 0; %i < 3; %i++)
%matrix = %matrix @ (getRandom() - 0.5) * 2 * 3.1415926 * %this.wetProjectileSpread @ " ";
%mat = MatrixCreateFromEuler(%matrix);
// Which we'll use to alter the projectile's initial vector with
%muzzleVector = MatrixMulVector(%mat, %vec);
}
else
{
// Weapon projectile doesn't have a spread factor so we fire it using
// the straight ahead aiming point of the gun.
%muzzleVector = %obj.getMuzzleVector(%slot);
}
// Get the player's velocity, we'll then add it to that of the projectile
%objectVelocity = %obj.getVelocity();
%muzzleVelocity = VectorAdd(
VectorScale(%muzzleVector, %this.wetProjectile.muzzleVelocity),
VectorScale(%objectVelocity, %this.wetProjectile.velInheritFactor));
// Create the projectile object
%p = new (%this.projectileType)()
{
dataBlock = %this.wetProjectile;
initialVelocity = %muzzleVelocity;
initialPosition = %obj.getMuzzlePoint(%slot);
sourceObject = %obj;
sourceSlot = %slot;
client = %obj.client;
};
MissionCleanup.add(%p);
return %p;
}
//-----------------------------------------------------------------------------
// Ammmo Class
//-----------------------------------------------------------------------------
function Ammo::onPickup(%this, %obj, %shape, %amount)
{
// The parent Item method performs the actual pickup.
if (Parent::onPickup(%this, %obj, %shape, %amount))
serverPlay3D(AmmoPickupSound, %shape.getTransform());
}
function Ammo::onInventory(%this, %obj, %amount)
{
// The ammo inventory state has changed, we need to update any
// mounted images using this ammo to reflect the new state.
for (%i = 0; %i < 8; %i++)
{
if ((%image = %obj.getMountedImage(%i)) > 0)
if (isObject(%image.ammo) && %image.ammo.getId() == %this.getId())
{
%obj.setImageAmmo(%i, %amount != 0);
%currentAmmo = %obj.getInventory(%this);
%obj.client.setAmmoAmountHud(%currentAmmo);
}
}
}
// ----------------------------------------------------------------------------
// Weapon cycling
// ----------------------------------------------------------------------------
// Could make this player namespace only or even a vehicle namespace method,
// but for the time being....
function ShapeBase::cycleWeapon(%this, %direction)
{
%slot = -1;
if (%this.getMountedImage($WeaponSlot) != 0)
{
%curWeapon = %this.getMountedImage($WeaponSlot).item.getName();
%slot = $weaponNameIndex[%curWeapon];
}
if (%direction $= "prev")
{
// Previous weapon...
if (%slot == 0 || %slot == -1)
{
%requestedSlot = $lastWeaponOrderSlot;
%slot = 0;
}
else
%requestedSlot = %slot - 1;
}
else
{
// Next weapon...
if (%slot == $lastWeaponOrderSlot || %slot == -1)
{
%requestedSlot = 0;
%slot = $lastWeaponOrderSlot;
}
else
%requestedSlot = %slot + 1;
}
%newSlot = -1;
while (%requestedSlot != %slot)
{
if ($weaponOrderIndex[%requestedSlot] !$= "" && %this.hasInventory($weaponOrderIndex[%requestedSlot]) && %this.hasAmmo($weaponOrderIndex[%requestedSlot]))
{
// player has this weapon and it has ammo or doesn't need ammo
%newSlot = %requestedSlot;
break;
}
if (%direction $= "prev")
{
if (%requestedSlot == 0)
%requestedSlot = $lastWeaponOrderSlot;
else
%requestedSlot--;
}
else
{
if (%requestedSlot == $lastWeaponOrderSlot)
%requestedSlot = 0;
else
%requestedSlot++;
}
}
if (%newSlot != -1)
%this.use($weaponOrderIndex[%newSlot]);
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
// -----===== autogenerated code =====-----
// ReSharper disable All
// generator: BasicUnitValuesGenerator, UnitJsonConverterGenerator, UnitExtensionsGenerator
namespace iSukces.UnitedValues
{
[Serializable]
[JsonConverter(typeof(KelvinTemperatureJsonConverter))]
public partial struct KelvinTemperature : IUnitedValue<KelvinTemperatureUnit>, IEquatable<KelvinTemperature>, IComparable<KelvinTemperature>, IFormattable
{
/// <summary>
/// creates instance of KelvinTemperature
/// </summary>
/// <param name="value">value</param>
/// <param name="unit">unit</param>
public KelvinTemperature(decimal value, KelvinTemperatureUnit unit)
{
Value = value;
if (unit is null)
throw new NullReferenceException(nameof(unit));
Unit = unit;
}
public int CompareTo(KelvinTemperature other)
{
return UnitedValuesUtils.Compare<KelvinTemperature, KelvinTemperatureUnit>(this, other);
}
public KelvinTemperature ConvertTo(KelvinTemperatureUnit newUnit)
{
// generator : BasicUnitValuesGenerator.Add_ConvertTo
if (Unit.Equals(newUnit))
return this;
var basic = GetBaseUnitValue();
var factor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
return new KelvinTemperature(basic / factor, newUnit);
}
public bool Equals(KelvinTemperature other)
{
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public bool Equals(IUnitedValue<KelvinTemperatureUnit> other)
{
if (other is null)
return false;
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public override bool Equals(object other)
{
return other is IUnitedValue<KelvinTemperatureUnit> unitedValue ? Equals(unitedValue) : false;
}
public decimal GetBaseUnitValue()
{
// generator : BasicUnitValuesGenerator.Add_GetBaseUnitValue
if (Unit.Equals(BaseUnit))
return Value;
var factor = GlobalUnitRegistry.Factors.Get(Unit);
if (!(factor is null))
return Value * factor.Value;
throw new Exception("Unable to find multiplication for unit " + Unit);
}
public override int GetHashCode()
{
unchecked
{
return (Value.GetHashCode() * 397) ^ Unit?.GetHashCode() ?? 0;
}
}
public KelvinTemperature Round(int decimalPlaces)
{
return new KelvinTemperature(Math.Round(Value, decimalPlaces), Unit);
}
/// <summary>
/// Returns unit name
/// </summary>
public override string ToString()
{
return Value.ToString(CultureInfo.InvariantCulture) + Unit.UnitName;
}
/// <summary>
/// Returns unit name
/// </summary>
/// <param name="format"></param>
/// <param name="provider"></param>
public string ToString(string format, IFormatProvider provider = null)
{
return this.ToStringFormat(format, provider);
}
/// <summary>
/// implements - operator
/// </summary>
/// <param name="value"></param>
public static KelvinTemperature operator -(KelvinTemperature value)
{
return new KelvinTemperature(-value.Value, value.Unit);
}
public static DeltaKelvinTemperature operator -(KelvinTemperature left, KelvinTemperature right)
{
// generator : BasicUnitValuesGenerator.Add_Algebra_PlusMinus
if (left.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(left.Unit?.UnitName))
return new DeltaKelvinTemperature(-right.Value, right.Unit);
if (right.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(right.Unit?.UnitName))
return new DeltaKelvinTemperature(left.Value, left.Unit);
right = right.ConvertTo(left.Unit);
return new DeltaKelvinTemperature(left.Value - right.Value, left.Unit);
}
public static bool operator !=(KelvinTemperature left, KelvinTemperature right)
{
return left.CompareTo(right) != 0;
}
/// <summary>
/// implements * operator
/// </summary>
/// <param name="value"></param>
/// <param name="number"></param>
public static KelvinTemperature operator *(KelvinTemperature value, decimal number)
{
return new KelvinTemperature(value.Value * number, value.Unit);
}
/// <summary>
/// implements * operator
/// </summary>
/// <param name="number"></param>
/// <param name="value"></param>
public static KelvinTemperature operator *(decimal number, KelvinTemperature value)
{
return new KelvinTemperature(value.Value * number, value.Unit);
}
/// <summary>
/// implements / operator
/// </summary>
/// <param name="value"></param>
/// <param name="number"></param>
public static KelvinTemperature operator /(KelvinTemperature value, decimal number)
{
return new KelvinTemperature(value.Value / number, value.Unit);
}
public static decimal operator /(KelvinTemperature left, KelvinTemperature right)
{
// generator : BasicUnitValuesGenerator.Add_Algebra_MulDiv
right = right.ConvertTo(left.Unit);
return left.Value / right.Value;
}
public static KelvinTemperature operator +(KelvinTemperature left, DeltaKelvinTemperature right)
{
// generator : BasicUnitValuesGenerator.Add_Algebra_PlusMinus
if (left.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(left.Unit?.UnitName))
return new KelvinTemperature(right.Value, left.Unit);
if (right.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(right.Unit?.UnitName))
return left;
right = right.ConvertTo(left.Unit);
return new KelvinTemperature(left.Value + right.Value, left.Unit);
}
public static KelvinTemperature operator +(DeltaKelvinTemperature left, KelvinTemperature right)
{
// generator : BasicUnitValuesGenerator.Add_Algebra_PlusMinus
if (left.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(left.Unit?.UnitName))
return right;
if (right.Value.Equals(decimal.Zero) && string.IsNullOrEmpty(right.Unit?.UnitName))
return new KelvinTemperature(left.Value, right.Unit);
right = right.ConvertTo(left.Unit);
return new KelvinTemperature(left.Value + right.Value, left.Unit);
}
public static bool operator <(KelvinTemperature left, KelvinTemperature right)
{
return left.CompareTo(right) < 0;
}
public static bool operator <=(KelvinTemperature left, KelvinTemperature right)
{
return left.CompareTo(right) <= 0;
}
public static bool operator ==(KelvinTemperature left, KelvinTemperature right)
{
return left.CompareTo(right) == 0;
}
public static bool operator >(KelvinTemperature left, KelvinTemperature right)
{
return left.CompareTo(right) > 0;
}
public static bool operator >=(KelvinTemperature left, KelvinTemperature right)
{
return left.CompareTo(right) >= 0;
}
/// <summary>
/// creates kelvinTemperature from value in K
/// </summary>
/// <param name="value">KelvinTemperature value in K</param>
public static KelvinTemperature FromDegree(decimal value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new KelvinTemperature(value, KelvinTemperatureUnits.Degree);
}
/// <summary>
/// creates kelvinTemperature from value in K
/// </summary>
/// <param name="value">KelvinTemperature value in K</param>
public static KelvinTemperature FromDegree(double value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new KelvinTemperature((decimal)value, KelvinTemperatureUnits.Degree);
}
/// <summary>
/// creates kelvinTemperature from value in K
/// </summary>
/// <param name="value">KelvinTemperature value in K</param>
public static KelvinTemperature FromDegree(int value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new KelvinTemperature(value, KelvinTemperatureUnits.Degree);
}
/// <summary>
/// creates kelvinTemperature from value in K
/// </summary>
/// <param name="value">KelvinTemperature value in K</param>
public static KelvinTemperature FromDegree(long value)
{
// generator : BasicUnitValuesGenerator.Add_FromMethods
return new KelvinTemperature(value, KelvinTemperatureUnits.Degree);
}
public static KelvinTemperature Parse(string value)
{
// generator : BasicUnitValuesGenerator.Add_Parse
var parseResult = CommonParse.Parse(value, typeof(KelvinTemperature));
return new KelvinTemperature(parseResult.Value, new KelvinTemperatureUnit(parseResult.UnitName));
}
/// <summary>
/// value
/// </summary>
public decimal Value { get; }
/// <summary>
/// unit
/// </summary>
public KelvinTemperatureUnit Unit { get; }
public static readonly KelvinTemperatureUnit BaseUnit = KelvinTemperatureUnits.Degree;
public static readonly KelvinTemperature Zero = new KelvinTemperature(0, BaseUnit);
}
public static partial class KelvinTemperatureExtensions
{
public static KelvinTemperature Sum(this IEnumerable<KelvinTemperature> items)
{
if (items is null)
return KelvinTemperature.Zero;
var c = items.ToArray();
if (c.Length == 0)
return KelvinTemperature.Zero;
if (c.Length == 1)
return c[0];
var unit = c[0].Unit;
var value = c.Aggregate(0m, (x, y) => x + y.ConvertTo(unit).Value);
return new KelvinTemperature(value, unit);
}
public static KelvinTemperature Sum(this IEnumerable<KelvinTemperature?> items)
{
if (items is null)
return KelvinTemperature.Zero;
return items.Where(a => a != null).Select(a => a.Value).Sum();
}
public static KelvinTemperature Sum<T>(this IEnumerable<T> items, Func<T, KelvinTemperature> map)
{
if (items is null)
return KelvinTemperature.Zero;
return items.Select(map).Sum();
}
}
public partial class KelvinTemperatureJsonConverter : AbstractUnitJsonConverter<KelvinTemperature, KelvinTemperatureUnit>
{
protected override KelvinTemperature Make(decimal value, string unit)
{
unit = unit?.Trim();
return new KelvinTemperature(value, string.IsNullOrEmpty(unit) ? KelvinTemperature.BaseUnit : new KelvinTemperatureUnit(unit));
}
protected override KelvinTemperature Parse(string txt)
{
return KelvinTemperature.Parse(txt);
}
}
}
| |
/*
* Magix - A Web Application Framework for Humans
* Copyright 2010 - 2014 - thomas@magixilluminate.com
* Magix is licensed as MITx11, see enclosed License.txt File for Details.
*/
using System;
using System.IO;
using System.Web;
using System.Threading;
using System.Configuration;
using System.Collections.Generic;
using Magix.Core;
namespace Magix.data
{
/*
* data storage
*/
internal static class Database
{
private static object _locker = new object();
private static object _transactionalLocker = new object();
private static string _dbPath;
private static Node _database;
private static Tuple<Guid, Node> _transaction = new Tuple<Guid, Node>(Guid.Empty, new Node());
#region [ -- initialization -- ]
internal static void Initialize()
{
lock (_locker)
{
lock (_transactionalLocker)
{
if (_dbPath != null)
return; // multiple initializations might occur
_dbPath = ConfigurationManager.AppSettings["magix.core.database-path"];
_database = new Node();
foreach (string idxDirectory in GetDirectories(_dbPath))
{
foreach (string idxFile in GetFiles(idxDirectory))
{
_database.Add(LoadFile(idxFile));
}
}
}
}
}
/*
* returns all directories within db path
*/
private static IEnumerable<string> GetDirectories(string directory)
{
Node directories = new Node();
directories["directory"].Value = directory;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.file.list-directories",
directories);
directories["directories"].Sort(
delegate(Node left, Node right)
{
int leftInt = int.Parse(left.Name.Replace(_dbPath, "").Substring(2));
int rightInt = int.Parse(right.Name.Replace(_dbPath, "").Substring(2));
return leftInt.CompareTo(rightInt);
});
foreach (Node idxDirectory in directories["directories"])
yield return idxDirectory.Name;
}
/*
* returns files within directory
*/
private static IEnumerable<string> GetFiles(string directory)
{
Node files = new Node();
files["filter"].Value = "db*.hl";
files["directory"].Value = directory;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.file.list-files",
files);
files["files"].Sort(
delegate(Node left, Node right)
{
int leftInt = int.Parse(left.Name.Replace(directory, "").Substring(3).Replace(".hl", ""));
int rightInt = int.Parse(right.Name.Replace(directory, "").Substring(3).Replace(".hl", ""));
return leftInt.CompareTo(rightInt);
});
foreach (Node idxFile in files["files"])
yield return idxFile.Name;
}
/*
* loads file as node
*/
private static Node LoadFile(string filename)
{
Node file = new Node();
file["file"].Value = filename;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.execute.code-2-node",
file);
file["node"].Name = filename;
return file[filename].UnTie();
}
#endregion
#region [ -- transactional support -- ]
/*
* creates a database transaction
*/
internal static void ExecuteTransaction(Node pars)
{
if (pars.Contains("_database-transaction"))
throw new ApplicationException("there is already an open transaction towards the database");
lock (_transactionalLocker)
{
_transaction = new Tuple<Guid, Node>(Guid.NewGuid(), _database.Clone());
pars["_database-transaction"].Value = _transaction.Item1;
try
{
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.execute",
pars);
}
finally
{
pars["_database-transaction"].UnTie();
Rollback(_transaction.Item1);
}
}
}
/*
* rolls back a transaction
*/
internal static void Rollback(Guid transaction)
{
if (_transaction.Item1 != transaction)
return; // already committed ...
_transaction = new Tuple<Guid, Node>(Guid.Empty, new Node());
}
/*
* commits the active transaction
*/
internal static void Commit(Node pars)
{
lock (_locker)
{
Guid transaction = pars["_database-transaction"].UnTie().Get<Guid>();
if (_transaction.Item1 != transaction)
throw new ApplicationException("transaction id mismatch in commit");
_database = _transaction.Item2;
_transaction = new Tuple<Guid, Node>(Guid.Empty, new Node());
// removing items that should be removed first
CommitRemoveEmptyFiles(_database);
// updating changed items
CommitUpdateChangedFiles(_database);
// adding new items
CommitSaveNewObjects(_database);
}
}
/*
* removing empty files from database in commit
*/
private static void CommitRemoveEmptyFiles(Node database)
{
List<Node> toBeRemoved = new List<Node>();
foreach (Node idxFileNode in database)
{
// removing empty files, unless they were added during this transaction
if (idxFileNode.Count == 0 && idxFileNode.Name != "added:")
toBeRemoved.Add(idxFileNode);
}
foreach (Node idxFileNode in toBeRemoved)
{
RemoveFileFromDatabase(idxFileNode);
}
}
/*
* updating changed files from database in commit
*/
private static void CommitUpdateChangedFiles(Node database)
{
foreach (Node idxFileNode in database)
{
// updating changed files, unless they have zero objects
if (idxFileNode.Name.StartsWith("changed:") && idxFileNode.Count > 0)
{
idxFileNode.Name = idxFileNode.Name.Substring(8);
SaveFileNodeToDisc(idxFileNode);
}
}
}
/*
* saving new objects into available files in commit
*/
private static void CommitSaveNewObjects(Node database)
{
List<Node> nodesToRemove = new List<Node>();
int objectsPerFile = int.Parse(ConfigurationManager.AppSettings["magix.core.database-objects-per-file"]);
foreach (Node idxFileNode in database)
{
// finding all objects in database that were added during this transaction
if (idxFileNode.Name == "added:")
{
// looping as long as we have more objects to add
Node availableNode = FindAvailableNode();
while (idxFileNode.Count > 0)
{
// making sure no files have more objects than what the database is configured to handle
while (availableNode.Count < objectsPerFile && idxFileNode.Count > 0)
{
availableNode.Add(idxFileNode[0].UnTie());
}
SaveFileNodeToDisc(availableNode);
availableNode = FindAvailableNode();
}
nodesToRemove.Add(idxFileNode);
break;
}
}
foreach (Node idxFileNode in nodesToRemove)
{
_database.Remove(idxFileNode);
}
}
#endregion
#region [ -- public methods -- ]
/*
* loads items from database
*/
internal static void Load(Node ip, Node prototype, int start, int end, Guid transaction, bool onlyId)
{
if (transaction != _transaction.Item1)
{
lock (_transactionalLocker)
{
Load(ip, prototype, start, end, transaction, onlyId);
}
}
lock (_locker)
{
int curMatchingItem = 0;
foreach (Node idxFileNode in GetDatabase())
{
foreach (Node idxObjectNode in idxFileNode)
{
// loading by prototype
if (idxObjectNode["value"].HasNodes(prototype))
{
if ((start == 0 || curMatchingItem >= start) && (end == -1 || curMatchingItem < end))
{
Node objectNode = new Node("object");
objectNode["id"].Value = idxObjectNode.Get<string>();
objectNode["created"].Value = idxObjectNode["created"].Value;
objectNode["revision-count"].Value = idxObjectNode["revision-count"].Value;
if (!onlyId)
objectNode["value"].AddRange(idxObjectNode["value"].Clone());
ip["objects"].Add(objectNode);
}
curMatchingItem += 1;
}
}
}
}
}
/*
* loads one item from database
*/
internal static void Load(Node ip, string id, Guid transaction)
{
if (transaction != _transaction.Item1)
{
lock (_transactionalLocker)
{
Load(ip, id, transaction);
}
}
lock (_locker)
{
foreach (Node idxFileNode in GetDatabase())
{
foreach (Node idxObjectNode in idxFileNode)
{
if (id == idxObjectNode.Get<string>())
{
// loading by id
ip["created"].Value = idxObjectNode["created"].Value;
ip["revision-count"].Value = idxObjectNode["revision-count"].Value;
ip["value"].AddRange(idxObjectNode["value"].Clone());
return;
}
}
}
}
}
/*
* counts records in database
*/
internal static int CountRecords(Node ip, Node prototype, Guid transaction)
{
if (transaction != _transaction.Item1)
{
lock (_transactionalLocker)
{
CountRecords(ip, prototype, transaction);
}
}
lock (_locker)
{
int count = 0;
foreach (Node idxFileNode in GetDatabase())
{
foreach (Node idxObjectNode in idxFileNode)
{
if (prototype == null)
count += 1;
else if (idxObjectNode["value"].HasNodes(prototype))
count += 1;
}
}
return count;
}
}
/*
* saves an object by its id
*/
internal static void SaveById(Node value, string id, Guid transaction)
{
if (transaction != _transaction.Item1)
{
lock (_transactionalLocker)
{
SaveById(value, id, transaction);
}
}
lock (_locker)
{
value.Value = id;
value.Name = "id";
// checking to see if object already exist
foreach (Node idxFileNode in GetDatabase())
{
foreach (Node idxObjectNode in idxFileNode)
{
if (idxObjectNode.Get<string>() == id)
{
idxObjectNode["value"].UnTie();
idxObjectNode["updated"].Value = DateTime.Now;
idxObjectNode["revision-count"].Value = idxObjectNode["revision-count"].Get<decimal>() + 1M;
idxObjectNode["value"].AddRange(value);
SaveFileNodeToDisc(idxFileNode);
return;
}
}
}
// object didn't exist, saving new object
SaveNewObject(value, id);
}
}
/*
* saves a new object
*/
internal static string SaveNewObject(Node value, Guid transaction)
{
if (transaction != _transaction.Item1)
{
lock (_transactionalLocker)
{
SaveNewObject(value, transaction);
}
}
lock (_locker)
{
return SaveNewObject(value, null);
}
}
/*
* removes items from database according to prototype
*/
internal static int RemoveByPrototype(Node prototype, Guid transaction)
{
if (transaction != _transaction.Item1)
{
lock (_transactionalLocker)
{
return RemoveByPrototype(prototype, transaction);
}
}
lock (_locker)
{
List<Node> nodesToRemove = new List<Node>();
List<string> filesToUpdate = new List<string>();
foreach (Node idxFileNode in GetDatabase())
{
foreach (Node idxObjectNode in idxFileNode)
{
if (idxObjectNode["value"].HasNodes(prototype))
{
nodesToRemove.Add(idxObjectNode);
if (!filesToUpdate.Exists(
delegate(string idxFileName)
{
return idxFileName == idxFileNode.Name;
}))
filesToUpdate.Add(idxFileNode.Name);
}
}
}
foreach (Node idx in nodesToRemove)
idx.UnTie();
foreach (string idx in filesToUpdate)
{
if (GetDatabase()[idx].Count == 0)
RemoveFileFromDatabase(GetDatabase()[idx]);
else
SaveFileNodeToDisc(GetDatabase()[idx]);
}
return nodesToRemove.Count;
}
}
/*
* removes a node by its id
*/
internal static int RemoveById(string id, Guid transaction)
{
if (transaction != _transaction.Item1)
{
lock (_transactionalLocker)
{
return RemoveById(id, transaction);
}
}
lock (_locker)
{
foreach (Node idxFileNode in GetDatabase())
{
foreach (Node idxObjectNode in idxFileNode)
{
if (idxObjectNode.Get<string>() == id)
{
idxObjectNode.UnTie();
if (idxFileNode.Count > 0)
SaveFileNodeToDisc(idxFileNode);
else
RemoveFileFromDatabase(idxFileNode);
return 1;
}
}
}
return 0;
}
}
#endregion
#region [ -- private helpers -- ]
/*
* returns database reference
*/
private static Node GetDatabase()
{
if (_transaction.Item1 != Guid.Empty)
return _transaction.Item2; // we have an open transaction
// no open transaction
return _database;
}
/*
* saves a new object
*/
private static string SaveNewObject(Node value, string id)
{
if (string.IsNullOrEmpty(id))
id = Guid.NewGuid().ToString().Replace("-", "");
Node newObject = new Node("id", id);
newObject["created"].Value = DateTime.Now;
newObject["revision-count"].Value = 1M;
newObject["value"].AddRange(value.Clone());
Node availableFileNode = FindAvailableNode();
availableFileNode.Add(newObject);
SaveFileNodeToDisc(availableFileNode);
return id;
}
/*
* saves a file node to disc
*/
private static void SaveFileNodeToDisc(Node fileNode)
{
if (_transaction.Item1 != Guid.Empty)
{
// not saving to disc if we have an open transaction
if (fileNode.Name.StartsWith("changed:") || fileNode.Name == "added:")
return;
fileNode.Name = "changed:" + fileNode.Name;
return;
}
// transforming node to code
Node codeNode = new Node();
codeNode["node"].Value = fileNode;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.execute.node-2-code",
codeNode);
// saving file
Node fileSaveNode = new Node();
fileSaveNode["file"].Value = fileNode.Name;
fileSaveNode["value"].Value = codeNode["code"].Get<string>();
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.file.save",
fileSaveNode);
}
/*
* returns next available filename
*/
private static string FindAvailableNewFileName()
{
int maxFilesPerDirectory = int.Parse(ConfigurationManager.AppSettings["magix.core.database-files-per-directory"]);
// checking to see if we can use existing directory
List<string> directoryList = new List<string>(GetDirectories(_dbPath));
foreach (string idxDirectory in directoryList)
{
List<string> filesList = new List<string>(GetFiles(idxDirectory));
if (filesList.Count >= maxFilesPerDirectory)
continue;
for (int idxNo = 0; idxNo < filesList.Count; idxNo++)
{
if (!filesList.Exists(
delegate(string file)
{
return file == idxDirectory + "/db" + idxNo + ".hl";
}))
return idxDirectory + "/db" + idxNo + ".hl";
}
return idxDirectory + "/db" + filesList.Count + ".hl";
}
// didn't find an available filename, without creating new directory
for (int idxNo = 0; idxNo < directoryList.Count; idxNo++)
{
if (!directoryList.Exists(
delegate(string dirNode)
{
return dirNode == _dbPath + "db" + idxNo;
}))
{
CreateNewDirectory(_dbPath + "db" + idxNo);
return _dbPath + "db" + idxNo + "/db0.hl";
}
}
CreateNewDirectory(_dbPath + "db" + directoryList.Count);
return _dbPath + "db" + directoryList.Count + "/db0.hl";
}
/*
* helper to create directory
*/
private static void CreateNewDirectory(string directory)
{
Node createDirectoryNode = new Node();
createDirectoryNode["directory"].Value = directory;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.file.create-directory",
createDirectoryNode);
}
/*
* returns an available file node
*/
private static Node FindAvailableNode()
{
if (_transaction.Item1 != Guid.Empty)
{
// returning our "collection node" if we have an open transaction
return GetDatabase()["added:"];
}
int objectsPerFile = int.Parse(ConfigurationManager.AppSettings["magix.core.database-objects-per-file"]);
foreach (Node idxFileNode in _database)
{
if (idxFileNode.Count < objectsPerFile && !idxFileNode.Name.StartsWith("added:"))
return idxFileNode;
}
// no node existed, creating new
Node newNode = new Node(FindAvailableNewFileName());
_database.Add(newNode);
return newNode;
}
/*
* removes a file node from database
*/
private static void RemoveFileFromDatabase(Node fileObject)
{
if (_transaction.Item1 != Guid.Empty)
{
// not removing from disc if we have an open transaction
return;
}
Node deleteFileNode = new Node();
deleteFileNode["file"].Value = fileObject.Name;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.file.delete",
deleteFileNode);
string directoryName = fileObject.Name.Substring(0, fileObject.Name.LastIndexOf("/"));
// checking to see if directory is empty
List<string> files = new List<string>(GetFiles(directoryName));
if (files.Count == 0)
{
// deleting directory
Node deleteDirectory = new Node();
deleteDirectory["directory"].Value = directoryName;
ActiveEvents.Instance.RaiseActiveEvent(
typeof(Database),
"magix.file.delete-directory",
deleteDirectory);
}
fileObject.UnTie();
}
#endregion
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerController : MonoBehaviour {
//System
public LevelManager levelManager;
private RuntimePlatform platform;
private CharacterController controller;
//Movement
public float speedMax;
public float jump;
public float jet;
public float maxJet;
public float gravity;
private float speed;
private bool isControlable;
private Vector3 moveDirection = Vector3.zero;
//SFX & Animation
public float barSpeed;
public GameObject FX, jetBeam, flames;
public AudioClip[] sounds;
private AudioSource audioSource;
private ParticleSystem[] flamesFX;
private ParticleSystem[] jetBeamFX;
private Animator anim;
//Shield
public Color positiveShieldColor;
public Color negativeShieldColor;
public float shieldColorLerp;
public GameObject personalShield;
private MeshRenderer shield;
private SphereCollider shieldSphere;
private float timeHitted;
//Drone
private bool hasDrone;
//Magnet
public GameObject magnet;
private bool hasMagnet;
//Dead self instance
public GameObject deadRobot;
//Other variables
public float fuelLossRate;
private float magnetTimer;
private bool isDead;
private float fuel;
private float energy;
private int score;
//GUI
private Image fuelBar;
private Image shieldBar;
private Button menuButton;
private Text scoreText;
private Rect menu;
//Debug
private bool immortal;
// Draw rectangle on pause menu position to not jump when clicked/touched menu button
void OnGUI(){
menu = new Rect (menuButton.transform.position.x, menuButton.transform.position.y, Screen.width, Screen.height);
}
void Start () {
speed = speedMax;
immortal = false;
isControlable = false;
fuelBar = FindObjectOfType<UIManager> ().GetFuelBar ();
shieldBar = FindObjectOfType<UIManager> ().GetShieldBar ();
menuButton = FindObjectOfType<GameMenuController> ().GetMenuButton ();
scoreText = FindObjectOfType<UIManager> ().GetScoreText ();
platform = Application.platform;
controller = GetComponent<CharacterController>();
audioSource = GetComponent<AudioSource> ();
anim = GetComponent<Animator> ();
fuel = 100f;
energy = 100f;
isDead = false;
Time.timeScale = 1f;
FX.SetActive (true);
flamesFX = flames.GetComponentsInChildren<ParticleSystem> ();
jetBeamFX = jetBeam.GetComponentsInChildren<ParticleSystem> ();
Unjet ();
shieldSphere = personalShield.GetComponent<SphereCollider> ();
shield = personalShield.GetComponent<MeshRenderer> ();
hasDrone = PlayerPrefsManager.GetDrone ();
hasMagnet = PlayerPrefsManager.GetMagnet ();
score = PlayerPrefsManager.GetScore ();
scoreText.text = score.ToString ();
}
void Update () {
if(Time.timeScale <= 0){
audioSource.Pause ();
} else {
if (energy > 0) {
shieldSphere.enabled = true;
} else {
shieldSphere.enabled = false;
}
if (isDead) {
Death ();
} else {
if (controller.isGrounded || (controller.collisionFlags & CollisionFlags.Below) != 0) {
Unjet ();
anim.SetBool ("inAir", false);
anim.SetBool ("jump", false);
if(!audioSource.isPlaying || audioSource.clip != sounds [0]){
audioSource.loop = true;
audioSource.clip = sounds [0];
audioSource.Play ();
}
} else {
anim.SetBool ("inAir", true);
// anim.SetBool ("jump", false);
}
moveDirection.z = speed;
moveDirection.y -= controller.isGrounded ? 0 : gravity * Time.deltaTime;
if (isControlable) {
if (platform == RuntimePlatform.Android || platform == RuntimePlatform.IPhonePlayer) {
if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began && controller.isGrounded && !menu.Contains (Input.GetTouch (0).position)) {
Jump ();
} else if ((controller.collisionFlags & CollisionFlags.Above) != 0 && !controller.isGrounded && moveDirection.y > 0) {
moveDirection.y = 0f;
} else if (controller.velocity.y <= maxJet && Input.touchCount > 0 && fuel > 0 && (controller.collisionFlags & CollisionFlags.Above) == 0 && !menu.Contains (Input.GetTouch (0).position)) {
Jet ();
} else if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended) {
Unjet ();
} else if (Input.touchCount == 0 || controller.velocity.y < maxJet || fuel <= 0) {
Unjet ();
}
} else {
if (Input.GetMouseButtonDown (0) && controller.isGrounded && !menu.Contains (Input.mousePosition)) {
Jump ();
} else if ((controller.collisionFlags & CollisionFlags.Above) != 0 && !controller.isGrounded && moveDirection.y > 0) {
moveDirection.y = 0f;
} else if (controller.velocity.y <= maxJet && Input.GetMouseButton (0) && fuel > 0 && (controller.collisionFlags & CollisionFlags.Above) == 0 && !menu.Contains (Input.mousePosition)) {
Jet ();
} else if (Input.GetMouseButtonUp (0) || controller.velocity.y < maxJet || fuel <= 0) {
Unjet ();
}
}
}
// if (magnetTimer > 0) {
// foreach (GameObject obj in GameObject.FindGameObjectsWithTag ("Pick Up")) {
// if (Vector3.Distance (obj.transform.position, transform.position) <= 5) {
// PickUp (obj);
// }
// }
// magnetTimer -= Time.deltaTime;
// }
if (!isDead)
controller.Move (moveDirection * Time.deltaTime);
}
// fuelBar.fillAmount = Mathf.Lerp (0.0f, 1.0f, fuel / 100);
// fuelBar.fillAmount = Mathf.Lerp (0.0f, 1.0f, fuel / 100);
// if (fuelBar.fillAmount < fuel / 100) {
// fuelBar.fillAmount += Time.deltaTime * barSpeed;
// } else if (fuelBar.fillAmount > fuel / 100){
// fuelBar.fillAmount -= Time.deltaTime * barSpeed;
// }
// if (shieldBar.fillAmount < energy / 100) {
// shieldBar.fillAmount += Time.deltaTime * barSpeed;
// } else if (shieldBar.fillAmount > energy / 100){
// shieldBar.fillAmount -= Time.deltaTime * barSpeed;
// }
if (fuelBar.fillAmount != fuel / 100) {
fuelBar.fillAmount = Mathf.Lerp (fuelBar.fillAmount, fuel / 100, barSpeed * Time.deltaTime);
}
if (shieldBar.fillAmount != energy / 100) {
shieldBar.fillAmount = Mathf.Lerp (shieldBar.fillAmount, energy / 100, barSpeed * Time.deltaTime);
}
if (shield.material.GetColor ("_TintColor").a > 0f) {
Color tempColor = shield.material.GetColor ("_TintColor");
tempColor.a = 0f;
float lerp = (Time.time - timeHitted) / shieldColorLerp;
Color newShieldColor = Color.Lerp (shield.material.GetColor ("_TintColor"), tempColor, lerp);
shield.material.SetColor ("_TintColor", newShieldColor);
}
}
}
void Jump(){
moveDirection.y = jump;
anim.SetBool ("jump", true);
anim.SetBool ("inAir", true);
audioSource.loop = false;
audioSource.clip = sounds [1];
audioSource.Play ();
}
void Jet(){
moveDirection.y += jet * Time.deltaTime;
fuel -= fuelLossRate * Time.deltaTime;
fuel = Mathf.Clamp (fuel, 0, 100);
foreach (ParticleSystem system in flamesFX) {
var em = system.emission;
em.enabled = false;
}
foreach (ParticleSystem system in jetBeamFX) {
var em = system.emission;
em.enabled = true;
}
if (!audioSource.isPlaying || audioSource.clip != sounds [2]) {
audioSource.loop = true;
audioSource.clip = sounds [2];
audioSource.PlayOneShot (sounds [2]);
}
}
void Unjet(){
foreach (ParticleSystem system in flamesFX) {
var em = system.emission;
em.enabled = true;
}
foreach (ParticleSystem system in jetBeamFX) {
var em = system.emission;
em.enabled = false;
}
if (audioSource.isPlaying && audioSource.clip == sounds [2]) {
audioSource.Stop ();
}
}
void OnTriggerEnter (Collider other){
if (other.CompareTag ("Start")) {
FindObjectOfType<CameraController> ().Follow ();
isControlable = true;
} else if (other.CompareTag ("Finish")) {
PlayerPrefsManager.SetScore (score);
levelManager.UnlockNextLevel ();
PickupsController pickups = FindObjectOfType<PickupsController> ();
if(pickups){
pickups.SaveItemsState ();
}
EndLevel ();
} else if (other.CompareTag ("Freeze")) {
speed = 0;
} else if (other.CompareTag ("Drone") && hasDrone) {
other.GetComponent<DroneController> ().Activate (gameObject);
} else if (other.CompareTag ("Magnet") && hasMagnet) {
magnet.GetComponent<MagnetController> ().Activate ();
} else if (other.CompareTag ("Pick Up")) {
ApplyGain("Score", other.gameObject.GetComponent<PickUpController> ().ammount);
} else if (other.CompareTag ("Void")) {
isDead = true;
}
}
void OnTriggerExit (Collider other){
if (other.CompareTag ("Freeze")) {
speed = speedMax;
}
}
public void ApplyGain(string type, float ammount){
switch (type) {
case "Shield":
energy += ammount;
energy = Mathf.Clamp (energy, 0, 100);
ShieldFlash (true);
break;
case "Fuel":
fuel += ammount;
fuel = Mathf.Clamp (fuel, 0, 100);
break;
case "Score":
score += (int)ammount;
score = Mathf.Clamp (score, 0, 9999);
scoreText.text = score.ToString ();
break;
}
}
public void ApplyDamage(float dmg){
if (immortal)
return;
if (energy > 0) {
ShieldFlash (false);
energy -= dmg;
energy = Mathf.Clamp (energy, 0, 100);
} else
isDead = true;
}
void ShieldFlash(bool isPositive){
Color newShieldColor;
if (isPositive) {
newShieldColor = positiveShieldColor;
} else {
newShieldColor = negativeShieldColor;
}
// newShieldColor.a = 1.0f;
newShieldColor.a = energy / 100;
shield.material.SetColor ("_TintColor", newShieldColor);
timeHitted = Time.time;
}
public void Death(){
menuButton.interactable = false;
energy = 0.0f;
shieldBar.fillAmount = energy / 100;
FX.SetActive (false);
controller.enabled = false;
tag = "Untagged";
FindObjectOfType<DeathTextFader> ().enabled = true;
FindObjectOfType<CameraController> ().Blur (true);
GameObject deadInstance = Instantiate (deadRobot, transform.position, transform.rotation) as GameObject;
deadInstance.GetComponent<DeadRobotController> ().playerVelocity = controller.velocity;
Destroy (gameObject);
}
public void InvokeDeath(){
isDead = true;
}
void EndLevel(){
isControlable = false;
immortal = true;
FindObjectOfType<CameraController> ().Unfollow ();
FindObjectOfType<CameraController> ().Blur (true);
FindObjectOfType<LevelEndController> ().OpenMenu ();
menuButton.interactable = false;
}
public GameObject GetPlayer(){
return gameObject;
}
}
| |
/*
* 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 log4net;
using OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public class UndoState
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public Vector3 Position = Vector3.Zero;
public Vector3 Scale = Vector3.Zero;
public Quaternion Rotation = Quaternion.Identity;
/// <summary>
/// Is this undo state for an entire group?
/// </summary>
public bool ForGroup;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="part"></param>
/// <param name="forGroup">True if the undo is for an entire group</param>
public UndoState(SceneObjectPart part, bool forGroup)
{
if (part.ParentID == 0)
{
ForGroup = forGroup;
// if (ForGroup)
Position = part.ParentGroup.AbsolutePosition;
// else
// Position = part.OffsetPosition;
// m_log.DebugFormat(
// "[UNDO STATE]: Storing undo position {0} for root part", Position);
Rotation = part.RotationOffset;
// m_log.DebugFormat(
// "[UNDO STATE]: Storing undo rotation {0} for root part", Rotation);
Scale = part.Shape.Scale;
// m_log.DebugFormat(
// "[UNDO STATE]: Storing undo scale {0} for root part", Scale);
}
else
{
Position = part.OffsetPosition;
// m_log.DebugFormat(
// "[UNDO STATE]: Storing undo position {0} for child part", Position);
Rotation = part.RotationOffset;
// m_log.DebugFormat(
// "[UNDO STATE]: Storing undo rotation {0} for child part", Rotation);
Scale = part.Shape.Scale;
// m_log.DebugFormat(
// "[UNDO STATE]: Storing undo scale {0} for child part", Scale);
}
}
/// <summary>
/// Compare the relevant state in the given part to this state.
/// </summary>
/// <param name="part"></param>
/// <returns>true if both the part's position, rotation and scale match those in this undo state. False otherwise.</returns>
public bool Compare(SceneObjectPart part)
{
if (part != null)
{
if (part.ParentID == 0)
return
Position == part.ParentGroup.AbsolutePosition
&& Rotation == part.RotationOffset
&& Scale == part.Shape.Scale;
else
return
Position == part.OffsetPosition
&& Rotation == part.RotationOffset
&& Scale == part.Shape.Scale;
}
return false;
}
public void PlaybackState(SceneObjectPart part)
{
part.Undoing = true;
if (part.ParentID == 0)
{
// m_log.DebugFormat(
// "[UNDO STATE]: Undoing position to {0} for root part {1} {2}",
// Position, part.Name, part.LocalId);
if (Position != Vector3.Zero)
{
if (ForGroup)
part.ParentGroup.AbsolutePosition = Position;
else
part.ParentGroup.UpdateRootPosition(Position);
}
// m_log.DebugFormat(
// "[UNDO STATE]: Undoing rotation {0} to {1} for root part {2} {3}",
// part.RotationOffset, Rotation, part.Name, part.LocalId);
if (ForGroup)
part.UpdateRotation(Rotation);
else
part.ParentGroup.UpdateRootRotation(Rotation);
if (Scale != Vector3.Zero)
{
// m_log.DebugFormat(
// "[UNDO STATE]: Undoing scale {0} to {1} for root part {2} {3}",
// part.Shape.Scale, Scale, part.Name, part.LocalId);
if (ForGroup)
part.ParentGroup.GroupResize(Scale);
else
part.Resize(Scale);
}
part.ParentGroup.ScheduleGroupForTerseUpdate();
}
else
{
// Note: Updating these properties on sop automatically schedules an update if needed
if (Position != Vector3.Zero)
{
// m_log.DebugFormat(
// "[UNDO STATE]: Undoing position {0} to {1} for child part {2} {3}",
// part.OffsetPosition, Position, part.Name, part.LocalId);
part.OffsetPosition = Position;
}
// m_log.DebugFormat(
// "[UNDO STATE]: Undoing rotation {0} to {1} for child part {2} {3}",
// part.RotationOffset, Rotation, part.Name, part.LocalId);
part.UpdateRotation(Rotation);
if (Scale != Vector3.Zero)
{
// m_log.DebugFormat(
// "[UNDO STATE]: Undoing scale {0} to {1} for child part {2} {3}",
// part.Shape.Scale, Scale, part.Name, part.LocalId);
part.Resize(Scale);
}
}
part.Undoing = false;
}
public void PlayfwdState(SceneObjectPart part)
{
part.Undoing = true;
if (part.ParentID == 0)
{
if (Position != Vector3.Zero)
part.ParentGroup.AbsolutePosition = Position;
if (Rotation != Quaternion.Identity)
part.UpdateRotation(Rotation);
if (Scale != Vector3.Zero)
{
if (ForGroup)
part.ParentGroup.GroupResize(Scale);
else
part.Resize(Scale);
}
part.ParentGroup.ScheduleGroupForTerseUpdate();
}
else
{
// Note: Updating these properties on sop automatically schedules an update if needed
if (Position != Vector3.Zero)
part.OffsetPosition = Position;
if (Rotation != Quaternion.Identity)
part.UpdateRotation(Rotation);
if (Scale != Vector3.Zero)
part.Resize(Scale);
}
part.Undoing = false;
}
}
public class LandUndoState
{
public ITerrainModule m_terrainModule;
public ITerrainChannel m_terrainChannel;
public LandUndoState(ITerrainModule terrainModule, ITerrainChannel terrainChannel)
{
m_terrainModule = terrainModule;
m_terrainChannel = terrainChannel;
}
public bool Compare(ITerrainChannel terrainChannel)
{
return m_terrainChannel == terrainChannel;
}
public void PlaybackState()
{
m_terrainModule.UndoTerrain(m_terrainChannel);
}
}
}
| |
#if MONO
#define __APPLE__
#endif
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Globalization {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
using PermissionSet = System.Security.PermissionSet;
using System.Security.Permissions;
/*=================================JapaneseCalendar==========================
**
** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as
** Gregorian calendar. However, the year value is an offset to the Gregorian
** year based on the era.
**
** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor,
** and the era begins on the day an emperor ascends the throne and continues until his death.
** The era changes at 12:00AM.
**
** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st.
** 1989/1/8 A.D. is also Heisei 1st 1/8.
**
** Any date in the year during which era is changed can be reckoned in either era. For example,
** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year.
**
** Note:
** The DateTime can be represented by the JapaneseCalendar are limited to two factors:
** 1. The min value and max value of DateTime class.
** 2. The available era information.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 1868/09/08 9999/12/31
** Japanese Meiji 01/01 Heisei 8011/12/31
============================================================================*/
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class JapaneseCalendar : Calendar
{
internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8);
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Japanese calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
//
// Using a field initializer rather than a static constructor so that the whole class can be lazy
// init.
static internal volatile EraInfo[] japaneseEraInfo;
#if !__APPLE__
private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
#endif
//
// Read our era info
//
// m_EraInfo must be listed in reverse chronological order. The most recent era
// should be the first element.
// That is, m_EraInfo[0] contains the most recent era.
//
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
//
internal static EraInfo[] GetEraInfo()
{
// See if we need to build it
if (japaneseEraInfo == null)
{
#if !__APPLE__
// See if we have any eras from the registry
japaneseEraInfo = GetErasFromRegistry();
#endif
// See if we have to use the built-in eras
if (japaneseEraInfo == null)
{
// We know about some built-in ranges
EraInfo[] defaultEraRanges = new EraInfo[4];
defaultEraRanges[0] = new EraInfo( 4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988,
"\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear
defaultEraRanges[1] = new EraInfo( 3, 1926, 12, 25, 1925, 1, 1989-1925,
"\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear
defaultEraRanges[2] = new EraInfo( 2, 1912, 7, 30, 1911, 1, 1926-1911,
"\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear
defaultEraRanges[3] = new EraInfo( 1, 1868, 1, 1, 1867, 1, 1912-1867,
"\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear
// Remember the ranges we built
japaneseEraInfo = defaultEraRanges;
}
}
// return the era we found/made
return japaneseEraInfo;
}
#if !__APPLE__
//
// GetErasFromRegistry()
//
// We know about 4 built-in eras, however users may add additional era(s) from the
// registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
[System.Security.SecuritySafeCritical] // auto-generated
private static EraInfo[] GetErasFromRegistry()
{
// Look in the registry key and see if we can find any ranges
int iFoundEras = 0;
EraInfo[] registryEraRanges = null;
#if !MONO
try
{
// Need to access registry
PermissionSet permSet = new PermissionSet(PermissionState.None);
permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_japaneseErasHivePermissionList));
permSet.Assert();
RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false);
// Abort if we didn't find anything
if (key == null) return null;
// Look up the values in our reg key
String[] valueNames = key.GetValueNames();
if (valueNames != null && valueNames.Length > 0)
{
registryEraRanges = new EraInfo[valueNames.Length];
// Loop through the registry and read in all the values
for (int i = 0; i < valueNames.Length; i++)
{
// See if the era is a valid date
EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
// continue if not valid
if (era == null) continue;
// Remember we found one.
registryEraRanges[iFoundEras] = era;
iFoundEras++;
}
}
}
catch (System.Security.SecurityException)
{
// If we weren't allowed to read, then just ignore the error
return null;
}
catch (System.IO.IOException)
{
// If key is being deleted just ignore the error
return null;
}
catch (System.UnauthorizedAccessException)
{
// Registry access rights permissions, just ignore the error
return null;
}
//
// If we didn't have valid eras, then fail
// should have at least 4 eras
//
if (iFoundEras < 4) return null;
//
// Now we have eras, clean them up.
//
// Clean up array length
Array.Resize(ref registryEraRanges, iFoundEras);
// Sort them
Array.Sort(registryEraRanges, CompareEraRanges);
// Clean up era information
for (int i = 0; i < registryEraRanges.Length; i++)
{
// eras count backwards from length to 1 (and are 1 based indexes into string arrays)
registryEraRanges[i].era = registryEraRanges.Length - i;
// update max era year
if (i == 0)
{
// First range is 'til the end of the calendar
registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
}
else
{
// Rest are until the next era (remember most recent era is first in array)
registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset;
}
}
#endif
// Return our ranges
return registryEraRanges;
}
//
// Compare two era ranges, eg just the ticks
// Remember the era array is supposed to be in reverse chronological order
//
private static int CompareEraRanges(EraInfo a, EraInfo b)
{
return b.ticks.CompareTo(a.ticks);
}
//
// GetEraFromValue
//
// Parse the registry value name/data pair into an era
//
// Registry values look like:
// yyyy.mm.dd=era_abbrev_english_englishabbrev
//
// Where yyyy.mm.dd is the registry value name, and also the date of the era start.
// yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
// era is the Japanese Era name
// abbrev is the Abbreviated Japanese Era Name
// english is the English name for the Era (unused)
// englishabbrev is the Abbreviated English name for the era.
// . is a delimiter, but the value of . doesn't matter.
// '_' marks the space between the japanese era name, japanese abbreviated era name
// english name, and abbreviated english names.
private static EraInfo GetEraFromValue(String value, String data)
{
// Need inputs
if (value == null || data == null) return null;
//
// Get Date
//
// Need exactly 10 characters in name for date
// yyyy.mm.dd although the . can be any character
if (value.Length != 10) return null;
int year;
int month;
int day;
if (!Number.TryParseInt32(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
!Number.TryParseInt32(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
!Number.TryParseInt32(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
{
// Couldn't convert integer, fail
return null;
}
//
// Get Strings
//
// Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
String[] names = data.Split(new char[] {'_'});
// Should have exactly 4 parts
// 0 - Era Name
// 1 - Abbreviated Era Name
// 2 - English Era Name
// 3 - Abbreviated English Era Name
if (names.Length != 4) return null;
// Each part should have data in it
if (names[0].Length == 0 ||
names[1].Length == 0 ||
names[2].Length == 0 ||
names[3].Length == 0)
return null;
//
// Now we have an era we can build
// Note that the era # and max era year need cleaned up after sorting
// Don't use the full English Era Name (names[2])
//
return new EraInfo( 0, year, month, day, year - 1, 1, 0,
names[0], names[1], names[3]);
}
#endif // !__APPLE__
internal static volatile Calendar s_defaultInstance;
internal GregorianCalendarHelper helper;
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance() {
if (s_defaultInstance == null) {
s_defaultInstance = new JapaneseCalendar();
}
return (s_defaultInstance);
}
public JapaneseCalendar() {
try {
new CultureInfo("ja-JP");
} catch (ArgumentException e) {
throw new TypeInitializationException(this.GetType().FullName, e);
}
helper = new GregorianCalendarHelper(this, GetEraInfo());
}
internal override int ID {
get {
return (CAL_JAPAN);
}
}
public override DateTime AddMonths(DateTime time, int months) {
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years) {
return (helper.AddYears(time, years));
}
/*=================================GetDaysInMonth==========================
**Action: Returns the number of days in the month given by the year and month arguments.
**Returns: The number of days in the given month.
**Arguments:
** year The year in Japanese calendar.
** month The month
** era The Japanese era value.
**Exceptions
** ArgumentException If month is less than 1 or greater * than 12.
============================================================================*/
public override int GetDaysInMonth(int year, int month, int era) {
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era) {
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time) {
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time) {
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era)
{
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
/*=================================GetEra==========================
**Action: Get the era value of the specified time.
**Returns: The era value for the specified time.
**Arguments:
** time the specified date time.
**Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges.
============================================================================*/
public override int GetEra(DateTime time) {
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time) {
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time) {
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era) {
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era) {
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
// For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years.
// Therefore, for any two digit number, we just return the original number.
public override int ToFourDigitYear(int year) {
if (year <= 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
if (year > helper.MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
helper.MaxYear));
}
return (year);
}
public override int[] Eras {
get {
return (helper.Eras);
}
}
//
// Return the various era strings
// Note: The arrays are backwards of the eras
//
internal static String[] EraNames()
{
EraInfo[] eras = GetEraInfo();
String[] eraNames = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
eraNames[i] = eras[eras.Length - i - 1].eraName;
}
return eraNames;
}
internal static String[] AbbrevEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasAbbrev = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName;
}
return erasAbbrev;
}
internal static String[] EnglishEraNames()
{
EraInfo[] eras = GetEraInfo();
String[] erasEnglish = new String[eras.Length];
for (int i = 0; i < eras.Length; i++)
{
// Strings are in chronological order, eras are backwards order.
erasEnglish[i] = eras[eras.Length - i - 1].englishEraName;
}
return erasEnglish;
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
internal override bool IsValidYear(int year, int era) {
return helper.IsValidYear(year, era);
}
public override int TwoDigitYearMax {
get {
if (twoDigitYearMax == -1) {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set {
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
}
}
| |
// Copyright (c) 2013-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE
using System;
using System.Runtime.InteropServices;
#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif
namespace SharpNav.Geometry
{
/// <summary>
/// A 3d triangle.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Triangle3 : IEquatable<Triangle3>
{
#region Fields
/// <summary>
/// The first point.
/// </summary>
public Vector3 A;
/// <summary>
/// The second point.
/// </summary>
public Vector3 B;
/// <summary>
/// The third point.
/// </summary>
public Vector3 C;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Triangle3"/> struct.
/// </summary>
/// <param name="a">The second point.</param>
/// <param name="b">The first point.</param>
/// <param name="c">The third point.</param>
public Triangle3(Vector3 a, Vector3 b, Vector3 c)
{
A = a;
B = b;
C = c;
}
#endregion
#region Properties
/// <summary>
/// Gets the directed line segment from <see cref="A"/> to <see cref="B"/>.
/// </summary>
public Vector3 AB
{
get
{
Vector3 result;
Vector3.Subtract(ref B, ref A, out result);
return result;
}
}
/// <summary>
/// Gets the directed line segment from <see cref="A"/> to <see cref="C"/>.
/// </summary>
public Vector3 AC
{
get
{
Vector3 result;
Vector3.Subtract(ref C, ref A, out result);
return result;
}
}
/// <summary>
/// Gets the directed line segment from <see cref="B"/> to <see cref="A"/>.
/// </summary>
public Vector3 BA
{
get
{
Vector3 result;
Vector3.Subtract(ref A, ref B, out result);
return result;
}
}
/// <summary>
/// Gets the directed line segment from <see cref="B"/> to <see cref="C"/>.
/// </summary>
public Vector3 BC
{
get
{
Vector3 result;
Vector3.Subtract(ref C, ref B, out result);
return result;
}
}
/// <summary>
/// Gets the directed line segment from <see cref="C"/> to <see cref="A"/>.
/// </summary>
public Vector3 CA
{
get
{
Vector3 result;
Vector3.Subtract(ref A, ref C, out result);
return result;
}
}
/// <summary>
/// Gets the directed line segment from <see cref="C"/> to <see cref="B"/>.
/// </summary>
public Vector3 CB
{
get
{
Vector3 result;
Vector3.Subtract(ref B, ref C, out result);
return result;
}
}
/// <summary>
/// Gets the area of the triangle.
/// </summary>
public float Area
{
get
{
return Vector3.Cross(AB, AC).Length() * 0.5f;
}
}
/// <summary>
/// Gets the perimeter of the triangle.
/// </summary>
public float Perimeter
{
get
{
return AB.Length() + AC.Length() + BC.Length();
}
}
/// <summary>
/// Gets the centroid of the triangle.
/// </summary>
public Vector3 Centroid
{
get
{
const float OneThird = 1f / 3f;
return A * OneThird + B * OneThird + C * OneThird;
}
}
/// <summary>
/// Gets the <see cref="Triangle3"/>'s surface normal. Assumes clockwise ordering of A, B, and C.
/// </summary>
public Vector3 Normal
{
get
{
return Vector3.Normalize(Vector3.Cross(AB, AC));
}
}
#endregion
#region Operators
/// <summary>
/// Compares two <see cref="Triangle3"/>'s for equality.
/// </summary>
/// <param name="left">The first triangle.</param>
/// <param name="right">The second triangle.</param>
/// <returns>A value indicating whether the two triangles are equal.</returns>
public static bool operator ==(Triangle3 left, Triangle3 right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two <see cref="Triangle3"/>'s for inequality.
/// </summary>
/// <param name="left">The first triangle.</param>
/// <param name="right">The second triangle.</param>
/// <returns>A value indicating whether the two triangles are not equal.</returns>
public static bool operator !=(Triangle3 left, Triangle3 right)
{
return !left.Equals(right);
}
#endregion
#region Methods
/// <summary>
/// Calculates the bounding box of a triangle.
/// </summary>
/// <param name="tri">A triangle.</param>
/// <returns>The triangle's bounding box.</returns>
public static BBox3 GetBoundingBox(Triangle3 tri)
{
BBox3 b;
GetBoundingBox(ref tri, out b);
return b;
}
/// <summary>
/// Calculates the bounding box of a triangle.
/// </summary>
/// <param name="tri">A triangle.</param>
/// <param name="bbox">The triangle's bounding box.</param>
public static void GetBoundingBox(ref Triangle3 tri, out BBox3 bbox)
{
GetBoundingBox(ref tri.A, ref tri.B, ref tri.C, out bbox);
}
/// <summary>
/// Calculates the bounding box of a triangle from its vertices.
/// </summary>
/// <param name="a">The first vertex.</param>
/// <param name="b">The second vertex.</param>
/// <param name="c">The third vertex.</param>
/// <param name="bbox">The bounding box between the points.</param>
public static void GetBoundingBox(ref Vector3 a, ref Vector3 b, ref Vector3 c, out BBox3 bbox)
{
Vector3 min = a, max = a;
if (b.X < min.X) min.X = b.X;
if (b.Y < min.Y) min.Y = b.Y;
if (b.Z < min.Z) min.Z = b.Z;
if (c.X < min.X) min.X = c.X;
if (c.Y < min.Y) min.Y = c.Y;
if (c.Z < min.Z) min.Z = c.Z;
if (b.X > max.X) max.X = b.X;
if (b.Y > max.Y) max.Y = b.Y;
if (b.Z > max.Z) max.Z = b.Z;
if (c.X > max.X) max.X = c.X;
if (c.Y > max.Y) max.Y = c.Y;
if (c.Z > max.Z) max.Z = c.Z;
bbox.Min = min;
bbox.Max = max;
}
/// <summary>
/// Gets the area of the triangle projected onto the XZ-plane.
/// </summary>
/// <param name="a">The first point.</param>
/// <param name="b">The second point.</param>
/// <param name="c">The third point.</param>
/// <param name="area">The calculated area.</param>
public static void Area2D(ref Vector3 a, ref Vector3 b, ref Vector3 c, out float area)
{
float abx = b.X - a.X;
float abz = b.Z - a.Z;
float acx = c.X - a.X;
float acz = c.Z - a.Z;
area = acx * abz - abx * acz;
}
/// <summary>
/// Gets the area of the triangle projected onto the XZ-plane.
/// </summary>
/// <param name="a">The first point.</param>
/// <param name="b">The second point.</param>
/// <param name="c">The third point.</param>
/// <returns>The calculated area.</returns>
public static float Area2D(Vector3 a, Vector3 b, Vector3 c)
{
float result;
Area2D(ref a, ref b, ref c, out result);
return result;
}
/// <summary>
/// Checks for equality with another <see cref="Triangle3"/>.
/// </summary>
/// <param name="other">The other triangle.</param>
/// <returns>A value indicating whether other is equivalent to the triangle.</returns>
public bool Equals(Triangle3 other)
{
return
A.Equals(other.A) &&
B.Equals(other.B) &&
C.Equals(other.C);
}
/// <summary>
/// Checks for equality with another object.
/// </summary>
/// <param name="obj">The other object.</param>
/// <returns>A value indicating whether other is equivalent to the triangle.</returns>
public override bool Equals(object obj)
{
Triangle3? other = obj as Triangle3?;
if (other.HasValue)
return this.Equals(other.Value);
else
return false;
}
/// <summary>
/// Gets a unique hash code for the triangle.
/// </summary>
/// <returns>A hash code.</returns>
public override int GetHashCode()
{
//see http://stackoverflow.com/a/263416/1122135
int hash = 17;
hash = hash * 23 + A.GetHashCode();
hash = hash * 23 + B.GetHashCode();
hash = hash * 23 + C.GetHashCode();
return hash;
}
/// <summary>
/// Converts the triangle's data into a human-readable format.
/// </summary>
/// <returns>A string containing the triangle's data.</returns>
public override string ToString()
{
return "(" + A.ToString() + ", " + B.ToString() + ", " + C.ToString() + ")";
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Collections;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Threading;
using NUnit.Framework;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.BuildEngine.Shared;
using System.IO;
namespace Microsoft.Build.UnitTests
{
[TestFixture]
public class TaskWorkerThread_Tests
{
private Engine engine;
private List<TaskExecutionStateHelper> InitializeTaskState()
{
BuildPropertyGroup projectLevelProprtiesForInference;
BuildPropertyGroup projectLevelPropertiesForExecution;
Hashtable[] inferenceBucketItemsByName;
Hashtable[] inferenceBucketMetaData;
Hashtable projectLevelItemsForInference;
Hashtable[] executionBucketItemsByName;
Hashtable[] executionBucketMetaData;
Hashtable projectLevelItemsForExecution;
ITaskHost hostObject;
EngineLoggingServicesHelper loggingHelper;
string projectFileOfTaskNode;
string parentProjectFullFileName;
int nodeProxyId;
int projectId;
string executionDirectory;
XmlElement taskNode = new XmlDocument().CreateElement("MockTask");
LoadedType taskClass = new LoadedType(typeof(MockTask), new AssemblyLoadInfo(typeof(MockTask).Assembly.FullName, null));
loggingHelper = new EngineLoggingServicesHelper();
engine.LoggingServices = loggingHelper;
Project project = new Project(engine);
nodeProxyId = engine.EngineCallback.CreateTaskContext(project, null, null, taskNode, EngineCallback.inProcNode, new BuildEventContext(BuildEventContext.InvalidNodeId, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId));
// Set up some "fake data" which will be passed to the Task Execution State object
Hashtable[] fakeArray = new Hashtable[1];
fakeArray[0] = new Hashtable();
projectLevelProprtiesForInference = new BuildPropertyGroup();
projectLevelPropertiesForExecution = new BuildPropertyGroup();
inferenceBucketItemsByName = fakeArray;
inferenceBucketMetaData = fakeArray;
projectLevelItemsForInference = new Hashtable();
executionBucketItemsByName = fakeArray;
executionBucketMetaData = fakeArray;
projectLevelItemsForExecution = new Hashtable();
hostObject = null;
projectFileOfTaskNode = "In Memory";
parentProjectFullFileName = project.FullFileName;
executionDirectory = Directory.GetCurrentDirectory();
projectId = project.Id;
MockTaskExecutionModule taskExecutionModule = taskExecutionModule = new MockTaskExecutionModule(new EngineCallback(engine));
TaskExecutionMode howToExecuteTask = TaskExecutionMode.InferOutputsOnly;
List<TaskExecutionStateHelper> executionStates = new List<TaskExecutionStateHelper>();
TaskExecutionStateHelper executionStateNormal1 = new TaskExecutionStateHelper(
howToExecuteTask,
LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
taskNode,
hostObject,
projectFileOfTaskNode,
parentProjectFullFileName,
executionDirectory,
nodeProxyId);
executionStateNormal1.LoggingService = loggingHelper;
executionStateNormal1.TargetInferenceSuccessful = true;
executionStateNormal1.ParentModule = taskExecutionModule;
executionStates.Add(executionStateNormal1);
TaskExecutionStateHelper executionStateCallBack = new TaskExecutionStateHelper(
howToExecuteTask,
LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
taskNode,
hostObject,
projectFileOfTaskNode,
parentProjectFullFileName,
executionDirectory,
nodeProxyId);
executionStateCallBack.LoggingService = loggingHelper;
executionStateCallBack.TargetInferenceSuccessful = true;
executionStates.Add(executionStateCallBack);
TaskExecutionStateHelper executionStateNormal2 = new TaskExecutionStateHelper(
howToExecuteTask,
LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
taskNode,
hostObject,
projectFileOfTaskNode,
parentProjectFullFileName,
executionDirectory,
nodeProxyId);
executionStateNormal2.LoggingService = loggingHelper;
executionStateNormal2.TargetInferenceSuccessful = true;
executionStateNormal2.ParentModule = taskExecutionModule;
executionStates.Add(executionStateNormal2);
TaskExecutionStateHelper executionStateNormal3 = new TaskExecutionStateHelper(
howToExecuteTask,
LookupHelpers.CreateLookup(projectLevelProprtiesForInference, projectLevelItemsForInference),
LookupHelpers.CreateLookup(projectLevelPropertiesForExecution, projectLevelItemsForExecution),
taskNode,
hostObject,
projectFileOfTaskNode,
parentProjectFullFileName,
executionDirectory,
nodeProxyId);
executionStateNormal3.LoggingService = loggingHelper;
executionStateNormal3.TargetInferenceSuccessful = true;
executionStateNormal3.ParentModule = taskExecutionModule;
executionStates.Add(executionStateNormal3);
return executionStates;
}
/// <summary>
/// Right now we are just testing the fact that the TaskWorker thread will take in a couple of tasks, some doing blocking
/// callbacks and make sure that each of the tasks completed correctly. Since the tasks are the ones which will
/// in the end set the exit event, if the test does not complete then the test has failed.
/// </summary>
[Test]
public void TaskWorkerThreadTest()
{
// This event will be triggered right before a "engine" call back is made.
// Once this event is fired we insert another item into the queue
ManualResetEvent rightBeforeCallbackBlock = new ManualResetEvent(false);
engine = new Engine(@"c:\");
TaskExecutionModule TEM = new TaskExecutionModule(new EngineCallback(engine), TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, false);
// Create a worker thread and make it the active node thread
TaskWorkerThread workerThread = TEM.GetWorkerThread();
// Get some tasks which we can then provide execution methods to
List<TaskExecutionStateHelper> tasks = InitializeTaskState();
tasks[1].ExecutionTaskDelegateParameter = rightBeforeCallbackBlock;
tasks[1].ExecuteDelegate = delegate(object parameter)
{
((ManualResetEvent)parameter).Set();
workerThread.WaitForResults(tasks[1].HandleId, new BuildResult[] { new BuildResult(null, new Hashtable(StringComparer.OrdinalIgnoreCase), true, tasks[1].HandleId, 0, 2, false, string.Empty, string.Empty, 0, 0, 0) }, new BuildRequest[1]);
};
// Task 0 will cause a baseActiveThread to start up and run
workerThread.PostWorkItem(tasks[0]);
// Since this will do a callback and will generate a waitingActiveThread
workerThread.PostWorkItem(tasks[1]);
workerThread.ActivateThread();
// Wait for the call back to happen
rightBeforeCallbackBlock.WaitOne();
// Lets insert a execution task which and post a work item which will cause a localDoneEvent to be set
tasks[2].ExecutionTaskDelegateParameter = null;
tasks[2].ExecuteDelegate = null;
// TaskWorkerThread.PostBuildResult(new BuildResult(null, true, tasks[2].NodeProxyId, 0));
workerThread.PostWorkItem(tasks[2]);
//Post a build Result while one of the threads is waiting active, this should cause us to reuse the first thread
workerThread.PostBuildResult(new BuildResult(null, new Hashtable(StringComparer.OrdinalIgnoreCase), true, tasks[2].HandleId, 0, 2, false, string.Empty, string.Empty, 0, 0, 0));
tasks[3].ExecutionTaskDelegateParameter = null;
tasks[3].ExecuteDelegate = null;
workerThread.PostWorkItem(tasks[3]);
TEM.Shutdown();
// Count up the number of threads used during the execution of the tasks
List<int> threadsUsedForExecution = new List<int>();
foreach (TaskExecutionStateHelper state in tasks)
{
// If the list does not contain the threadId add it to the list
if (!threadsUsedForExecution.Contains(state.ThreadId))
{
threadsUsedForExecution.Add(state.ThreadId);
}
}
// Make sure we use less threads then the number of sumbitted tasks which would indicate that threads are reused
Assert.IsTrue(threadsUsedForExecution.Count < tasks.Count, "Expected for the number of unique threads to be less than the number of tasks as threads should have been reused");
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
#if FEATURE_NUMERICS
using System.Numerics;
#else
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#endif
namespace IronPython.Runtime.Binding {
using Ast = Expression;
/// <summary>
/// Provides a MetaObject for instances of Python's old-style classes.
///
/// TODO: Lots of CodeConetxt references, need to move CodeContext onto OldClass and pull it from there.
/// </summary>
class MetaOldInstance : MetaPythonObject, IPythonInvokable, IPythonGetable, IPythonOperable, IPythonConvertible {
public MetaOldInstance(Expression/*!*/ expression, BindingRestrictions/*!*/ restrictions, OldInstance/*!*/ value)
: base(expression, BindingRestrictions.Empty, value) {
Assert.NotNull(value);
}
#region IPythonInvokable Members
public DynamicMetaObject/*!*/ Invoke(PythonInvokeBinder/*!*/ pythonInvoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) {
return InvokeWorker(pythonInvoke, codeContext, args);
}
#endregion
#region IPythonGetable Members
public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObject codeContext) {
// no codeContext filtering but avoid an extra site by handling this action directly
return MakeMemberAccess(member, member.Name, MemberAccess.Get, this);
}
#endregion
#region MetaObject Overrides
public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
return MakeMemberAccess(action, action.Name, MemberAccess.Invoke, args);
}
public override DynamicMetaObject/*!*/ BindGetMember(GetMemberBinder/*!*/ member) {
return MakeMemberAccess(member, member.Name, MemberAccess.Get, this);
}
public override DynamicMetaObject/*!*/ BindSetMember(SetMemberBinder/*!*/ member, DynamicMetaObject/*!*/ value) {
return MakeMemberAccess(member, member.Name, MemberAccess.Set, this, value);
}
public override DynamicMetaObject/*!*/ BindDeleteMember(DeleteMemberBinder/*!*/ member) {
return MakeMemberAccess(member, member.Name, MemberAccess.Delete, this);
}
public override DynamicMetaObject/*!*/ BindBinaryOperation(BinaryOperationBinder/*!*/ binder, DynamicMetaObject/*!*/ arg) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass BinaryOperation" + binder.Operation);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass BinaryOperation");
return PythonProtocol.Operation(binder, this, arg, null);
}
public override DynamicMetaObject/*!*/ BindUnaryOperation(UnaryOperationBinder/*!*/ binder) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass UnaryOperation" + binder.Operation);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass UnaryOperation");
return PythonProtocol.Operation(binder, this, null);
}
public override DynamicMetaObject/*!*/ BindGetIndex(GetIndexBinder/*!*/ binder, DynamicMetaObject/*!*/[]/*!*/ indexes) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass GetIndex" + indexes.Length);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass GetIndex");
return PythonProtocol.Index(binder, PythonIndexType.GetItem, ArrayUtils.Insert(this, indexes));
}
public override DynamicMetaObject/*!*/ BindSetIndex(SetIndexBinder/*!*/ binder, DynamicMetaObject/*!*/[]/*!*/ indexes, DynamicMetaObject/*!*/ value) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass SetIndex" + indexes.Length);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass SetIndex");
return PythonProtocol.Index(binder, PythonIndexType.SetItem, ArrayUtils.Insert(this, ArrayUtils.Append(indexes, value)));
}
public override DynamicMetaObject/*!*/ BindDeleteIndex(DeleteIndexBinder/*!*/ binder, DynamicMetaObject/*!*/[]/*!*/ indexes) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass DeleteIndex" + indexes.Length);
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass DeleteIndex");
return PythonProtocol.Index(binder, PythonIndexType.DeleteItem, ArrayUtils.Insert(this, indexes));
}
public override DynamicMetaObject BindConvert(ConvertBinder/*!*/ conversion) {
return ConvertWorker(conversion, conversion.Type, conversion.Type, conversion.Explicit ? ConversionResultKind.ExplicitCast : ConversionResultKind.ImplicitCast);
}
public DynamicMetaObject BindConvert(PythonConversionBinder binder) {
return ConvertWorker(binder, binder.Type, binder.ReturnType, binder.ResultKind);
}
public DynamicMetaObject ConvertWorker(DynamicMetaObjectBinder binder, Type type, Type retType, ConversionResultKind kind) {
if (!type.IsEnum()) {
switch (type.GetTypeCode()) {
case TypeCode.Boolean:
return MakeConvertToBool(binder);
case TypeCode.Int32:
return MakeConvertToCommon(binder, type, retType, "__int__");
case TypeCode.Double:
return MakeConvertToCommon(binder, type, retType, "__float__");
case TypeCode.String:
return MakeConvertToCommon(binder, type, retType, "__str__");
case TypeCode.Object:
if (type == typeof(BigInteger)) {
return MakeConvertToCommon(binder, type, retType, "__long__");
} else if (type == typeof(Complex)) {
return MakeConvertToCommon(binder, type, retType, "__complex__");
} else if (type == typeof(IEnumerable)) {
return MakeConvertToIEnumerable(binder);
} else if (type == typeof(IEnumerator)) {
return MakeConvertToIEnumerator(binder);
} else if (type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
return MakeConvertToIEnumerable(binder, type, type.GetGenericArguments()[0]);
} else if (type.IsSubclassOf(typeof(Delegate))) {
return MakeDelegateTarget(binder, type, Restrict(typeof(OldInstance)));
}
break;
}
}
return FallbackConvert(binder);
}
public override DynamicMetaObject/*!*/ BindInvoke(InvokeBinder/*!*/ invoke, params DynamicMetaObject/*!*/[]/*!*/ args) {
return InvokeWorker(invoke, PythonContext.GetCodeContext(invoke), args);
}
public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() {
foreach (object o in ((IPythonMembersList)Value).GetMemberNames(DefaultContext.Default)) {
if (o is string) {
yield return (string)o;
}
}
}
#endregion
#region Invoke Implementation
private DynamicMetaObject/*!*/ InvokeWorker(DynamicMetaObjectBinder/*!*/ invoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/[] args) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass Invoke");
DynamicMetaObject self = Restrict(typeof(OldInstance));
Expression[] exprArgs = new Expression[args.Length + 1];
for (int i = 0; i < args.Length; i++) {
exprArgs[i + 1] = args[i].Expression;
}
ParameterExpression tmp = Ast.Variable(typeof(object), "callFunc");
exprArgs[0] = tmp;
return new DynamicMetaObject(
// we could get better throughput w/ a more specific rule against our current custom old class but
// this favors less code generation.
Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Expression.Not(
Expression.TypeIs(
Expression.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceTryGetBoundCustomMember"),
codeContext,
self.Expression,
AstUtils.Constant("__call__")
)
),
typeof(OperationFailed)
)
),
Ast.Block(
Utils.Try(
Ast.Call(typeof(PythonOps).GetMethod("FunctionPushFrameCodeContext"), codeContext),
Ast.Assign(
tmp,
DynamicExpression.Dynamic(
PythonContext.GetPythonContext(invoke).Invoke(
BindingHelpers.GetCallSignature(invoke)
),
typeof(object),
ArrayUtils.Insert(codeContext, exprArgs)
)
)
).Finally(
Ast.Call(typeof(PythonOps).GetMethod("FunctionPopFrame"))
),
tmp
),
Utils.Convert(
BindingHelpers.InvokeFallback(invoke, codeContext, this, args).Expression,
typeof(object)
)
)
),
self.Restrictions.Merge(BindingRestrictions.Combine(args))
);
}
#endregion
#region Conversions
private DynamicMetaObject/*!*/ MakeConvertToIEnumerable(DynamicMetaObjectBinder/*!*/ conversion) {
ParameterExpression tmp = Ast.Variable(typeof(IEnumerable), "res");
DynamicMetaObject self = Restrict(typeof(OldInstance));
return new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceConvertToIEnumerableNonThrowing"),
AstUtils.Constant(PythonContext.GetPythonContext(conversion).SharedContext),
self.Expression
)
),
AstUtils.Constant(null)
),
tmp,
AstUtils.Convert(
AstUtils.Convert( // first to object (incase it's a throw), then to IEnumerable
FallbackConvert(conversion).Expression,
typeof(object)
),
typeof(IEnumerable)
)
)
),
self.Restrictions
);
}
private DynamicMetaObject/*!*/ MakeConvertToIEnumerator(DynamicMetaObjectBinder/*!*/ conversion) {
ParameterExpression tmp = Ast.Variable(typeof(IEnumerator), "res");
DynamicMetaObject self = Restrict(typeof(OldInstance));
return new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceConvertToIEnumeratorNonThrowing"),
AstUtils.Constant(PythonContext.GetPythonContext(conversion).SharedContext),
self.Expression
)
),
AstUtils.Constant(null)
),
tmp,
AstUtils.Convert(
AstUtils.Convert(
FallbackConvert(conversion).Expression,
typeof(object)
),
typeof(IEnumerator)
)
)
),
self.Restrictions
);
}
private DynamicMetaObject/*!*/ MakeConvertToIEnumerable(DynamicMetaObjectBinder/*!*/ conversion, Type toType, Type genericType) {
ParameterExpression tmp = Ast.Variable(toType, "res");
DynamicMetaObject self = Restrict(typeof(OldInstance));
return new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceConvertToIEnumerableOfTNonThrowing").MakeGenericMethod(genericType),
AstUtils.Constant(PythonContext.GetPythonContext(conversion).SharedContext),
self.Expression
)
),
AstUtils.Constant(null)
),
tmp,
AstUtils.Convert(
AstUtils.Convert(
FallbackConvert(conversion).Expression,
typeof(object)
),
toType
)
)
),
self.Restrictions
);
}
private DynamicMetaObject/*!*/ MakeConvertToCommon(DynamicMetaObjectBinder/*!*/ conversion, Type toType, Type retType, string name) {
// TODO: support trys
ParameterExpression tmp = Ast.Variable(typeof(object), "convertResult");
DynamicMetaObject self = Restrict(typeof(OldInstance));
return new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
MakeOneConvert(conversion, self, name, tmp),
Expression.Convert(
tmp,
retType
),
FallbackConvert(conversion).Expression
)
),
self.Restrictions
);
}
private static BinaryExpression/*!*/ MakeOneConvert(DynamicMetaObjectBinder/*!*/ conversion, DynamicMetaObject/*!*/ self, string name, ParameterExpression/*!*/ tmp) {
return Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceConvertNonThrowing"),
AstUtils.Constant(PythonContext.GetPythonContext(conversion).SharedContext),
self.Expression,
AstUtils.Constant(name)
)
),
AstUtils.Constant(null)
);
}
private DynamicMetaObject/*!*/ MakeConvertToBool(DynamicMetaObjectBinder/*!*/ conversion) {
DynamicMetaObject self = Restrict(typeof(OldInstance));
ParameterExpression tmp = Ast.Variable(typeof(bool?), "tmp");
DynamicMetaObject fallback = FallbackConvert(conversion);
Type resType = BindingHelpers.GetCompatibleType(typeof(bool), fallback.Expression.Type);
return new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceConvertToBoolNonThrowing"),
AstUtils.Constant(PythonContext.GetPythonContext(conversion).SharedContext),
self.Expression
)
),
AstUtils.Constant(null)
),
AstUtils.Convert(tmp, resType),
AstUtils.Convert(fallback.Expression, resType)
)
),
self.Restrictions
);
}
#endregion
#region Member Access
private DynamicMetaObject/*!*/ MakeMemberAccess(DynamicMetaObjectBinder/*!*/ member, string name, MemberAccess access, params DynamicMetaObject/*!*/[]/*!*/ args) {
DynamicMetaObject self = Restrict(typeof(OldInstance));
CustomInstanceDictionaryStorage dict;
int key = GetCustomStorageSlot(name, out dict);
if (key == -1) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldInstance " + access + " NoOptimized");
return MakeDynamicMemberAccess(member, name, access, args);
}
ParameterExpression tmp = Ast.Variable(typeof(object), "dict");
Expression target;
ValidationInfo test = new ValidationInfo(
Ast.NotEqual(
Ast.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceGetOptimizedDictionary"),
self.Expression,
AstUtils.Constant(dict.KeyVersion)
)
),
AstUtils.Constant(null)
)
);
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldInstance " + access + " Optimized");
switch (access) {
case MemberAccess.Invoke:
ParameterExpression value = Ast.Variable(typeof(object), "value");
target = Ast.Block(
new[] { value },
Ast.Condition(
Ast.Call(
typeof(PythonOps).GetMethod("TryOldInstanceDictionaryGetValueHelper"),
tmp,
Ast.Constant(key),
AstUtils.Convert(Expression, typeof(object)),
value
),
AstUtils.Convert(
((InvokeMemberBinder)member).FallbackInvoke(new DynamicMetaObject(value, BindingRestrictions.Empty), args, null).Expression,
typeof(object)
),
AstUtils.Convert(
((InvokeMemberBinder)member).FallbackInvokeMember(self, args).Expression,
typeof(object)
)
)
);
break;
case MemberAccess.Get:
// BUG: There's a missing Fallback path here that's always been present even
// in the version that used rules.
target = Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceDictionaryGetValueHelper"),
tmp,
AstUtils.Constant(key),
AstUtils.Convert(Expression, typeof(object))
);
break;
case MemberAccess.Set:
target = Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceDictionarySetExtraValue"),
tmp,
AstUtils.Constant(key),
AstUtils.Convert(args[1].Expression, typeof(object))
);
break;
case MemberAccess.Delete:
target = Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceDeleteCustomMember"),
AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext),
AstUtils.Convert(Expression, typeof(OldInstance)),
AstUtils.Constant(name)
);
break;
default:
throw new InvalidOperationException();
}
return BindingHelpers.AddDynamicTestAndDefer(
member,
new DynamicMetaObject(
target,
BindingRestrictions.Combine(args).Merge(self.Restrictions)
),
args,
test,
tmp
);
}
private int GetCustomStorageSlot(string name, out CustomInstanceDictionaryStorage dict) {
dict = Value.Dictionary._storage as CustomInstanceDictionaryStorage;
if (dict == null || Value._class.HasSetAttr) {
return -1;
}
return dict.FindKey(name);
}
private enum MemberAccess {
Get,
Set,
Delete,
Invoke
}
private DynamicMetaObject/*!*/ MakeDynamicMemberAccess(DynamicMetaObjectBinder/*!*/ member, string/*!*/ name, MemberAccess access, DynamicMetaObject/*!*/[]/*!*/ args) {
DynamicMetaObject self = Restrict(typeof(OldInstance));
Expression target;
ParameterExpression tmp = Ast.Variable(typeof(object), "result");
switch (access) {
case MemberAccess.Invoke:
target = Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Expression.Not(
Expression.TypeIs(
Expression.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceTryGetBoundCustomMember"),
AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext),
self.Expression,
AstUtils.Constant(name)
)
),
typeof(OperationFailed)
)
),
((InvokeMemberBinder)member).FallbackInvoke(new DynamicMetaObject(tmp, BindingRestrictions.Empty), args, null).Expression,
AstUtils.Convert(
((InvokeMemberBinder)member).FallbackInvokeMember(this, args).Expression,
typeof(object)
)
)
);
break;
case MemberAccess.Get:
target = Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Expression.Not(
Expression.TypeIs(
Expression.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceTryGetBoundCustomMember"),
AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext),
self.Expression,
AstUtils.Constant(name)
)
),
typeof(OperationFailed)
)
),
tmp,
AstUtils.Convert(
FallbackGet(member, args),
typeof(object)
)
)
);
break;
case MemberAccess.Set:
target = Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceSetCustomMember"),
AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext),
self.Expression,
AstUtils.Constant(name),
AstUtils.Convert(args[1].Expression, typeof(object))
);
break;
case MemberAccess.Delete:
target = Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceDeleteCustomMember"),
AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext),
self.Expression,
AstUtils.Constant(name)
);
break;
default:
throw new InvalidOperationException();
}
return new DynamicMetaObject(
target,
self.Restrictions.Merge(BindingRestrictions.Combine(args))
);
}
private Expression FallbackGet(DynamicMetaObjectBinder member, DynamicMetaObject[] args) {
GetMemberBinder sa = member as GetMemberBinder;
if (sa != null) {
return sa.FallbackGetMember(args[0]).Expression;
}
PythonGetMemberBinder pyGetMem = member as PythonGetMemberBinder;
if (pyGetMem.IsNoThrow) {
return Ast.Field(
null,
typeof(OperationFailed).GetDeclaredField("Value")
);
} else {
return member.Throw(
Ast.Call(
typeof(PythonOps).GetMethod("AttributeError"),
AstUtils.Constant("{0} instance has no attribute '{1}'"),
Ast.NewArrayInit(
typeof(object),
AstUtils.Constant(((OldInstance)Value)._class._name),
AstUtils.Constant(pyGetMem.Name)
)
)
);
}
}
#endregion
#region Helpers
public new OldInstance/*!*/ Value {
get {
return (OldInstance)base.Value;
}
}
#endregion
#region IPythonOperable Members
DynamicMetaObject IPythonOperable.BindOperation(PythonOperationBinder action, DynamicMetaObject[] args) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass PythonOperation " + action.Operation);
if (action.Operation == PythonOperationKind.IsCallable) {
return MakeIsCallable(action);
}
return null;
}
private DynamicMetaObject/*!*/ MakeIsCallable(PythonOperationBinder/*!*/ operation) {
DynamicMetaObject self = Restrict(typeof(OldInstance));
return new DynamicMetaObject(
Ast.Call(
typeof(PythonOps).GetMethod("OldInstanceIsCallable"),
AstUtils.Constant(PythonContext.GetPythonContext(operation).SharedContext),
self.Expression
),
self.Restrictions
);
}
#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 gcev = Google.Cloud.ErrorReporting.V1Beta1;
using sys = System;
namespace Google.Cloud.ErrorReporting.V1Beta1
{
/// <summary>Resource name for the <c>ErrorGroup</c> resource.</summary>
public sealed partial class ErrorGroupName : gax::IResourceName, sys::IEquatable<ErrorGroupName>
{
/// <summary>The possible contents of <see cref="ErrorGroupName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}/groups/{group}</c>.</summary>
ProjectGroup = 1,
}
private static gax::PathTemplate s_projectGroup = new gax::PathTemplate("projects/{project}/groups/{group}");
/// <summary>Creates a <see cref="ErrorGroupName"/> 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="ErrorGroupName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ErrorGroupName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ErrorGroupName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ErrorGroupName"/> with the pattern <c>projects/{project}/groups/{group}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="groupId">The <c>Group</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ErrorGroupName"/> constructed from the provided ids.</returns>
public static ErrorGroupName FromProjectGroup(string projectId, string groupId) =>
new ErrorGroupName(ResourceNameType.ProjectGroup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), groupId: gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ErrorGroupName"/> with pattern
/// <c>projects/{project}/groups/{group}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="groupId">The <c>Group</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ErrorGroupName"/> with pattern
/// <c>projects/{project}/groups/{group}</c>.
/// </returns>
public static string Format(string projectId, string groupId) => FormatProjectGroup(projectId, groupId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ErrorGroupName"/> with pattern
/// <c>projects/{project}/groups/{group}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="groupId">The <c>Group</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ErrorGroupName"/> with pattern
/// <c>projects/{project}/groups/{group}</c>.
/// </returns>
public static string FormatProjectGroup(string projectId, string groupId) =>
s_projectGroup.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)));
/// <summary>Parses the given resource name string into a new <see cref="ErrorGroupName"/> 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}/groups/{group}</c></description></item></list>
/// </remarks>
/// <param name="errorGroupName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ErrorGroupName"/> if successful.</returns>
public static ErrorGroupName Parse(string errorGroupName) => Parse(errorGroupName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ErrorGroupName"/> 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}/groups/{group}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="errorGroupName">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="ErrorGroupName"/> if successful.</returns>
public static ErrorGroupName Parse(string errorGroupName, bool allowUnparsed) =>
TryParse(errorGroupName, allowUnparsed, out ErrorGroupName 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="ErrorGroupName"/> 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}/groups/{group}</c></description></item></list>
/// </remarks>
/// <param name="errorGroupName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ErrorGroupName"/>, 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 errorGroupName, out ErrorGroupName result) =>
TryParse(errorGroupName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ErrorGroupName"/> 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}/groups/{group}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="errorGroupName">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="ErrorGroupName"/>, 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 errorGroupName, bool allowUnparsed, out ErrorGroupName result)
{
gax::GaxPreconditions.CheckNotNull(errorGroupName, nameof(errorGroupName));
gax::TemplatedResourceName resourceName;
if (s_projectGroup.TryParseName(errorGroupName, out resourceName))
{
result = FromProjectGroup(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(errorGroupName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ErrorGroupName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string groupId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
GroupId = groupId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ErrorGroupName"/> class from the component parts of pattern
/// <c>projects/{project}/groups/{group}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="groupId">The <c>Group</c> ID. Must not be <c>null</c> or empty.</param>
public ErrorGroupName(string projectId, string groupId) : this(ResourceNameType.ProjectGroup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), groupId: gax::GaxPreconditions.CheckNotNullOrEmpty(groupId, nameof(groupId)))
{
}
/// <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>Group</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string GroupId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { 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.ProjectGroup: return s_projectGroup.Expand(ProjectId, GroupId);
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 ErrorGroupName);
/// <inheritdoc/>
public bool Equals(ErrorGroupName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ErrorGroupName a, ErrorGroupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ErrorGroupName a, ErrorGroupName b) => !(a == b);
}
public partial class ErrorGroup
{
/// <summary>
/// <see cref="gcev::ErrorGroupName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcev::ErrorGroupName ErrorGroupName
{
get => string.IsNullOrEmpty(Name) ? null : gcev::ErrorGroupName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="" file="FileOperationProgressSink.cs">
//
// </copyright>
// <summary>
// The file operation progress sink.
// </summary>
//
// --------------------------------------------------------------------------------------------------------------------
namespace FileOperation
{
using System;
using System.Diagnostics;
/// <summary>
/// The file operation progress sink.
/// </summary>
public class FileOperationProgressSink : IFileOperationProgressSink
{
/// <summary>
/// The start operations.
/// </summary>
public virtual void StartOperations()
{
TraceAction("StartOperations", string.Empty, 0);
}
/// <summary>
/// The finish operations.
/// </summary>
/// <param name="hrResult">
/// The hr result.
/// </param>
public virtual void FinishOperations(uint hrResult)
{
TraceAction("FinishOperations", string.Empty, hrResult);
}
/// <summary>
/// The pre rename item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiItem">
/// The psi item.
/// </param>
/// <param name="pszNewName">
/// The psz new name.
/// </param>
public virtual void PreRenameItem(uint dwFlags, IShellItem psiItem, string pszNewName)
{
TraceAction("PreRenameItem", psiItem, 0);
}
/// <summary>
/// The post rename item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiItem">
/// The psi item.
/// </param>
/// <param name="pszNewName">
/// The psz new name.
/// </param>
/// <param name="hrRename">
/// The hr rename.
/// </param>
/// <param name="psiNewlyCreated">
/// The psi newly created.
/// </param>
public virtual void PostRenameItem(uint dwFlags,
IShellItem psiItem, string pszNewName,
uint hrRename, IShellItem psiNewlyCreated)
{
TraceAction("PostRenameItem", psiNewlyCreated, hrRename);
}
/// <summary>
/// The pre move item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiItem">
/// The psi item.
/// </param>
/// <param name="psiDestinationFolder">
/// The psi destination folder.
/// </param>
/// <param name="pszNewName">
/// The psz new name.
/// </param>
public virtual void PreMoveItem(
uint dwFlags, IShellItem psiItem,
IShellItem psiDestinationFolder, string pszNewName)
{
TraceAction("PreMoveItem", psiItem, 0);
}
/// <summary>
/// The post move item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiItem">
/// The psi item.
/// </param>
/// <param name="psiDestinationFolder">
/// The psi destination folder.
/// </param>
/// <param name="pszNewName">
/// The psz new name.
/// </param>
/// <param name="hrMove">
/// The hr move.
/// </param>
/// <param name="psiNewlyCreated">
/// The psi newly created.
/// </param>
public virtual void PostMoveItem(
uint dwFlags, IShellItem psiItem,
IShellItem psiDestinationFolder,
string pszNewName, uint hrMove,
IShellItem psiNewlyCreated)
{
TraceAction("PostMoveItem", psiNewlyCreated, hrMove);
}
/// <summary>
/// The pre copy item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiItem">
/// The psi item.
/// </param>
/// <param name="psiDestinationFolder">
/// The psi destination folder.
/// </param>
/// <param name="pszNewName">
/// The psz new name.
/// </param>
public virtual void PreCopyItem(
uint dwFlags, IShellItem psiItem,
IShellItem psiDestinationFolder, string pszNewName)
{
TraceAction("PreCopyItem", psiItem, 0);
}
public virtual void PostCopyItem(uint flags, IShellItem psiItem,
IShellItem psiDestinationFolder, string pszNewName,
CopyEngineResult copyResult, IShellItem psiNewlyCreated)
{
TraceAction("PostCopyItem", psiNewlyCreated, (uint)copyResult);
}
/// <summary>
/// The pre delete item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiItem">
/// The psi item.
/// </param>
public virtual void PreDeleteItem(
uint dwFlags, IShellItem psiItem)
{
TraceAction("PreDeleteItem", psiItem, 0);
}
/// <summary>
/// The post delete item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiItem">
/// The psi item.
/// </param>
/// <param name="hrDelete">
/// The hr delete.
/// </param>
/// <param name="psiNewlyCreated">
/// The psi newly created.
/// </param>
public virtual void PostDeleteItem(
uint dwFlags, IShellItem psiItem,
uint hrDelete, IShellItem psiNewlyCreated)
{
TraceAction("PostDeleteItem", psiItem, hrDelete);
}
/// <summary>
/// The pre new item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiDestinationFolder">
/// The psi destination folder.
/// </param>
/// <param name="pszNewName">
/// The psz new name.
/// </param>
public virtual void PreNewItem(uint dwFlags,
IShellItem psiDestinationFolder, string pszNewName)
{
TraceAction("PreNewItem", pszNewName, 0);
}
/// <summary>
/// The post new item.
/// </summary>
/// <param name="dwFlags">
/// The dw flags.
/// </param>
/// <param name="psiDestinationFolder">
/// The psi destination folder.
/// </param>
/// <param name="pszNewName">
/// The psz new name.
/// </param>
/// <param name="pszTemplateName">
/// The psz template name.
/// </param>
/// <param name="dwFileAttributes">
/// The dw file attributes.
/// </param>
/// <param name="hrNew">
/// The hr new.
/// </param>
/// <param name="psiNewItem">
/// The psi new item.
/// </param>
public virtual void PostNewItem(uint dwFlags,
IShellItem psiDestinationFolder, string pszNewName,
string pszTemplateName, uint dwFileAttributes,
uint hrNew, IShellItem psiNewItem)
{
TraceAction("PostNewItem", psiNewItem, hrNew);
}
/// <summary>
/// The update progress.
/// </summary>
/// <param name="iWorkTotal">
/// The i work total.
/// </param>
/// <param name="iWorkSoFar">
/// The i work so far.
/// </param>
public virtual void UpdateProgress(uint iWorkTotal, uint iWorkSoFar)
{
Debug.WriteLine("UpdateProgress: " + iWorkSoFar + "/" + iWorkTotal);
}
/// <summary>
/// The reset timer.
/// </summary>
public void ResetTimer()
{
}
/// <summary>
/// The pause timer.
/// </summary>
public void PauseTimer()
{
}
/// <summary>
/// The resume timer.
/// </summary>
public void ResumeTimer()
{
}
/// <summary>
/// The trace action.
/// </summary>
/// <param name="action">
/// The action.
/// </param>
/// <param name="item">
/// The item.
/// </param>
/// <param name="hresult">
/// The hresult.
/// </param>
[Conditional("DEBUG")]
private static void TraceAction(string action, string item, uint hresult)
{
var message = string.Format("{0} ({1})", action, (CopyEngineResult)hresult);
if (!string.IsNullOrEmpty(item))
{
message += " : " + item;
}
Debug.WriteLine(message);
}
/// <summary>
/// The trace action.
/// </summary>
/// <param name="action">
/// The action.
/// </param>
/// <param name="item">
/// The item.
/// </param>
/// <param name="hresult">
/// The hresult.
/// </param>
[Conditional("DEBUG")]
private static void TraceAction(
string action, IShellItem item, uint hresult)
{
TraceAction(action,
item != null ? item.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY) : null,
hresult);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RichToolTip.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#if NET
namespace Catel.Windows.Controls
{
using System;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Threading;
/// <summary>
/// A kind-of Tooltip implementation that stays open once element is hovered and the content inside is responsive
/// <para />
/// It corresponds to most of the TooltipService attached properties so use them as you wish
/// <para />
/// Usage: (Like Tooltip)
/// <![CDATA[
/// <Control ToolTipService.Placement="Right">
/// <xmlns-pfx:RichToolTip.PopupContent>
/// <TextBlock Text="This will be displayed in the popup" />
/// </xmlns-pfx:RichToolTip.PopupContent>
/// </Control>
///
/// <Control ToolTipService.Placement="Right">
/// <xmlns-pfx:RichToolTip.PopupContent>
/// <RichToolTip Placement="..." PlacementTarget="..." HorizontalOffset=".." and so on>
/// <TextBlock Text="This will be displayed in the popup" />
/// </RichToolTip>
/// </xmlns-pfx:RichToolTip.PopupContent>
/// </Control>
/// ]]>
/// <para />
/// Known Issues:
/// 1 - I didn't have the time nor the strength to care about repositioning. I simply hide the popup whenever it would need repositioning. (Window movement, etc..) But it's ok since it's the default behavior of popup overall.
/// 2 - XBap mode sets transparency through a hack! supported only in full trust.
/// 3 - In XBap mode, moving the mouse slowly towards the popup will cause it to hide
/// 4 - In XBap mode, moving the mouse over the element shows the tooltip even when the browser isn't the active window
/// </summary>
/// <remarks>
/// Originally found at http://blogs.microsoft.co.il/blogs/zuker/archive/2009/01/18/wpf-popups-and-tooltip-behavior-solution.aspx
/// </remarks>
public class RichToolTip : ContentControl
{
#region Fields
const int AnimationDurationInMs = 200;
const int ShowDeferredMilliseconds = 500;
const bool AnimationEnabledDefault = true;
delegate void Action();
Popup _parentPopup;
static RichToolTip lastShownPopup;
#endregion
#region Properties
/// <summary>
/// Gets the related object.
/// </summary>
/// <value>The related object.</value>
public UIElement RelatedObject { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to enable animation or not
/// </summary>
/// <value><c>true</c> if animation should be enabled; otherwise, <c>false</c>.</value>
public bool EnableAnimation { get; set; }
#endregion
#region Constructors
/// <summary>
/// Initializes the <see cref="RichToolTip"/> class.
/// </summary>
static RichToolTip()
{
EventManager.RegisterClassHandler(typeof(UIElement), UIElement.MouseDownEvent, new MouseButtonEventHandler(OnElementMouseDown), true);
EventManager.RegisterClassHandler(typeof(RichToolTip), ButtonBase.ClickEvent, new RoutedEventHandler(OnButtonBaseClick), false);
//EventManager.RegisterClassHandler(typeof(UIElement), UIElement.MouseEnterEvent, new MouseEventHandler(element_MouseEnter), true);
//EventManager.RegisterClassHandler(typeof(UIElement), UIElement.MouseLeaveEvent, new MouseEventHandler(element_MouseLeave), true);
EventManager.RegisterClassHandler(typeof(Selector), Selector.SelectionChangedEvent, new SelectionChangedEventHandler(selector_SelectionChangedEvent), true);
//only in XBap mode
if (BrowserInteropHelper.IsBrowserHosted)
{
EventManager.RegisterClassHandler(typeof(NavigationWindow), UIElement.MouseLeaveEvent, new RoutedEventHandler(OnNavigationWindowMouseLeaveEvent), true);
}
else
{
EventManager.RegisterClassHandler(typeof(Window), Window.SizeChangedEvent, new RoutedEventHandler(OnWindowSizeChanged), true);
}
CommandManager.RegisterClassCommandBinding(typeof(RichToolTip), new CommandBinding(CloseCommand, ExecuteCloseCommand));
InitStoryboards();
}
/// <summary>
/// Initializes a new instance of the <see cref="RichToolTip"/> class.
/// </summary>
public RichToolTip()
{
Loaded += ContentTooltip_Loaded;
Unloaded += ContentTooltip_Unloaded;
}
/// <summary>
/// Initializes a new instance of the <see cref="RichToolTip"/> class.
/// </summary>
/// <param name="relatedObject">The related object.</param>
public RichToolTip(UIElement relatedObject)
: this()
{
Load(relatedObject);
}
#endregion
#region Loading
/// <summary>
/// Loads the specified related object.
/// </summary>
/// <param name="relatedObject">The related object.</param>
internal void Load(UIElement relatedObject)
{
RelatedObject = relatedObject;
FrameworkElement fe = relatedObject as FrameworkElement;
if (fe == null)
{
throw new InvalidOperationException("The element is not supported");
}
RelatedObject.MouseEnter += element_MouseEnter;
RelatedObject.MouseLeave += element_MouseLeave;
fe.Unloaded += RelatedObject_Unloaded;
BindRootVisual();
}
private void RelatedObject_Unloaded(object sender, RoutedEventArgs e)
{
RelatedObject.MouseEnter -= element_MouseEnter;
RelatedObject.MouseLeave -= element_MouseLeave;
}
private void ContentTooltip_Unloaded(object sender, RoutedEventArgs e)
{
UnbindRootVisual();
}
private void ContentTooltip_Loaded(object sender, RoutedEventArgs e)
{
BindRootVisual();
}
#endregion
#region Popup Creation
private static readonly Type PopupType = typeof(Popup);
private static readonly Type PopupSecurityHelperType = PopupType.GetNestedType("PopupSecurityHelper", BindingFlags.Public | BindingFlags.NonPublic);
private static readonly FieldInfo Popup_secHelper = PopupType.GetField("_secHelper", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly FieldInfo PopupSecurityHelper_isChildPopupInitialized = PopupSecurityHelperType.GetField("_isChildPopupInitialized", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly FieldInfo PopupSecurityHelper_isChildPopup = PopupSecurityHelperType.GetField("_isChildPopup", BindingFlags.Instance | BindingFlags.NonPublic);
void HookupParentPopup()
{
//Create the Popup and attach the CustomControl to it.
_parentPopup = new Popup();
//THIS IS A HACK!
//This enables transparency on the popup - needed for XBap versions!
//NOTE - this requires that the xbap app will run in full trust
if (BrowserInteropHelper.IsBrowserHosted)
{
try
{
new ReflectionPermission(PermissionState.Unrestricted).Demand();
DoPopupHacks();
}
catch (SecurityException) { }
}
_parentPopup.AllowsTransparency = true;
Popup.CreateRootPopup(_parentPopup, this);
}
void DoPopupHacks()
{
object secHelper = Popup_secHelper.GetValue(_parentPopup);
PopupSecurityHelper_isChildPopupInitialized.SetValue(secHelper, true);
PopupSecurityHelper_isChildPopup.SetValue(secHelper, false);
}
#endregion
#region Commands
/// <summary>
/// Close command.
/// </summary>
public static RoutedCommand CloseCommand = new RoutedCommand("Close", typeof(RichToolTip));
static void ExecuteCloseCommand(object sender, ExecutedRoutedEventArgs e)
{
HideLastShown(true);
}
#endregion
#region Dependency Properties
/// <summary>
/// Placement property.
/// </summary>
public static readonly DependencyProperty PlacementProperty = ToolTipService.PlacementProperty.AddOwner(typeof(RichToolTip));
/// <summary>
/// Gets or sets the placement.
/// </summary>
/// <value>The placement.</value>
public PlacementMode Placement
{
get { return (PlacementMode)GetValue(PlacementProperty); }
set { SetValue(PlacementProperty, value); }
}
/// <summary>
/// Placement target property.
/// </summary>
public static readonly DependencyProperty PlacementTargetProperty = ToolTipService.PlacementTargetProperty.AddOwner(typeof(RichToolTip));
/// <summary>
/// Gets or sets the placement target.
/// </summary>
/// <value>The placement target.</value>
public UIElement PlacementTarget
{
get { return (UIElement)GetValue(PlacementTargetProperty); }
set { SetValue(PlacementTargetProperty, value); }
}
/// <summary>
/// Placement rectangle property.
/// </summary>
public static readonly DependencyProperty PlacementRectangleProperty = ToolTipService.PlacementRectangleProperty.AddOwner(typeof(RichToolTip));
/// <summary>
/// Gets or sets the placement rectangle.
/// </summary>
/// <value>The placement rectangle.</value>
public Rect PlacementRectangle
{
get { return (Rect)GetValue(PlacementRectangleProperty); }
set { SetValue(PlacementRectangleProperty, value); }
}
/// <summary>
/// Horizontal offset property.
/// </summary>
public static readonly DependencyProperty HorizontalOffsetProperty = ToolTipService.HorizontalOffsetProperty.AddOwner(typeof(RichToolTip));
/// <summary>
/// Gets or sets the horizontal offset.
/// </summary>
/// <value>The horizontal offset.</value>
public double HorizontalOffset
{
get { return (double)GetValue(HorizontalOffsetProperty); }
set { SetValue(HorizontalOffsetProperty, value); }
}
/// <summary>
/// Vertical offset property.
/// </summary>
public static readonly DependencyProperty VerticalOffsetProperty = ToolTipService.VerticalOffsetProperty.AddOwner(typeof(RichToolTip));
/// <summary>
/// Gets or sets the vertical offset.
/// </summary>
/// <value>The vertical offset.</value>
public double VerticalOffset
{
get { return (double)GetValue(VerticalOffsetProperty); }
set { SetValue(VerticalOffsetProperty, value); }
}
/// <summary>
/// IsOpen property.
/// </summary>
public static readonly DependencyProperty IsOpenProperty = Popup.IsOpenProperty.AddOwner(typeof(RichToolTip),
new FrameworkPropertyMetadata( false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsOpenChanged));
/// <summary>
/// Gets or sets a value indicating whether this instance is open.
/// </summary>
/// <value><c>true</c> if this instance is open; otherwise, <c>false</c>.</value>
public bool IsOpen
{
get { return (bool)GetValue(IsOpenProperty); }
set { SetValue(IsOpenProperty, value); }
}
private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RichToolTip ctrl = (RichToolTip)d;
if ((bool)e.NewValue)
{
if (ctrl._parentPopup == null)
{
ctrl.HookupParentPopup();
}
}
}
#endregion
#region Attached Properties
#region HideOnClick
/// <summary>
/// Gets the hide on click.
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static bool GetHideOnClick(DependencyObject obj)
{
return (bool)obj.GetValue(HideOnClickProperty);
}
/// <summary>
/// Sets the hide on click.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="value">if set to <c>true</c> [value].</param>
public static void SetHideOnClick(DependencyObject obj, bool value)
{
obj.SetValue(HideOnClickProperty, value);
}
/// <summary>
/// Hide on click property.
/// </summary>
public static readonly DependencyProperty HideOnClickProperty =
DependencyProperty.RegisterAttached("HideOnClick", typeof(bool), typeof(RichToolTip), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits));
#endregion
#region PopupContent
/// <summary>
/// Gets the content of the popup.
/// </summary>
/// <param name="obj">The obj.</param>
/// <returns></returns>
public static object GetPopupContent(DependencyObject obj)
{
return obj.GetValue(PopupContentProperty);
}
/// <summary>
/// Sets the content of the popup.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="value">The value.</param>
public static void SetPopupContent(DependencyObject obj, object value)
{
obj.SetValue(PopupContentProperty, value);
}
/// <summary>
/// Popup content property.
/// </summary>
public static readonly DependencyProperty PopupContentProperty =
DependencyProperty.RegisterAttached("PopupContent", typeof(object), typeof(RichToolTip), new FrameworkPropertyMetadata(OnPopupContentChanged));
private static void OnPopupContentChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
UIElement element = o as UIElement;
if (element == null)
{
throw new InvalidOperationException("Can't hook to events other than UI Element");
}
if (e.NewValue != null)
{
RichToolTip popup = e.NewValue as RichToolTip;
if (popup != null)
{
popup.Load(element);
}
else
{
popup = new RichToolTip(element);
Binding binding = new Binding
{
Path = new PropertyPath(PopupContentProperty),
Mode = BindingMode.OneWay,
Source = o,
};
popup.SetBinding(ContentProperty, binding);
}
//popup.SetBinding(DataContextProperty, new Binding { Source = element, Path = new PropertyPath(DataContextProperty) });
SetContentTooltipWrapper(o, popup);
}
}
#endregion
#region ContentTooltipWrapper
internal static RichToolTip GetContentTooltipWrapper(DependencyObject obj)
{
return (RichToolTip)obj.GetValue(ContentTooltipWrapperProperty);
}
internal static void SetContentTooltipWrapper(DependencyObject obj, RichToolTip value)
{
obj.SetValue(ContentTooltipWrapperProperty, value);
}
internal static readonly DependencyProperty ContentTooltipWrapperProperty =
DependencyProperty.RegisterAttached("ContentTooltipWrapper", typeof(RichToolTip), typeof(RichToolTip));
#endregion
#endregion
#region Root Visual Binding
bool boundToRoot = false;
bool hasParentWindow = false;
Window parentWindow = null;
void BindRootVisual()
{
if (!boundToRoot)
{
if (!BrowserInteropHelper.IsBrowserHosted)
{
parentWindow = RelatedObject.FindLogicalAncestorByType<Window>() ?? RelatedObject.FindVisualAncestorByType<Window>();
if (parentWindow != null)
{
hasParentWindow = true;
parentWindow.Deactivated += window_Deactivated;
parentWindow.LocationChanged += window_LocationChanged;
}
}
boundToRoot = true;
}
}
void UnbindRootVisual()
{
if (boundToRoot)
{
if (parentWindow != null)
{
parentWindow.Deactivated -= window_Deactivated;
parentWindow.LocationChanged -= window_LocationChanged;
}
boundToRoot = false;
}
}
#endregion
#region Animations & Intervals
static DispatcherTimer _timer;
static Storyboard showStoryboard;
static Storyboard hideStoryboard;
bool setRenderTransform;
static void InitStoryboards()
{
showStoryboard = new Storyboard();
hideStoryboard = new Storyboard();
TimeSpan duration = TimeSpan.FromMilliseconds(AnimationDurationInMs);
DoubleAnimation animation = new DoubleAnimation(1, duration, FillBehavior.Stop);
Storyboard.SetTargetProperty(animation, new PropertyPath(UIElement.OpacityProperty));
showStoryboard.Children.Add(animation);
animation = new DoubleAnimation(0.1, 1, duration, FillBehavior.Stop);
Storyboard.SetTargetProperty(animation, new PropertyPath("(0).(1)", FrameworkElement.RenderTransformProperty, ScaleTransform.ScaleXProperty));
showStoryboard.Children.Add(animation);
animation = new DoubleAnimation(0.1, 1, duration, FillBehavior.Stop);
Storyboard.SetTargetProperty(animation, new PropertyPath("(0).(1)", FrameworkElement.RenderTransformProperty, ScaleTransform.ScaleYProperty));
showStoryboard.Children.Add(animation);
animation = new DoubleAnimation(0, duration, FillBehavior.Stop);
Storyboard.SetTargetProperty(animation, new PropertyPath(UIElement.OpacityProperty));
hideStoryboard.Children.Add(animation);
hideStoryboard.Completed += delegate { OnAnimationCompleted(); };
}
static void InitTimer()
{
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(ShowDeferredMilliseconds);
}
static void ResetTimer(RichToolTip tooltip)
{
if (_timer != null)
{
_timer.Tick -= tooltip.ShowDeferred;
_timer.Stop();
}
}
void Animate(bool show)
{
if (show)
{
if (!setRenderTransform)
{
RenderTransform = new ScaleTransform();
setRenderTransform = true;
}
showStoryboard.Begin(this);
}
else
{
hideStoryboard.Begin(this);
}
}
static void OnAnimationCompleted()
{
HideLastShown(false);
}
#endregion
#region Event Invocations
void element_MouseEnter(object sender, MouseEventArgs e)
{
DependencyObject o = sender as DependencyObject;
//implementation for static subscribing:
//if (o != null)
//{
// RichToolTip tooltip = GetContentTooltipWrapper(o);
// if (tooltip != null && (tooltip != lastShownPopup || tooltip.RelatedObject != o))
// {
// tooltip.Show();
// }
//}
if (!IsShown() && this != lastShownPopup)
{
if (!hasParentWindow || parentWindow.IsActive)
{
Show(true);
}
}
}
void element_MouseLeave(object sender, MouseEventArgs e)
{
//implementation for static subscribing:
//DependencyObject o = sender as DependencyObject;
//if (o != null)
//{
// RichToolTip tooltip = GetContentTooltipWrapper(o);
// if (tooltip != null)
// {
// ResetTimer(tooltip);
// }
//}
ResetTimer(this);
}
static void OnNavigationWindowMouseLeaveEvent(object sender, RoutedEventArgs e)
{
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
if (lastShownPopup != null && !lastShownPopup.IsMouseOver)
{
HideLastShown(false);
}
}));
}
void window_LocationChanged(object sender, EventArgs e)
{
if (IsShown())
{
HideLastShown(false);
}
}
void window_Deactivated(object sender, EventArgs e)
{
if (IsShown())
{
HideLastShown(false);
}
}
static void OnWindowSizeChanged(object sender, RoutedEventArgs e)
{
HideLastShown();
}
static void OnElementMouseDown(object sender, MouseButtonEventArgs e)
{
if (lastShownPopup != null && lastShownPopup.IsShown())
{
RichToolTip popup;
DependencyObject o = e.OriginalSource as DependencyObject;
if (!TryFindPopupParent(e.OriginalSource, out popup))
{
HideLastShown(true);
}
}
}
static void OnButtonBaseClick(object sender, RoutedEventArgs e)
{
if (lastShownPopup != null && lastShownPopup.IsShown())
{
DependencyObject o = e.OriginalSource as DependencyObject;
bool hide = GetHideOnClick(o);
if (hide)
{
HideLastShown(true);
e.Handled = true;
}
}
}
static void selector_SelectionChangedEvent(object sender, SelectionChangedEventArgs e)
{
HideLastShown();
}
static bool TryFindPopupParent(object source, out RichToolTip popup)
{
popup = null;
UIElement element = source as UIElement;
if (element != null)
{
popup = element.FindVisualAncestorByType<RichToolTip>();
if (popup == null)
{
popup = element.FindLogicalAncestorByType<RichToolTip>();
}
return popup != null;
}
return false;
}
#endregion
#region Show / Hide
bool showAnimate = AnimationEnabledDefault;
bool IsShown()
{
return IsOpen;
}
/// <summary>
/// Shows the specified animate.
/// </summary>
/// <param name="animate">if set to <c>true</c> [animate].</param>
public void Show(bool animate)
{
showAnimate = animate;
if (_timer == null)
{
InitTimer();
}
_timer.Tick += ShowDeferred;
if (!_timer.IsEnabled)
{
_timer.Start();
}
}
private void ShowDeferred(object sender, EventArgs e)
{
ResetTimer(this);
HideLastShown(false);
ShowInternal();
if (showAnimate && EnableAnimation)
{
Animate(true);
}
else
{
this.Opacity = 1;
}
lastShownPopup = this;
}
private void ShowInternal()
{
Visibility = Visibility.Visible;
IsOpen = true;
}
static void HideLastShown()
{
HideLastShown(false);
}
static void HideLastShown(bool animate)
{
if (lastShownPopup != null)
{
lastShownPopup.Hide(animate);
}
}
/// <summary>
/// Hides the specified animate.
/// </summary>
/// <param name="animate">if set to <c>true</c> [animate].</param>
public void Hide(bool animate)
{
if (animate && EnableAnimation)
{
Animate(false);
}
else
{
HideInternal();
}
}
private void HideInternal()
{
Visibility = Visibility.Collapsed;
IsOpen = false;
lastShownPopup = null;
}
#endregion
}
}
#endif
| |
// --------------------------------------------------------------------------------------------
// <copyright from='2011' to='2011' company='SIL International'>
// Copyright (c) 2011, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
// --------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using Palaso.Reporting;
using Palaso.WritingSystems;
using Palaso.UI.WindowsForms.Keyboarding.Interfaces;
using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces;
#if __MonoCS__
using Palaso.UI.WindowsForms.Keyboarding.Linux;
#else
using Palaso.UI.WindowsForms.Keyboarding.Windows;
#endif
using Palaso.UI.WindowsForms.Keyboarding.Types;
namespace Palaso.UI.WindowsForms.Keyboarding
{
/// <summary>
/// Singleton class with methods for registering different keyboarding engines (e.g. Windows
/// system, Keyman, XKB, IBus keyboards), and activating keyboards.
/// Clients have to call KeyboardController.Initialize() before they can start using the
/// keyboarding functionality, and they have to call KeyboardController.Shutdown() before
/// the application or the unit test exits.
/// </summary>
public static class KeyboardController
{
#region Nested Manager class
/// <summary>
/// Allows setting different keyboard adapters which is needed for tests. Also allows
/// registering keyboard layouts.
/// </summary>
public static class Manager
{
/// <summary>
/// Sets the available keyboard adaptors. Note that if this is called more than once, the adapters
/// installed previously will be closed and no longer useable. Do not pass adapter instances that have been
/// previously passed. At least one adapter must be of type System.
/// </summary>
public static void SetKeyboardAdaptors(IKeyboardAdaptor[] adaptors)
{
if (!(Keyboard.Controller is IKeyboardControllerImpl))
Keyboard.Controller = new KeyboardControllerImpl();
Instance.Keyboards.Clear(); // InitializeAdaptors below will fill it in again.
if (Adaptors != null)
{
foreach (var adaptor in Adaptors)
adaptor.Close();
}
Adaptors = adaptors;
InitializeAdaptors();
}
/// <summary>
/// Resets the keyboard adaptors to the default ones.
/// </summary>
public static void Reset()
{
SetKeyboardAdaptors(new IKeyboardAdaptor[] {
#if __MonoCS__
new XkbKeyboardAdaptor(), new IbusKeyboardAdaptor(), new CombinedKeyboardAdaptor(),
new CinnamonIbusAdaptor()
#else
new WinKeyboardAdaptor(), new KeymanKeyboardAdaptor(),
#endif
});
}
public static void InitializeAdaptors()
{
// this will also populate m_keyboards
foreach (var adaptor in Adaptors)
adaptor.Initialize();
}
/// <summary>
/// Adds a keyboard to the list of installed keyboards
/// </summary>
/// <param name='description'>Keyboard description object</param>
public static void RegisterKeyboard(IKeyboardDefinition description)
{
if (!Instance.Keyboards.Contains(description))
Instance.Keyboards.Add(description);
}
internal static void ClearAllKeyboards()
{
Instance.Keyboards.Clear();
}
}
#endregion
#region Class KeyboardControllerImpl
private sealed class KeyboardControllerImpl : IKeyboardController, IKeyboardControllerImpl, IDisposable
{
private List<string> LanguagesAlreadyShownKeyboardNotFoundMessages { get; set; }
private IKeyboardDefinition m_ActiveKeyboard;
public KeyboardCollection Keyboards { get; private set; }
public Dictionary<Control, object> EventHandlers { get; private set; }
public event RegisterEventHandler ControlAdded;
public event ControlEventHandler ControlRemoving;
public KeyboardControllerImpl()
{
Keyboards = new KeyboardCollection();
EventHandlers = new Dictionary<Control, object>();
LanguagesAlreadyShownKeyboardNotFoundMessages = new List<string>();
}
public void UpdateAvailableKeyboards()
{
Keyboards.Clear();
foreach (var adapter in Adaptors)
adapter.UpdateAvailableKeyboards();
}
#region Disposable stuff
#if DEBUG
/// <summary/>
~KeyboardControllerImpl()
{
Dispose(false);
}
#endif
/// <summary/>
public bool IsDisposed { get; private set; }
/// <summary/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary/>
private void Dispose(bool fDisposing)
{
System.Diagnostics.Debug.WriteLineIf(!fDisposing,
"****** Missing Dispose() call for " + GetType() + ". *******");
if (fDisposing && !IsDisposed)
{
// dispose managed and unmanaged objects
if (Adaptors != null)
{
foreach (var adaptor in Adaptors)
adaptor.Close();
Adaptors = null;
}
}
IsDisposed = true;
}
#endregion
public IKeyboardDefinition DefaultKeyboard
{
get { return Adaptors.First(adaptor => adaptor.Type == KeyboardType.System).DefaultKeyboard; }
}
public IKeyboardDefinition GetKeyboard(string layoutNameWithLocale)
{
if (string.IsNullOrEmpty(layoutNameWithLocale))
return KeyboardDescription.Zero;
if (Keyboards.Contains(layoutNameWithLocale))
return Keyboards[layoutNameWithLocale];
var parts = layoutNameWithLocale.Split('|');
if (parts.Length == 2)
{
// This is the way Paratext stored IDs in 7.4-7.5 while there was a temporary bug-fix in place)
return GetKeyboard(parts[0], parts[1]);
}
// Handle old Palaso IDs
parts = layoutNameWithLocale.Split('-');
if (parts.Length > 1)
{
for (int i = 1; i < parts.Length; i++)
{
var kb = GetKeyboard(string.Join("-", parts.Take(i)), string.Join("-", parts.Skip(i)));
if (!kb.Equals(KeyboardDescription.Zero))
return kb;
}
}
return KeyboardDescription.Zero;
}
public IKeyboardDefinition GetKeyboard(string layoutName, string locale)
{
if (string.IsNullOrEmpty(layoutName) && string.IsNullOrEmpty(locale))
return KeyboardDescription.Zero;
return Keyboards.Contains(layoutName, locale) ?
Keyboards[layoutName, locale] : KeyboardDescription.Zero;
}
/// <summary>
/// Tries to get the keyboard for the specified <paramref name="writingSystem"/>.
/// </summary>
/// <returns>
/// Returns <c>KeyboardDescription.Zero</c> if no keyboard can be found.
/// </returns>
public IKeyboardDefinition GetKeyboard(IWritingSystemDefinition writingSystem)
{
if (writingSystem == null)
return KeyboardDescription.Zero;
return writingSystem.LocalKeyboard ?? KeyboardDescription.Zero;
}
public IKeyboardDefinition GetKeyboard(IInputLanguage language)
{
// NOTE: on Windows InputLanguage.LayoutName returns a wrong name in some cases.
// Therefore we need this overload so that we can identify the keyboard correctly.
return Keyboards
.Where(keyboard => keyboard is KeyboardDescription &&
((KeyboardDescription)keyboard).InputLanguage != null &&
((KeyboardDescription)keyboard).InputLanguage.Equals(language))
.DefaultIfEmpty(KeyboardDescription.Zero)
.First();
}
/// <summary>
/// Sets the keyboard.
/// </summary>
/// <param name='layoutName'>Keyboard layout name</param>
public void SetKeyboard(string layoutName)
{
var keyboard = GetKeyboard(layoutName);
if (keyboard.Equals(KeyboardDescription.Zero))
{
if (!LanguagesAlreadyShownKeyboardNotFoundMessages.Contains(layoutName))
{
LanguagesAlreadyShownKeyboardNotFoundMessages.Add(layoutName);
ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(),
"Could not find a keyboard ime that had a keyboard named '{0}'", layoutName);
}
return;
}
SetKeyboard(keyboard);
}
public void SetKeyboard(string layoutName, string locale)
{
SetKeyboard(GetKeyboard(layoutName, locale));
}
public void SetKeyboard(IWritingSystemDefinition writingSystem)
{
SetKeyboard(writingSystem.LocalKeyboard);
}
public void SetKeyboard(IInputLanguage language)
{
SetKeyboard(GetKeyboard(language));
}
public void SetKeyboard(IKeyboardDefinition keyboard)
{
keyboard.Activate();
}
/// <summary>
/// Activates the keyboard of the default input language
/// </summary>
public void ActivateDefaultKeyboard()
{
if (CinnamonKeyboardHandling)
{
#if __MonoCS__
CinnamonIbusAdaptor wasta = Adaptors.First(adaptor => adaptor.GetType().ToString().Contains("CinnamonIbus")) as CinnamonIbusAdaptor;
wasta.ActivateDefaultKeyboard();
#endif
}
else
{
SetKeyboard(DefaultKeyboard);
}
}
/// <summary>
/// Returns everything that is installed on the system and available to be used.
/// This would typically be used to populate a list of available keyboards in configuring a writing system.
/// </summary>
public IEnumerable<IKeyboardDefinition> AllAvailableKeyboards
{
get { return Keyboards; }
}
/// <summary>
/// Creates and returns a keyboard definition object based on the layout and locale.
/// </summary>
public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale)
{
var existingKeyboard = AllAvailableKeyboards.FirstOrDefault(keyboard => keyboard.Layout == layout && keyboard.Locale == locale);
return existingKeyboard ??
Adaptors.First(adaptor => adaptor.Type == KeyboardType.System)
.CreateKeyboardDefinition(layout, locale);
}
/// <summary>
/// Gets or sets the currently active keyboard
/// </summary>
public IKeyboardDefinition ActiveKeyboard
{
get
{
if (m_ActiveKeyboard == null)
{
try
{
var lang = InputLanguage.CurrentInputLanguage;
m_ActiveKeyboard = GetKeyboard(lang.LayoutName, lang.Culture.Name);
}
catch (CultureNotFoundException)
{
}
if (m_ActiveKeyboard == null)
m_ActiveKeyboard = KeyboardDescription.Zero;
}
return m_ActiveKeyboard;
}
set { m_ActiveKeyboard = value; }
}
/// <summary>
/// Figures out the system default keyboard for the specified writing system (the one to use if we have no available KnownKeyboards).
/// The implementation may use obsolete fields such as Keyboard
/// </summary>
public IKeyboardDefinition DefaultForWritingSystem(IWritingSystemDefinition ws)
{
return LegacyForWritingSystem(ws) ?? DefaultKeyboard;
}
/// <summary>
/// Finds a keyboard specified using one of the legacy fields. If such a keyboard is found, it is appropriate to
/// automatically add it to KnownKeyboards. If one is not, a general DefaultKeyboard should NOT be added.
/// </summary>
/// <param name="ws"></param>
/// <returns></returns>
public IKeyboardDefinition LegacyForWritingSystem(IWritingSystemDefinition ws)
{
var legacyWs = ws as ILegacyWritingSystemDefinition;
if (legacyWs == null)
return DefaultKeyboard;
return LegacyKeyboardHandling.GetKeyboardFromLegacyWritingSystem(legacyWs, this);
}
/// <summary>
/// Registers the control for keyboarding. Called by KeyboardController.Register.
/// </summary>
public void RegisterControl(Control control, object eventHandler)
{
EventHandlers[control] = eventHandler;
if (ControlAdded != null)
ControlAdded(this, new RegisterEventArgs(control, eventHandler));
}
/// <summary>
/// Unregisters the control from keyboarding. Called by KeyboardController.Unregister.
/// </summary>
/// <param name="control">Control.</param>
public void UnregisterControl(Control control)
{
if (ControlRemoving != null)
ControlRemoving(this, new ControlEventArgs(control));
EventHandlers.Remove(control);
}
#region Legacy keyboard handling
private static class LegacyKeyboardHandling
{
public static IKeyboardDefinition GetKeyboardFromLegacyWritingSystem(ILegacyWritingSystemDefinition ws,
KeyboardControllerImpl controller)
{
if (!string.IsNullOrEmpty(ws.WindowsLcid))
{
var keyboard = HandleFwLegacyKeyboards(ws, controller);
if (keyboard != null)
return keyboard;
}
if (!string.IsNullOrEmpty(ws.Keyboard))
{
if (controller.Keyboards.Contains(ws.Keyboard))
return controller.Keyboards[ws.Keyboard];
// Palaso WinIME keyboard
var locale = GetLocaleName(ws.Keyboard);
var layout = GetLayoutName(ws.Keyboard);
if (controller.Keyboards.Contains(layout, locale))
return controller.Keyboards[layout, locale];
// Palaso Keyman or Ibus keyboard
var keyboard = controller.Keyboards.FirstOrDefault(kbd => kbd.Layout == layout);
if (keyboard != null)
return keyboard;
}
return null;
}
private static IKeyboardDefinition HandleFwLegacyKeyboards(ILegacyWritingSystemDefinition ws,
KeyboardControllerImpl controller)
{
var lcid = GetLcid(ws);
if (lcid >= 0)
{
try
{
if (string.IsNullOrEmpty(ws.Keyboard))
{
// FW system keyboard
var keyboard = controller.Keyboards.FirstOrDefault(
kbd =>
{
var keyboardDescription = kbd as KeyboardDescription;
if (keyboardDescription == null || keyboardDescription.InputLanguage == null || keyboardDescription.InputLanguage.Culture == null)
return false;
return keyboardDescription.InputLanguage.Culture.LCID == lcid;
});
if (keyboard != null)
return keyboard;
}
else
{
// FW keyman keyboard
var culture = new CultureInfo(lcid);
if (controller.Keyboards.Contains(ws.Keyboard, culture.Name))
return controller.Keyboards[ws.Keyboard, culture.Name];
}
}
catch (CultureNotFoundException)
{
// Culture specified by LCID is not supported on current system. Just ignore.
}
}
return null;
}
private static int GetLcid(ILegacyWritingSystemDefinition ws)
{
int lcid;
if (!Int32.TryParse(ws.WindowsLcid, out lcid))
lcid = -1; // can't convert ws.WindowsLcid to a valid LCID. Just ignore.
return lcid;
}
private static string GetLocaleName(string name)
{
var split = name.Split(new[] { '-' });
string localeName;
if (split.Length <= 1)
{
localeName = string.Empty;
}
else if (split.Length > 1 && split.Length <= 3)
{
localeName = string.Join("-", split.Skip(1).ToArray());
}
else
{
localeName = string.Join("-", split.Skip(split.Length - 2).ToArray());
}
return localeName;
}
private static string GetLayoutName(string name)
{
//Just cut off the length of the locale + 1 for the dash
var locale = GetLocaleName(name);
if (string.IsNullOrEmpty(locale))
{
return name;
}
var layoutName = name.Substring(0, name.Length - (locale.Length + 1));
return layoutName;
}
}
#endregion
}
#endregion
#region Static methods and properties
/// <summary>
/// Gets the current keyboard controller singleton.
/// </summary>
private static IKeyboardControllerImpl Instance
{
get
{
return Keyboard.Controller as IKeyboardControllerImpl;
}
}
/// <summary>
/// Enables the PalasoUIWinForms keyboarding. This should be called during application startup.
/// </summary>
public static void Initialize()
{
// Note: arguably it is undesirable to install this as the public keyboard controller before we initialize it
// (the Reset call). However, we have not in general attempted thread safety for the keyboarding code; it seems
// highly unlikely that any but the UI thread wants to manipulate keyboards. Apart from other threads, nothing
// has a chance to access this before we return. If initialization does not complete successfully, we clear the
// global.
try
{
Keyboard.Controller = new KeyboardControllerImpl();
Manager.Reset();
}
catch (Exception)
{
Keyboard.Controller = null;
throw;
}
}
/// <summary>
/// Ends support for the PalasoUIWinForms keyboarding
/// </summary>
public static void Shutdown()
{
if (Instance == null)
return;
Instance.Dispose();
Keyboard.Controller = null;
}
/// <summary>
/// Gets or sets the available keyboard adaptors.
/// </summary>
internal static IKeyboardAdaptor[] Adaptors { get; private set; }
#if __MonoCS__
/// <summary>
/// Flag that Linux is using the combined keyboard handling (Ubuntu saucy/trusty/later?)
/// </summary>
public static bool CombinedKeyboardHandling { get; internal set; }
#endif
/// <summary>
/// Flag that Linux is Wasta-14 (Mint 17/Cinnamon) using IBus for keyboarding.
/// </summary>
public static bool CinnamonKeyboardHandling { get; internal set; }
/// <summary>
/// Gets the currently active keyboard
/// </summary>
public static IKeyboardDefinition ActiveKeyboard
{
get { return Instance.ActiveKeyboard; }
}
/// <summary>
/// Returns <c>true</c> if KeyboardController.Initialize() got called before.
/// </summary>
public static bool IsInitialized { get { return Instance != null; }}
/// <summary>
/// Register the control for keyboarding, optionally providing an event handler for
/// a keyboarding adapter. If <paramref ref="eventHandler"/> is <c>null</c> the
/// default handler will be used.
/// The application should call this method for each control that needs IME input before
/// displaying the control, typically after calling the InitializeComponent() method.
/// </summary>
public static void Register(Control control, object eventHandler = null)
{
if (Instance == null)
throw new ApplicationException("KeyboardController is not initialized! Please call KeyboardController.Initialize() first.");
Instance.RegisterControl(control, eventHandler);
}
/// <summary>
/// Unregister the control from keyboarding. The application should call this method
/// prior to disposing the control so that the keyboard adapters can release unmanaged
/// resources.
/// </summary>
public static void Unregister(Control control)
{
Instance.UnregisterControl(control);
}
internal static IKeyboardControllerImpl EventProvider
{
get { return Instance; }
}
#endregion
}
}
| |
//
// Copyright 2012 Hakan Kjellerstrand
//
// 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.Linq;
using System.Text.RegularExpressions;
using Google.OrTools.ConstraintSolver;
public class FillAPix
{
static int X = -1;
//
// Default problem.
// Puzzle 1 from
// http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/rules
//
static int default_n = 10;
static int[,] default_puzzle = { { X, X, X, X, X, X, X, X, 0, X }, { X, 8, 8, X, 2, X, 0, X, X, X },
{ 5, X, 8, X, X, X, X, X, X, X }, { X, X, X, X, X, 2, X, X, X, 2 },
{ 1, X, X, X, 4, 5, 6, X, X, X }, { X, 0, X, X, X, 7, 9, X, X, 6 },
{ X, X, X, 6, X, X, 9, X, X, 6 }, { X, X, 6, 6, 8, 7, 8, 7, X, 5 },
{ X, 4, X, 6, 6, 6, X, 6, X, 4 }, { X, X, X, X, X, X, 3, X, X, X } };
// for the actual problem
static int n;
static int[,] puzzle;
/**
*
* Fill-a-Pix problem
*
* From
* http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/basiclogic
* """
* Each puzzle consists of a grid containing clues in various places. The
* object is to reveal a hidden picture by painting the squares around each
* clue so that the number of painted squares, including the square with
* the clue, matches the value of the clue.
* """
*
* http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/rules
* """
* Fill-a-Pix is a Minesweeper-like puzzle based on a grid with a pixilated
* picture hidden inside. Using logic alone, the solver determines which
* squares are painted and which should remain empty until the hidden picture
* is completely exposed.
* """
*
* Fill-a-pix History:
* http://www.conceptispuzzles.com/index.aspx?uri=puzzle/fill-a-pix/history
*
* Also see http://www.hakank.org/google_or_tools/fill_a_pix.py
*
*
*/
private static void Solve()
{
Solver solver = new Solver("FillAPix");
//
// data
//
int[] S = { -1, 0, 1 };
Console.WriteLine("Problem:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (puzzle[i, j] > X)
{
Console.Write(puzzle[i, j] + " ");
}
else
{
Console.Write("X ");
}
}
Console.WriteLine();
}
Console.WriteLine();
//
// Decision variables
//
IntVar[,] pict = solver.MakeIntVarMatrix(n, n, 0, 1, "pict");
IntVar[] pict_flat = pict.Flatten(); // for branching
//
// Constraints
//
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (puzzle[i, j] > X)
{
// this cell is the sum of all surrounding cells
var tmp = from a in S from b in S
where i +
a >= 0 && j + b >= 0 && i + a<n && j + b<n select(pict[i + a, j + b]);
solver.Add(tmp.ToArray().Sum() == puzzle[i, j]);
}
}
}
//
// Search
//
DecisionBuilder db = solver.MakePhase(pict_flat, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT);
solver.NewSearch(db);
int sol = 0;
while (solver.NextSolution())
{
sol++;
Console.WriteLine("Solution #{0} ", sol + " ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(pict[i, j].Value() == 1 ? "#" : " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine("\nSolutions: {0}", solver.Solutions());
Console.WriteLine("WallTime: {0}ms", solver.WallTime());
Console.WriteLine("Failures: {0}", solver.Failures());
Console.WriteLine("Branches: {0} ", solver.Branches());
solver.EndSearch();
}
/**
*
* Reads a Fill-a-Pix file.
* File format:
* # a comment which is ignored
* % a comment which also is ignored
* number of rows and columns (n x n)
* <
* row number of neighbours lines...
* >
*
* 0..8 means number of neighbours, "." mean unknown (may be a mine)
*
* Example (from fill_a_pix1.txt):
*
* 10
* ........0.
* .88.2.0...
* 5.8.......
* .....2...2
* 1...456...
* .0...79..6
* ...6..9..6
* ..668787.5
* .4.666.6.4
* ......3...
*
*/
private static void readFile(String file)
{
Console.WriteLine("readFile(" + file + ")");
int lineCount = 0;
TextReader inr = new StreamReader(file);
String str;
while ((str = inr.ReadLine()) != null && str.Length > 0)
{
str = str.Trim();
// ignore comments
if (str.StartsWith("#") || str.StartsWith("%"))
{
continue;
}
Console.WriteLine(str);
if (lineCount == 0)
{
n = Convert.ToInt32(str); // number of rows
puzzle = new int[n, n];
}
else
{
// the problem matrix
String[] row = Regex.Split(str, "");
for (int j = 1; j <= n; j++)
{
String s = row[j];
if (s.Equals("."))
{
puzzle[lineCount - 1, j - 1] = -1;
}
else
{
puzzle[lineCount - 1, j - 1] = Convert.ToInt32(s);
}
}
}
lineCount++;
} // end while
inr.Close();
} // end readFile
public static void Main(String[] args)
{
String file = "";
if (args.Length > 0)
{
file = args[0];
readFile(file);
}
else
{
puzzle = default_puzzle;
n = default_n;
}
Solve();
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Xml.Tests
{
public class DocumentElement_InsertBeforeTests
{
[Fact]
public static void NodeWithOneChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var firstChild = xmlDocument.DocumentElement.FirstChild;
var newNode = xmlDocument.CreateElement("newElem");
var returned = xmlDocument.DocumentElement.InsertBefore(newNode, firstChild);
Assert.Same(newNode, returned);
Assert.Same(xmlDocument.DocumentElement.ChildNodes[0], newNode);
Assert.Same(xmlDocument.DocumentElement.ChildNodes[1], firstChild);
}
[Fact]
public static void NodeWithNoChild()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a></a>");
var root = xmlDocument.DocumentElement;
Assert.False(root.HasChildNodes);
var newNode = xmlDocument.CreateElement("elem");
var result = root.InsertBefore(newNode, null);
Assert.Same(newNode, result);
Assert.Equal(1, root.ChildNodes.Count);
Assert.Same(result, root.ChildNodes[0]);
}
[Fact]
public static void RemoveAndInsert()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var root = xmlDocument.DocumentElement;
root.RemoveChild(root.FirstChild);
Assert.False(root.HasChildNodes);
var newNode = xmlDocument.CreateElement("elem");
var result = root.InsertBefore(newNode, null);
Assert.Same(newNode, result);
Assert.Equal(1, root.ChildNodes.Count);
Assert.Same(result, root.ChildNodes[0]);
}
[Fact]
public static void InsertNewNodeToElement()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var root = xmlDocument.DocumentElement;
var newNode = xmlDocument.CreateProcessingInstruction("PI", "pi data");
root.InsertBefore(newNode, root.FirstChild);
Assert.Equal(2, root.ChildNodes.Count);
}
[Fact]
public static void InsertCDataNodeToDocumentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a/>");
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(cDataSection, null));
}
[Fact]
public static void InsertCDataNodeToDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a/>");
var docFragment = xmlDocument.CreateDocumentFragment();
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Equal(0, docFragment.ChildNodes.Count);
docFragment.InsertBefore(cDataSection, null);
Assert.Equal(1, docFragment.ChildNodes.Count);
}
[Fact]
public static void InsertCDataNodeToAnAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a attr='test' />");
var attribute = xmlDocument.DocumentElement.Attributes[0];
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Equal(1, attribute.ChildNodes.Count);
Assert.Throws<InvalidOperationException>(() => attribute.InsertBefore(cDataSection, null));
Assert.Equal(1, attribute.ChildNodes.Count);
}
[Fact]
public static void InsertCDataToElementNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var node = xmlDocument.DocumentElement.FirstChild;
var cDataSection = xmlDocument.CreateCDataSection("data");
Assert.Equal(0, node.ChildNodes.Count);
Assert.Same(cDataSection, node.InsertBefore(cDataSection, null));
Assert.Equal(1, node.ChildNodes.Count);
}
[Fact]
public static void InsertChildNodeToItself()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<a><b/></a>");
var node = xmlDocument.DocumentElement.FirstChild;
var outerXmlBefore = xmlDocument.OuterXml;
var result = xmlDocument.DocumentElement.InsertBefore(node, node);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Same(node, result);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
Assert.Equal(outerXmlBefore, xmlDocument.OuterXml);
}
[Fact]
public static void InsertCommentNodeToDocumentFragment()
{
var xmlDocument = new XmlDocument();
var documentFragment = xmlDocument.CreateDocumentFragment();
var node = xmlDocument.CreateComment("some comment");
Assert.Equal(0, documentFragment.ChildNodes.Count);
var result = documentFragment.InsertBefore(node, null);
Assert.Same(node, result);
Assert.Equal(1, documentFragment.ChildNodes.Count);
}
[Fact]
public static void InsertCommentNodeToDocument()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
var node = xmlDocument.CreateComment("some comment");
Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count);
var result = xmlDocument.DocumentElement.InsertBefore(node, null);
Assert.Same(node, result);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
}
[Fact]
public static void InsertDocFragmentToDocFragment()
{
var xmlDocument = new XmlDocument();
var root = xmlDocument.CreateElement("root");
var docFrag1 = xmlDocument.CreateDocumentFragment();
var docFrag2 = xmlDocument.CreateDocumentFragment();
docFrag1.AppendChild(root);
docFrag2.InsertBefore(docFrag1, null);
Assert.Equal(1, docFrag2.ChildNodes.Count);
}
[Fact]
public static void InsertTextNodeToCommentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><!-- comment here--></root>");
var commentNode = xmlDocument.DocumentElement.FirstChild;
var textNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.Comment, commentNode.NodeType);
Assert.Throws<InvalidOperationException>(() => commentNode.InsertBefore(textNode, null));
}
[Fact]
public static void InsertTextNodeToProcessingInstructionNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><?PI pi instructions ?></root>");
var processingNode = xmlDocument.DocumentElement.FirstChild;
var textNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.ProcessingInstruction, processingNode.NodeType);
Assert.Throws<InvalidOperationException>(() => processingNode.InsertBefore(textNode, null));
}
[Fact]
public static void InsertTextNodeToTextNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root>text node</root>");
var textNode = xmlDocument.DocumentElement.FirstChild;
var newTextNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.Text, textNode.NodeType);
Assert.Throws<InvalidOperationException>(() => textNode.InsertBefore(newTextNode, null));
}
[Fact]
public static void InsertTextNodeToElementNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root><elem/></root>");
var node = xmlDocument.DocumentElement.FirstChild;
var newTextNode = xmlDocument.CreateTextNode("text node");
Assert.Equal(XmlNodeType.Element, node.NodeType);
var result = node.InsertBefore(newTextNode, null);
Assert.Equal(1, node.ChildNodes.Count);
Assert.Equal(result, node.ChildNodes[0]);
}
[Fact]
public static void InsertTextNodeToDocumentFragment()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
var node = xmlDocument.CreateTextNode("some comment");
var result = xmlDocument.DocumentElement.InsertBefore(node, null);
Assert.Same(node, result);
Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count);
}
[Fact]
public static void InsertAttributeNodeToDocumentNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root/>");
var attribute = xmlDocument.CreateAttribute("attr");
Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(attribute, null));
}
[Fact]
public static void InsertAttributeNodeToAttributeNode()
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<root attr='value'/>");
var attribute = xmlDocument.CreateAttribute("attr");
Assert.Throws<InvalidOperationException>(() => xmlDocument.InsertBefore(attribute, null));
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.dll Alpha
// Description: The core assembly for the DotSpatial 6.0 distribution.
// ********************************************************************************************************
//
// The Original Code is DotSpatial.dll
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/29/2008 3:48:03 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace DotSpatial.Data.Forms
{
/// <summary>
/// frmInputBox
/// </summary>
public class InputBox : Form
{
#region Private Variables
private ValidationType _validation;
private Button cmdCancel;
private Button cmdOk;
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
private Label lblMessageText;
private TextBox txtInput;
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InputBox));
this.lblMessageText = new System.Windows.Forms.Label();
this.txtInput = new System.Windows.Forms.TextBox();
this.cmdOk = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lblMessageText
//
resources.ApplyResources(this.lblMessageText, "lblMessageText");
this.lblMessageText.Name = "lblMessageText";
//
// txtInput
//
resources.ApplyResources(this.txtInput, "txtInput");
this.txtInput.Name = "txtInput";
//
// cmdOk
//
resources.ApplyResources(this.cmdOk, "cmdOk");
this.cmdOk.BackColor = System.Drawing.Color.Transparent;
this.cmdOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.cmdOk.Name = "cmdOk";
this.cmdOk.UseVisualStyleBackColor = false;
this.cmdOk.Click += new System.EventHandler(this.cmdOk_Click);
//
// cmdCancel
//
resources.ApplyResources(this.cmdCancel, "cmdCancel");
this.cmdCancel.BackColor = System.Drawing.Color.Transparent;
this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.UseVisualStyleBackColor = false;
this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
//
// InputBox
//
this.AcceptButton = this.cmdOk;
this.CancelButton = this.cmdCancel;
resources.ApplyResources(this, "$this");
this.Controls.Add(this.cmdCancel);
this.Controls.Add(this.cmdOk);
this.Controls.Add(this.txtInput);
this.Controls.Add(this.lblMessageText);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "InputBox";
this.ShowIcon = false;
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
public InputBox()
{
InitializeComponent();
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="text">Sets the text of the message to show.</param>
public InputBox(string text)
: this()
{
lblMessageText.Text = text;
_validation = ValidationType.None;
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
public InputBox(string text, string caption)
: this()
{
lblMessageText.Text = text;
_validation = ValidationType.None;
base.Text = caption;
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
public InputBox(string text, string caption, ValidationType validation)
: this()
{
lblMessageText.Text = text;
_validation = validation;
base.Text = caption;
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="icon">Specifies an icon to appear on this messagebox.</param>
public InputBox(string text, string caption, ValidationType validation, Icon icon)
: this()
{
lblMessageText.Text = text;
_validation = validation;
base.Text = caption;
ShowIcon = true;
Icon = icon;
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">Sets the text of the message to show.</param>
public InputBox(Form owner, string text)
: this()
{
Owner = owner;
lblMessageText.Text = text;
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
public InputBox(Form owner, string text, string caption)
: this()
{
Owner = owner;
lblMessageText.Text = text;
base.Text = caption;
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
public InputBox(Form owner, string text, string caption, ValidationType validation)
: this()
{
Owner = owner;
lblMessageText.Text = text;
base.Text = caption;
_validation = validation;
}
/// <summary>
/// Creates a new instance of frmInputBox
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="icon">Specifies an icon to appear on this messagebox.</param>
public InputBox(Form owner, string text, string caption, ValidationType validation, Icon icon)
: this()
{
Owner = owner;
_validation = validation;
lblMessageText.Text = text;
base.Text = caption;
ShowIcon = true;
Icon = icon;
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// The string result that was entered for this text box.
/// </summary>
public string Result
{
get
{
return txtInput.Text;
}
}
/// <summary>
/// Gets or sets the type of validation to force on the value before the OK option is permitted.
/// </summary>
public ValidationType Validation
{
get { return _validation; }
set { _validation = value; }
}
#endregion
#region Events
#endregion
#region Event Handlers
#endregion
#region Private Functions
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
private void cmdCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void cmdOk_Click(object sender, EventArgs e)
{
// Parse the value entered in the text box. If the value doesn't match the criteria, don't
// allow the user to exit the dialog by pressing ok.
switch (_validation)
{
case ValidationType.Byte:
if (Global.IsByte(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "byte"));
return;
}
break;
case ValidationType.Double:
if (Global.IsDouble(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "double"));
return;
}
break;
case ValidationType.Float:
if (Global.IsFloat(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "float"));
return;
}
break;
case ValidationType.Integer:
if (Global.IsInteger(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "integer"));
return;
}
break;
case ValidationType.PositiveDouble:
if (Global.IsDouble(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "double"));
return;
}
if (Global.GetDouble(txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive double"));
return;
}
break;
case ValidationType.PositiveFloat:
if (Global.IsFloat(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "float"));
return;
}
if (Global.GetFloat(txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive float"));
return;
}
break;
case ValidationType.PositiveInteger:
if (Global.IsInteger(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "integer"));
return;
}
if (Global.GetInteger(txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive integer"));
return;
}
break;
case ValidationType.PositiveShort:
if (Global.IsShort(txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "short"));
return;
}
if (Global.GetShort(txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive short"));
return;
}
break;
}
DialogResult = DialogResult.OK;
Close();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.