context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation
/// To make an FPS style character:
/// - Create a capsule.
/// - Add the MouseLook script to the capsule.
/// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSInputController script to the capsule
/// -> A CharacterMotor and a CharacterController component will be automatically added.
/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
/// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {
public GameObject sys;
private MainScript mainScript;
public enum RotationAxes {MouseXAndY = 0, MouseX = 1, MouseY = 2, MouseZ = 3 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public float sensitivityX = 7F;
public float sensitivityY = 7F;
public float minimumX = -360F;
public float maximumX = 360F;
public float minimumY = -90F;
public float maximumY = 90F;
float rotationY = 0F;
float rotationX = 0F;
float rotationZ = 0F;
public float calibX = 0.0F;
public float calibY = 0.0F;
public float calibZ = 0.0F;
public float offsetX = 0.0F;
public float offsetY = 335.0F;
public float offsetZ = 0.0F;
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getRoll ();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getPitch ();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getYaw ();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getDragX ();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getDragY ();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getPSQuatW ();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getPSQuatX ();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getPSQuatY();
[DllImport("RenderingPlugin_Binoculars")]
private static extern float getPSQuatZ ();
Quaternion mobileDeviceRotation;
Quaternion phaseSpaceRotation;
void Awake()
{
sys = GameObject.Find("System");
mainScript = sys.GetComponent<MainScript>();
mobileDeviceRotation = Quaternion.identity;
phaseSpaceRotation = Quaternion.identity;
}
bool isFirstTouch = true;
float firstTouchX = 0.0f;
float firstTouchY = 0.0f;
float oldDragX = 0.0f;
float oldDragY = 0.0f;
void Update ()
{
if(mainScript.getExperimentInterface() != (int)MainScript.interfaces.WIM)
{
float roll = getRoll ();
float pitch = getPitch ();
//float yaw = -getYaw (); //minus to turn phone 180 degrees on other landscape
float yaw = getYaw ();
// float phaseSpaceX = getPSQuatX();
// float phaseSpaceY = getPSQuatY();
// float phaseSpaceZ = getPSQuatZ();
// float phaseSpaceW = getPSQuatW();
mobileDeviceRotation = Quaternion.Euler (pitch /*- calibY*/, roll /*- calibX + 335f*/, yaw); // 335 is the rotation halfway between the two scene cameras (used for calibration)
// phaseSpaceRotation = new Quaternion(phaseSpaceX, phaseSpaceY, phaseSpaceZ, phaseSpaceW);
Vector3 mobileDeviceRotEuler = mobileDeviceRotation.eulerAngles;
// Vector3 PSRotEuler = phaseSpaceRotation.eulerAngles;
mobileDeviceRotEuler.x = mobileDeviceRotEuler.x - calibX + offsetX;
mobileDeviceRotEuler.y = mobileDeviceRotEuler.y - calibY + offsetY;
mobileDeviceRotEuler.z = mobileDeviceRotEuler.z - calibZ + offsetZ;
// PSRotEuler.x = PSRotEuler.x - calibX + offsetX;
// PSRotEuler.y = PSRotEuler.y - calibY + offsetY;
// PSRotEuler.z = PSRotEuler.z - calibZ + offsetZ;
//
mobileDeviceRotation = Quaternion.Euler (mobileDeviceRotEuler);
// phaseSpaceRotation = Quaternion.Euler (PSRotEuler);
transform.rotation = mobileDeviceRotation;
// transform.rotation = phaseSpaceRotation;
//transform.localRotation = Quaternion.Euler (30f,30f,0f);
//transform.localEulerAngles = new Vector3(30f,30f,0f);
// if (axes == RotationAxes.MouseX)
// {
//
//
// //rotationX += Input.GetAxis("Mouse X") * sensitivityX;
// rotationX = roll - calibX + 330.0f;
// rotationX = Mathf.Clamp (rotationX, minimumX, maximumX);
// transform.localEulerAngles = new Vector3(0, rotationX, 0);
// //Debug.Log ("X: " + Input.GetAxis("Mouse X"));
// }
// else if (axes == RotationAxes.MouseY)
// {
// //rotationY += -1*Input.GetAxis("Mouse Y") * sensitivityY;
// rotationY = pitch - calibY;
// rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
// transform.localEulerAngles = new Vector3(rotationY, 0, 0);
//
// }
// else
// {
// //rotationZ += Input.GetAxis("Mouse Y") * sensitivityY;
// rotationZ = yaw - calibZ;
// transform.localEulerAngles = new Vector3(0, 0, rotationZ);
// }
//
if(Input.GetKeyDown("c"))
{
calibY = roll; //- 180;
calibX = pitch; //- 180;
calibZ = yaw;
//calibY = PSRotEuler.y;//roll;
//calibX = PSRotEuler.x;//pitch;
}
//Offsets should be continuously updated with PhaseSpace
//Something like:
// calibX = PSRotEuler.x - pitch;
// calibY = PSRotEuler.y - roll;
// calibZ = PSRotEuler.z - yaw;
//Debug.Log(roll + " "+ pitch + " " + yaw);
}
else
{
float dragX = getDragX ();
float dragY = getDragY ();
if(axes == RotationAxes.MouseZ)
{
transform.localEulerAngles = new Vector3(0, 0, 0);
}
if(dragX != 0 && dragY != 0)
{
if(isFirstTouch)
{
oldDragX = dragX;
oldDragY = dragY;
isFirstTouch = false;
}
else if (axes == RotationAxes.MouseX)
{
rotationX += dragX - oldDragX;
oldDragX = dragX;
//rotationX = Mathf.Clamp (rotationX, minimumX, maximumX);
transform.localEulerAngles = new Vector3(0, -rotationX/sensitivityX, 0);
//transform.Rotate(Vector3.right, rotationX);
}
else if (axes == RotationAxes.MouseY)
{
rotationY += dragY - oldDragY;
oldDragY = dragY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(rotationY/sensitivityY, 0, 0);
//transform.Rotate(Vector3.up, rotationY);
}
}
else
{
isFirstTouch = true;
}
}
//transform.localEulerAngles = new Vector3(rotationY, rotationX, 0);
//transform.Rotate(new Vector3(roll, pitch, yaw));
}
void Start ()
{
// Make the rigid body not change rotation
if (GetComponent<Rigidbody>())
GetComponent<Rigidbody>().freezeRotation = true;
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.DeviceFarm.Model;
namespace Amazon.DeviceFarm
{
/// <summary>
/// Interface for accessing DeviceFarm
///
/// AWS Device Farm is a service that enables mobile app developers to test Android, iOS,
/// and Fire OS apps on physical phones, tablets, and other devices in the cloud.
/// </summary>
public partial interface IAmazonDeviceFarm : IDisposable
{
#region CreateDevicePool
/// <summary>
/// Initiates the asynchronous execution of the CreateDevicePool operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateDevicePool operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateDevicePoolResponse> CreateDevicePoolAsync(CreateDevicePoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateProject
/// <summary>
/// Creates a new project.
/// </summary>
/// <param name="name">The project's name.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the CreateProject service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<CreateProjectResponse> CreateProjectAsync(string name, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the CreateProject operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateProject operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateProjectResponse> CreateProjectAsync(CreateProjectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateUpload
/// <summary>
/// Initiates the asynchronous execution of the CreateUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateUploadResponse> CreateUploadAsync(CreateUploadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetAccountSettings
/// <summary>
/// Returns the number of unmetered iOS and/or unmetered Android devices that have been
/// purchased by the account.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetAccountSettings service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetAccountSettingsResponse> GetAccountSettingsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetAccountSettings operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetAccountSettings operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetAccountSettingsResponse> GetAccountSettingsAsync(GetAccountSettingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetDevice
/// <summary>
/// Gets information about a unique device type.
/// </summary>
/// <param name="arn">The device type's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetDevice service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetDeviceResponse> GetDeviceAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetDevice operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetDevice operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetDeviceResponse> GetDeviceAsync(GetDeviceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetDevicePool
/// <summary>
/// Gets information about a device pool.
/// </summary>
/// <param name="arn">The device pool's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetDevicePool service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetDevicePoolResponse> GetDevicePoolAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetDevicePool operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetDevicePool operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetDevicePoolResponse> GetDevicePoolAsync(GetDevicePoolRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetDevicePoolCompatibility
/// <summary>
/// Initiates the asynchronous execution of the GetDevicePoolCompatibility operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetDevicePoolCompatibility operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetDevicePoolCompatibilityResponse> GetDevicePoolCompatibilityAsync(GetDevicePoolCompatibilityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetJob
/// <summary>
/// Gets information about a job.
/// </summary>
/// <param name="arn">The job's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetJob service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetJobResponse> GetJobAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetJob operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetJob operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetJobResponse> GetJobAsync(GetJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetProject
/// <summary>
/// Gets information about a project.
/// </summary>
/// <param name="arn">The project's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetProject service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetProjectResponse> GetProjectAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetProject operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetProject operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetProjectResponse> GetProjectAsync(GetProjectRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetRun
/// <summary>
/// Gets information about a run.
/// </summary>
/// <param name="arn">The run's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetRun service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetRunResponse> GetRunAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetRun operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetRun operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetRunResponse> GetRunAsync(GetRunRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetSuite
/// <summary>
/// Gets information about a suite.
/// </summary>
/// <param name="arn">The suite's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetSuite service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetSuiteResponse> GetSuiteAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetSuite operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetSuite operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetSuiteResponse> GetSuiteAsync(GetSuiteRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetTest
/// <summary>
/// Gets information about a test.
/// </summary>
/// <param name="arn">The test's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetTest service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetTestResponse> GetTestAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetTest operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTest operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetTestResponse> GetTestAsync(GetTestRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region GetUpload
/// <summary>
/// Gets information about an upload.
/// </summary>
/// <param name="arn">The upload's ARN.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the GetUpload service method, as returned by DeviceFarm.</returns>
/// <exception cref="Amazon.DeviceFarm.Model.ArgumentException">
/// An invalid argument was specified.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.LimitExceededException">
/// A limit was exceeded.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.NotFoundException">
/// The specified entity was not found.
/// </exception>
/// <exception cref="Amazon.DeviceFarm.Model.ServiceAccountException">
/// There was a problem with the service account.
/// </exception>
Task<GetUploadResponse> GetUploadAsync(string arn, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the GetUpload operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetUpload operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<GetUploadResponse> GetUploadAsync(GetUploadRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListArtifacts
/// <summary>
/// Initiates the asynchronous execution of the ListArtifacts operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListArtifacts operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListArtifactsResponse> ListArtifactsAsync(ListArtifactsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListDevicePools
/// <summary>
/// Initiates the asynchronous execution of the ListDevicePools operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListDevicePools operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListDevicePoolsResponse> ListDevicePoolsAsync(ListDevicePoolsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListDevices
/// <summary>
/// Initiates the asynchronous execution of the ListDevices operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListDevices operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListDevicesResponse> ListDevicesAsync(ListDevicesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListJobs
/// <summary>
/// Initiates the asynchronous execution of the ListJobs operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListJobs operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListJobsResponse> ListJobsAsync(ListJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListProjects
/// <summary>
/// Initiates the asynchronous execution of the ListProjects operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListProjects operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListProjectsResponse> ListProjectsAsync(ListProjectsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListRuns
/// <summary>
/// Initiates the asynchronous execution of the ListRuns operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListRuns operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListRunsResponse> ListRunsAsync(ListRunsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListSamples
/// <summary>
/// Initiates the asynchronous execution of the ListSamples operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListSamples operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListSamplesResponse> ListSamplesAsync(ListSamplesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListSuites
/// <summary>
/// Initiates the asynchronous execution of the ListSuites operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListSuites operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListSuitesResponse> ListSuitesAsync(ListSuitesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListTests
/// <summary>
/// Initiates the asynchronous execution of the ListTests operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListTests operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListTestsResponse> ListTestsAsync(ListTestsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListUniqueProblems
/// <summary>
/// Initiates the asynchronous execution of the ListUniqueProblems operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListUniqueProblems operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListUniqueProblemsResponse> ListUniqueProblemsAsync(ListUniqueProblemsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ListUploads
/// <summary>
/// Initiates the asynchronous execution of the ListUploads operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ListUploads operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ListUploadsResponse> ListUploadsAsync(ListUploadsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ScheduleRun
/// <summary>
/// Initiates the asynchronous execution of the ScheduleRun operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ScheduleRun operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ScheduleRunResponse> ScheduleRunAsync(ScheduleRunRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
/**
* Copyright 2015-2016 GetSocial B.V.
*
* 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.
*/
#if UNITY_ANDROID
using System;
using UnityEngine;
using System.Collections.Generic;
namespace GetSocialSdk.Core
{
sealed class GetSocialNativeBridgeAndroid : IGetSocialNativeBridge
{
private static GetSocialNativeBridgeAndroid instance;
private AndroidJavaObject getSocialJavaObject;
#region initialization
private GetSocialNativeBridgeAndroid()
{
InitializeGetSocial();
}
public static IGetSocialNativeBridge GetInstance()
{
if(instance == null)
{
instance = new GetSocialNativeBridgeAndroid();
}
return instance;
}
#endregion
#region IGetSocial implementation
public void OnResume()
{
getSocialJavaObject.Call("onResume");
}
public void OnPause()
{
getSocialJavaObject.Call("onPause");
}
public bool IsInitialized
{
get { return getSocialJavaObject.Call<bool>("isInitialized"); }
}
#region current_user
public string UserGuid
{
get
{
return getSocialJavaObject.Call<string>("getUserGuid");
}
}
public string UserDisplayName
{
get
{
return getSocialJavaObject.Call<string>("getUserDisplayName");
}
}
public string UserAvatarUrl
{
get
{
return getSocialJavaObject.Call<string>("getUserAvatarUrl");
}
}
public bool IsUserAnonymous
{
get
{
return getSocialJavaObject.Call<bool>("isUserAnonymous");
}
}
public string[] UserIdentities
{
get
{
return getSocialJavaObject.Call<string[]>("getUserIdentities");
}
}
public bool UserHasIdentityForProvider(string provider)
{
return getSocialJavaObject.Call<bool>("userHasIdentityForProvider", provider);
}
public string GetUserIdForProvider(string provider)
{
return getSocialJavaObject.Call<string>("getUserIdForProvider", provider);
}
public void SetDisplayName(string displayName, Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("setUserDisplayName", displayName, new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void SetAvatarUrl(string avatarUrl, Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("setUserAvatarUrl", avatarUrl, new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void AddUserIdentity(string serializedIdentity, Action<CurrentUser.AddIdentityResult> onComplete, Action<string> onFailure,
CurrentUser.OnAddIdentityConflictDelegate onConflict)
{
getSocialJavaObject.Call("addUserIdentity", serializedIdentity, new AddUserIdentityObserverProxy(onComplete, onFailure, onConflict));
}
public void RemoveUserIdentity(string provider, Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("removeUserIdentity", provider, new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void ResetUser(Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("resetUser", new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void FollowUser(string guid, Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("followUserByGuid", guid, new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void FollowUser(string provider, string id, Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("followUserOnProvider", provider, id, new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void UnfollowUser(string guid, Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("unfollowUserByGuid", guid, new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void UnfollowUser(string provider, string id, Action onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("unfollowUserOnProvider", provider, id, new OperationVoidCallbackProxy(onSuccess, onFailure));
}
public void GetFollowing(int offset, int count, Action<List<User>> onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("getFollowing", offset, count,
new OperationCallbackProxy<List<User>>(onSuccess, onFailure, ParseUtils.ParseUserList));
}
public void GetFollowers(int offset, int count, Action<List<User>> onSuccess, Action<string> onFailure)
{
getSocialJavaObject.Call("getFollowers", offset, count,
new OperationCallbackProxy<List<User>>(onSuccess, onFailure, ParseUtils.ParseUserList));
}
#endregion
public IConfiguration Configuration
{
get { return ConfigurationAndroid.GetInstance(getSocialJavaObject); }
}
public int UnreadNotificationsCount
{
get { return getSocialJavaObject.Call<int>("getNumberOfUnreadNotifications"); }
}
public string Version
{
get { return getSocialJavaObject.Call<string>("getVersion"); }
}
public string ApiVersion
{
get { return getSocialJavaObject.Call<string>("getApiVersion"); }
}
public string Environment
{
get { return getSocialJavaObject.Call<string>("getEnvironment"); }
}
public void Init(string key, Action onSuccess, Action onFailure = null)
{
getSocialJavaObject.Call("init", key, new OperationVoidCallbackProxy(
() =>
{
if(onSuccess != null)
{
InstantiateUnityLifecycleHelper(); // Start listening onResume/onPause
onSuccess();
}
},
error =>
{
if(onFailure != null)
{
onFailure();
}
}
));
}
// Start listening for Android onPause/onResume
private void InstantiateUnityLifecycleHelper()
{
// Just in case
var aliveLifecycleHelpers = UnityEngine.Object.FindObjectsOfType<UnityLifecycleHelper>();
for(int i = 0; i < aliveLifecycleHelpers.Length; i++)
{
UnityEngine.Object.Destroy(aliveLifecycleHelpers[i]);
}
if(Debug.isDebugBuild)
{
Debug.Log("Instantiating " + typeof(UnityLifecycleHelper).Name + " to listen onPause/onResume callbacks");
}
var go = new GameObject { name = "GetSocialAndroidUnityLifecycleHelper" };
var lifecycleHelper = go.AddComponent<UnityLifecycleHelper>();
lifecycleHelper.Init(OnPause, OnResume);
UnityEngine.Object.DontDestroyOnLoad(lifecycleHelper);
}
public void RegisterPlugin(string providerId, IPlugin plugin)
{
if(plugin is IInvitePlugin)
{
IInvitePlugin invitePlugin = (IInvitePlugin)plugin;
getSocialJavaObject.Call("registerInvitePlugin", providerId, new UnityInvitePluginProxy(invitePlugin));
}
else
{
Debug.LogWarning("For now, GetSocial supports only Invite plugins");
}
}
public void ShowView(string serializedViewBuilder, ViewBuilder.OnViewActionDelegate onViewAction = null)
{
Debug.LogWarning("ShowView: " + onViewAction);
getSocialJavaObject.Call("showSerializedView", serializedViewBuilder,
new ViewBuilderActionObserverProxy(onViewAction));
}
public void CloseView(bool saveViewState)
{
getSocialJavaObject.Call("closeView", saveViewState);
}
public void RestoreView()
{
getSocialJavaObject.Call("restoreView");
}
public void Save(string state, Action onSuccess = null, Action<string> onFailure = null)
{
getSocialJavaObject.Call("save", state);
if(onSuccess != null)
{
onSuccess();
}
}
public void GetLastSave(Action<string> onSuccess, Action<string> onFailure = null)
{
getSocialJavaObject.Call("getLastSave", new OperationStringCallbackProxy(onSuccess, onFailure));
}
public void PostActivity(string text, byte[] image, string buttonText, string actionId, string[] tags,
Action<string> onSuccess, Action onFailure)
{
var tagsString = AndroidUtils.MergeActivityTags(tags);
getSocialJavaObject.Call("postActivity", text, image, buttonText, actionId, tagsString,
new OperationStringCallbackProxy(onSuccess, error => onFailure()));
}
public void SetOnWindowStateChangeListener(Action onOpen, Action onClose)
{
getSocialJavaObject.Call("setOnWindowStateChangeListener",
new OnWindowStateChangeListenerProxy(onOpen, onClose));
}
public void SetOnInviteFriendsListener(Action onInviteFriendsIntent, Action<int> onFriendsInvited)
{
getSocialJavaObject.Call("setOnInviteFriendsListener",
new InviteFriendsListenerProxy(onInviteFriendsIntent, onFriendsInvited));
}
public void SetOnUserActionPerformedListener(OnUserActionPerformed onUserActionPerformed)
{
getSocialJavaObject.Call("setOnActionPerformListener",
new OnUserActionPerformedListenerProxy(onUserActionPerformed));
}
public void SetOnUserAvatarClickListener(OnUserAvatarClick onUserAvatarClick)
{
getSocialJavaObject.Call("setOnUserAvatarClickHandler",
new OnUserAvatarClickListenerProxy(onUserAvatarClick));
}
public void SetOnAppAvatarClickListener(OnAppAvatarClick onAppAvatarClick)
{
getSocialJavaObject.Call("setOnAppAvatarClickHandler", new OnAppAvatarClickHandlerProxy(onAppAvatarClick));
}
public void SetOnActivityActionClickListener(OnActivityActionClick onActivityActionClick)
{
getSocialJavaObject.Call("setOnActivityActionClickListener",
new OnActivityActionClickHandlerProxy(onActivityActionClick));
}
public void SetOnInviteButtonClickListener(OnInviteButtonClick onInviteButtonClick)
{
getSocialJavaObject.Call("setOnInviteButtonClickListener",
new OnInviteButtonClickHandlerProxy(onInviteButtonClick));
}
public void SetOnUserGeneratedContentListener(OnUserGeneratedContent onUserGeneratedContent)
{
getSocialJavaObject.Call("setOnUserGeneratedContentListener",
new OnUserGeneratedContentListenerProxy(onUserGeneratedContent));
}
public void SetOnReferralDataReceivedListener(OnReferralDataReceived onReferralDataReceived)
{
getSocialJavaObject.Call("setOnReferralDataReceivedListener",
new OnReferralDataReceivedHandlerProxy(onReferralDataReceived));
}
public void SetOnUnreadNotificationsCountChangeListener(Action<int> onUnreadNotificationsCountChange)
{
getSocialJavaObject.Call("setOnUnreadNotificationsCountChangeListener",
new OnUnreadNotificationsCountChangedListenerProxy(onUnreadNotificationsCountChange));
}
public void SetLanguage(string languageCode)
{
getSocialJavaObject.Call("setLanguage", languageCode);
}
public string[] GetSupportedInviteProviders()
{
return getSocialJavaObject.Call<string[]>("getSupportedInviteProviders");
}
public void InviteFriendsUsingProvider(string provider, string subject = null, string text = null,
byte[] image = null, IDictionary<string, string> referralData = null)
{
string referralDataJson = null;
if(referralData != null)
{
referralDataJson = new JSONObject(referralData).ToString();
}
getSocialJavaObject.Call("inviteFriendsUsingProvider", provider, subject, text, image, referralDataJson);
}
public void GetLeaderboard(string leaderboardId, Action<string> onSuccess, Action<string> onFailure = null)
{
getSocialJavaObject.Call("getLeaderboard", leaderboardId, new OperationStringCallbackProxy(onSuccess, onFailure));
}
public void GetLeaderboards(HashSet<string> leaderboardIds, Action<string> onSuccess,
Action<string> onFailure = null)
{
var javaList = AndroidUtils.ConvertToArrayList(new List<string>(leaderboardIds));
getSocialJavaObject.Call("getLeaderboards", javaList, new OperationStringCallbackProxy(onSuccess, onFailure));
}
public void GetLeaderboards(int offset, int count, Action<string> onSuccess, Action<string> onFailure = null)
{
getSocialJavaObject.Call("getLeaderboards", offset, count, new OperationStringCallbackProxy(onSuccess, onFailure));
}
public void GetLeaderboardScores(string leaderboardId, int offset, int count, LeaderboardScoreType scoreType,
Action<string> onSuccess, Action<string> onFailure = null)
{
getSocialJavaObject.Call("getLeaderboardScores", leaderboardId, offset, count, (int)scoreType,
new OperationStringCallbackProxy(onSuccess, onFailure));
}
public void SubmitLeaderboardScore(string leaderboardId, int score, Action<int> onSuccess = null,
Action onFailure = null)
{
getSocialJavaObject.Call("submitLeaderboardScore", leaderboardId, score,
new SubmitLeaderboardScoreListenerProxy(onSuccess, onFailure));
}
#endregion
#region private methods
private void InitializeGetSocial()
{
using(AndroidJavaObject clazz = new AndroidJavaClass("im.getsocial.sdk.core.unity.GetSocialUnityBridge"))
{
getSocialJavaObject = clazz.CallStatic<AndroidJavaObject>("initBridge");
}
if(getSocialJavaObject.IsJavaNull())
{
throw new Exception("Failed to instantiate Android GetSocial SDK");
}
if(!AndroidUtils.IsUnityBuildOfGetSocialAndroidSDK())
{
throw new Exception(
"Wrong version of GetSocial Android SDK is included into the build. BuildConfig.TARGET_PLATFORM != \"UNITY\"");
}
// Call OnResume manually first time
OnResume();
MainThreadExecutor.Init();
}
#endregion
}
}
#endif
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.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 = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// PermissionProfile
/// </summary>
[DataContract]
public partial class PermissionProfile : IEquatable<PermissionProfile>, IValidatableObject
{
public PermissionProfile()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="PermissionProfile" /> class.
/// </summary>
/// <param name="ModifiedByUsername">ModifiedByUsername.</param>
/// <param name="ModifiedDateTime">ModifiedDateTime.</param>
/// <param name="PermissionProfileId">PermissionProfileId.</param>
/// <param name="PermissionProfileName">PermissionProfileName.</param>
/// <param name="Settings">Settings.</param>
/// <param name="UserCount">UserCount.</param>
/// <param name="Users">Users.</param>
public PermissionProfile(string ModifiedByUsername = default(string), string ModifiedDateTime = default(string), string PermissionProfileId = default(string), string PermissionProfileName = default(string), AccountRoleSettings Settings = default(AccountRoleSettings), string UserCount = default(string), List<UserInformation> Users = default(List<UserInformation>))
{
this.ModifiedByUsername = ModifiedByUsername;
this.ModifiedDateTime = ModifiedDateTime;
this.PermissionProfileId = PermissionProfileId;
this.PermissionProfileName = PermissionProfileName;
this.Settings = Settings;
this.UserCount = UserCount;
this.Users = Users;
}
/// <summary>
/// Gets or Sets ModifiedByUsername
/// </summary>
[DataMember(Name="modifiedByUsername", EmitDefaultValue=false)]
public string ModifiedByUsername { get; set; }
/// <summary>
/// Gets or Sets ModifiedDateTime
/// </summary>
[DataMember(Name="modifiedDateTime", EmitDefaultValue=false)]
public string ModifiedDateTime { get; set; }
/// <summary>
/// Gets or Sets PermissionProfileId
/// </summary>
[DataMember(Name="permissionProfileId", EmitDefaultValue=false)]
public string PermissionProfileId { get; set; }
/// <summary>
/// Gets or Sets PermissionProfileName
/// </summary>
[DataMember(Name="permissionProfileName", EmitDefaultValue=false)]
public string PermissionProfileName { get; set; }
/// <summary>
/// Gets or Sets Settings
/// </summary>
[DataMember(Name="settings", EmitDefaultValue=false)]
public AccountRoleSettings Settings { get; set; }
/// <summary>
/// Gets or Sets UserCount
/// </summary>
[DataMember(Name="userCount", EmitDefaultValue=false)]
public string UserCount { get; set; }
/// <summary>
/// Gets or Sets Users
/// </summary>
[DataMember(Name="users", EmitDefaultValue=false)]
public List<UserInformation> Users { 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 PermissionProfile {\n");
sb.Append(" ModifiedByUsername: ").Append(ModifiedByUsername).Append("\n");
sb.Append(" ModifiedDateTime: ").Append(ModifiedDateTime).Append("\n");
sb.Append(" PermissionProfileId: ").Append(PermissionProfileId).Append("\n");
sb.Append(" PermissionProfileName: ").Append(PermissionProfileName).Append("\n");
sb.Append(" Settings: ").Append(Settings).Append("\n");
sb.Append(" UserCount: ").Append(UserCount).Append("\n");
sb.Append(" Users: ").Append(Users).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PermissionProfile);
}
/// <summary>
/// Returns true if PermissionProfile instances are equal
/// </summary>
/// <param name="other">Instance of PermissionProfile to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PermissionProfile other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ModifiedByUsername == other.ModifiedByUsername ||
this.ModifiedByUsername != null &&
this.ModifiedByUsername.Equals(other.ModifiedByUsername)
) &&
(
this.ModifiedDateTime == other.ModifiedDateTime ||
this.ModifiedDateTime != null &&
this.ModifiedDateTime.Equals(other.ModifiedDateTime)
) &&
(
this.PermissionProfileId == other.PermissionProfileId ||
this.PermissionProfileId != null &&
this.PermissionProfileId.Equals(other.PermissionProfileId)
) &&
(
this.PermissionProfileName == other.PermissionProfileName ||
this.PermissionProfileName != null &&
this.PermissionProfileName.Equals(other.PermissionProfileName)
) &&
(
this.Settings == other.Settings ||
this.Settings != null &&
this.Settings.Equals(other.Settings)
) &&
(
this.UserCount == other.UserCount ||
this.UserCount != null &&
this.UserCount.Equals(other.UserCount)
) &&
(
this.Users == other.Users ||
this.Users != null &&
this.Users.SequenceEqual(other.Users)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ModifiedByUsername != null)
hash = hash * 59 + this.ModifiedByUsername.GetHashCode();
if (this.ModifiedDateTime != null)
hash = hash * 59 + this.ModifiedDateTime.GetHashCode();
if (this.PermissionProfileId != null)
hash = hash * 59 + this.PermissionProfileId.GetHashCode();
if (this.PermissionProfileName != null)
hash = hash * 59 + this.PermissionProfileName.GetHashCode();
if (this.Settings != null)
hash = hash * 59 + this.Settings.GetHashCode();
if (this.UserCount != null)
hash = hash * 59 + this.UserCount.GetHashCode();
if (this.Users != null)
hash = hash * 59 + this.Users.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebClientTestApp.Areas.HelpPage.ModelDescriptions;
using WebClientTestApp.Areas.HelpPage.Models;
namespace WebClientTestApp.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* 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 Mono.Addins;
using OpenSim.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace OpenSim.Server.Base
{
/// <summary>
/// Command manager -
/// Wrapper for OpenSim.Framework.PluginManager to allow
/// us to add commands to the console to perform operations
/// on our repos and plugins
/// </summary>
public class CommandManager
{
public AddinRegistry PluginRegistry;
protected PluginManager PluginManager;
public CommandManager(AddinRegistry registry)
{
PluginRegistry = registry;
PluginManager = new PluginManager(PluginRegistry);
AddManagementCommands();
}
private void AddManagementCommands()
{
// add plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin add", "plugin add \"plugin index\"",
"Install plugin from repository.",
HandleConsoleInstallPlugin);
// remove plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin remove", "plugin remove \"plugin index\"",
"Remove plugin from repository",
HandleConsoleUnInstallPlugin);
// list installed plugins
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin list installed",
"plugin list installed","List install plugins",
HandleConsoleListInstalledPlugin);
// list plugins available from registered repositories
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin list available",
"plugin list available","List available plugins",
HandleConsoleListAvailablePlugin);
// List available updates
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin updates", "plugin updates","List availble updates",
HandleConsoleListUpdates);
// Update plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin update", "plugin update \"plugin index\"","Update the plugin",
HandleConsoleUpdatePlugin);
// Add repository
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo add", "repo add \"url\"","Add repository",
HandleConsoleAddRepo);
// Refresh repo
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo refresh", "repo refresh \"url\"", "Sync with a registered repository",
HandleConsoleGetRepo);
// Remove repository from registry
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo remove",
"repo remove \"[url | index]\"",
"Remove repository from registry",
HandleConsoleRemoveRepo);
// Enable repo
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo enable", "repo enable \"[url | index]\"",
"Enable registered repository",
HandleConsoleEnableRepo);
// Disable repo
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo disable", "repo disable\"[url | index]\"",
"Disable registered repository",
HandleConsoleDisableRepo);
// List registered repositories
MainConsole.Instance.Commands.AddCommand("Repository", true,
"repo list", "repo list",
"List registered repositories",
HandleConsoleListRepos);
// *
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin info", "plugin info \"plugin index\"","Show detailed information for plugin",
HandleConsoleShowAddinInfo);
// Plugin disable
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin disable", "plugin disable \"plugin index\"",
"Disable a plugin",
HandleConsoleDisablePlugin);
// Enable plugin
MainConsole.Instance.Commands.AddCommand("Plugin", true,
"plugin enable", "plugin enable \"plugin index\"",
"Enable the selected plugin plugin",
HandleConsoleEnablePlugin);
}
#region console handlers
// Handle our console commands
//
// Install plugin from registered repository
/// <summary>
/// Handles the console install plugin command. Attempts to install the selected plugin
/// and
/// </summary>
/// <param name='module'>
/// Module.
/// </param>
/// <param name='cmd'>
/// Cmd.
/// </param>
private void HandleConsoleInstallPlugin(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (cmd.Length == 3)
{
int ndx = Convert.ToInt16(cmd[2]);
if (PluginManager.InstallPlugin(ndx, out result) == true)
{
ArrayList s = new ArrayList();
s.AddRange(result.Keys);
s.Sort();
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
Dictionary<string, object> plugin = (Dictionary<string, object>)result[k];
bool enabled = (bool)plugin["enabled"];
MainConsole.Instance.OutputFormat("{0}) {1} {2} rev. {3}",
k,
enabled == true ? "[ ]" : "[X]",
plugin["name"], plugin["version"]);
}
}
}
return;
}
// Remove installed plugin
private void HandleConsoleUnInstallPlugin(string module, string[] cmd)
{
if (cmd.Length == 3)
{
int ndx = Convert.ToInt16(cmd[2]);
PluginManager.UnInstall(ndx);
}
return;
}
// List installed plugins
private void HandleConsoleListInstalledPlugin(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
PluginManager.ListInstalledAddins(out result);
ArrayList s = new ArrayList();
s.AddRange(result.Keys);
s.Sort();
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
Dictionary<string, object> plugin = (Dictionary<string, object>)result[k];
bool enabled = (bool)plugin["enabled"];
MainConsole.Instance.OutputFormat("{0}) {1} {2} rev. {3}",
k,
enabled == true ? "[ ]" : "[X]",
plugin["name"], plugin["version"]);
}
return;
}
// List available plugins on registered repositories
private void HandleConsoleListAvailablePlugin(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
PluginManager.ListAvailable(out result);
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
// name, version, repository
Dictionary<string, object> plugin = (Dictionary<string, object>)result[k];
MainConsole.Instance.OutputFormat("{0}) {1} rev. {2} {3}",
k,
plugin["name"],
plugin["version"],
plugin["repository"]);
}
return;
}
// List available updates **not ready
private void HandleConsoleListUpdates(string module, string[] cmd)
{
PluginManager.ListUpdates();
return;
}
// Update plugin **not ready
private void HandleConsoleUpdatePlugin(string module, string[] cmd)
{
MainConsole.Instance.Output(PluginManager.Update());
return;
}
// Register repository
private void HandleConsoleAddRepo(string module, string[] cmd)
{
if ( cmd.Length == 3)
{
PluginManager.AddRepository(cmd[2]);
}
return;
}
// Get repository status **not working
private void HandleConsoleGetRepo(string module, string[] cmd)
{
PluginManager.GetRepository();
return;
}
// Remove registered repository
private void HandleConsoleRemoveRepo(string module, string[] cmd)
{
if (cmd.Length == 3)
PluginManager.RemoveRepository(cmd);
return;
}
// Enable repository
private void HandleConsoleEnableRepo(string module, string[] cmd)
{
PluginManager.EnableRepository(cmd);
return;
}
// Disable repository
private void HandleConsoleDisableRepo(string module, string[] cmd)
{
PluginManager.DisableRepository(cmd);
return;
}
// List repositories
private void HandleConsoleListRepos(string module, string[] cmd)
{
Dictionary<string, object> result = new Dictionary<string, object>();
PluginManager.ListRepositories(out result);
var list = result.Keys.ToList();
list.Sort();
foreach (var k in list)
{
Dictionary<string, object> repo = (Dictionary<string, object>)result[k];
bool enabled = (bool)repo["enabled"];
MainConsole.Instance.OutputFormat("{0}) {1} {2}",
k,
enabled == true ? "[ ]" : "[X]",
repo["name"], repo["url"]);
}
return;
}
// Show description information
private void HandleConsoleShowAddinInfo(string module, string[] cmd)
{
if (cmd.Length >= 3)
{
Dictionary<string, object> result = new Dictionary<string, object>();
int ndx = Convert.ToInt16(cmd[2]);
PluginManager.AddinInfo(ndx, out result);
MainConsole.Instance.OutputFormat("Name: {0}\nURL: {1}\nFile: {2}\nAuthor: {3}\nCategory: {4}\nDesc: {5}",
result["name"],
result["url"],
result["file_name"],
result["author"],
result["category"],
result["description"]);
return;
}
}
// Disable plugin
private void HandleConsoleDisablePlugin(string module, string[] cmd)
{
PluginManager.DisablePlugin(cmd);
return;
}
// Enable plugin
private void HandleConsoleEnablePlugin(string module, string[] cmd)
{
PluginManager.EnablePlugin(cmd);
return;
}
#endregion
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Extensions.Logging;
using Orleans.Messaging;
using Orleans.Serialization;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Hosting;
namespace Orleans.Runtime.Messaging
{
internal class Gateway
{
private readonly MessageCenter messageCenter;
private readonly MessageFactory messageFactory;
private readonly GatewayAcceptor acceptor;
private readonly Lazy<GatewaySender>[] senders;
private readonly GatewayClientCleanupAgent dropper;
// clients is the main authorative collection of all connected clients.
// Any client currently in the system appears in this collection.
// In addition, we use clientSockets collection for fast retrival of ClientState.
// Anything that appears in those 2 collections should also appear in the main clients collection.
private readonly ConcurrentDictionary<GrainId, ClientState> clients;
private readonly ConcurrentDictionary<Socket, ClientState> clientSockets;
private readonly SiloAddress gatewayAddress;
private int nextGatewaySenderToUseForRoundRobin;
private readonly ClientsReplyRoutingCache clientsReplyRoutingCache;
private ClientObserverRegistrar clientRegistrar;
private readonly object lockable;
private readonly SerializationManager serializationManager;
private readonly ExecutorService executorService;
private readonly ILogger logger;
private readonly ILoggerFactory loggerFactory;
private readonly SiloMessagingOptions messagingOptions;
public Gateway(
MessageCenter msgCtr,
ILocalSiloDetails siloDetails,
MessageFactory messageFactory,
SerializationManager serializationManager,
ExecutorService executorService,
ILoggerFactory loggerFactory,
IOptions<EndpointOptions> endpointOptions,
IOptions<SiloMessagingOptions> options,
IOptions<MultiClusterOptions> multiClusterOptions,
OverloadDetector overloadDetector)
{
this.messagingOptions = options.Value;
this.loggerFactory = loggerFactory;
messageCenter = msgCtr;
this.messageFactory = messageFactory;
this.logger = this.loggerFactory.CreateLogger<Gateway>();
this.serializationManager = serializationManager;
this.executorService = executorService;
acceptor = new GatewayAcceptor(
msgCtr,
this,
endpointOptions.Value.GetListeningProxyEndpoint(),
this.messageFactory,
this.serializationManager,
executorService,
siloDetails,
multiClusterOptions,
loggerFactory,
overloadDetector);
senders = new Lazy<GatewaySender>[messagingOptions.GatewaySenderQueues];
nextGatewaySenderToUseForRoundRobin = 0;
dropper = new GatewayClientCleanupAgent(this, executorService, loggerFactory, messagingOptions.ClientDropTimeout);
clients = new ConcurrentDictionary<GrainId, ClientState>();
clientSockets = new ConcurrentDictionary<Socket, ClientState>();
clientsReplyRoutingCache = new ClientsReplyRoutingCache(messagingOptions.ResponseTimeout);
this.gatewayAddress = siloDetails.GatewayAddress;
lockable = new object();
}
internal void Start(ClientObserverRegistrar clientRegistrar)
{
this.clientRegistrar = clientRegistrar;
this.clientRegistrar.SetGateway(this);
acceptor.Start();
for (int i = 0; i < senders.Length; i++)
{
int capture = i;
senders[capture] = new Lazy<GatewaySender>(() =>
{
var sender = new GatewaySender("GatewaySiloSender_" + capture, this, this.messageFactory, this.serializationManager, this.executorService, this.loggerFactory);
sender.Start();
return sender;
}, LazyThreadSafetyMode.ExecutionAndPublication);
}
dropper.Start();
}
internal void Stop()
{
dropper.Stop();
foreach (var sender in senders)
{
if (sender != null && sender.IsValueCreated)
sender.Value.Stop();
}
acceptor.Stop();
}
internal ICollection<GrainId> GetConnectedClients()
{
return clients.Keys;
}
internal void RecordOpenedSocket(Socket sock, GrainId clientId)
{
lock (lockable)
{
logger.Info(ErrorCode.GatewayClientOpenedSocket, "Recorded opened socket from endpoint {0}, client ID {1}.", sock.RemoteEndPoint, clientId);
ClientState clientState;
if (clients.TryGetValue(clientId, out clientState))
{
var oldSocket = clientState.Socket;
if (oldSocket != null)
{
// The old socket will be closed by itself later.
ClientState ignore;
clientSockets.TryRemove(oldSocket, out ignore);
}
QueueRequest(clientState, null);
}
else
{
int gatewayToUse = nextGatewaySenderToUseForRoundRobin % senders.Length;
nextGatewaySenderToUseForRoundRobin++; // under Gateway lock
clientState = new ClientState(clientId, gatewayToUse, messagingOptions.ClientDropTimeout);
clients[clientId] = clientState;
MessagingStatisticsGroup.ConnectedClientCount.Increment();
}
clientState.RecordConnection(sock);
clientSockets[sock] = clientState;
clientRegistrar.ClientAdded(clientId);
NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket();
}
}
internal void RecordClosedSocket(Socket sock)
{
if (sock == null) return;
lock (lockable)
{
ClientState cs = null;
if (!clientSockets.TryGetValue(sock, out cs)) return;
EndPoint endPoint = null;
try
{
endPoint = sock.RemoteEndPoint;
}
catch (Exception) { } // guard against ObjectDisposedExceptions
logger.Info(ErrorCode.GatewayClientClosedSocket, "Recorded closed socket from endpoint {0}, client ID {1}.", endPoint != null ? endPoint.ToString() : "null", cs.Id);
ClientState ignore;
clientSockets.TryRemove(sock, out ignore);
cs.RecordDisconnection();
}
}
internal SiloAddress TryToReroute(Message msg)
{
// ** Special routing rule for system target here **
// When a client make a request/response to/from a SystemTarget, the TargetSilo can be set to either
// - the GatewayAddress of the target silo (for example, when the client want get the cluster typemap)
// - the "internal" Silo-to-Silo address, if the client want to send a message to a specific SystemTarget
// activation that is on a silo on which there is no gateway available (or if the client is not
// connected to that gateway)
// So, if the TargetGrain is a SystemTarget we always trust the value from Message.TargetSilo and forward
// it to this address...
// EXCEPT if the value is equal to the current GatewayAdress: in this case we will return
// null and the local dispatcher will forward the Message to a local SystemTarget activation
if (msg.TargetGrain.IsSystemTarget && !IsTargetingLocalGateway(msg.TargetSilo))
return msg.TargetSilo;
// for responses from ClientAddressableObject to ClientGrain try to use clientsReplyRoutingCache for sending replies directly back.
if (!msg.SendingGrain.IsClient || !msg.TargetGrain.IsClient) return null;
if (msg.Direction != Message.Directions.Response) return null;
SiloAddress gateway;
return clientsReplyRoutingCache.TryFindClientRoute(msg.TargetGrain, out gateway) ? gateway : null;
}
internal void DropDisconnectedClients()
{
lock (lockable)
{
List<ClientState> clientsToDrop = clients.Values.Where(cs => cs.ReadyToDrop()).ToList();
foreach (ClientState client in clientsToDrop)
DropClient(client);
}
}
internal void DropExpiredRoutingCachedEntries()
{
lock (lockable)
{
clientsReplyRoutingCache.DropExpiredEntries();
}
}
private bool IsTargetingLocalGateway(SiloAddress siloAddress)
{
// Special case if the address used by the client was loopback
return this.gatewayAddress.Matches(siloAddress)
|| (IPAddress.IsLoopback(siloAddress.Endpoint.Address)
&& siloAddress.Endpoint.Port == this.gatewayAddress.Endpoint.Port
&& siloAddress.Generation == this.gatewayAddress.Generation);
}
// This function is run under global lock
// There is NO need to acquire individual ClientState lock, since we only access client Id (immutable) and close an older socket.
private void DropClient(ClientState client)
{
logger.Info(ErrorCode.GatewayDroppingClient, "Dropping client {0}, {1} after disconnect with no reconnect",
client.Id, DateTime.UtcNow.Subtract(client.DisconnectedSince));
ClientState ignore;
clients.TryRemove(client.Id, out ignore);
clientRegistrar.ClientDropped(client.Id);
Socket oldSocket = client.Socket;
if (oldSocket != null)
{
// this will not happen, since we drop only already disconnected clients, for socket is already null. But leave this code just to be sure.
client.RecordDisconnection();
clientSockets.TryRemove(oldSocket, out ignore);
SocketManager.CloseSocket(oldSocket);
}
MessagingStatisticsGroup.ConnectedClientCount.DecrementBy(1);
}
/// <summary>
/// See if this message is intended for a grain we're proxying, and queue it for delivery if so.
/// </summary>
/// <param name="msg"></param>
/// <returns>true if the message should be delivered to a proxied grain, false if not.</returns>
internal bool TryDeliverToProxy(Message msg)
{
// See if it's a grain we're proxying.
ClientState client;
// not taking global lock on the crytical path!
if (!clients.TryGetValue(msg.TargetGrain, out client))
return false;
// when this Gateway receives a message from client X to client addressale object Y
// it needs to record the original Gateway address through which this message came from (the address of the Gateway that X is connected to)
// it will use this Gateway to re-route the REPLY from Y back to X.
if (msg.SendingGrain.IsClient && msg.TargetGrain.IsClient)
{
clientsReplyRoutingCache.RecordClientRoute(msg.SendingGrain, msg.SendingSilo);
}
msg.TargetSilo = null;
// Override the SendingSilo only if the sending grain is not
// a system target
if (!msg.SendingGrain.IsSystemTarget)
msg.SendingSilo = gatewayAddress;
QueueRequest(client, msg);
return true;
}
private void QueueRequest(ClientState clientState, Message msg)
{
//int index = senders.Length == 1 ? 0 : Math.Abs(clientId.GetHashCode()) % senders.Length;
int index = clientState.GatewaySenderNumber;
senders[index].Value.QueueRequest(new OutgoingClientMessage(clientState.Id, msg));
}
internal void SendMessage(Message msg)
{
messageCenter.SendMessage(msg);
}
private class ClientState
{
private readonly TimeSpan clientDropTimeout;
internal Queue<Message> PendingToSend { get; private set; }
internal Queue<List<Message>> PendingBatchesToSend { get; private set; }
internal Socket Socket { get; private set; }
internal DateTime DisconnectedSince { get; private set; }
internal GrainId Id { get; private set; }
internal int GatewaySenderNumber { get; private set; }
internal bool IsConnected { get { return Socket != null; } }
internal ClientState(GrainId id, int gatewaySenderNumber, TimeSpan clientDropTimeout)
{
Id = id;
GatewaySenderNumber = gatewaySenderNumber;
this.clientDropTimeout = clientDropTimeout;
PendingToSend = new Queue<Message>();
PendingBatchesToSend = new Queue<List<Message>>();
}
internal void RecordDisconnection()
{
if (Socket == null) return;
DisconnectedSince = DateTime.UtcNow;
Socket = null;
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
internal void RecordConnection(Socket sock)
{
Socket = sock;
DisconnectedSince = DateTime.MaxValue;
}
internal bool ReadyToDrop()
{
return !IsConnected &&
(DateTime.UtcNow.Subtract(DisconnectedSince) >= clientDropTimeout);
}
}
private class GatewayClientCleanupAgent : DedicatedAsynchAgent
{
private readonly Gateway gateway;
private readonly TimeSpan clientDropTimeout;
internal GatewayClientCleanupAgent(Gateway gateway, ExecutorService executorService, ILoggerFactory loggerFactory, TimeSpan clientDropTimeout)
:base(executorService, loggerFactory)
{
this.gateway = gateway;
this.clientDropTimeout = clientDropTimeout;
}
#region Overrides of AsynchAgent
protected override void Run()
{
while (!Cts.IsCancellationRequested)
{
gateway.DropDisconnectedClients();
gateway.DropExpiredRoutingCachedEntries();
Thread.Sleep(clientDropTimeout);
}
}
#endregion
}
// this cache is used to record the addresses of Gateways from which clients connected to.
// it is used to route replies to clients from client addressable objects
// without this cache this Gateway will not know how to route the reply back to the client
// (since clients are not registered in the directory and this Gateway may not be proxying for the client for whom the reply is destined).
private class ClientsReplyRoutingCache
{
// for every client: the Gateway to use to route repies back to it plus the last time that client connected via this Gateway.
private readonly ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>> clientRoutes;
private readonly TimeSpan TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
internal ClientsReplyRoutingCache(TimeSpan responseTimeout)
{
clientRoutes = new ConcurrentDictionary<GrainId, Tuple<SiloAddress, DateTime>>();
TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES = responseTimeout.Multiply(5);
}
internal void RecordClientRoute(GrainId client, SiloAddress gateway)
{
var now = DateTime.UtcNow;
clientRoutes.AddOrUpdate(client, new Tuple<SiloAddress, DateTime>(gateway, now), (k, v) => new Tuple<SiloAddress, DateTime>(gateway, now));
}
internal bool TryFindClientRoute(GrainId client, out SiloAddress gateway)
{
gateway = null;
Tuple<SiloAddress, DateTime> tuple;
bool ret = clientRoutes.TryGetValue(client, out tuple);
if (ret)
gateway = tuple.Item1;
return ret;
}
internal void DropExpiredEntries()
{
List<GrainId> clientsToDrop = clientRoutes.Where(route => Expired(route.Value.Item2)).Select(kv => kv.Key).ToList();
foreach (GrainId client in clientsToDrop)
{
Tuple<SiloAddress, DateTime> tuple;
clientRoutes.TryRemove(client, out tuple);
}
}
private bool Expired(DateTime lastUsed)
{
return DateTime.UtcNow.Subtract(lastUsed) >= TIME_BEFORE_ROUTE_CACHED_ENTRY_EXPIRES;
}
}
private class GatewaySender : AsynchQueueAgent<OutgoingClientMessage>
{
private readonly Gateway gateway;
private readonly MessageFactory messageFactory;
private readonly CounterStatistic gatewaySends;
private readonly SerializationManager serializationManager;
internal GatewaySender(string name, Gateway gateway, MessageFactory messageFactory, SerializationManager serializationManager, ExecutorService executorService, ILoggerFactory loggerFactory)
: base(name, executorService, loggerFactory)
{
this.gateway = gateway;
this.messageFactory = messageFactory;
this.serializationManager = serializationManager;
gatewaySends = CounterStatistic.FindOrCreate(StatisticNames.GATEWAY_SENT);
OnFault = FaultBehavior.RestartOnFault;
}
protected override void Process(OutgoingClientMessage request)
{
if (Cts.IsCancellationRequested) return;
var client = request.Item1;
var msg = request.Item2;
// Find the client state
ClientState clientState;
bool found;
// TODO: Why do we need this lock here if clients is a ConcurrentDictionary?
//lock (gateway.lockable)
{
found = gateway.clients.TryGetValue(client, out clientState);
}
// This should never happen -- but make sure to handle it reasonably, just in case
if (!found || (clientState == null))
{
if (msg == null) return;
Log.Info(ErrorCode.GatewayTryingToSendToUnrecognizedClient, "Trying to send a message {0} to an unrecognized client {1}", msg.ToString(), client);
MessagingStatisticsGroup.OnFailedSentMessage(msg);
// Message for unrecognized client -- reject it
if (msg.Direction == Message.Directions.Request)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = this.messageFactory.CreateRejectionResponse(
msg,
Message.RejectionTypes.Unrecoverable,
"Unknown client " + client);
gateway.SendMessage(error);
}
else
{
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
return;
}
// if disconnected - queue for later.
if (!clientState.IsConnected)
{
if (msg == null) return;
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Queued message {0} for client {1}", msg, client);
clientState.PendingToSend.Enqueue(msg);
return;
}
// if the queue is non empty - drain it first.
if (clientState.PendingToSend.Count > 0)
{
if (msg != null)
clientState.PendingToSend.Enqueue(msg);
// For now, drain in-line, although in the future this should happen in yet another asynch agent
Drain(clientState);
return;
}
// the queue was empty AND we are connected.
// If the request includes a message to send, send it (or enqueue it for later)
if (msg == null) return;
if (!Send(msg, clientState.Socket))
{
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Queued message {0} for client {1}", msg, client);
clientState.PendingToSend.Enqueue(msg);
}
else
{
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Sent message {0} to client {1}", msg, client);
}
}
private void Drain(ClientState clientState)
{
// For now, drain in-line, although in the future this should happen in yet another asynch agent
while (clientState.PendingToSend.Count > 0)
{
var m = clientState.PendingToSend.Peek();
if (Send(m, clientState.Socket))
{
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Sent queued message {0} to client {1}", m, clientState.Id);
clientState.PendingToSend.Dequeue();
}
else
{
return;
}
}
}
private bool Send(Message msg, Socket sock)
{
if (Cts.IsCancellationRequested) return false;
if (sock == null) return false;
// Send the message
List<ArraySegment<byte>> data;
int headerLength;
try
{
int bodyLength;
data = msg.Serialize(this.serializationManager, out headerLength, out bodyLength);
if (headerLength + bodyLength > this.serializationManager.LargeObjectSizeThreshold)
{
Log.Info(ErrorCode.Messaging_LargeMsg_Outgoing, "Preparing to send large message Size={0} HeaderLength={1} BodyLength={2} #ArraySegments={3}. Msg={4}",
headerLength + bodyLength + Message.LENGTH_HEADER_SIZE, headerLength, bodyLength, data.Count, this.ToString());
if (Log.IsEnabled(LogLevel.Trace)) Log.Trace("Sending large message {0}", msg.ToLongString());
}
}
catch (Exception exc)
{
this.OnMessageSerializationFailure(msg, exc);
return true;
}
int length = data.Sum(x => x.Count);
int bytesSent = 0;
bool exceptionSending = false;
bool countMismatchSending = false;
string sendErrorStr;
try
{
bytesSent = sock.Send(data);
if (bytesSent != length)
{
// The complete message wasn't sent, even though no error was reported; treat this as an error
countMismatchSending = true;
sendErrorStr = String.Format("Byte count mismatch on send: sent {0}, expected {1}", bytesSent, length);
Log.Warn(ErrorCode.GatewayByteCountMismatch, sendErrorStr);
}
}
catch (Exception exc)
{
exceptionSending = true;
string remoteEndpoint = "";
if (!(exc is ObjectDisposedException))
{
try
{
remoteEndpoint = sock.RemoteEndPoint.ToString();
}
catch (Exception){}
}
sendErrorStr = String.Format("Exception sending to client at {0}: {1}", remoteEndpoint, exc);
Log.Warn(ErrorCode.GatewayExceptionSendingToClient, sendErrorStr, exc);
}
MessagingStatisticsGroup.OnMessageSend(msg.TargetSilo, msg.Direction, bytesSent, headerLength, SocketDirection.GatewayToClient);
bool sendError = exceptionSending || countMismatchSending;
if (sendError)
{
gateway.RecordClosedSocket(sock);
SocketManager.CloseSocket(sock);
}
gatewaySends.Increment();
msg.ReleaseBodyAndHeaderBuffers();
return !sendError;
}
private void OnMessageSerializationFailure(Message msg, Exception exc)
{
// we only get here if we failed to serialize the msg (or any other catastrophic failure).
// Request msg fails to serialize on the sending silo, so we just enqueue a rejection msg.
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
Log.Warn(ErrorCode.Messaging_Gateway_SerializationError, String.Format("Unexpected error serializing message {0} on the gateway", msg.ToString()), exc);
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
}
}
| |
// Copyright (c) Ugo Lattanzi. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using StackExchange.Redis.Extensions.Tests.Helpers;
using Xunit;
using static System.Linq.Enumerable;
namespace StackExchange.Redis.Extensions.Core.Tests;
public abstract partial class CacheClientTestBase
{
[Fact]
public async Task HashSetSingleValueNX_ValueDoesntExists_ShouldInsertAndRetrieveValue()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
var entryValue = new TestClass<DateTime>("test", DateTime.UtcNow);
// act
var res = await Sut.GetDefaultDatabase().HashSetAsync(hashKey, entryKey, entryValue, true).ConfigureAwait(false);
// assert
Assert.True(res);
var redisValue = await db.HashGetAsync(hashKey, entryKey).ConfigureAwait(false);
var data = serializer.Deserialize<TestClass<DateTime>>(redisValue);
Assert.Equal(entryValue, data);
}
[Fact]
public async Task HashSetSingleValueNX_ValueExists_ShouldNotInsertOriginalValueNotChanged()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
var entryValue = new TestClass<DateTime>("test1", DateTime.UtcNow);
var initialValue = new TestClass<DateTime>("test2", DateTime.UtcNow);
var initRes = await Sut.GetDefaultDatabase().HashSetAsync(hashKey, entryKey, initialValue).ConfigureAwait(false);
// act
var res = await Sut.GetDefaultDatabase().HashSetAsync(hashKey, entryKey, entryValue, true).ConfigureAwait(false);
// assert
Assert.True(initRes);
Assert.False(res);
var redisvalue = await db.HashGetAsync(hashKey, entryKey).ConfigureAwait(false);
var data = serializer.Deserialize<TestClass<DateTime>>(redisvalue);
Assert.Equal(initialValue, data);
}
[Fact]
public async Task HashSetSingleValue_ValueExists_ShouldUpdateValue()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
var entryValue = new TestClass<DateTime>("test1", DateTime.UtcNow);
var initialValue = new TestClass<DateTime>("test2", DateTime.UtcNow);
var initRes = Sut.GetDefaultDatabase().Database.HashSet(hashKey, entryKey, serializer.Serialize(initialValue));
// act
var res = await Sut.GetDefaultDatabase().HashSetAsync(hashKey, entryKey, entryValue, false).ConfigureAwait(false);
// assert
Assert.True(initRes, "Initial value was not set");
Assert.False(res); // NOTE: HSET returns: 1 if new field was created and value set, or 0 if field existed and value set. reference: http://redis.io/commands/HSET
var data = serializer.Deserialize<TestClass<DateTime>>(Sut.GetDefaultDatabase().Database.HashGet(hashKey, entryKey));
Assert.Equal(entryValue, data);
}
[Fact]
public async Task HashSetMultipleValues_HashGetMultipleValues_ShouldInsert()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var values = Range(0, 100).Select(_ => new TestClass<DateTime>(Guid.NewGuid().ToString(), DateTime.UtcNow));
var map = values.ToDictionary(val => Guid.NewGuid().ToString());
// act
await Sut.GetDefaultDatabase().HashSetAsync(hashKey, map).ConfigureAwait(false);
await Task.Delay(500).ConfigureAwait(false);
// assert
var data = db
.HashGet(hashKey, map.Keys.Select(x => (RedisValue)x).ToArray())
.ToList()
.ConvertAll(x => serializer.Deserialize<TestClass<DateTime>>(x));
Assert.Equal(map.Count, data.Count);
foreach (var val in data)
Assert.True(map.ContainsValue(val), $"result map doesn't contain value: {val}");
}
[Fact]
public async Task HashDelete_KeyExists_ShouldDelete()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
var entryValue = new TestClass<DateTime>(Guid.NewGuid().ToString(), DateTime.UtcNow);
Assert.True(db.HashSet(hashKey, entryKey, Sut.GetDefaultDatabase().Serializer.Serialize(entryValue)), "Failed setting test value into redis");
// act
var result = await Sut.GetDefaultDatabase().HashDeleteAsync(hashKey, entryKey).ConfigureAwait(false);
// assert
Assert.True(result);
Assert.True((await db.HashGetAsync(hashKey, entryKey).ConfigureAwait(false)).IsNull);
}
[Fact]
public async Task HashDelete_KeyDoesntExist_ShouldReturnFalse()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
// act
var result = await Sut.GetDefaultDatabase().HashDeleteAsync(hashKey, entryKey).ConfigureAwait(false);
// assert
Assert.False(result);
Assert.True((await db.HashGetAsync(hashKey, entryKey).ConfigureAwait(false)).IsNull);
}
[Fact]
public async Task HashDeleteMultiple_AllKeysExist_ShouldDeleteAll()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var values =
Range(0, 1000)
.Select(x => new TestClass<int>(Guid.NewGuid().ToString(), x))
.ToDictionary(x => x.Key);
await db.HashSetAsync(hashKey, values.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
// act
var result = await Sut.GetDefaultDatabase().HashDeleteAsync(hashKey, values.Keys.ToArray()).ConfigureAwait(false);
// assert
Assert.Equal(values.Count, result);
var dbValues = await db.HashGetAsync(hashKey, values.Select(x => (RedisValue)x.Key).ToArray()).ConfigureAwait(false);
Assert.NotNull(dbValues);
Assert.DoesNotContain(dbValues, x => !x.IsNull);
Assert.Equal(0, await db.HashLengthAsync(hashKey).ConfigureAwait(false));
}
[Fact]
public async Task HashDeleteMultiple_NotAllKeysExist_ShouldDeleteAllOnlyRequested()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var valuesDelete =
Range(0, 1000)
.Select(x => new TestClass<int>(Guid.NewGuid().ToString(), x))
.ToDictionary(x => x.Key);
var valuesKeep =
Range(0, 1000)
.Select(x => new TestClass<int>(Guid.NewGuid().ToString(), x))
.ToDictionary(x => x.Key);
await db.HashSetAsync(hashKey, valuesDelete.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
await db.HashSetAsync(hashKey, valuesKeep.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
// act
var result = await Sut.GetDefaultDatabase().HashDeleteAsync(hashKey, valuesDelete.Keys.ToArray()).ConfigureAwait(false);
// assert
Assert.Equal(valuesDelete.Count, result);
var dbDeletedValues = await db.HashGetAsync(hashKey, valuesDelete.Select(x => (RedisValue)x.Key).ToArray()).ConfigureAwait(false);
Assert.NotNull(dbDeletedValues);
Assert.DoesNotContain(dbDeletedValues, x => !x.IsNull);
var dbValues = await db.HashGetAsync(hashKey, valuesKeep.Select(x => (RedisValue)x.Key).ToArray()).ConfigureAwait(false);
Assert.NotNull(dbValues);
Assert.DoesNotContain(dbValues, x => x.IsNull);
Assert.Equal(1000, await db.HashLengthAsync(hashKey).ConfigureAwait(false));
Assert.Equal(1000, dbValues.Length);
Assert.All(dbValues, x => Assert.True(valuesKeep.ContainsKey(Sut.GetDefaultDatabase().Serializer.Deserialize<TestClass<int>>(x).Key)));
}
[Fact]
public async Task HashExists_KeyExists_ReturnTrue()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
var entryValue = new TestClass<DateTime>(Guid.NewGuid().ToString(), DateTime.UtcNow);
Assert.True(await db.HashSetAsync(hashKey, entryKey, Sut.GetDefaultDatabase().Serializer.Serialize(entryValue)).ConfigureAwait(false), "Failed setting test value into redis");
// act
var result = await Sut.GetDefaultDatabase().HashExistsAsync(hashKey, entryKey).ConfigureAwait(false);
// assert
Assert.True(result, "Entry doesn't exist in hash, but it should");
}
[Fact]
public async Task HashExists_KeyDoesntExists_ReturnFalse()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
// act
var result = await Sut.GetDefaultDatabase().HashExistsAsync(hashKey, entryKey).ConfigureAwait(false);
// assert
Assert.False(result, "Entry doesn't exist in hash, but call returned true");
}
[Fact]
public async Task HashKeys_HashEmpty_ReturnEmptyCollection()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
// act
var result = await Sut.GetDefaultDatabase().HashKeysAsync(hashKey).ConfigureAwait(false);
// assert
Assert.NotNull(result);
Assert.Empty(result);
}
[Fact]
public async Task HashKeys_HashNotEmpty_ReturnKeysCollection()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var values =
Range(0, 1000)
.Select(x => new TestClass<int>(Guid.NewGuid().ToString(), x))
.ToDictionary(x => x.Key);
await db.HashSetAsync(hashKey, values.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
// act
var result = await Sut.GetDefaultDatabase().HashKeysAsync(hashKey).ConfigureAwait(false);
// assert
Assert.NotNull(result);
var collection = result as IList<string> ?? result.ToList();
Assert.NotEmpty(collection);
Assert.Equal(values.Count, collection.Count);
foreach (var key in collection)
Assert.True(values.ContainsKey(key));
}
[Fact]
public async Task HashValues_HashEmpty_ReturnEmptyCollection()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
// act
var result = await Sut.GetDefaultDatabase().HashValuesAsync<string>(hashKey).ConfigureAwait(false);
// assert
Assert.NotNull(result);
Assert.Empty(result);
}
[Fact]
public async Task HashValues_HashNotEmpty_ReturnAllValues()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var values =
Range(0, 1000)
.Select(x => new TestClass<DateTime>(Guid.NewGuid().ToString(), DateTime.UtcNow))
.ToDictionary(x => x.Key);
await db.HashSetAsync(hashKey, values.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
// act
var result = await Sut.GetDefaultDatabase().HashValuesAsync<TestClass<DateTime>>(hashKey).ConfigureAwait(false);
// assert
Assert.NotNull(result);
var collection = result as IList<TestClass<DateTime>> ?? result.ToList();
Assert.NotEmpty(collection);
Assert.Equal(values.Count, collection.Count);
foreach (var key in collection)
Assert.Contains(key, values.Values);
}
[Fact]
public async Task HashLength_HashEmpty_ReturnZero()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
// act
var result = await Sut.GetDefaultDatabase().HashLengthAsync(hashKey).ConfigureAwait(false);
// assert
Assert.Equal(0, result);
}
[Fact]
public async Task HashLength_HashNotEmpty_ReturnCorrectCount()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var values =
Range(0, 1000)
.Select(x => new TestClass<int>(Guid.NewGuid().ToString(), x))
.ToDictionary(x => x.Key);
await db.HashSetAsync(hashKey, values.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
// act
var result = await Sut.GetDefaultDatabase().HashLengthAsync(hashKey).ConfigureAwait(false);
// assert
Assert.Equal(1000, result);
}
[Fact]
public async Task HashIncerementByLong_ValueDoesntExist_EntryCreatedWithValue()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
const int incBy = 1;
// act
Assert.False(db.HashExists(hashKey, entryKey));
var result = await Sut.GetDefaultDatabase().HashIncerementByAsync(hashKey, entryKey, incBy).ConfigureAwait(false);
// assert
Assert.Equal(incBy, result);
Assert.True(await Sut.GetDefaultDatabase().HashExistsAsync(hashKey, entryKey).ConfigureAwait(false));
Assert.Equal(incBy, db.HashGet(hashKey, entryKey));
}
[Fact]
public async Task HashIncerementByLong_ValueExist_EntryIncrementedCorrectValueReturned()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
const int entryValue = 15;
const int incBy = 1;
Assert.True(db.HashSet(hashKey, entryKey, entryValue));
// act
var result = await Sut.GetDefaultDatabase().HashIncerementByAsync(hashKey, entryKey, incBy).ConfigureAwait(false);
// assert
const int expected = entryValue + incBy;
Assert.Equal(expected, result);
Assert.Equal(expected, await db.HashGetAsync(hashKey, entryKey).ConfigureAwait(false));
}
[Fact]
public async Task HashIncerementByDouble_ValueDoesntExist_EntryCreatedWithValue()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
const double incBy = 0.9;
// act
Assert.False(db.HashExists(hashKey, entryKey));
var result = await Sut.GetDefaultDatabase().HashIncerementByAsync(hashKey, entryKey, incBy).ConfigureAwait(false);
// assert
Assert.Equal(incBy, result);
Assert.True(await Sut.GetDefaultDatabase().HashExistsAsync(hashKey, entryKey).ConfigureAwait(false));
Assert.Equal(incBy, (double)await db.HashGetAsync(hashKey, entryKey).ConfigureAwait(false), 6); // have to provide epsilon due to double error
}
[Fact]
public async Task HashIncerementByDouble_ValueExist_EntryIncrementedCorrectValueReturned()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var entryKey = Guid.NewGuid().ToString();
const double entryValue = 14.3;
const double incBy = 9.7;
Assert.True(db.HashSet(hashKey, entryKey, entryValue));
// act
var result = await Sut.GetDefaultDatabase().HashIncerementByAsync(hashKey, entryKey, incBy).ConfigureAwait(false);
// assert
const double expected = entryValue + incBy;
Assert.Equal(expected, result);
Assert.Equal(expected, db.HashGet(hashKey, entryKey));
}
[Fact]
public void HashScan_EmptyHash_ReturnEmptyCursor()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
Assert.True(db.HashLength(hashKey) == 0);
// act
var result = Sut.GetDefaultDatabase().HashScan<string>(hashKey, "*");
// assert
Assert.Empty(result);
}
[Fact]
public async Task HashScan_EntriesExistUseAstrisk_ReturnCursorToAllEntries()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var values =
Range(0, 1000)
.Select(x => new TestClass<DateTime>(Guid.NewGuid().ToString(), DateTime.UtcNow))
.ToDictionary(x => x.Key);
await db.HashSetAsync(hashKey, values.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
// act
var result = Sut.GetDefaultDatabase().HashScan<TestClass<DateTime>>(hashKey, "*");
// assert
Assert.NotNull(result);
var resultEnum = result.ToDictionary(x => x.Key, x => x.Value);
Assert.Equal(1000, resultEnum.Count);
foreach (var key in values.Keys)
{
Assert.True(resultEnum.ContainsKey(key));
Assert.Equal(values[key], resultEnum[key]);
}
}
[Fact]
public async Task HashScan_EntriesExistUseAstrisk_ReturnCursorToAllEntriesBeginningWithTwo()
{
// arrange
var hashKey = Guid.NewGuid().ToString();
var values =
Range(0, 1000)
.Select(x => new TestClass<DateTime>(Guid.NewGuid().ToString(), DateTime.UtcNow))
.ToDictionary(x => x.Key);
await db.HashSetAsync(hashKey, values.Select(x => new HashEntry(x.Key, Sut.GetDefaultDatabase().Serializer.Serialize(x.Value))).ToArray()).ConfigureAwait(false);
// act
var result = Sut.GetDefaultDatabase().HashScan<TestClass<DateTime>>(hashKey, "2*");
// assert
Assert.NotNull(result);
var resultEnum = result.ToDictionary(x => x.Key, x => x.Value);
Assert.Equal(values.Keys.Count(x => x.StartsWith("2", StringComparison.Ordinal)), resultEnum.Count);
foreach (var key in values.Keys.Where(x => x.StartsWith("2", StringComparison.Ordinal)))
{
Assert.True(resultEnum.ContainsKey(key));
Assert.Equal(values[key], resultEnum[key]);
}
}
}
| |
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Security;
using Rainbow.Framework.Settings;
using Rainbow.Framework.Site.Configuration;
using Rainbow.Framework.Site.Data;
using Rainbow.Framework.Users.Data;
using System.Collections.Generic;
using Rainbow.Framework.Providers.RainbowRoleProvider;
namespace Rainbow.Framework.Security
{
/// <summary>
/// The PortalSecurity class encapsulates two helper methods that enable
/// developers to easily check the role status of the current browser client.
/// </summary>
[History("jminond", "2004/09/29", "added killsession method mimic of sign out, as well as modified sign on to use cookieexpire in rainbow.config")]
[History("gman3001", "2004/09/29", "Call method for recording the user's last visit date on successful signon")]
[History("jviladiu@portalServices.net", "2004/09/23", "Get users & roles from true portal if UseSingleUserBase=true")]
[History("jviladiu@portalServices.net", "2004/08/23", "Deleted repeated code in HasxxxPermissions and GetxxxPermissions")]
[History("cisakson@yahoo.com", "2003/04/28", "Changed the IsInRole function so it support's a custom setting for Windows portal admins!")]
[History("Geert.Audenaert@Syntegra.Com", "2003/03/26", "Changed the IsInRole function so it support's users to in case of windowsauthentication!")]
[History("Thierry (tiptopweb)", "2003/04/12", "Migrate shopping cart in SignOn for E-Commerce")]
public class PortalSecurity
{
const string strPortalSettings = "PortalSettings";
// [Flags]
// public enum SecurityPermission : uint
// {
// NoAccess = 0x0000,
// View = 0x0001,
// Add = 0x0002,
// Edit = 0x0004,
// Delete = 0x0008
// }
/// <summary>
/// PortalSecurity.IsInRole() Method
/// The IsInRole method enables developers to easily check the role
/// status of the current browser client.
/// </summary>
/// <param name="role">The role.</param>
/// <returns>
/// <c>true</c> if [is in role] [the specified role]; otherwise, <c>false</c>.
/// </returns>
public static bool IsInRole(string role)
{
// Check if integrated windows authentication is used ?
bool useNTLM = HttpContext.Current.User is WindowsPrincipal;
// Check if the user is in the Admins role.
if ( useNTLM && role.Trim() == "Admins" )
{
// Obtain PortalSettings from Current Context
// WindowsAdmins added 28.4.2003 Cory Isakson
PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items[strPortalSettings];
StringBuilder winRoles = new StringBuilder();
winRoles.Append(portalSettings.CustomSettings["WindowsAdmins"]);
winRoles.Append(";");
//jes1111 - winRoles.Append(ConfigurationSettings.AppSettings["ADAdministratorGroup"]);
winRoles.Append(Config.ADAdministratorGroup);
return IsInRoles(winRoles.ToString());
}
// Allow giving access to users
if ( useNTLM && role == HttpContext.Current.User.Identity.Name )
return true;
else
{
return HttpContext.Current.User.IsInRole(role);
}
}
/// <summary>
/// The IsInRoles method enables developers to easily check the role
/// status of the current browser client against an array of roles
/// </summary>
/// <param name="roles">The roles.</param>
/// <returns>
/// <c>true</c> if [is in roles] [the specified roles]; otherwise, <c>false</c>.
/// </returns>
public static bool IsInRoles(string roles)
{
HttpContext context = HttpContext.Current;
if (roles != null)
{
foreach (string splitRole in roles.Split( new char[] {';'} ))
{
string role = splitRole.Trim();
if (role != null && role.Length != 0 && ((role == "All Users") || (IsInRole(role))))
{
return true;
}
// Authenticated user role added
// 15 nov 2002 - by manudea
if ((role == "Authenticated Users") && (context.Request.IsAuthenticated))
{
return true;
}
// end authenticated user role added
// Unauthenticated user role added
// 30/01/2003 - by manudea
if ((role == "Unauthenticated Users") && (!context.Request.IsAuthenticated))
{
return true;
}
// end Unauthenticated user role added
}
}
return false;
}
#region Current user permissions
/// <summary>
/// Determines whether the specified module ID has permissions.
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <param name="procedureName">Name of the procedure.</param>
/// <param name="parameterRol">The parameter rol.</param>
/// <returns>
/// <c>true</c> if the specified module ID has permissions; otherwise, <c>false</c>.
/// </returns>
private static bool hasPermissions (int moduleID, string procedureName, string parameterRol)
{
if (RecyclerDB.ModuleIsInRecycler(moduleID))
procedureName = procedureName + "Recycler";
if (moduleID <= 0) return false;
// Obtain PortalSettings from Current Context
PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items[strPortalSettings];
int portalID = portalSettings.PortalID;
// jviladiu@portalServices.net: Get users & roles from true portal (2004/09/23)
if (Config.UseSingleUserBase) portalID = 0;
// Create Instance of Connection and Command Object
using (SqlConnection myConnection = Config.SqlConnectionString)
{
using (SqlCommand myCommand = new SqlCommand(procedureName, myConnection))
{
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
parameterModuleID.Value = moduleID;
myCommand.Parameters.Add(parameterModuleID);
SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4);
parameterPortalID.Value = portalID;
myCommand.Parameters.Add(parameterPortalID);
// Add out parameters to Sproc
SqlParameter parameterAccessRoles = new SqlParameter("@AccessRoles", SqlDbType.NVarChar, 256);
parameterAccessRoles.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(parameterAccessRoles);
SqlParameter parameterRoles = new SqlParameter(parameterRol, SqlDbType.NVarChar, 256);
parameterRoles.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(parameterRoles);
// Open the database connection and execute the command
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
return IsInRoles(parameterAccessRoles.Value.ToString()) &&
IsInRoles(parameterRoles.Value.ToString());
}
}
}
/// <summary>
/// The HasEditPermissions method enables developers to easily check
/// whether the current browser client has access to edit the settings
/// of a specified portal module.
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// <c>true</c> if [has edit permissions] [the specified module ID]; otherwise, <c>false</c>.
/// </returns>
public static bool HasEditPermissions(int moduleID)
{
// if (RecyclerDB.ModuleIsInRecycler(moduleID))
// return hasPermissions (moduleID, "rb_GetAuthEditRolesRecycler", "@EditRoles");
// else
return hasPermissions (moduleID, "rb_GetAuthEditRoles", "@EditRoles");
}
/// <summary>
/// The HasViewPermissions method enables developers to easily check
/// whether the current browser client has access to view the
/// specified portal module
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// <c>true</c> if [has view permissions] [the specified module ID]; otherwise, <c>false</c>.
/// </returns>
[History("JB - john@bowenweb.com","2005/06/11","Added support for module Recycle Bin")]
public static bool HasViewPermissions(int moduleID)
{
return hasPermissions (moduleID, "rb_GetAuthViewRoles", "@ViewRoles");
}
/// <summary>
/// The HasAddPermissions method enables developers to easily check
/// whether the current browser client has access to Add the
/// specified portal module
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// <c>true</c> if [has add permissions] [the specified module ID]; otherwise, <c>false</c>.
/// </returns>
public static bool HasAddPermissions(int moduleID)
{
return hasPermissions (moduleID, "rb_GetAuthAddRoles", "@AddRoles");
}
/// <summary>
/// The HasDeletePermissions method enables developers to easily check
/// whether the current browser client has access to Delete the
/// specified portal module
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// <c>true</c> if [has delete permissions] [the specified module ID]; otherwise, <c>false</c>.
/// </returns>
public static bool HasDeletePermissions(int moduleID)
{
return hasPermissions (moduleID, "rb_GetAuthDeleteRoles", "@DeleteRoles");
}
/// <summary>
/// The HasPropertiesPermissions method enables developers to easily check
/// whether the current browser client has access to Properties the
/// specified portal module
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// <c>true</c> if [has properties permissions] [the specified module ID]; otherwise, <c>false</c>.
/// </returns>
public static bool HasPropertiesPermissions(int moduleID)
{
return hasPermissions (moduleID, "rb_GetAuthPropertiesRoles", "@PropertiesRoles");
}
/// <summary>
/// The HasApprovePermissions method enables developers to easily check
/// whether the current browser client has access to Approve the
/// specified portal module
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// <c>true</c> if [has approve permissions] [the specified module ID]; otherwise, <c>false</c>.
/// </returns>
public static bool HasApprovePermissions(int moduleID)
{
return hasPermissions (moduleID, "rb_GetAuthApproveRoles", "@ApproveRoles");
}
/// <summary>
/// The HasPublishPermissions method enables developers to easily check
/// whether the current browser client has access to Approve the
/// specified portal module
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// <c>true</c> if [has publish permissions] [the specified module ID]; otherwise, <c>false</c>.
/// </returns>
public static bool HasPublishPermissions(int moduleID)
{
return hasPermissions (moduleID, "rb_GetAuthPublishingRoles", "@PublishingRoles");
}
#endregion
#region GetRoleList Methods - Added by John Mandia (www.whitelightsolutions.com) 15/08/04
private static string getPermissions (int moduleID, string procedureName, string parameterRol)
{
// Obtain PortalSettings from Current Context
PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items[strPortalSettings];
int portalID = portalSettings.PortalID;
// jviladiu@portalServices.net: Get users & roles from true portal (2004/09/23)
if (Config.UseSingleUserBase) portalID = 0;
// Create Instance of Connection and Command Object
using (SqlConnection myConnection = Config.SqlConnectionString)
{
using (SqlCommand myCommand = new SqlCommand(procedureName, myConnection))
{
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);
parameterModuleID.Value = moduleID;
myCommand.Parameters.Add(parameterModuleID);
SqlParameter parameterPortalID = new SqlParameter("@PortalID", SqlDbType.Int, 4);
parameterPortalID.Value = portalID;
myCommand.Parameters.Add(parameterPortalID);
// Add out parameters to Sproc
SqlParameter parameterAccessRoles = new SqlParameter("@AccessRoles", SqlDbType.NVarChar, 256);
parameterAccessRoles.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(parameterAccessRoles);
SqlParameter parameterRoles = new SqlParameter(parameterRol, SqlDbType.NVarChar, 256);
parameterRoles.Direction = ParameterDirection.Output;
myCommand.Parameters.Add(parameterRoles);
// Open the database connection and execute the command
myConnection.Open();
try
{
myCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
return parameterRoles.Value.ToString();
}
}
}
/// <summary>
/// The GetEditPermissions method enables developers to easily retrieve
/// a list of roles that have Edit Permissions
/// of a specified portal module.
/// </summary>
/// <param name="moduleID"></param>
/// <returns>A list of roles that have Edit permissions seperated by ;</returns>
public static string GetEditPermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthEditRoles", "@EditRoles");
}
/// <summary>
/// The GetViewPermissions method enables developers to easily retrieve
/// a list of roles that have View permissions for the
/// specified portal module
/// </summary>
/// <param name="moduleID"></param>
/// <returns>A list of roles that have View permissions for the specified module seperated by ;</returns>
public static string GetViewPermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthViewRoles", "@ViewRoles");
}
/// <summary>
/// The GetAddPermissions method enables developers to easily retrieve
/// a list of roles that have Add permissions for the
/// specified portal module
/// </summary>
/// <param name="moduleID"></param>
/// <returns>A list of roles that have Add permissions for the specified module seperated by ;</returns>
public static string GetAddPermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthAddRoles", "@AddRoles");
}
/// <summary>
/// The GetDeletePermissions method enables developers to easily retrieve
/// a list of roles that have access to Delete the
/// specified portal module
/// </summary>
/// <param name="moduleID"></param>
/// <returns>A list of roles that have delete permissions for the specified module seperated by ;</returns>
public static string GetDeletePermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthDeleteRoles", "@DeleteRoles");
}
/// <summary>
/// The GetPropertiesPermissions method enables developers to easily retrieve
/// a list of roles that have access to Properties for the
/// specified portal module
/// </summary>
/// <param name="moduleID"></param>
/// <returns>A list of roles that have Properties permission for the specified module seperated by ;</returns>
public static string GetPropertiesPermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthPropertiesRoles", "@PropertiesRoles");
}
/// <summary>
/// The GetMoveModulePermissions method enables developers to easily retrieve
/// a list of roles that have access to move specified portal moduleModule.
/// </summary>
/// <param name="moduleID"></param>
/// <returns>A list of roles that have move module permission for the specified module seperated by ;</returns>
public static string GetMoveModulePermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthMoveModuleRoles", "@MoveModuleRoles");
}
/// <summary>
/// The GetDeleteModulePermissions method enables developers to easily retrieve
/// a list of roles that have access to delete specified portal moduleModule.
/// </summary>
/// <param name="moduleID"></param>
/// <returns>A list of roles that have delete module permission for the specified module seperated by ;</returns>
public static string GetDeleteModulePermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthDeleteModuleRoles", "@DeleteModuleRoles");
}
/// <summary>
/// The GetApprovePermissions method enables developers to easily retrieve
/// a list of roles that have Approve permissions for the
/// specified portal module
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// A string of roles that have approve permissions seperated by ;
/// </returns>
public static string GetApprovePermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthApproveRoles", "@ApproveRoles");
}
/// <summary>
/// The GetPublishPermissions method enables developers to easily retrieve
/// the list of roles that have Publish Permissions.
/// </summary>
/// <param name="moduleID">The module ID.</param>
/// <returns>
/// A list of roles that has Publish Permissions seperated by ;
/// </returns>
public static string GetPublishPermissions(int moduleID)
{
return getPermissions(moduleID, "rb_GetAuthPublishingRoles", "@PublishingRoles");
}
#endregion
#region Sign methods
/// <summary>
/// Single point for logging on an user, not persistent.
/// </summary>
/// <param name="user">Username or email</param>
/// <param name="password">Password</param>
/// <returns></returns>
public static string SignOn(string user, string password)
{
return SignOn(user, password, false);
}
/// <summary>
/// Single point for logging on an user.
/// </summary>
/// <param name="user">Username or email</param>
/// <param name="password">Password</param>
/// <param name="persistent">Use a cookie to make it persistent</param>
/// <returns></returns>
public static string SignOn(string user, string password, bool persistent)
{
return SignOn(user, password, persistent, null);
}
/// <summary>
/// Single point for logging on an user.
/// </summary>
/// <param name="user">Username or email</param>
/// <param name="password">Password</param>
/// <param name="persistent">Use a cookie to make it persistent</param>
/// <param name="redirectPage">The redirect page.</param>
/// <returns></returns>
[History("bja@reedtek.com", "2003/05/16", "Support for collapsable")]
public static string SignOn(string user, string password, bool persistent, string redirectPage)
{
// Obtain PortalSettings from Current Context
PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items[strPortalSettings];
MembershipUser usr;
UsersDB accountSystem = new UsersDB();
// Attempt to Validate User Credentials using UsersDB
usr = accountSystem.Login(user, password);
// Thierry (tiptopweb), 12 Apr 2003: Save old ShoppingCartID
// ShoppingCartDB shoppingCart = new ShoppingCartDB();
// string tempCartID = ShoppingCartDB.GetCurrentShoppingCartID();
if (usr != null)
{
// Ender, 31 July 2003: Support for the monitoring module by Paul Yarrow
if(Config.EnableMonitoring)
{
try
{
Monitoring.LogEntry((Guid)usr.ProviderUserKey, portalSettings.PortalID, -1, "Logon", string.Empty);
}
catch
{
ErrorHandler.Publish(LogLevel.Info, "Cannot monitoring login user " + usr.UserName);
}
}
// Use security system to set the UserID within a client-side Cookie
FormsAuthentication.SetAuthCookie(usr.ToString(), persistent);
// Rainbow Security cookie Required if we are sharing a single domain
// with portal Alias in the URL
// Set a cookie to persist authentication for each portal
// so user can be reauthenticated
// automatically if they chose to Remember Login
HttpCookie hck = HttpContext.Current.Response.Cookies["Rainbow_" + portalSettings.PortalAlias.ToLower()];
hck.Value = usr.ToString(); //Fill all data: name + email + id
hck.Path = "/";
if (persistent) // Keep the cookie?
{
hck.Expires = DateTime.Now.AddYears(50);
}
else
{
//jminond - option to kill cookie after certain time always
// jes1111
// if(ConfigurationSettings.AppSettings["CookieExpire"] != null)
// {
// int minuteAdd = int.Parse(ConfigurationSettings.AppSettings["CookieExpire"]);
int minuteAdd = Config.CookieExpire;
DateTime time = DateTime.Now;
TimeSpan span = new TimeSpan(0, 0, minuteAdd, 0, 0);
hck.Expires = time.Add(span);
// }
}
if (redirectPage == null || redirectPage.Length == 0)
{
// Redirect browser back to originating page
if(HttpContext.Current.Request.UrlReferrer != null)
{
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.UrlReferrer.ToString());
}
else
{
HttpContext.Current.Response.Redirect(Path.ApplicationRoot);
}
return usr.Email;
}
else
{
HttpContext.Current.Response.Redirect(redirectPage);
}
}
return null;
}
/// <summary>
/// ExtendCookie
/// </summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="minuteAdd">The minute add.</param>
public static void ExtendCookie(PortalSettings portalSettings, int minuteAdd)
{
DateTime time = DateTime.Now;
TimeSpan span = new TimeSpan(0, 0, minuteAdd, 0, 0);
HttpContext.Current.Response.Cookies["Rainbow_" + portalSettings.PortalAlias].Expires = time.Add(span);
return;
}
/// <summary>
/// ExtendCookie
/// </summary>
/// <param name="portalSettings">The portal settings.</param>
public static void ExtendCookie(PortalSettings portalSettings)
{
int minuteAdd = Config.CookieExpire;
ExtendCookie(portalSettings, minuteAdd);
return;
}
/// <summary>
/// Single point logoff
/// </summary>
public static void SignOut()
{
SignOut(HttpUrlBuilder.BuildUrl("~/Default.aspx"), true);
}
/// <summary>
/// Kills session after timeout
/// jminond - fix kill session after timeout.
/// </summary>
public static void KillSession()
{
SignOut(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logon.aspx"), true);
//HttpContext.Current.Response.Redirect(urlToRedirect);
//PortalSecurity.AccessDenied();
}
/// <summary>
/// Single point logoff
/// </summary>
public static void SignOut(string urlToRedirect, bool removeLogin)
{
// Log User Off from Cookie Authentication System
FormsAuthentication.SignOut();
// Invalidate roles token
HttpCookie hck = HttpContext.Current.Response.Cookies["portalroles"];
hck.Value = null;
hck.Expires = new DateTime(1999, 10, 12);
hck.Path = "/";
if (removeLogin)
{
// Obtain PortalSettings from Current Context
PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items[strPortalSettings];
// Invalidate Portal Alias Cookie security
HttpCookie xhck = HttpContext.Current.Response.Cookies["Rainbow_" + portalSettings.PortalAlias.ToLower()];
xhck.Value = null;
xhck.Expires = new DateTime(1999, 10, 12);
xhck.Path = "/";
}
// [START] bja@reedtek.com remove user window information
// User Information
// valid user
if (HttpContext.Current.User != null)
{
// Obtain PortalSettings from Current Context
//Ender 4 July 2003: Added to support the Monitoring module by Paul Yarrow
PortalSettings portalSettings = (PortalSettings)HttpContext.Current.Items[strPortalSettings];
// User Information
UsersDB users = new UsersDB();
MembershipUser user = users.GetSingleUser( HttpContext.Current.User.Identity.Name );
// get user id
// by ghalib ghniem Guid uid = (Guid)user.ProviderUserKey;
//ghalib ghniem admin@itinfoplus.com 22 February 2010
//cause already in context there is the old user name, and there is no
//data retrived when we ask for that old one that we changed it, it ( Guid userId = (Guid)user.ProviderUserKey;) will make an exception
//so we have to check before we say Guid userId = (Guid)user.ProviderUserKey;
Guid uid = Guid.Empty;
if (user != null)
{
uid = (Guid)user.ProviderUserKey;
}
//end of ghalib changes
if ( !uid.Equals(Guid.Empty) )
{
try
{
if(Config.EnableMonitoring)
{
Monitoring.LogEntry(uid, portalSettings.PortalID, -1, "Logoff", string.Empty);
}
}
catch {}
}
}
// [END ] bja@reedtek.com remove user window information
//Redirect user back to the Portal Home Page
if (urlToRedirect.Length > 0)
HttpContext.Current.Response.Redirect(urlToRedirect);
}
#endregion
/// <summary>
/// Redirect user back to the Portal Home Page.
/// Mainily used after a succesfull login.
/// </summary>
public static void PortalHome()
{
HttpContext.Current.Response.Redirect(HttpUrlBuilder.BuildUrl("~/Default.aspx"));
}
/// <summary>
/// Single point access deny.
/// Called when there is an unauthorized access attempt.
/// </summary>
public static void AccessDenied()
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
throw new HttpException(403, "Access Denied", 2);
else
HttpContext.Current.Response.Redirect(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logon.aspx"));
}
/// <summary>
/// Single point edit access deny.
/// Called when there is an unauthorized access attempt to an edit page.
/// </summary>
public static void AccessDeniedEdit()
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
throw new HttpException(403, "Access Denied Edit", 3);
else
HttpContext.Current.Response.Redirect(HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Admin/Logon.aspx"));
}
/// <summary>
/// Single point edit access deny from the Secure server (SSL)
/// Called when there is an unauthorized access attempt to an edit page.
/// </summary>
public static void SecureAccessDenied()
{
throw new HttpException(403, "Secure Access Denied", 3);
}
/// <summary>
/// Single point get roles
/// </summary>
public static IList<RainbowRole> GetRoles()
{
// Obtain PortalSettings from Current Context
PortalSettings portalSettings = (PortalSettings) HttpContext.Current.Items[strPortalSettings];
int portalID = portalSettings.PortalID;
// john.mandia@whitelightsolutions.com: 29th May 2004 When retrieving/editing/adding roles or users etc then portalID should be 0 if it is shared
// But I commented this out as this check is done in UsersDB.GetRoles Anyway
//if (Config.UseSingleUserBase) portalID = 0;
IList<RainbowRole> roles;
// TODO: figure out if we could persist role Guid in cookies
//// Create the roles cookie if it doesn't exist yet for this session.
//if ((HttpContext.Current.Request.Cookies["portalroles"] == null) || (HttpContext.Current.Request.Cookies["portalroles"].Value == string.Empty) || (HttpContext.Current.Request.Cookies["portalroles"].Expires < DateTime.Now))
//{
try
{
// Get roles from UserRoles table, and add to cookie
UsersDB accountSystem = new UsersDB();
MembershipUser u = accountSystem.GetSingleUser( HttpContext.Current.User.Identity.Name );
roles = accountSystem.GetRoles(u.Email, portalSettings.PortalAlias);
}
catch
{
//no roles
roles = new List<RainbowRole>();
}
// // Create a string to persist the roles
// string roleStr = string.Empty;
// foreach ( RainbowRole role in roles )
// {
// roleStr += role.Name;
// roleStr += ";";
// }
// // Create a cookie authentication ticket.
// FormsAuthenticationTicket ticket = new FormsAuthenticationTicket
// (
// 1, // version
// HttpContext.Current.User.Identity.Name, // user name
// DateTime.Now, // issue time
// DateTime.Now.AddHours(1), // expires every hour
// false, // don't persist cookie
// roleStr // roles
// );
// // Encrypt the ticket
// string cookieStr = FormsAuthentication.Encrypt(ticket);
// // Send the cookie to the client
// HttpContext.Current.Response.Cookies["portalroles"].Value = cookieStr;
// HttpContext.Current.Response.Cookies["portalroles"].Path = "/";
// HttpContext.Current.Response.Cookies["portalroles"].Expires = DateTime.Now.AddMinutes(1);
//}
//else
//{
// // Get roles from roles cookie
// FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies["portalroles"].Value);
// //convert the string representation of the role data into a string array
// ArrayList userRoles = new ArrayList();
// //by Jes
// string _ticket = ticket.UserData.TrimEnd(new char[] {';'});
// foreach (string role in _ticket.Split(new char[] {';'} ))
// {
// userRoles.Add(role + ";");
// }
// roles = (string[]) userRoles.ToArray(typeof(string));
//}
return roles;
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using System;
using System.Collections.Immutable;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class NoPIATests : ExpressionCompilerTestBase
{
[WorkItem(1033598)]
[Fact]
public void ExplicitEmbeddedType()
{
var source =
@"using System.Runtime.InteropServices;
[TypeIdentifier]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D8"")]
public interface I
{
object F();
}
class C
{
void M()
{
var o = (I)null;
}
static void Main()
{
(new C()).M();
}
}";
var compilation0 = CSharpTestBase.CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugExe,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
var runtime = CreateRuntimeInstance(compilation0);
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("this", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (I V_0) //o
IL_0000: ldarg.0
IL_0001: ret
}");
}
[WorkItem(1035310)]
[Fact]
public void EmbeddedType()
{
var sourcePIA =
@"using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssembly(0, 0)]
[assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DA"")]
[ComImport]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DA"")]
public interface I
{
object F();
}";
var source =
@"class C
{
static void M()
{
var o = (I)null;
}
}";
var compilationPIA = CreateCompilationWithMscorlib(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: Guid.NewGuid().ToString("D"),
references: new MetadataReference[] { referencePIA });
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
// References should not include PIA.
Assert.Equal(references.Length, 1);
Assert.True(references[0].Display.StartsWith("mscorlib"));
var runtime = CreateRuntimeInstance(
Guid.NewGuid().ToString("D"),
references,
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("o", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (I V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}");
}
/// <summary>
/// Duplicate type definitions: in PIA
/// and as embedded type.
/// </summary>
[Fact]
public void PIATypeAndEmbeddedType()
{
var sourcePIA =
@"using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssembly(0, 0)]
[assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DC"")]
[ComImport]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DC"")]
public interface I
{
object F();
}";
var sourceA =
@"public class A
{
public static void M(I x)
{
}
}";
var sourceB =
@"class B
{
static void Main()
{
I y = null;
A.M(y);
}
}";
var compilationPIA = CreateCompilationWithMscorlib(sourcePIA, options: TestOptions.DebugDll);
byte[] exePIA;
byte[] pdbPIA;
ImmutableArray<MetadataReference> referencesPIA;
compilationPIA.EmitAndGetReferences(out exePIA, out pdbPIA, out referencesPIA);
var metadataPIA = AssemblyMetadata.CreateFromImage(exePIA);
var referencePIA = metadataPIA.GetReference();
// csc /t:library /l:PIA.dll A.cs
var compilationA = CreateCompilationWithMscorlib(
sourceA,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: new MetadataReference[] { metadataPIA.GetReference(embedInteropTypes: true) });
byte[] exeA;
byte[] pdbA;
ImmutableArray<MetadataReference> referencesA;
compilationA.EmitAndGetReferences(out exeA, out pdbA, out referencesA);
var metadataA = AssemblyMetadata.CreateFromImage(exeA);
var referenceA = metadataA.GetReference();
// csc /r:A.dll /r:PIA.dll B.cs
var compilationB = CreateCompilationWithMscorlib(
sourceB,
options: TestOptions.DebugExe,
assemblyName: Guid.NewGuid().ToString("D"),
references: new MetadataReference[] { metadataA.GetReference(), metadataPIA.GetReference() });
byte[] exeB;
byte[] pdbB;
ImmutableArray<MetadataReference> referencesB;
compilationB.EmitAndGetReferences(out exeB, out pdbB, out referencesB);
var metadataB = AssemblyMetadata.CreateFromImage(exeB);
var referenceB = metadataB.GetReference();
// Create runtime from modules { mscorlib, PIA, A, B }.
var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance();
modulesBuilder.Add(MscorlibRef.ToModuleInstance(fullImage: null, symReader: null));
modulesBuilder.Add(referenceA.ToModuleInstance(fullImage: exeA, symReader: new SymReader(pdbA)));
modulesBuilder.Add(referencePIA.ToModuleInstance(fullImage: null, symReader: null));
modulesBuilder.Add(referenceB.ToModuleInstance(fullImage: exeB, symReader: new SymReader(pdbB)));
using (var runtime = new RuntimeInstance(modulesBuilder.ToImmutableAndFree()))
{
var context = CreateMethodContext(runtime, "A.M");
ResultProperties resultProperties;
string error;
// Bind to local of embedded PIA type.
var testData = new CompilationTestData();
context.CompileExpression("x", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
// Binding to method on original PIA should fail
// since it was not included in embedded type.
testData = new CompilationTestData();
context.CompileExpression("x.F()", out resultProperties, out error, testData);
Assert.Equal(error, "error CS1061: 'I' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?)");
// Binding to method on original PIA should succeed
// in assembly referencing PIA.dll.
context = CreateMethodContext(runtime, "B.Main");
testData = new CompilationTestData();
context.CompileExpression("y.F()", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
.locals init (I V_0) //y
IL_0000: ldloc.0
IL_0001: callvirt ""object I.F()""
IL_0006: ret
}");
}
}
}
}
| |
// 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.Diagnostics;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Classification;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo
{
public abstract class AbstractSemanticQuickInfoSourceTests
{
protected readonly ClassificationBuilder ClassificationBuilder;
protected AbstractSemanticQuickInfoSourceTests()
{
this.ClassificationBuilder = new ClassificationBuilder();
}
[DebuggerStepThrough]
protected Tuple<string, string> Struct(string value)
{
return ClassificationBuilder.Struct(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Enum(string value)
{
return ClassificationBuilder.Enum(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Interface(string value)
{
return ClassificationBuilder.Interface(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Class(string value)
{
return ClassificationBuilder.Class(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Delegate(string value)
{
return ClassificationBuilder.Delegate(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> TypeParameter(string value)
{
return ClassificationBuilder.TypeParameter(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> String(string value)
{
return ClassificationBuilder.String(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Verbatim(string value)
{
return ClassificationBuilder.Verbatim(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Keyword(string value)
{
return ClassificationBuilder.Keyword(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> WhiteSpace(string value)
{
return ClassificationBuilder.WhiteSpace(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Text(string value)
{
return ClassificationBuilder.Text(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> NumericLiteral(string value)
{
return ClassificationBuilder.NumericLiteral(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> PPKeyword(string value)
{
return ClassificationBuilder.PPKeyword(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> PPText(string value)
{
return ClassificationBuilder.PPText(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Identifier(string value)
{
return ClassificationBuilder.Identifier(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Inactive(string value)
{
return ClassificationBuilder.Inactive(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Comment(string value)
{
return ClassificationBuilder.Comment(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Number(string value)
{
return ClassificationBuilder.Number(value);
}
protected ClassificationBuilder.PunctuationClassificationTypes Punctuation
{
get { return ClassificationBuilder.Punctuation; }
}
protected ClassificationBuilder.OperatorClassificationTypes Operators
{
get { return ClassificationBuilder.Operator; }
}
protected ClassificationBuilder.XmlDocClassificationTypes XmlDoc
{
get { return ClassificationBuilder.XmlDoc; }
}
protected string Lines(params string[] lines)
{
return string.Join("\r\n", lines);
}
protected Tuple<string, string>[] ExpectedClassifications(
params Tuple<string, string>[] expectedClassifications)
{
return expectedClassifications;
}
protected Tuple<string, string>[] NoClassifications()
{
return null;
}
protected void WaitForDocumentationComment(object content)
{
if (content is QuickInfoDisplayDeferredContent)
{
var docCommentDeferredContent = ((QuickInfoDisplayDeferredContent)content).Documentation as DocumentationCommentDeferredContent;
if (docCommentDeferredContent != null)
{
docCommentDeferredContent.WaitForDocumentationCommentTask_ForTestingPurposesOnly();
}
}
}
internal Action<object> SymbolGlyph(Glyph expectedGlyph)
{
return (content) =>
{
var actualIcon = ((QuickInfoDisplayDeferredContent)content).SymbolGlyph;
Assert.Equal(expectedGlyph, actualIcon.Glyph);
};
}
protected Action<object> MainDescription(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
content.TypeSwitch(
(QuickInfoDisplayDeferredContent qiContent) =>
{
var actualContent = qiContent.MainDescription.ClassifiableContent;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
},
(ClassifiableDeferredContent classifiable) =>
{
var actualContent = classifiable.ClassifiableContent;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
});
};
}
protected Action<object> Documentation(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
var documentationCommentContent = ((QuickInfoDisplayDeferredContent)content).Documentation;
documentationCommentContent.TypeSwitch(
(DocumentationCommentDeferredContent docComment) =>
{
var documentationCommentBlock = (TextBlock)docComment.Create();
var actualText = documentationCommentBlock.Text;
Assert.Equal(expectedText, actualText);
},
(ClassifiableDeferredContent classifiable) =>
{
var actualContent = classifiable.ClassifiableContent;
Assert.Equal(expectedText, actualContent.GetFullText());
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
});
};
}
protected Action<object> TypeParameterMap(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
var actualContent = ((QuickInfoDisplayDeferredContent)content).TypeParameterMap.ClassifiableContent;
// The type parameter map should have an additional line break at the beginning. We
// create a copy here because we've captured expectedText and this delegate might be
// executed more than once (e.g. with different parse options).
// var expectedTextCopy = "\r\n" + expectedText;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
};
}
protected Action<object> AnonymousTypes(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
var actualContent = ((QuickInfoDisplayDeferredContent)content).AnonymousTypes.ClassifiableContent;
// The type parameter map should have an additional line break at the beginning. We
// create a copy here because we've captured expectedText and this delegate might be
// executed more than once (e.g. with different parse options).
// var expectedTextCopy = "\r\n" + expectedText;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
};
}
protected Action<object> NoTypeParameterMap
{
get
{
return (content) =>
{
Assert.Equal(string.Empty, ((QuickInfoDisplayDeferredContent)content).TypeParameterMap.ClassifiableContent.GetFullText());
};
}
}
protected Action<object> Usage(string expectedText, bool expectsWarningGlyph = false)
{
return (content) =>
{
var quickInfoContent = (QuickInfoDisplayDeferredContent)content;
Assert.Equal(expectedText, quickInfoContent.UsageText.ClassifiableContent.GetFullText());
Assert.Equal(expectsWarningGlyph, quickInfoContent.WarningGlyph != null && quickInfoContent.WarningGlyph.Glyph == Glyph.CompletionWarning);
};
}
protected static bool CanUseSpeculativeSemanticModel(Document document, int position)
{
var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var node = document.GetSyntaxRootAsync().Result.FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
protected abstract void Test(string markup, params Action<object>[] expectedResults);
}
}
| |
/*
* 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.Collections;
using Apache.NMS.Util;
using NUnit.Framework;
namespace Apache.NMS.Test
{
[TestFixture]
public class MapMessageTest : NMSTestSupport
{
protected bool a = true;
protected byte b = 123;
protected char c = 'c';
protected short d = 0x1234;
protected int e = 0x12345678;
protected long f = 0x1234567812345678;
protected string g = "Hello World!";
protected bool h = false;
protected byte i = 0xFF;
protected short j = -0x1234;
protected int k = -0x12345678;
protected long l = -0x1234567812345678;
protected float m = 2.1F;
protected double n = 2.3;
protected byte[] o = {1, 2, 3, 4, 5};
[Test]
public void SendReceiveMapMessage(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
{
IDestination destination = CreateDestination(session, DestinationType.Queue);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
producer.DeliveryMode = deliveryMode;
IMapMessage request = session.CreateMapMessage();
request.Body["a"] = a;
request.Body["b"] = b;
request.Body["c"] = c;
request.Body["d"] = d;
request.Body["e"] = e;
request.Body["f"] = f;
request.Body["g"] = g;
request.Body["h"] = h;
request.Body["i"] = i;
request.Body["j"] = j;
request.Body["k"] = k;
request.Body["l"] = l;
request.Body["m"] = m;
request.Body["n"] = n;
request.Body["o"] = o;
producer.Send(request);
IMapMessage message = consumer.Receive(receiveTimeout) as IMapMessage;
Assert.IsNotNull(message, "No message returned!");
Assert.AreEqual(request.Body.Count, message.Body.Count, "Invalid number of message maps.");
Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");
Assert.AreEqual(ToHex(f), ToHex(message.Body.GetLong("f")), "map entry: f as hex");
// use generic API to access entries
Assert.AreEqual(a, message.Body["a"], "generic map entry: a");
Assert.AreEqual(b, message.Body["b"], "generic map entry: b");
Assert.AreEqual(c, message.Body["c"], "generic map entry: c");
Assert.AreEqual(d, message.Body["d"], "generic map entry: d");
Assert.AreEqual(e, message.Body["e"], "generic map entry: e");
Assert.AreEqual(f, message.Body["f"], "generic map entry: f");
Assert.AreEqual(g, message.Body["g"], "generic map entry: g");
Assert.AreEqual(h, message.Body["h"], "generic map entry: h");
Assert.AreEqual(i, message.Body["i"], "generic map entry: i");
Assert.AreEqual(j, message.Body["j"], "generic map entry: j");
Assert.AreEqual(k, message.Body["k"], "generic map entry: k");
Assert.AreEqual(l, message.Body["l"], "generic map entry: l");
Assert.AreEqual(m, message.Body["m"], "generic map entry: m");
Assert.AreEqual(n, message.Body["n"], "generic map entry: n");
Assert.AreEqual(o, message.Body["o"], "generic map entry: o");
// use type safe APIs
Assert.AreEqual(a, message.Body.GetBool("a"), "map entry: a");
Assert.AreEqual(b, message.Body.GetByte("b"), "map entry: b");
Assert.AreEqual(c, message.Body.GetChar("c"), "map entry: c");
Assert.AreEqual(d, message.Body.GetShort("d"), "map entry: d");
Assert.AreEqual(e, message.Body.GetInt("e"), "map entry: e");
Assert.AreEqual(f, message.Body.GetLong("f"), "map entry: f");
Assert.AreEqual(g, message.Body.GetString("g"), "map entry: g");
Assert.AreEqual(h, message.Body.GetBool("h"), "map entry: h");
Assert.AreEqual(i, message.Body.GetByte("i"), "map entry: i");
Assert.AreEqual(j, message.Body.GetShort("j"), "map entry: j");
Assert.AreEqual(k, message.Body.GetInt("k"), "map entry: k");
Assert.AreEqual(l, message.Body.GetLong("l"), "map entry: l");
Assert.AreEqual(m, message.Body.GetFloat("m"), "map entry: m");
Assert.AreEqual(n, message.Body.GetDouble("n"), "map entry: n");
Assert.AreEqual(o, message.Body.GetBytes("o"), "map entry: o");
}
}
}
}
[Test]
public void SendReceiveNestedMapMessage(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge))
{
IDestination destination = CreateDestination(session, DestinationType.Queue);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
try
{
producer.DeliveryMode = deliveryMode;
IMapMessage request = session.CreateMapMessage();
const string textFieldValue = "Nested Map Messages Rule!";
request.Body.SetString("textField", textFieldValue);
IDictionary grandChildMap = new Hashtable();
grandChildMap["x"] = "abc";
grandChildMap["y"] = new ArrayList(new object[] { "a", "b", "c" });
IDictionary nestedMap = new Hashtable();
nestedMap["a"] = "foo";
nestedMap["b"] = (int) 23;
nestedMap["c"] = (long) 45;
nestedMap["d"] = grandChildMap;
request.Body.SetDictionary("mapField", nestedMap);
request.Body.SetList("listField", new ArrayList(new Object[] { "a", "b", "c" }));
producer.Send(request);
IMapMessage message = consumer.Receive(receiveTimeout) as IMapMessage;
Assert.IsNotNull(message, "No message returned!");
Assert.AreEqual(request.Body.Count, message.Body.Count, "Invalid number of message maps.");
Assert.AreEqual(deliveryMode, message.NMSDeliveryMode, "NMSDeliveryMode does not match");
string textFieldResponse = message.Body.GetString("textField");
Assert.AreEqual(textFieldValue, textFieldResponse, "textField does not match.");
IDictionary nestedMapResponse = message.Body.GetDictionary("mapField");
Assert.IsNotNull(nestedMapResponse, "Nested map not returned.");
Assert.AreEqual(nestedMap.Count, nestedMapResponse.Count, "nestedMap: Wrong number of elements");
Assert.AreEqual("foo", nestedMapResponse["a"], "nestedMap: a");
Assert.AreEqual(23, nestedMapResponse["b"], "nestedMap: b");
Assert.AreEqual(45, nestedMapResponse["c"], "nestedMap: c");
IDictionary grandChildMapResponse = nestedMapResponse["d"] as IDictionary;
Assert.IsNotNull(grandChildMapResponse, "Grand child map not returned.");
Assert.AreEqual(grandChildMap.Count, grandChildMapResponse.Count, "grandChildMap: Wrong number of elements");
Assert.AreEqual(grandChildMapResponse["x"], "abc", "grandChildMap: x");
IList grandChildList = grandChildMapResponse["y"] as IList;
Assert.IsNotNull(grandChildList, "Grand child list not returned.");
Assert.AreEqual(3, grandChildList.Count, "grandChildList: Wrong number of list elements.");
Assert.AreEqual("a", grandChildList[0], "grandChildList: a");
Assert.AreEqual("b", grandChildList[1], "grandChildList: b");
Assert.AreEqual("c", grandChildList[2], "grandChildList: c");
IList listFieldResponse = message.Body.GetList("listField");
Assert.IsNotNull(listFieldResponse, "Nested list not returned.");
Assert.AreEqual(3, listFieldResponse.Count, "listFieldResponse: Wrong number of list elements.");
Assert.AreEqual("a", listFieldResponse[0], "listFieldResponse: a");
Assert.AreEqual("b", listFieldResponse[1], "listFieldResponse: b");
Assert.AreEqual("c", listFieldResponse[2], "listFieldResponse: c");
}
catch(NotSupportedException)
{
}
catch(NMSException e)
{
Assert.IsTrue(e.InnerException.GetType() == typeof(NotSupportedException));
}
}
}
}
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.IO;
using Xunit;
public class File_Copy_str_str
{
public static String s_strActiveBugNums = "";
public static String s_strDtTmVer = "2009/02/18";
public static String s_strClassMethod = "File.CopyTo(String, Boolean)";
public static String s_strTFName = "Copy_str_str.cs";
public static String s_strTFPath = Directory.GetCurrentDirectory();
[Fact]
public static void runTest()
{
int iCountErrors = 0;
int iCountTestcases = 0;
String strLoc = "Loc_000oo";
try
{
///////////////////////// START TESTS ////////////////////////////
///////////////////////////////////////////////////////////////////
FileInfo fil2 = null;
FileInfo fil1 = null;
Char[] cWriteArr, cReadArr;
StreamWriter sw2;
StreamReader sr2;
String filName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
try
{
new FileInfo(filName).Delete();
}
catch (Exception) { }
// [] ArgumentNullException if null is passed in for source file
strLoc = "Loc_498yg";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(null, fil2.FullName);
iCountErrors++;
printerr("Error_209uz! Expected exception not thrown, fil2==" + fil1.FullName);
fil1.Delete();
}
catch (ArgumentNullException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_21x99! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] ArgumentNullException if null is passed in for destination file
strLoc = "Loc_898gc";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, null);
iCountErrors++;
printerr("Error_8yt85! Expected exception not thrown");
}
catch (ArgumentNullException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_1298s! Incorrect exception thrown, exc==" + exc.ToString());
}
// [] String.Empty should throw ArgumentException
strLoc = "Loc_298vy";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, String.Empty);
iCountErrors++;
printerr("Error_092u9! Expected exception not thrown, fil2==" + fil1.FullName);
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_109uc! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Try to copy onto directory
strLoc = "Loc_289vy";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, TestInfo.CurrentDirectory);
iCountErrors++;
printerr("Error_301ju! Expected exception not thrown, fil2==" + fil1.FullName);
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_209us! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Copy onto itself should fail
strLoc = "Loc_r7yd9";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, fil2.FullName);
iCountErrors++;
printerr("Error_209us! Expected exception not thrown, fil2==" + fil1.FullName);
}
catch (IOException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_f588y! Unexpected exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Vanilla copy operation
strLoc = "Loc_f548y";
string destFile = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, destFile);
fil1 = new FileInfo(destFile);
if (!File.Exists(fil1.FullName))
{
iCountErrors++;
printerr("Error_2978y! File not copied");
}
if (!File.Exists(fil2.FullName))
{
iCountErrors++;
printerr("Error_239vr! Source file gone");
}
fil1.Delete();
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2987v! Unexpected exception, exc==" + exc.ToString());
}
fil2.Delete();
fil1.Delete();
// [] Filename with illiegal characters
strLoc = "Loc_984hg";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(fil2.FullName, "*\0*");
iCountErrors++;
printerr("Error_298xh! Expected exception not thrown, fil2==" + fil1.FullName);
fil1.Delete();
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2091s! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
// [] Move a file containing data
strLoc = "Loc_f888m";
string destFile2 = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
try
{
new FileInfo(destFile2).Delete();
}
catch (Exception) { }
try
{
sw2 = new StreamWriter(File.Create(filName));
cWriteArr = new Char[26];
int j = 0;
for (Char i = 'A'; i <= 'Z'; i++)
cWriteArr[j++] = i;
sw2.Write(cWriteArr, 0, cWriteArr.Length);
sw2.Flush();
sw2.Dispose();
fil2 = new FileInfo(filName);
File.Copy(fil2.FullName, destFile2);
fil1 = new FileInfo(destFile2);
iCountTestcases++;
if (!File.Exists(fil1.FullName))
{
iCountErrors++;
printerr("Error_9u99s! File not copied correctly: " + fil1.FullName);
}
if (!File.Exists(fil2.FullName))
{
iCountErrors++;
printerr("Error_29h7b! Source file gone");
}
FileStream fileStream = new FileStream(destFile2, FileMode.Open);
sr2 = new StreamReader(fileStream);
cReadArr = new Char[cWriteArr.Length];
sr2.Read(cReadArr, 0, cReadArr.Length);
iCountTestcases++;
for (int i = 0; i < cReadArr.Length; i++)
{
iCountTestcases++;
if (cReadArr[i] != cWriteArr[i])
{
iCountErrors++;
printerr("Error_98yv7! Expected==" + cWriteArr[i] + ", got value==" + cReadArr[i]);
}
}
sr2.Dispose();
fileStream.Dispose();
fil1.Delete();
fil2.Delete();
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_28vc8! Unexpected exception, exc==" + exc.ToString());
}
/* Scenario disabled while porting because it modifies state outside the test's working directory
#if !TEST_WINRT
String tmpFile;
// [] Interesting case:
strLoc = "Loc_478yb";
new FileStream(filName, FileMode.Create).Dispose();
File.Delete("\\TestFile.tmp");
fil2 = new FileInfo(filName);
//Cleanup root files
tmpFile = "..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\TestFile.tmp";
File.Copy(fil2.Name, tmpFile);
fil1 = new FileInfo(fil2.FullName.Substring(0, fil2.FullName.IndexOf("\\") + 1) + fil2.Name);
iCountTestcases++;
if (!fil1.FullName.Equals(fil2.FullName.Substring(0, fil2.FullName.IndexOf("\\") + 1) + fil2.Name))
{
iCountErrors++;
Console.WriteLine("[{0}][{1}]", fil1.FullName, Path.GetFullPath(tmpFile));
printerr("Error_298gc! Incorrect fullname set during copy");
}
new FileInfo(filName).Delete();
fil1.Delete();
if (File.Exists(tmpFile))
File.Delete(tmpFile);
#endif
*/
// [] Vanilla copy operation
strLoc = "Loc_090jd";
destFile = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName());
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy(filName, destFile, true);
fil1 = new FileInfo(destFile);
fil2 = new FileInfo(filName);
if (!File.Exists(fil1.FullName))
{
iCountErrors++;
printerr("Error_378ce! File not copied");
}
if (!File.Exists(fil2.FullName))
{
iCountErrors++;
printerr("Error_t948v! Source file gone");
}
fil1.Delete();
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_2987v! Unexpected exception, exc==" + exc.ToString());
}
fil2.Delete();
fil1.Delete();
// [] Filename with wildchars
strLoc = "Loc_100s8";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
iCountTestcases++;
try
{
File.Copy("*\0*", fil2.FullName, false);
iCountErrors++;
printerr("Error_43987! Expected exception not thrown, fil2==" + fil1.FullName);
fil1.Delete();
}
catch (ArgumentException)
{
}
catch (Exception exc)
{
iCountErrors++;
printerr("Error_3989v! Incorrect exception thrown, exc==" + exc.ToString());
}
fil2.Delete();
/* Scenario disabled while porting because it modifies state outside the test's working directory
#if !TEST_WINRT
// [] Interesting case: See if it rips off the unessary directory traversal
strLoc = "Loc_2489y";
File.Create(filName).Dispose();
fil2 = new FileInfo(filName);
tmpFile = "..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\TestFile.tmp";
File.Copy(fil2.Name, tmpFile, true);
iCountTestcases++;
fil1 = new FileInfo(fil2.FullName.Substring(0, fil2.FullName.IndexOf("\\") + 1) + fil2.Name);
if (!fil1.FullName.Equals(fil2.FullName.Substring(0, fil2.FullName.IndexOf("\\") + 1) + fil2.Name))
{
Console.WriteLine(fil1.FullName);
iCountErrors++;
printerr("Error_892su! Incorrect fullname set during copy");
}
fil1.Delete();
if (File.Exists(tmpFile))
File.Delete(tmpFile);
#endif
*/
// network path scenarios moved to RemoteIOTests.cs
try
{
new FileInfo(filName).Delete();
new FileInfo(destFile).Delete();
new FileInfo(destFile2).Delete();
}
catch (Exception ex)
{
Console.WriteLine("Failed to delete temp files:");
Console.WriteLine(ex);
Console.WriteLine("Not failing test.");
}
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine("Error Err_8888yyy! strLoc==" + strLoc + ", exc_general==" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors != 0)
{
Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + iCountErrors.ToString());
}
Assert.Equal(0, iCountErrors);
}
public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Scaly.Compiler.Model
{
public class Definition
{
public Source Source;
public Definition Parent;
public Span Span;
public string Name;
public bool IsPublic;
public bool IsIntrinsic;
public TypeSpec Type;
public List<Operand> Operands = new List<Operand>();
public Structure Structure;
public Dictionary<string, Definition> Definitions;
public List<Function> Functions;
public Dictionary<string, Operator> Operators;
public Dictionary<string, Implement> Implements;
public List<Source> Sources;
}
public class TypeSpec
{
public Span Span;
public string Name;
public List<TypeSpec> Arguments;
}
public class Structure
{
public Span Span;
public List<Member> Members;
}
public class Member
{
public Span Span;
public bool IsPrivate;
public string Name;
public TypeSpec Type;
}
public class Function
{
public Definition Definition;
public Source Source;
public Span Span;
public string Name;
public List<TypeSpec> GenericArguments;
public Routine Routine;
}
public class Operator
{
public Definition Definition;
public Span Span;
public string Name;
public Routine Routine;
}
public enum Implementation
{
Intern,
Extern,
Instruction,
Intrinsic
}
public class Routine
{
public Span Span;
public List<Parameter> Input;
public List<Parameter> Result;
public TypeSpec Error;
public Operation Operation;
public Implementation Implementation;
}
public class Parameter
{
public string Name;
public TypeSpec TypeSpec;
}
public class Implement
{
public string Name;
public List<Function> Functions;
public Dictionary<string, Operator> Operators;
}
public class Source
{
public string FileName;
public Dictionary<string, Namespace> Uses;
public List<Namespace> Usings;
public Dictionary<string, Definition> Definitions;
public List<Function> Functions;
public Dictionary<string, Operator> Operators;
public Dictionary<string, Implement> Implements;
public List<Source> Sources;
public List<Operation> Operations;
}
public class Namespace
{
public Span Span;
public string Path;
}
public interface Expression { }
public class Name : Expression
{
public Span Span;
public string Path;
}
public class Tuple : Expression
{
public Span Span;
public List<Component> Components;
}
public class Component
{
public Span Span;
public string Name;
public List<Operand> Value;
}
public class Vector : Expression
{
public Span Span;
public List<List<Operand>> Components;
}
public enum BindingType
{
Let,
Var,
Mutable
}
public class Scope : Expression
{
public List<Operation> Operations;
public Binding Binding;
}
public class Binding : Expression
{
public BindingType BindingType;
public string Identifier;
public Operation Operation;
public List<Operation> BodyOperations;
}
public class Operation : Expression
{
public List<Operand> TargetOperations;
public List<Operand> SourceOperands = new List<Operand>();
}
public class Operand
{
public Expression Expression;
public List<Postfix> Postfixes;
}
public class If : Expression
{
public Span Span;
public List<Operand> Condition = new List<Operand>();
public Operation Consequent;
public Operation Alternative;
}
public abstract class Postfix { }
public class MemberAccess
{
public string Name;
}
public class Catcher
{
public List<Catch> Catches;
public Drop Drop;
}
public class Catch
{
public Operation Condition;
public Operation Handler;
}
public class Drop
{
public Operation Handler;
}
public class Is
{
public List<Operand> Condition;
}
public enum IntegerType
{
Integer32,
}
public class IntegerConstant : Expression
{
public Span Span;
public IntegerType Type;
public int Value;
}
public class BooleanConstant : Expression
{
public Span Span;
public bool Value;
}
public class Modeler
{
public static List<Source> BuildFiles(string[] files)
{
var sources = files.ToList().ConvertAll(it => BuildSource(it));
sources.Add(BuildRuntime());
return sources;
}
public static Source BuildRuntime()
{
var runtime = BuildSource("scaly.scaly");
return runtime;
}
public static Source BuildProgram(string program)
{
var fileSyntax = parseFile("", program);
var source = BuildSource(fileSyntax);
var operations = source.Operations;
source = new Source
{
FileName = source.FileName,
Uses = source.Uses,
Usings = source.Usings,
Definitions = source.Definitions,
Functions = source.Functions,
Operators = source.Operators,
Implements = null,
Sources = source.Sources,
Operations = null,
};
if (source.Functions == null)
source.Functions = new List<Function>();
var main = BuildSource("main.scaly").Functions[0];
main.Routine.Operation = new Operation { SourceOperands = new List<Operand> { new Operand { Expression = new Scope { Operations = operations } } } };
main.Source = source;
source.Functions.Add(main);
return source;
}
public static Source BuildSource(string file)
{
var text = System.IO.File.ReadAllText(file);
return BuildSource(text, file);
}
static Source BuildSource(string text, string file)
{
var fileSyntax = parseFile(file, text);
return BuildSource(fileSyntax);
}
static Source BuildSource(FileSyntax fileSyntax)
{
var source = new Source { FileName = Path.GetFileName(fileSyntax.span.file) };
var origin = Path.GetDirectoryName(fileSyntax.span.file);
if (fileSyntax.declarations != null)
foreach (var declaration in fileSyntax.declarations)
HandleDeclaration(source, origin, declaration, null);
if (fileSyntax.statements != null)
source.Operations = BuildStatements(fileSyntax.statements.ToList());
return source;
}
static List<Operation> BuildStatements(List<object> statements)
{
if (statements == null)
return null;
var operations = new List<Operation>();
while (statements.Count > 0)
{
var statement = statements[0];
statements.RemoveAt(0);
switch (statement)
{
case OperationSyntax operationSyntax:
operations.Add(BuildOperation(operationSyntax));
break;
default:
throw new NotImplementedException($"{statement.GetType()} is not implemented.");
}
}
return operations;
}
static Operand BuildOperand(OperandSyntax operandSyntax)
{
var expression = BuildExpression(operandSyntax.expression);
List<Postfix> postfixes = null;
if (operandSyntax.postfixes != null)
{
foreach (var postfix in operandSyntax.postfixes)
{
postfixes.Add(BuildPostfix(postfix));
}
}
return new Operand { Expression = expression, Postfixes = postfixes };
}
static Expression BuildExpression(object expression)
{
switch (expression)
{
case NameSyntax nameSyntax:
return BuildName(nameSyntax);
case LiteralSyntax literalSyntax:
return BuildConstant(literalSyntax);
case BlockSyntax blockSyntax:
return BuildBlock(blockSyntax);
case ObjectSyntax objectSyntax:
return BuildObject(objectSyntax);
case VectorSyntax vectorSyntax:
return BuildVector(vectorSyntax);
case IfSyntax ifSyntax:
return BuildIf(ifSyntax);
default:
throw new NotImplementedException($"{expression.GetType()} is not implemented.");
}
}
static Expression BuildName(NameSyntax nameSyntax)
{
var pathBuilder = new StringBuilder(nameSyntax.name);
if (nameSyntax.extensions != null)
{
foreach (var extension in nameSyntax.extensions)
{
pathBuilder.Append('.');
pathBuilder.Append(extension.name);
}
}
return new Name { Path = pathBuilder.ToString(), Span = nameSyntax.span };
}
static Expression BuildConstant(LiteralSyntax literalSyntax)
{
switch (literalSyntax.literal)
{
case Integer integer:
return new IntegerConstant { Span = literalSyntax.span, Type = IntegerType.Integer32, Value = int.Parse(integer.value) };
case Bool boolean:
return new BooleanConstant { Span = literalSyntax.span, Value = boolean.value };
default:
throw new NotImplementedException($"{literalSyntax.literal.GetType()} is not implemented.");
}
}
static Expression BuildBlock(BlockSyntax blockSyntax)
{
var scope = new Scope();
if (blockSyntax.statements != null)
scope.Operations = BuildStatements(blockSyntax.statements.ToList());
return scope;
}
static Expression BuildObject(ObjectSyntax objectSyntax)
{
var @object = new Tuple { Span = objectSyntax.span };
if (objectSyntax.components != null)
@object.Components = objectSyntax.components.ToList().ConvertAll(it => BuildComponent(it));
return @object;
}
static Expression BuildVector(VectorSyntax vectorSyntax)
{
var vector = new Vector { Span = vectorSyntax.span };
if (vectorSyntax.elements != null)
vector.Components = vectorSyntax.elements.ToList().ConvertAll(it => BuildElement(it));
return vector;
}
static List<Operand> BuildElement(ElementSyntax elementSyntax)
{
if (elementSyntax.operation != null)
return elementSyntax.operation.operands.ToList().ConvertAll(it => BuildOperand(it));
return null;
}
static Component BuildComponent(ComponentSyntax componentSyntax)
{
var component = new Component { Span = componentSyntax.span };
if (componentSyntax.value != null)
{
if (componentSyntax.operands.Length != 1)
throw new CompilerException("Only one component supported currently.", componentSyntax.span);
}
else
{
if (componentSyntax.operands != null)
component.Value = componentSyntax.operands.ToList().ConvertAll(it => BuildOperand(it));
}
return component;
}
static Expression BuildIf(IfSyntax ifSyntax)
{
return new If
{
Span = ifSyntax.span,
Condition = ifSyntax.condition.operands.ToList().ConvertAll(it => BuildOperand(it)),
Consequent = BuildAction(ifSyntax.consequent),
Alternative = BuildAction(ifSyntax.alternative.alternative),
};
}
static Operation BuildAction(object action)
{
switch (action)
{
case OperationSyntax operationSyntax:
return BuildOperation(operationSyntax);
default:
throw new NotImplementedException($"{action.GetType()} is not implemented.");
}
}
static Postfix BuildPostfix(object postfix)
{
switch (postfix)
{
default:
throw new NotImplementedException($"{postfix.GetType()} is not implemented.");
}
}
static void HandleDeclaration(Source source, string origin, object declaration, Definition definition)
{
switch (declaration)
{
case PrivateSyntax privateSyntax:
HandlePrivate(source, definition, origin, privateSyntax);
break;
case DefinitionSyntax definitionSyntax:
if (source.Definitions == null)
source.Definitions = new Dictionary<string, Definition>();
HandleDefinition(definitionSyntax, source.Definitions, source, definition, origin, true);
break;
case FunctionSyntax functionSyntax:
if (source.Functions == null)
source.Functions = new List<Function>();
HandleFunction(functionSyntax, source, definition, source.Functions, false);
break;
case ProcedureSyntax procedureSyntax:
if (source.Functions == null)
source.Functions = new List<Function>();
HandleProcedure(procedureSyntax, source, definition, source.Functions, false);
break;
case OperatorSyntax operatorSyntax:
if (source.Operators == null)
source.Operators = new Dictionary<string, Operator>();
HandleOperator(operatorSyntax, source.Operators, definition);
break;
case ModuleSyntax moduleSyntax:
HandleModule(moduleSyntax, source.Definitions, source, origin, true);
break;
case UseSyntax useSyntax:
HandleUse(source, useSyntax);
break;
case ImplementSyntax implementSyntax:
if (source.Implements == null)
source.Implements = new Dictionary<string, Implement>();
HandleImplement(implementSyntax, source.Implements, definition);
break;
default:
throw new NotImplementedException($"{declaration.GetType()} is not implemented.");
}
}
static void HandleModule(ModuleSyntax moduleSyntax, Dictionary<string, Definition> definitions, Source source, string origin, bool isPublic)
{
if (moduleSyntax.name.extensions != null)
{
var extensionEnumerator = moduleSyntax.name.extensions.ToList().GetEnumerator();
var extensionAvailable = extensionEnumerator.MoveNext();
if (extensionAvailable)
{
if (definitions == null)
definitions = new Dictionary<string, Definition>();
if (!definitions.ContainsKey(moduleSyntax.name.name))
{
var definition = new Definition
{
Source = source,
Parent = null,
Span = moduleSyntax.span,
IsPublic = isPublic,
Type = new TypeSpec { Name = moduleSyntax.name.name },
Sources = null
};
definitions.Add(definition.Type.Name, definition);
}
switch (definitions[moduleSyntax.name.name])
{
case Definition definition:
BuildModuleRecursive(moduleSyntax, Path.Combine(origin, definition.Type.Name), extensionEnumerator.Current.name, extensionEnumerator, definition, isPublic);
break;
default:
throw new CompilerException($"A concept with name {moduleSyntax.name.name} already defined.", moduleSyntax.span);
}
}
}
else
{
string moduleFile = moduleSyntax.name.name + ".scaly";
if (origin != null)
moduleFile = Path.Combine(Path.Combine(origin, moduleFile));
var moduleSource = BuildSource(moduleFile);
if (source.Sources == null)
source.Sources = new List<Source>();
source.Sources.Add(moduleSource);
}
}
static void BuildModuleRecursive(ModuleSyntax moduleSyntax, string path, string name, List<ExtensionSyntax>.Enumerator extensionEnumerator, Definition definition, bool isPublic)
{
var extensionAvailable = extensionEnumerator.MoveNext();
if (extensionAvailable)
{
BuildModuleRecursive(moduleSyntax, Path.Combine(path, name), extensionEnumerator.Current.name, extensionEnumerator, definition, isPublic);
}
else
{
var moduleFile = Path.Combine(Path.Combine(path, name) + ".scaly");
var moduleSource = BuildSource(moduleFile);
if (definition.Sources == null)
definition.Sources = new List<Source>();
definition.Sources.Add(moduleSource);
}
}
static void HandleUse(Source source, UseSyntax useSyntax)
{
var pathBuilder = new StringBuilder( useSyntax.name.name );
var lastPart = useSyntax.name.name;
if (useSyntax.name.extensions != null)
{
foreach (var extension in useSyntax.name.extensions)
{
pathBuilder.Append('.');
pathBuilder.Append(extension.name);
lastPart = extension.name;
}
}
var path = pathBuilder.ToString();
if (lastPart == "*")
{
if (source.Usings == null)
source.Usings = new List<Namespace>();
source.Usings.Add(new Namespace { Span = useSyntax.span, Path = string.Join('.', path.Substring(0, path.Length - 2)) });
}
else
{
if (source.Uses == null)
source.Uses = new Dictionary<string, Namespace>();
if (source.Uses.ContainsKey(lastPart))
throw new CompilerException($"{lastPart} cannot be re-used.", useSyntax.span);
source.Uses.Add(lastPart, new Namespace { Span = useSyntax.span, Path = string.Join('.', pathBuilder) });
}
}
static void HandlePrivate(Source source, Definition definition, string origin, PrivateSyntax privateSyntax)
{
switch (privateSyntax.export)
{
case DefinitionSyntax definitionSyntax:
HandleDefinition(definitionSyntax, source.Definitions, source, definition, origin, false);
break;
case FunctionSyntax functionSyntax:
if (source.Functions == null)
source.Functions = new List<Function>();
HandleFunction(functionSyntax, source, definition, source.Functions, false);
break;
case ProcedureSyntax procedureSyntax:
if (source.Functions == null)
source.Functions = new List<Function>();
HandleProcedure(procedureSyntax, source, definition, source.Functions, false);
break;
case ModuleSyntax moduleSyntax:
HandleModule(moduleSyntax, source.Definitions, source, origin, false);
break;
default:
throw new NotImplementedException($"{privateSyntax.export.GetType()} is not implemented.");
}
}
static void HandleFunction(FunctionSyntax functionSyntax, Source source, Definition definition, List<Function> functions, bool isPublic)
{
BuildFunction(functionSyntax.name, source, definition, functionSyntax.generics, functionSyntax.routine, functions, isPublic, false);
}
static void HandleProcedure(ProcedureSyntax procedureSyntax, Source source, Definition definition, List<Function> functions, bool isPublic)
{
BuildFunction(procedureSyntax.name, source, definition, procedureSyntax.generics, procedureSyntax.routine, functions, isPublic, true);
}
static void BuildFunction(string name, Source source, Definition definition, GenericArgumentsSyntax generics, RoutineSyntax routine, List<Function> functions, bool isPublic, bool isModifying)
{
var function = new Function { Definition = definition, Source = source, Name = name, Span = routine.span, };
if (generics != null)
function.GenericArguments = generics.generics.ToList().ConvertAll(it => BuildType(it.spec));
function.Routine = BuildRoutine(routine);
functions.Add(function);
}
static Routine BuildRoutine(RoutineSyntax routineSyntax)
{
var routine = new Routine { Span = routineSyntax.span };
if (routineSyntax.parameters != null)
routine.Input = BuildParameters(routineSyntax.parameters);
if (routineSyntax.returns != null)
routine.Result = BuildParameters(routineSyntax.returns.parameters);
if (routineSyntax.throws != null)
routine.Error = BuildType(routineSyntax.throws.type);
switch (routineSyntax.implementation)
{
case OperationSyntax operationSyntax:
routine.Operation = BuildOperation(operationSyntax);
break;
case ExternSyntax _:
routine.Implementation = Implementation.Extern ;
break;
case InstructionSyntax _:
routine.Implementation = Implementation.Instruction;
break;
case IntrinsicSyntax _:
routine.Implementation = Implementation.Intrinsic;
break;
case SetSyntax _:
break;
default:
throw new NotImplementedException($"{routineSyntax.implementation.GetType()} is not implemented.");
}
return routine;
}
static Operation BuildOperation(OperationSyntax operationSyntax)
{
var operation = new Operation { SourceOperands = new List<Operand>() };
foreach (var operand in operationSyntax.operands)
{
operation.SourceOperands.Add(BuildOperand(operand));
}
return operation;
}
static List<Parameter> BuildParameters(object parameters)
{
switch (parameters)
{
case ParametersSyntax parametersSyntax:
if (parametersSyntax.properties != null)
return parametersSyntax.properties.ToList().ConvertAll(it => BuildProperty(it));
else
return null;
case PropertySyntax propertySyntax:
return new List<Parameter> { BuildProperty(propertySyntax) };
case TypeSyntax typeSyntax:
return new List<Parameter> { new Parameter { TypeSpec = BuildTypeSpec(typeSyntax) } };
default:
throw new NotImplementedException($"{parameters.GetType()} is not implemented.");
}
}
static Parameter BuildProperty(PropertySyntax propertySyntax)
{
var property = new Parameter { Name = propertySyntax.name };
if (propertySyntax.annotation != null)
property.TypeSpec = BuildTypeSpec(propertySyntax.annotation.spec);
return property;
}
static TypeSpec BuildTypeSpec(object spec)
{
switch (spec)
{
case TypeSyntax typeSyntax:
return BuildType(typeSyntax);
default:
throw new NotImplementedException($"{spec.GetType()} is not implemented.");
}
}
static TypeSpec BuildType(TypeSyntax typeSyntax)
{
var typeName = new StringBuilder(typeSyntax.name.name);
if (typeSyntax.name.extensions != null)
{
foreach (var extension in typeSyntax.name.extensions)
{
typeName.Append('.');
typeName.Append(extension.name);
}
}
var typeSpec = new TypeSpec { Name = typeName.ToString(), Span = typeSyntax.span };
if (typeSyntax.generics != null)
typeSpec.Arguments = typeSyntax.generics.generics.ToList().ConvertAll(it => BuildType(it.spec));
return typeSpec;
}
static void HandleOperator(OperatorSyntax operatorSyntax, Dictionary<string, Operator> operators, Definition definition)
{
var @operator = new Operator { Definition = definition, Span = operatorSyntax.span };
switch (operatorSyntax.target)
{
case RoutineSyntax routineSyntax:
@operator.Routine = BuildRoutine(routineSyntax);
break;
case SymbolSyntax symbolSyntax:
@operator.Name = symbolSyntax.name;
@operator.Routine = BuildSymbol(symbolSyntax);
break;
}
if (@operators.ContainsKey(@operator.Name))
throw new CompilerException($"The operator {@operator.Name} has already been defined.", @operator.Span);
operators.Add(@operator.Name, @operator);
}
static Routine BuildSymbol(SymbolSyntax symbolSyntax)
{
var routine = new Routine { Span = symbolSyntax.span };
if (symbolSyntax.returns != null)
routine.Result = BuildParameters(symbolSyntax.returns.parameters);
if (symbolSyntax.throws != null)
routine.Error = BuildType(symbolSyntax.throws.type);
switch (symbolSyntax.implementation)
{
case OperationSyntax operationSyntax:
routine.Operation = BuildOperation(operationSyntax);
break;
default:
throw new NotImplementedException($"{symbolSyntax.implementation.GetType()} is not implemented.");
}
return routine;
}
static void HandleImplement(ImplementSyntax implementSyntax, Dictionary<string, Implement> implementations, Definition definition)
{
if (implementations.ContainsKey(implementSyntax.type.name.name))
throw new CompilerException($"An implementation with name {implementSyntax.type.name.name} already defined.", implementSyntax.span);
var implementation = new Implement { Name = implementSyntax.type.name.name };
implementations.Add(implementation.Name, implementation);
if (implementSyntax.methods != null)
{
foreach (var method in implementSyntax.methods)
{
switch (method)
{
case FunctionSyntax functionSyntax:
if (implementation.Functions == null)
implementation.Functions = new List<Function>();
HandleFunction(functionSyntax, definition.Source, definition, implementation.Functions, false);
break;
case ProcedureSyntax procedureSyntax:
if (implementation.Functions == null)
implementation.Functions = new List<Function>();
HandleProcedure(procedureSyntax, definition.Source, definition, implementation.Functions, false);
break;
case OperatorSyntax operatorSyntax:
if (implementation.Operators == null)
implementation.Operators = new Dictionary<string, Operator>();
HandleOperator(operatorSyntax, implementation.Operators, definition);
break;
default:
throw new NotImplementedException($"{method.GetType()} is not implemented.");
}
}
}
}
static void HandleDefinition(DefinitionSyntax definitionSyntax, Dictionary<string, Definition> definitions, Source source, Definition parent, string origin, bool isPublic)
{
TypeSpec typeModel = BuildType(definitionSyntax.type);
if (definitions.ContainsKey(typeModel.Name))
throw new CompilerException($"Module {typeModel.Name} already defined.", definitionSyntax.span);
var definition = new Definition { Source = source, Parent = parent, Span = definitionSyntax.span, Type = typeModel };
definitions.Add(typeModel.Name, definition);
switch (definitionSyntax.concept)
{
case ClassSyntax classSyntax:
{
var bodySyntax = classSyntax.body;
if (classSyntax.structure.members != null)
definition.Structure = HandleStructure(classSyntax.structure);
if (classSyntax.body != null && classSyntax.body.declarations != null)
foreach (var declaration in classSyntax.body.declarations)
HandleDeclaration(definition, source, origin, declaration);
break;
}
case NamespaceSyntax namespaceSyntax:
{
var bodySyntax = namespaceSyntax.body;
if (bodySyntax.declarations != null)
foreach (var declaration in bodySyntax.declarations)
HandleDeclaration(definition, source, origin, declaration);
break;
}
case UnionSyntax unionSyntax:
{
var bodySyntax = unionSyntax.body;
if (bodySyntax.declarations != null)
foreach (var declaration in bodySyntax.declarations)
HandleDeclaration(definition, source, origin, declaration);
break;
}
case ConstantSyntax constantSyntax:
{
definition.Operands = constantSyntax.operation.operands.ToList().ConvertAll(it => BuildOperand(it));
break;
}
case IntrinsicSyntax _:
definition.IsIntrinsic = true;
break;
}
}
static Structure HandleStructure(StructureSyntax structureSyntax)
{
var structure = new Structure { Span = structureSyntax.span };
if (structureSyntax.members != null)
structure.Members = BuildMembers(structureSyntax.members);
return structure;
}
static List<Member> BuildMembers(object[] members)
{
return members.ToList().ConvertAll(it => BuildMember(it));
}
static Member BuildMember(object member)
{
switch (member)
{
case PropertySyntax propertySyntax:
if (propertySyntax.annotation == null)
return new Member { Span = propertySyntax.span, IsPrivate = false, Name = null, Type = new TypeSpec { Span = propertySyntax.span, Name = propertySyntax.name } };
return new Member { Span = propertySyntax.span, IsPrivate = false, Name = propertySyntax.name, Type = BuildTypeAnnotation(propertySyntax.annotation) };
case FieldSyntax fieldSyntax:
return new Member { Span = fieldSyntax.span, IsPrivate = true, Name = fieldSyntax.export.name, Type = BuildTypeAnnotation(fieldSyntax.export.annotation) };
default:
throw new NotImplementedException($"{member.GetType()} is not implemented.");
}
}
static TypeSpec BuildTypeAnnotation(TypeAnnotationSyntax annotationSyntax)
{
return BuildTypeSpec(annotationSyntax.spec);
}
static void HandleDeclaration(Definition definition, Source source, string origin, object declaration)
{
switch (declaration)
{
case PrivateSyntax privateSyntax:
HandlePrivate(definition, source, origin, privateSyntax);
break;
case DefinitionSyntax definitionSyntax:
if (definition.Definitions == null)
definition.Definitions = new Dictionary<string, Definition>();
HandleDefinition(definitionSyntax, definition.Definitions, source, definition, origin, true);
break;
case FunctionSyntax functionSyntax:
if (definition.Functions == null)
definition.Functions = new List<Function>();
HandleFunction(functionSyntax, source, definition, definition.Functions, false);
break;
case ProcedureSyntax procedureSyntax:
if (definition.Functions == null)
definition.Functions = new List<Function>();
HandleProcedure(procedureSyntax, source, definition, definition.Functions, false);
break;
case OperatorSyntax operatorSyntax:
if (definition.Operators == null)
definition.Operators = new Dictionary<string, Operator>();
HandleOperator(operatorSyntax, definition.Operators, definition);
break;
case ImplementSyntax implementSyntax:
if (definition.Implements == null)
definition.Implements = new Dictionary<string, Implement>();
HandleImplement(implementSyntax, definition.Implements, definition);
break;
default:
throw new NotImplementedException($"{declaration.GetType()} is not implemented.");
}
}
static void HandlePrivate(Definition definition, Source source, string origin, PrivateSyntax privateSyntax)
{
switch (privateSyntax.export)
{
case DefinitionSyntax definitionSyntax:
if (definition.Definitions == null)
definition.Definitions = new Dictionary<string, Definition>();
HandleDefinition(definitionSyntax, definition.Definitions, source, definition, origin, false);
break;
case FunctionSyntax functionSyntax:
if (definition.Functions == null)
definition.Functions = new List<Function>();
HandleFunction(functionSyntax, source, definition, definition.Functions, false);
break;
case ProcedureSyntax procedureSyntax:
if (definition.Functions == null)
definition.Functions = new List<Function>();
HandleProcedure(procedureSyntax, source, definition, definition.Functions, false);
break;
case ModuleSyntax moduleSyntax:
HandleModule(moduleSyntax, definition.Definitions, source, origin, false);
break;
default:
throw new NotImplementedException($"{privateSyntax.export.GetType()} is not implemented.");
}
}
static string ExpandName(NameSyntax name)
{
var ret = name.name;
if (name.extensions != null)
ret += string.Join('.', name.extensions.ToList());
return ret;
}
static FileSyntax parseFile(string file_name, string text)
{
var parser = new Parser(text);
var fileSyntax = parser.parse_file(file_name);
if (!parser.is_at_end())
throw new CompilerException
("Unexpected content at end of file.",
new Span
{
file = file_name,
start = new Position { line = parser.get_current_line(), column = parser.get_current_column() },
end = new Position { line = parser.get_current_line(), column = parser.get_current_column() }
}
);
return fileSyntax;
}
}
}
| |
using System.Globalization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NBitcoin.OpenAsset;
namespace NBitcoin
{
public static class MoneyExtensions
{
public static Money Sum(this IEnumerable<Money> moneys)
{
if (moneys is null)
throw new ArgumentNullException(nameof(moneys));
long result = 0;
foreach (var money in moneys)
{
result = checked(result + money.Satoshi);
}
return new Money(result);
}
public static IMoney Sum(this IEnumerable<IMoney> moneys, IMoney zero)
{
if (moneys is null)
throw new ArgumentNullException(nameof(moneys));
if (zero is null)
throw new ArgumentNullException(nameof(zero));
IMoney result = zero;
foreach (var money in moneys)
{
result = result.Add(money);
}
return result;
}
public static AssetMoney Sum(this IEnumerable<AssetMoney> moneys, AssetId assetId)
{
if (moneys is null)
throw new ArgumentNullException(nameof(moneys));
if (assetId is null)
throw new ArgumentNullException(nameof(assetId));
long result = 0;
AssetId id = null;
foreach (var money in moneys)
{
result = checked(result + money.Quantity);
if (id is null)
id = money.Id;
else if (id != money.Id)
throw new ArgumentException("Impossible to add AssetMoney with different asset ids", nameof(moneys));
}
if (id is null)
return new AssetMoney(assetId);
return new AssetMoney(id, result);
}
}
public enum MoneyUnit : int
{
BTC = 100_000_000,
MilliBTC = 100_000,
Bit = 100,
Satoshi = 1
}
public interface IMoney : IComparable, IComparable<IMoney>, IEquatable<IMoney>
{
IMoney Add(IMoney money);
IMoney Sub(IMoney money);
IMoney Negate();
bool IsCompatible(IMoney money);
IEnumerable<IMoney> Split(int parts);
}
public class MoneyBag : IMoney, IEnumerable<IMoney>, IEquatable<MoneyBag>
{
private readonly List<IMoney> _bag = new List<IMoney>();
public MoneyBag()
: this(new List<MoneyBag>())
{
}
public MoneyBag(MoneyBag money)
: this(money._bag)
{
}
public MoneyBag(params IMoney[] bag)
: this((IEnumerable<IMoney>)bag)
{
}
private MoneyBag(IEnumerable<IMoney> bag)
{
foreach (var money in bag)
{
AppendMoney(money);
}
}
private void AppendMoney(MoneyBag money)
{
foreach (var m in money._bag)
{
AppendMoney(m);
}
}
private void AppendMoney(IMoney money)
{
var moneyBag = money as MoneyBag;
if (moneyBag != null)
{
AppendMoney(moneyBag);
return;
}
var firstCompatible = _bag.FirstOrDefault(x => x.IsCompatible(money));
if (firstCompatible is null)
{
_bag.Add(money);
}
else
{
_bag.Remove(firstCompatible);
var zero = firstCompatible.Sub(firstCompatible);
var total = firstCompatible.Add(money);
if (!zero.Equals(total))
_bag.Add(total);
}
}
public int CompareTo(object obj)
{
throw new NotSupportedException("Comparisons are not possible for MoneyBag");
}
public int CompareTo(IMoney other)
{
throw new NotSupportedException("Comparisons are not possible for MoneyBag");
}
public bool Equals(MoneyBag other)
{
return Equals(other as IMoney);
}
public bool Equals(IMoney other)
{
if (other is null)
return false;
var m = new MoneyBag(other);
return m._bag.SequenceEqual(_bag);
}
public static MoneyBag operator -(MoneyBag left, IMoney right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return (MoneyBag)((IMoney)left).Sub(right);
}
public static MoneyBag operator +(MoneyBag left, IMoney right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return (MoneyBag)((IMoney)left).Add(right);
}
IMoney IMoney.Add(IMoney money)
{
var m = new MoneyBag(_bag);
m.AppendMoney(money);
return m;
}
IMoney IMoney.Sub(IMoney money)
{
return ((IMoney)this).Add(money.Negate());
}
IMoney IMoney.Negate()
{
return new MoneyBag(_bag.Select(x => x.Negate()));
}
bool IMoney.IsCompatible(IMoney money)
{
return true;
}
/// <summary>
/// Get the Money corresponding to the input assetId
/// </summary>
/// <param name="assetId">The asset id, if null, will assume bitcoin amount</param>
/// <returns>Never returns null, either the AssetMoney or Money if assetId is null</returns>
public IMoney GetAmount(AssetId assetId = null)
{
if (assetId is null)
return this.OfType<Money>().FirstOrDefault() ?? Money.Zero;
else
return this.OfType<AssetMoney>().Where(a => a.Id == assetId).FirstOrDefault() ?? new AssetMoney(assetId, 0);
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var money in _bag)
{
sb.AppendFormat("{0} ", money);
}
return sb.ToString();
}
public IEnumerator<IMoney> GetEnumerator()
{
return _bag.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _bag.GetEnumerator();
}
/// <summary>
/// Split the MoneyBag in several one, without loss
/// </summary>
/// <param name="parts">The number of parts (must be more than 0)</param>
/// <returns>The splitted money</returns>
public IEnumerable<MoneyBag> Split(int parts)
{
if (parts <= 0)
throw new ArgumentOutOfRangeException(nameof(parts), "Parts should be more than 0");
List<List<IMoney>> splits = new List<List<IMoney>>();
foreach (var money in this)
{
splits.Add(money.Split(parts).ToList());
}
for (int i = 0; i < parts; i++)
{
MoneyBag bag = new MoneyBag();
foreach (var split in splits)
{
bag += split[i];
}
yield return bag;
}
}
#region IMoney Members
IEnumerable<IMoney> IMoney.Split(int parts)
{
return Split(parts);
}
public TMoney GetAmount<TMoney>(TMoney zero) where TMoney : IMoney
{
return _bag.Where(m => m.IsCompatible(zero)).OfType<TMoney>().FirstOrDefault() ?? zero;
}
#endregion
}
public class Money : IComparable, IComparable<Money>, IEquatable<Money>, IMoney
{
// for decimal.TryParse. None of the NumberStyles' composed values is useful for bitcoin style
private const NumberStyles BitcoinStyle =
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite
| NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint;
/// <summary>
/// Parse a bitcoin amount (Culture Invariant)
/// </summary>
/// <param name="bitcoin"></param>
/// <param name="nRet"></param>
/// <returns></returns>
public static bool TryParse(string bitcoin, out Money nRet)
{
nRet = null;
decimal value;
if (!decimal.TryParse(bitcoin, BitcoinStyle, CultureInfo.InvariantCulture, out value))
{
return false;
}
try
{
nRet = new Money(value, MoneyUnit.BTC);
return true;
}
catch (OverflowException)
{
return false;
}
}
/// <summary>
/// Parse a bitcoin amount (Culture Invariant)
/// </summary>
/// <param name="bitcoin"></param>
/// <returns></returns>
public static Money Parse(string bitcoin)
{
Money result;
if (TryParse(bitcoin, out result))
{
return result;
}
throw new FormatException("Impossible to parse the string in a bitcoin amount");
}
long _Satoshis;
public long Satoshi
{
get
{
return _Satoshis;
}
// used as a central point where long.MinValue checking can be enforced
private set
{
CheckLongMinValue(value);
_Satoshis = value;
}
}
/// <summary>
/// Get absolute value of the instance
/// </summary>
/// <returns></returns>
public Money Abs()
{
var a = this;
if (a < Money.Zero)
a = -a;
return a;
}
[Obsolete("You shouldn't use 'int' for a satoshi amount; you should use long/int64, as Int32.MaxValue is only 2,147,483,647, while there can be 21,000,000*100,000,000 satoshis")]
public Money(int satoshis)
{
Satoshi = satoshis;
}
[Obsolete("You shouldn't use 'uint' for a satoshi amount; you should use long/int64, as UInt32.MaxValue is only 4,294,967,295, while there can be 21,000,000*100,000,000 satoshis")]
public Money(uint satoshis)
{
Satoshi = satoshis;
}
public Money(long satoshis)
{
Satoshi = satoshis;
}
public Money(ulong satoshis)
{
// overflow check.
// ulong.MaxValue is greater than long.MaxValue
checked
{
Satoshi = (long)satoshis;
}
}
public Money(decimal amount, MoneyUnit unit)
{
// sanity check. Only valid units are allowed
CheckMoneyUnit(unit, nameof(unit));
checked
{
var satoshi = amount * (int)unit;
Satoshi = (long)satoshi;
}
}
public Money(long amount, MoneyUnit unit)
{
// sanity check. Only valid units are allowed
CheckMoneyUnit(unit, nameof(unit));
checked
{
Satoshi = amount * (int)unit;
}
}
public Money(ulong amount, MoneyUnit unit)
{
// sanity check. Only valid units are allowed
CheckMoneyUnit(unit, nameof(unit));
checked
{
var satoshi = (long)amount * (int)unit;
Satoshi = satoshi;
}
}
/// <summary>
/// Split the Money in parts without loss
/// </summary>
/// <param name="parts">The number of parts (must be more than 0)</param>
/// <returns>The splitted money</returns>
public IEnumerable<Money> Split(int parts)
{
if (parts <= 0)
throw new ArgumentOutOfRangeException(nameof(parts), "Parts should be more than 0");
long remain;
long result = DivRem(_Satoshis, parts, out remain);
for (int i = 0; i < parts; i++)
{
yield return Money.Satoshis(result + (remain > 0 ? 1 : 0));
remain--;
}
}
private static long DivRem(long a, long b, out long result)
{
result = a % b;
return a / b;
}
public static Money FromUnit(decimal amount, MoneyUnit unit)
{
return new Money(amount, unit);
}
/// <summary>
/// Convert Money to decimal (same as ToDecimal)
/// </summary>
/// <param name="unit"></param>
/// <returns></returns>
public decimal ToUnit(MoneyUnit unit)
{
CheckMoneyUnit(unit, nameof(unit));
// overflow safe because (long / int) always fit in decimal
// decimal operations are checked by default
return (decimal)Satoshi / (int)unit;
}
/// <summary>
/// Convert Money to decimal (same as ToUnit)
/// </summary>
/// <param name="unit"></param>
/// <returns></returns>
public decimal ToDecimal(MoneyUnit unit)
{
return ToUnit(unit);
}
public static Money Coins(decimal coins)
{
// overflow safe.
// decimal operations are checked by default
return new Money(coins * COIN, MoneyUnit.Satoshi);
}
public static Money Bits(decimal bits)
{
// overflow safe.
// decimal operations are checked by default
return new Money(bits * CENT, MoneyUnit.Satoshi);
}
public static Money Cents(decimal cents)
{
// overflow safe.
// decimal operations are checked by default
return new Money(cents * CENT, MoneyUnit.Satoshi);
}
public static Money Satoshis(decimal sats)
{
return new Money(sats, MoneyUnit.Satoshi);
}
public static Money Satoshis(ulong sats)
{
return new Money(sats);
}
public static Money Satoshis(long sats)
{
return new Money(sats);
}
#region IEquatable<Money> Members
public bool Equals(Money other)
{
if (other is null)
return false;
return _Satoshis.Equals(other._Satoshis);
}
public int CompareTo(Money other)
{
if (other is null)
return 1;
return _Satoshis.CompareTo(other._Satoshis);
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
if (obj is null)
return 1;
Money m = obj as Money;
if (m != null)
return _Satoshis.CompareTo(m._Satoshis);
#if !NETSTANDARD1X
return _Satoshis.CompareTo(obj);
#else
return _Satoshis.CompareTo((long)obj);
#endif
}
#endregion
public static Money operator -(Money left, Money right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return new Money(checked(left._Satoshis - right._Satoshis));
}
public static Money operator -(Money left)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
return new Money(checked(-left._Satoshis));
}
public static Money operator +(Money left, Money right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return new Money(checked(left._Satoshis + right._Satoshis));
}
public static Money operator *(int left, Money right)
{
if (right is null)
throw new ArgumentNullException(nameof(right));
return Money.Satoshis(checked(left * right._Satoshis));
}
public static Money operator *(Money right, int left)
{
if (right is null)
throw new ArgumentNullException(nameof(right));
return Money.Satoshis(checked(right._Satoshis * left));
}
public static Money operator *(long left, Money right)
{
if (right is null)
throw new ArgumentNullException(nameof(right));
return Money.Satoshis(checked(left * right._Satoshis));
}
public static Money operator *(Money right, long left)
{
if (right is null)
throw new ArgumentNullException(nameof(right));
return Money.Satoshis(checked(left * right._Satoshis));
}
public static Money operator /(Money left, long right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
return new Money(checked(left._Satoshis / right));
}
public static bool operator <(Money left, Money right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return left._Satoshis < right._Satoshis;
}
public static bool operator >(Money left, Money right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return left._Satoshis > right._Satoshis;
}
public static bool operator <=(Money left, Money right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return left._Satoshis <= right._Satoshis;
}
public static bool operator >=(Money left, Money right)
{
if (left is null)
throw new ArgumentNullException(nameof(left));
if (right is null)
throw new ArgumentNullException(nameof(right));
return left._Satoshis >= right._Satoshis;
}
public static implicit operator Money(long value)
{
return new Money(value);
}
[Obsolete("You shouldn't use 'int' for a satoshi amount; you should use long/int64, as Int32.MaxValue is only 2,147,483,647, while there can be 21,000,000*100,000,000 satoshis")]
public static implicit operator Money(int value)
{
return new Money(value);
}
[Obsolete("You shouldn't use 'int' for a satoshi amount; you should use long/int64, as Int32.MaxValue is only 2,147,483,647, while there can be 21,000,000*100,000,000 satoshis")]
public static implicit operator Money(uint value)
{
return new Money(value);
}
public static implicit operator Money(ulong value)
{
return new Money(checked((long)value));
}
public static implicit operator long(Money value)
{
return value.Satoshi;
}
public static implicit operator ulong(Money value)
{
return checked((ulong)value.Satoshi);
}
public static implicit operator Money(string value)
{
return Money.Parse(value);
}
public override bool Equals(object obj)
{
Money item = obj as Money;
if (item is null)
return false;
return _Satoshis.Equals(item._Satoshis);
}
public static bool operator ==(Money a, Money b)
{
if (Object.ReferenceEquals(a, b))
return true;
if (a is null || b is null)
return false;
return a._Satoshis == b._Satoshis;
}
public static bool operator !=(Money a, Money b)
{
return !(a == b);
}
public override int GetHashCode()
{
return _Satoshis.GetHashCode();
}
/// <summary>
/// Returns a culture invariant string representation of Bitcoin amount
/// </summary>
/// <returns></returns>
public override string ToString()
{
return ToString(false, false);
}
/// <summary>
/// Returns a culture invariant string representation of Bitcoin amount
/// </summary>
/// <param name="fplus">True if show + for a positive amount</param>
/// <param name="trimExcessZero">True if trim excess zeros</param>
/// <returns></returns>
public string ToString(bool fplus, bool trimExcessZero = true)
{
var fmt = string.Format(CultureInfo.InvariantCulture, "{{0:{0}{1}B}}",
(fplus ? "+" : null),
(trimExcessZero ? "2" : "8"));
return string.Format(BitcoinFormatter.Formatter, fmt, _Satoshis);
}
static readonly Money _Zero = new Money(0L);
public static Money Zero
{
get
{
return _Zero;
}
}
/// <summary>
/// Tell if amount is almost equal to this instance
/// </summary>
/// <param name="amount"></param>
/// <param name="dust">more or less amount</param>
/// <returns>true if equals, else false</returns>
public bool Almost(Money amount, Money dust)
{
if (amount is null)
throw new ArgumentNullException(nameof(amount));
if (dust is null)
throw new ArgumentNullException(nameof(dust));
return (amount - this).Abs() <= dust;
}
/// <summary>
/// Tell if amount is almost equal to this instance
/// </summary>
/// <param name="amount"></param>
/// <param name="margin">error margin (between 0 and 1)</param>
/// <returns>true if equals, else false</returns>
public bool Almost(Money amount, decimal margin)
{
if (amount is null)
throw new ArgumentNullException(nameof(amount));
if (margin < 0.0m || margin > 1.0m)
throw new ArgumentOutOfRangeException(nameof(margin), "margin should be between 0 and 1");
var dust = Money.Satoshis(this.Satoshi * margin);
return Almost(amount, dust);
}
public static Money Min(Money a, Money b)
{
if (a is null)
throw new ArgumentNullException(nameof(a));
if (b is null)
throw new ArgumentNullException(nameof(b));
if (a <= b)
return a;
return b;
}
public static Money Max(Money a, Money b)
{
if (a is null)
throw new ArgumentNullException(nameof(a));
if (b is null)
throw new ArgumentNullException(nameof(b));
if (a >= b)
return a;
return b;
}
private static void CheckLongMinValue(long value)
{
if (value == long.MinValue)
throw new OverflowException("satoshis amount should be greater than long.MinValue");
}
private static void CheckMoneyUnit(MoneyUnit value, string paramName)
{
var typeOfMoneyUnit = typeof(MoneyUnit);
if (!Enum.IsDefined(typeOfMoneyUnit, value))
{
throw new ArgumentException("Invalid value for MoneyUnit", paramName);
}
}
#region IMoney Members
IMoney IMoney.Add(IMoney money)
{
return this + (Money)money;
}
IMoney IMoney.Sub(IMoney money)
{
return this - (Money)money;
}
IMoney IMoney.Negate()
{
return -this;
}
#endregion
#region IComparable Members
int IComparable.CompareTo(object obj)
{
return this.CompareTo(obj);
}
#endregion
#region IComparable<IMoney> Members
int IComparable<IMoney>.CompareTo(IMoney other)
{
return this.CompareTo(other);
}
#endregion
#region IEquatable<IMoney> Members
bool IEquatable<IMoney>.Equals(IMoney other)
{
return this.Equals(other);
}
bool IMoney.IsCompatible(IMoney money)
{
if (money is null)
throw new ArgumentNullException(nameof(money));
return money is Money;
}
#endregion
public const long COIN = 100 * 1000 * 1000;
public const long CENT = COIN / 100;
public const long NANO = CENT / 100;
#region IMoney Members
IEnumerable<IMoney> IMoney.Split(int parts)
{
return Split(parts);
}
#endregion
}
static class CharExtensions
{
// .NET Char class already provides an static IsDigit method however
// it behaves differently depending on if char is a Latin or not.
public static bool IsDigit(this char c)
{
return c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9';
}
}
internal class BitcoinFormatter : IFormatProvider, ICustomFormatter
{
public static readonly BitcoinFormatter Formatter = new BitcoinFormatter();
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? this : null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (!this.Equals(formatProvider))
{
return null;
}
var i = 0;
var plus = format[i] == '+';
if (plus)
i++;
int decPos = 0;
if (int.TryParse(format.Substring(i, 1), out decPos))
{
i++;
}
var unit = format[i];
var unitToUseInCalc = MoneyUnit.BTC;
switch (unit)
{
case 'B':
unitToUseInCalc = MoneyUnit.BTC;
break;
}
var val = Convert.ToDecimal(arg, CultureInfo.InvariantCulture) / (int)unitToUseInCalc;
var zeros = new string('0', decPos);
var rest = new string('#', 10 - decPos);
var fmt = plus && val > 0 ? "+" : string.Empty;
fmt += "{0:0" + (decPos > 0 ? "." + zeros + rest : string.Empty) + "}";
return string.Format(CultureInfo.InvariantCulture, fmt, val);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
namespace Microsoft.DotNet.CodeFormatting.Rules
{
[SyntaxRule(CopyrightHeaderRule.Name, CopyrightHeaderRule.Description, SyntaxRuleOrder.CopyrightHeaderRule, DefaultRule=false)]
internal sealed partial class CopyrightHeaderRule : SyntaxFormattingRule, ISyntaxFormattingRule
{
internal const string Name = FormattingDefaults.CopyrightRuleName;
internal const string Description = "Insert the copyright header into every file";
private abstract class CommonRule
{
/// <summary>
/// This is the normalized copyright header that has no comment delimiters.
/// </summary>
private readonly ImmutableArray<string> _header;
protected CommonRule(ImmutableArray<string> header)
{
_header = header;
}
internal SyntaxNode Process(SyntaxNode syntaxNode)
{
if (_header.IsDefaultOrEmpty)
{
return syntaxNode;
}
if (HasCopyrightHeader(syntaxNode))
return syntaxNode;
return AddCopyrightHeader(syntaxNode);
}
private bool HasCopyrightHeader(SyntaxNode syntaxNode)
{
var existingHeader = GetExistingHeader(syntaxNode.GetLeadingTrivia());
return SequnceStartsWith(_header, existingHeader);
}
private bool SequnceStartsWith(ImmutableArray<string> header, List<string> existingHeader)
{
// Only try if the existing header is at least as long as the new copyright header
if (existingHeader.Count >= header.Count())
{
return !header.Where((headerLine, i) => existingHeader[i] != headerLine).Any();
}
return false;
}
private SyntaxNode AddCopyrightHeader(SyntaxNode syntaxNode)
{
var list = new List<SyntaxTrivia>();
foreach (var headerLine in _header)
{
list.Add(CreateLineComment(headerLine));
list.Add(CreateNewLine());
}
list.Add(CreateNewLine());
var triviaList = RemoveExistingHeader(syntaxNode.GetLeadingTrivia());
var i = 0;
MovePastBlankLines(triviaList, ref i);
while (i < triviaList.Count)
{
list.Add(triviaList[i]);
i++;
}
return syntaxNode.WithLeadingTrivia(CreateTriviaList(list));
}
private List<string> GetExistingHeader(SyntaxTriviaList triviaList)
{
var i = 0;
MovePastBlankLines(triviaList, ref i);
var headerList = new List<string>();
while (i < triviaList.Count && IsLineComment(triviaList[i]))
{
headerList.Add(GetCommentText(triviaList[i].ToFullString()));
i++;
MoveToNextLineOrTrivia(triviaList, ref i);
}
return headerList;
}
/// <summary>
/// Remove any copyright header that already exists.
/// </summary>
private SyntaxTriviaList RemoveExistingHeader(SyntaxTriviaList oldList)
{
var foundHeader = false;
var i = 0;
MovePastBlankLines(oldList, ref i);
while (i < oldList.Count && IsLineComment(oldList[i]))
{
if (oldList[i].ToFullString().IndexOf("copyright", StringComparison.OrdinalIgnoreCase) >= 0)
{
foundHeader = true;
}
i++;
}
if (!foundHeader)
{
return oldList;
}
MovePastBlankLines(oldList, ref i);
return CreateTriviaList(oldList.Skip(i));
}
private void MovePastBlankLines(SyntaxTriviaList list, ref int index)
{
while (index < list.Count && (IsWhitespace(list[index]) || IsNewLine(list[index])))
{
index++;
}
}
private void MoveToNextLineOrTrivia(SyntaxTriviaList list, ref int index)
{
MovePastWhitespaces(list, ref index);
if (index < list.Count && IsNewLine(list[index]))
{
index++;
}
}
private void MovePastWhitespaces(SyntaxTriviaList list, ref int index)
{
while (index < list.Count && IsWhitespace(list[index]))
{
index++;
}
}
protected abstract SyntaxTriviaList CreateTriviaList(IEnumerable<SyntaxTrivia> e);
protected abstract bool IsLineComment(SyntaxTrivia trivia);
protected abstract bool IsWhitespace(SyntaxTrivia trivia);
protected abstract bool IsNewLine(SyntaxTrivia trivia);
protected abstract SyntaxTrivia CreateLineComment(string commentText);
protected abstract SyntaxTrivia CreateNewLine();
}
private readonly Options _options;
private ImmutableArray<string> _cachedHeader;
private ImmutableArray<string> _cachedHeaderSource;
[ImportingConstructor]
internal CopyrightHeaderRule(Options options)
{
_options = options;
}
private ImmutableArray<string> GetHeader()
{
if (_cachedHeaderSource != _options.CopyrightHeader)
{
_cachedHeaderSource = _options.CopyrightHeader;
_cachedHeader = _options.CopyrightHeader.Select(GetCommentText).ToImmutableArray();
}
return _cachedHeader;
}
private static string GetCommentText(string line)
{
if (line.StartsWith("'"))
{
return line.Substring(1).TrimStart();
}
if (line.StartsWith("//"))
{
return line.Substring(2).TrimStart();
}
return line;
}
public override bool SupportsLanguage(string languageName)
{
return languageName == LanguageNames.CSharp || languageName == LanguageNames.VisualBasic;
}
public override SyntaxNode ProcessCSharp(SyntaxNode syntaxNode)
{
return (new CSharpRule(GetHeader())).Process(syntaxNode);
}
public override SyntaxNode ProcessVisualBasic(SyntaxNode syntaxNode)
{
return (new VisualBasicRule(GetHeader())).Process(syntaxNode);
}
}
}
| |
/*
* 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.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionInterestRegexInterest3Tests : ThinClientRegionSteps
{
#region Private members and methods
private UnitProcess m_client1, m_client2, m_client3, m_feeder;
private static string[] m_regexes = { "Key-*1", "Key-*2",
"Key-*3", "Key-*4" };
private const string m_regex23 = "Key-[23]";
private const string m_regexWildcard = "Key-.*";
private const int m_numUnicodeStrings = 5;
private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" };
private static string[] m_keysForRegex = {"key-regex-1",
"key-regex-2", "key-regex-3" };
private static string[] RegionNamesForInterestNotify =
{ "RegionTrue", "RegionFalse", "RegionOther" };
string GetUnicodeString(int index)
{
return new string('\x0905', 40) + index.ToString("D10");
}
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
m_feeder = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Steps for Thin Client IRegion<object, object> with Interest
public void StepFourIL()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepFourRegex3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
try
{
Util.Log("Registering empty regular expression.");
region0.GetSubscriptionService().RegisterRegex(string.Empty);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering null regular expression.");
region1.GetSubscriptionService().RegisterRegex(null);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering non-existent regular expression.");
region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
}
public void StepFourFailoverRegex()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true);
UnregisterRegexes(null, m_regexes[2]);
}
public void StepFiveIL()
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void StepFiveRegex()
{
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void CreateAllEntries(string regionName)
{
CreateEntry(regionName, m_keys[0], m_vals[0]);
CreateEntry(regionName, m_keys[1], m_vals[1]);
CreateEntry(regionName, m_keys[2], m_vals[2]);
CreateEntry(regionName, m_keys[3], m_vals[3]);
}
public void VerifyAllEntries(string regionName, bool newVal, bool checkVal)
{
string[] vals = newVal ? m_nvals : m_vals;
VerifyEntry(regionName, m_keys[0], vals[0], checkVal);
VerifyEntry(regionName, m_keys[1], vals[1], checkVal);
VerifyEntry(regionName, m_keys[2], vals[2], checkVal);
VerifyEntry(regionName, m_keys[3], vals[3], checkVal);
}
public void VerifyInvalidAll(string regionName, params string[] keys)
{
if (keys != null)
{
foreach (string key in keys)
{
VerifyInvalid(regionName, key);
}
}
}
public void UpdateAllEntries(string regionName, bool checkVal)
{
UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal);
UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal);
UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal);
UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal);
}
public void DoNetsearchAllEntries(string regionName, bool newVal,
bool checkNoKey)
{
string[] vals;
if (newVal)
{
vals = m_nvals;
}
else
{
vals = m_vals;
}
DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey);
DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey);
DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey);
DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey);
}
public void StepFiveFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false);
}
public void StepSixIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]);
region0.Remove(m_keys[1]);
region1.Remove(m_keys[3]);
}
public void StepSixRegex()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UnregisterRegexes(null, m_regexes[3]);
}
public void StepSixFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false);
}
public void StepSevenIL()
{
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void StepSevenRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
UnregisterRegexes(null, m_regexes[1]);
}
public void StepSevenRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true);
UpdateAllEntries(m_regionNames[1], true);
}
public void StepSevenInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterRegex(m_regex23);
VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true);
}
public void StepSevenFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]);
}
public void StepEightIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
public void StepEightRegex()
{
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true);
}
public void StepEightInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region.GetSubscriptionService().RegisterAllKeys();
VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1],
m_keys[2], m_keys[3]);
UpdateAllEntries(m_regionNames[0], true);
}
public void StepEightFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepNineRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
}
public void StepNineRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]);
}
public void StepNineInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().UnregisterRegex(m_regex23);
List<Object> keys = new List<Object>();
keys.Add(m_keys[0]);
keys.Add(m_keys[1]);
keys.Add(m_keys[2]);
region.GetSubscriptionService().RegisterKeys(keys);
VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]);
}
public void PutUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object val;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
val = index + 100;
}
else
{
val = (float)index + 20.0F;
}
region[key] = val;
}
}
public void RegisterUnicodeKeys(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string[] keys = new string[m_numUnicodeStrings];
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index);
}
region.GetSubscriptionService().RegisterKeys(keys);
}
public void VerifyUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object expectedVal;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
expectedVal = index + 100;
Assert.AreEqual(expectedVal, region.GetEntry(key).Value,
"Got unexpected value");
}
else
{
expectedVal = (float)index + 20.0F;
Assert.AreEqual(expectedVal, region[key],
"Got unexpected value");
}
}
}
public void CreateRegionsInterestNotify_Pool(string[] regionNames,
string locators, string poolName, bool notify, string nbs)
{
Properties<string, string> props = Properties<string, string>.Create<string, string>();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
}
/*
public void CreateRegionsInterestNotify(string[] regionNames,
string endpoints, bool notify, string nbs)
{
Properties props = Properties.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion(regionNames[0], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[1], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[2], true, false,
new TallyListener(), endpoints, notify);
}
* */
public void DoFeed()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "00";
}
foreach (string key in m_keysForRegex)
{
region[key] = "00";
}
}
}
public void DoFeederOps()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
foreach (string key in m_keysForRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
}
}
public void DoRegister()
{
DoRegisterInterests(RegionNamesForInterestNotify[0], true);
DoRegisterInterests(RegionNamesForInterestNotify[1], false);
// We intentionally do not register interest in Region3
//DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]);
}
public void DoRegisterInterests(string regionName, bool receiveValues)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues);
region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues);
}
public void DoUnregister()
{
DoUnregisterInterests(RegionNamesForInterestNotify[0]);
DoUnregisterInterests(RegionNamesForInterestNotify[1]);
}
public void DoUnregisterInterests(string regionName)
{
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
region.GetSubscriptionService().UnregisterKeys(keys.ToArray());
region.GetSubscriptionService().UnregisterRegex("key-regex.*");
}
public void DoValidation(string clientName, string regionName,
int creates, int updates, int invalidates, int destroys)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>;
Util.Log(clientName + ": " + regionName + ": creates expected=" + creates +
", actual=" + listener.Creates);
Util.Log(clientName + ": " + regionName + ": updates expected=" + updates +
", actual=" + listener.Updates);
Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates +
", actual=" + listener.Invalidates);
Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys +
", actual=" + listener.Destroys);
Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName);
Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName);
Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName);
Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName);
}
#endregion
[Test]
public void RegexInterest3()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
try {
m_client1.Call(RegisterRegexes, "a*", "*[*2-[");
Assert.Fail("Did not get expected exception!");
} catch (Exception ex) {
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
Util.Log("StepThree complete.");
m_client2.Call(StepFourRegex3);
Util.Log("StepFour complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetObjectsWithFullDetailsSpectraS3Request : Ds3Request
{
private string _bucketId;
public string BucketId
{
get { return _bucketId; }
set { WithBucketId(value); }
}
private long? _endDate;
public long? EndDate
{
get { return _endDate; }
set { WithEndDate(value); }
}
private bool? _includePhysicalPlacement;
public bool? IncludePhysicalPlacement
{
get { return _includePhysicalPlacement; }
set { WithIncludePhysicalPlacement(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private bool? _latest;
public bool? Latest
{
get { return _latest; }
set { WithLatest(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private long? _startDate;
public long? StartDate
{
get { return _startDate; }
set { WithStartDate(value); }
}
private S3ObjectType? _type;
public S3ObjectType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetObjectsWithFullDetailsSpectraS3Request WithBucketId(Guid? bucketId)
{
this._bucketId = bucketId.ToString();
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId.ToString());
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithBucketId(string bucketId)
{
this._bucketId = bucketId;
if (bucketId != null)
{
this.QueryParams.Add("bucket_id", bucketId);
}
else
{
this.QueryParams.Remove("bucket_id");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithEndDate(long? endDate)
{
this._endDate = endDate;
if (endDate != null)
{
this.QueryParams.Add("end_date", endDate.ToString());
}
else
{
this.QueryParams.Remove("end_date");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithIncludePhysicalPlacement(bool? includePhysicalPlacement)
{
this._includePhysicalPlacement = includePhysicalPlacement;
if (includePhysicalPlacement != null)
{
this.QueryParams.Add("include_physical_placement", includePhysicalPlacement.ToString());
}
else
{
this.QueryParams.Remove("include_physical_placement");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithLatest(bool? latest)
{
this._latest = latest;
if (latest != null)
{
this.QueryParams.Add("latest", latest.ToString());
}
else
{
this.QueryParams.Remove("latest");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithStartDate(long? startDate)
{
this._startDate = startDate;
if (startDate != null)
{
this.QueryParams.Add("start_date", startDate.ToString());
}
else
{
this.QueryParams.Remove("start_date");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request WithType(S3ObjectType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetObjectsWithFullDetailsSpectraS3Request()
{
this.QueryParams.Add("full_details", null);
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/object";
}
}
}
}
| |
// 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.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
#pragma warning disable 4014
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class TrackBassTest
{
private BassTestComponents bass;
private TrackBass track;
[SetUp]
public void Setup()
{
bass = new BassTestComponents();
track = bass.GetTrack();
bass.Update();
}
[TearDown]
public void Teardown()
{
bass?.Dispose();
}
[Test]
public void TestStart()
{
track.StartAsync();
bass.Update();
Thread.Sleep(50);
bass.Update();
Assert.IsTrue(track.IsRunning);
Assert.Greater(track.CurrentTime, 0);
}
[Test]
public void TestStop()
{
track.StartAsync();
bass.Update();
track.StopAsync();
bass.Update();
Assert.IsFalse(track.IsRunning);
double expectedTime = track.CurrentTime;
Thread.Sleep(50);
Assert.AreEqual(expectedTime, track.CurrentTime);
}
[Test]
public void TestStopAtEnd()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
bass.Update();
track.StopAsync();
bass.Update();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(track.Length, track.CurrentTime);
}
[Test]
public void TestSeek()
{
track.SeekAsync(1000);
bass.Update();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(1000, track.CurrentTime);
}
[Test]
public void TestSeekWhileRunning()
{
track.StartAsync();
bass.Update();
track.SeekAsync(1000);
bass.Update();
Thread.Sleep(50);
bass.Update();
Assert.IsTrue(track.IsRunning);
Assert.GreaterOrEqual(track.CurrentTime, 1000);
}
/// <summary>
/// Bass does not allow seeking to the end of the track. It should fail and the current time should not change.
/// </summary>
[Test]
public void TestSeekToEndFails()
{
bool? success = null;
bass.RunOnAudioThread(() => { success = track.Seek(track.Length); });
bass.Update();
Assert.AreEqual(0, track.CurrentTime);
Assert.IsFalse(success);
}
[Test]
public void TestSeekBackToSamePosition()
{
track.SeekAsync(1000);
track.SeekAsync(0);
bass.Update();
Thread.Sleep(50);
bass.Update();
Assert.GreaterOrEqual(track.CurrentTime, 0);
Assert.Less(track.CurrentTime, 1000);
}
[Test]
public void TestPlaybackToEnd()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
bass.Update();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(track.Length, track.CurrentTime);
}
/// <summary>
/// Bass restarts the track from the beginning if Start is called when the track has been completed.
/// This is blocked locally in <see cref="TrackBass"/>, so this test expects the track to not restart.
/// </summary>
[Test]
public void TestStartFromEndDoesNotRestart()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
bass.Update();
track.StartAsync();
bass.Update();
Assert.AreEqual(track.Length, track.CurrentTime);
}
[Test]
public void TestRestart()
{
startPlaybackAt(1000);
Thread.Sleep(50);
bass.Update();
restartTrack();
Assert.IsTrue(track.IsRunning);
Assert.Less(track.CurrentTime, 1000);
}
[Test]
public void TestRestartAtEnd()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
bass.Update();
restartTrack();
Assert.IsTrue(track.IsRunning);
Assert.LessOrEqual(track.CurrentTime, 1000);
}
[Test]
public void TestRestartFromRestartPoint()
{
track.RestartPoint = 1000;
startPlaybackAt(3000);
restartTrack();
Assert.IsTrue(track.IsRunning);
Assert.GreaterOrEqual(track.CurrentTime, 1000);
Assert.Less(track.CurrentTime, 3000);
}
[TestCase(0)]
[TestCase(1000)]
public void TestLoopingRestart(double restartPoint)
{
track.Looping = true;
track.RestartPoint = restartPoint;
startPlaybackAt(track.Length - 1);
takeEffectsAndUpdateAfter(50);
// In a perfect world the track will be running after the update above, but during testing it's possible that the track is in
// a stalled state due to updates running on Bass' own thread, so we'll loop until the track starts running again
// Todo: This should be fixed in the future if/when we invoke Bass.Update() ourselves
int loopCount = 0;
while (++loopCount < 50 && !track.IsRunning)
{
bass.Update();
Thread.Sleep(10);
}
if (loopCount == 50)
throw new TimeoutException("Track failed to start in time.");
Assert.GreaterOrEqual(track.CurrentTime, restartPoint);
Assert.LessOrEqual(track.CurrentTime, restartPoint + 1000);
}
[Test]
public void TestSetTempoNegative()
{
Assert.Throws<ArgumentException>(() => track.Tempo.Value = -1);
Assert.Throws<ArgumentException>(() => track.Tempo.Value = 0.04f);
Assert.IsFalse(track.IsReversed);
track.Tempo.Value = 0.05f;
Assert.IsFalse(track.IsReversed);
Assert.AreEqual(0.05f, track.Tempo.Value);
}
[Test]
public void TestRateWithAggregateAdjustments()
{
track.AddAdjustment(AdjustableProperty.Frequency, new BindableDouble(1.5f));
Assert.AreEqual(1.5, track.Rate);
}
[Test]
public void TestLoopingTrackDoesntSetCompleted()
{
bool completedEvent = false;
track.Completed += () => completedEvent = true;
track.Looping = true;
startPlaybackAt(track.Length - 1);
takeEffectsAndUpdateAfter(50);
Assert.IsFalse(track.HasCompleted);
Assert.IsFalse(completedEvent);
bass.Update();
Assert.IsTrue(track.IsRunning);
}
[Test]
public void TestHasCompletedResetsOnSeekBack()
{
// start playback and wait for completion.
startPlaybackAt(track.Length - 1);
takeEffectsAndUpdateAfter(50);
Assert.IsTrue(track.HasCompleted);
// ensure seeking to end doesn't reset completed state.
track.SeekAsync(track.Length);
bass.Update();
Assert.IsTrue(track.HasCompleted);
// seeking back reset completed state.
track.SeekAsync(track.Length - 1);
bass.Update();
Assert.IsFalse(track.HasCompleted);
}
[Test]
public void TestZeroFrequencyHandling()
{
// start track.
track.StartAsync();
takeEffectsAndUpdateAfter(50);
// ensure running and has progressed.
Assert.IsTrue(track.IsRunning);
Assert.Greater(track.CurrentTime, 0);
// now set to zero frequency and update track to take effects.
track.Frequency.Value = 0;
bass.Update();
var currentTime = track.CurrentTime;
// assert time is frozen after 50ms sleep and didn't change with full precision, but "IsRunning" is still true.
Thread.Sleep(50);
bass.Update();
Assert.IsTrue(track.IsRunning);
Assert.AreEqual(currentTime, track.CurrentTime);
// set back to one and update track.
track.Frequency.Value = 1;
takeEffectsAndUpdateAfter(50);
// ensure time didn't jump away, and is progressing normally.
Assert.IsTrue(track.IsRunning);
Assert.Greater(track.CurrentTime, currentTime);
Assert.Less(track.CurrentTime, currentTime + 1000.0);
}
/// <summary>
/// Ensure setting a paused (or not yet played) track's frequency from zero to one doesn't resume / play it.
/// </summary>
[Test]
public void TestZeroFrequencyDoesntResumeTrack()
{
// start at zero frequency and wait a bit.
track.Frequency.Value = 0;
track.StartAsync();
takeEffectsAndUpdateAfter(50);
// ensure started but not progressing.
Assert.IsTrue(track.IsRunning);
Assert.AreEqual(0, track.CurrentTime);
// stop track and update.
track.StopAsync();
bass.Update();
Assert.IsFalse(track.IsRunning);
// set back to 1 frequency.
track.Frequency.Value = 1;
takeEffectsAndUpdateAfter(50);
// assert track channel still paused regardless of frequency because it's stopped via Stop() above.
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(0, track.CurrentTime);
}
[Test]
public void TestBitrate()
{
Assert.Greater(track.Bitrate, 0);
}
[Test]
public void TestCurrentTimeUpdatedAfterInlineSeek()
{
track.StartAsync();
bass.Update();
bass.RunOnAudioThread(() => track.Seek(20000));
Assert.That(track.CurrentTime, Is.EqualTo(20000).Within(100));
}
private void takeEffectsAndUpdateAfter(int after)
{
bass.Update();
Thread.Sleep(after);
bass.Update();
}
private void startPlaybackAt(double time)
{
track.SeekAsync(time);
track.StartAsync();
bass.Update();
}
private void restartTrack()
{
bass.RunOnAudioThread(() =>
{
track.Restart();
bass.Update();
});
}
}
}
#pragma warning restore 4014
| |
using System;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
[TestFixture]
public class CookieImplementationTest : DriverTestFixture
{
private Random random = new Random();
private bool isOnAlternativeHostName;
private string hostname;
[SetUp]
public void GoToSimplePageAndDeleteCookies()
{
GotoValidDomainAndClearCookies("animals");
AssertNoCookiesArePresent();
}
[Test]
public void ShouldGetCookieByName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = string.Format("key_{0}", new Random().Next());
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key);
Cookie cookie = driver.Manage().Cookies.GetCookieNamed(key);
Assert.AreEqual("set", cookie.Value);
}
[Test]
public void ShouldBeAbleToAddCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = GenerateUniqueKey();
string value = "foo";
Cookie cookie = new Cookie(key, value);
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieHasValue(key, value);
Assert.That(driver.Manage().Cookies.AllCookies.Contains(cookie), "Cookie was not added successfully");
}
[Test]
public void GetAllCookies()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key1 = GenerateUniqueKey();
string key2 = GenerateUniqueKey();
AssertCookieIsNotPresentWithName(key1);
AssertCookieIsNotPresentWithName(key2);
ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
int count = cookies.Count;
Cookie one = new Cookie(key1, "value");
Cookie two = new Cookie(key2, "value");
driver.Manage().Cookies.AddCookie(one);
driver.Manage().Cookies.AddCookie(two);
driver.Url = simpleTestPage;
cookies = driver.Manage().Cookies.AllCookies;
Assert.AreEqual(count + 2, cookies.Count);
Assert.That(cookies, Does.Contain(one));
Assert.That(cookies, Does.Contain(two));
}
[Test]
public void DeleteAllCookies()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = 'foo=set';");
AssertSomeCookiesArePresent();
driver.Manage().Cookies.DeleteAllCookies();
AssertNoCookiesArePresent();
}
[Test]
public void DeleteCookieWithName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key1 = GenerateUniqueKey();
string key2 = GenerateUniqueKey();
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key1);
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key2);
AssertCookieIsPresentWithName(key1);
AssertCookieIsPresentWithName(key2);
driver.Manage().Cookies.DeleteCookieNamed(key1);
AssertCookieIsNotPresentWithName(key1);
AssertCookieIsPresentWithName(key2);
}
[Test]
public void ShouldNotDeleteCookiesWithASimilarName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieOneName = "fish";
Cookie cookie1 = new Cookie(cookieOneName, "cod");
Cookie cookie2 = new Cookie(cookieOneName + "x", "earth");
IOptions options = driver.Manage();
AssertCookieIsNotPresentWithName(cookie1.Name);
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
AssertCookieIsPresentWithName(cookie1.Name);
options.Cookies.DeleteCookieNamed(cookieOneName);
Assert.That(driver.Manage().Cookies.AllCookies, Does.Not.Contain(cookie1));
Assert.That(driver.Manage().Cookies.AllCookies, Does.Contain(cookie2));
}
[Test]
public void AddCookiesWithDifferentPathsThatAreRelatedToOurs()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder;
driver.Url = builder.WhereIs("animals");
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
AssertCookieIsPresentWithName(cookie1.Name);
AssertCookieIsPresentWithName(cookie2.Name);
driver.Url = builder.WhereIs("simpleTest.html");
AssertCookieIsNotPresentWithName(cookie1.Name);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Chrome does not retrieve cookies when in frame.")]
public void GetCookiesInAFrame()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
Cookie cookie1 = new Cookie("fish", "cod", "/common/animals");
driver.Manage().Cookies.AddCookie(cookie1);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("frameWithAnimals.html");
AssertCookieIsNotPresentWithName(cookie1.Name);
driver.SwitchTo().Frame("iframe1");
AssertCookieIsPresentWithName(cookie1.Name);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void CannotGetCookiesWithPathDifferingOnlyInCase()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "fish";
driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod", "/Common/animals"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
Assert.That(driver.Manage().Cookies.GetCookieNamed(cookieName), Is.Null);
}
[Test]
public void ShouldNotGetCookieOnDifferentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "fish";
driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod"));
AssertCookieIsPresentWithName(cookieName);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html");
AssertCookieIsNotPresentWithName(cookieName);
}
[Test]
public void ShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
AssertCookieIsNotPresentWithName("name");
Regex replaceRegex = new Regex(".*?\\.");
string shorter = replaceRegex.Replace(this.hostname, ".", 1);
Cookie cookie = new Cookie("name", "value", shorter, "/", GetTimeInTheFuture());
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName("name");
}
[Test]
public void ShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "name";
AssertCookieIsNotPresentWithName(cookieName);
Regex replaceRegex = new Regex(".*?\\.");
string subdomain = replaceRegex.Replace(this.hostname, "subdomain.", 1);
Cookie cookie = new Cookie(cookieName, "value", subdomain, "/", GetTimeInTheFuture());
string originalUrl = driver.Url;
string subdomainUrl = originalUrl.Replace(this.hostname, subdomain);
driver.Url = subdomainUrl;
driver.Manage().Cookies.AddCookie(cookie);
driver.Url = originalUrl;
AssertCookieIsNotPresentWithName(cookieName);
}
[Test]
public void ShouldBeAbleToIncludeLeadingPeriodInDomainName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
AssertCookieIsNotPresentWithName("name");
// Replace the first part of the name with a period
Regex replaceRegex = new Regex(".*?\\.");
string shorter = replaceRegex.Replace(this.hostname, ".", 1);
Cookie cookie = new Cookie("name", "value", shorter, "/", DateTime.Now.AddSeconds(100000));
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName("name");
}
[Test]
public void ShouldBeAbleToSetDomainToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
Uri url = new Uri(driver.Url);
String host = url.Host + ":" + url.Port.ToString();
Cookie cookie1 = new Cookie("fish", "cod", host, "/", null);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
driver.Url = javascriptPage;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Contain(cookie1));
}
[Test]
public void ShouldWalkThePathToDeleteACookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod");
driver.Manage().Cookies.AddCookie(cookie1);
int count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = childPage;
Cookie cookie2 = new Cookie("rodent", "hamster", "/" + basePath + "/child");
driver.Manage().Cookies.AddCookie(cookie2);
count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = grandchildPage;
Cookie cookie3 = new Cookie("dog", "dalmation", "/" + basePath + "/child/grandchild/");
driver.Manage().Cookies.AddCookie(cookie3);
count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("child/grandchild"));
driver.Manage().Cookies.DeleteCookieNamed("rodent");
count = driver.Manage().Cookies.AllCookies.Count;
Assert.That(driver.Manage().Cookies.GetCookieNamed("rodent"), Is.Null);
ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
Assert.That(cookies, Has.Count.EqualTo(2));
Assert.That(cookies, Does.Contain(cookie1));
Assert.That(cookies, Does.Contain(cookie3));
driver.Manage().Cookies.DeleteAllCookies();
driver.Url = grandchildPage;
AssertNoCookiesArePresent();
}
[Test]
public void ShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
Uri uri = new Uri(driver.Url);
string host = string.Format("{0}:{1}", uri.Host, uri.Port);
string cookieName = "name";
AssertCookieIsNotPresentWithName(cookieName);
Cookie cookie = new Cookie(cookieName, "value", host, "/", null);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName(cookieName);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void CookieEqualityAfterSetAndGet()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
DateTime time = DateTime.Now.AddDays(1);
Cookie cookie1 = new Cookie("fish", "cod", null, "/common/animals", time);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Cookie retrievedCookie = null;
foreach (Cookie tempCookie in cookies)
{
if (cookie1.Equals(tempCookie))
{
retrievedCookie = tempCookie;
break;
}
}
Assert.That(retrievedCookie, Is.Not.Null);
//Cookie.equals only compares name, domain and path
Assert.AreEqual(cookie1, retrievedCookie);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void ShouldRetainCookieExpiry()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
// DateTime.Now contains milliseconds; the returned cookie expire date
// will not. So we need to truncate the milliseconds.
DateTime current = DateTime.Now;
DateTime expireDate = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, current.Second, DateTimeKind.Local).AddDays(1);
Cookie addCookie = new Cookie("fish", "cod", "/common/animals", expireDate);
IOptions options = driver.Manage();
options.Cookies.AddCookie(addCookie);
Cookie retrieved = options.Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
Assert.AreEqual(addCookie.Expiry, retrieved.Expiry, "Cookies are not equal");
}
[Test]
[IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")]
[IgnoreBrowser(Browser.Edge, "Browser does not handle untrusted SSL certificates.")]
public void CanHandleSecureCookie()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals");
Cookie addedCookie = new ReturnedCookie("fish", "cod", null, "/common/animals", null, true, false);
driver.Manage().Cookies.AddCookie(addedCookie);
driver.Navigate().Refresh();
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
}
[Test]
[IgnoreBrowser(Browser.IE, "Browser does not handle untrusted SSL certificates.")]
[IgnoreBrowser(Browser.Edge, "Browser does not handle untrusted SSL certificates.")]
public void ShouldRetainCookieSecure()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("animals");
ReturnedCookie addedCookie = new ReturnedCookie("fish", "cod", string.Empty, "/common/animals", null, true, false);
driver.Manage().Cookies.AddCookie(addedCookie);
driver.Navigate().Refresh();
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
Assert.That(retrieved.Secure, "Secure attribute not set to true");
}
[Test]
public void CanHandleHttpOnlyCookie()
{
StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereIs("cookie"));
url.Append("?action=add");
url.Append("&name=").Append("fish");
url.Append("&value=").Append("cod");
url.Append("&path=").Append("/common/animals");
url.Append("&httpOnly=").Append("true");
driver.Url = url.ToString();
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
}
[Test]
public void ShouldRetainHttpOnlyFlag()
{
StringBuilder url = new StringBuilder(EnvironmentManager.Instance.UrlBuilder.WhereElseIs("cookie"));
url.Append("?action=add");
url.Append("&name=").Append("fish");
url.Append("&value=").Append("cod");
url.Append("&path=").Append("/common/animals");
url.Append("&httpOnly=").Append("true");
driver.Url = url.ToString();
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
Cookie retrieved = driver.Manage().Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Not.Null);
Assert.That(retrieved.IsHttpOnly, "HttpOnly attribute not set to true");
}
[Test]
public void SettingACookieThatExpiredInThePast()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
DateTime expires = DateTime.Now.AddSeconds(-1000);
Cookie cookie = new Cookie("expired", "yes", "/common/animals", expires);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie);
cookie = options.Cookies.GetCookieNamed("expired");
Assert.That(cookie, Is.Null, "Cookie expired before it was set, so nothing should be returned: " + cookie);
}
[Test]
public void CanSetCookieWithoutOptionalFieldsSet()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = GenerateUniqueKey();
string value = "foo";
Cookie cookie = new Cookie(key, value);
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieHasValue(key, value);
}
[Test]
public void DeleteNotExistedCookie()
{
String key = GenerateUniqueKey();
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.DeleteCookieNamed(key);
}
[Test]
public void DeleteAllCookiesDifferentUrls()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish1", "cod", EnvironmentManager.Instance.UrlBuilder.HostName, null, null);
Cookie cookie2 = new Cookie("fish2", "tune", EnvironmentManager.Instance.UrlBuilder.AlternateHostName, null, null);
string url1 = EnvironmentManager.Instance.UrlBuilder.WhereIs("");
string url2 = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
AssertCookieIsPresentWithName(cookie1.Name);
driver.Url = url2;
options.Cookies.AddCookie(cookie2);
AssertCookieIsNotPresentWithName(cookie1.Name);
AssertCookieIsPresentWithName(cookie2.Name);
driver.Url = url1;
AssertCookieIsPresentWithName(cookie1.Name);
AssertCookieIsNotPresentWithName(cookie2.Name);
options.Cookies.DeleteAllCookies();
AssertCookieIsNotPresentWithName(cookie1.Name);
driver.Url = url2;
AssertCookieIsPresentWithName(cookie2.Name);
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void CanSetCookiesOnADifferentPathOfTheSameHost()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/galaxy");
IOptions options = driver.Manage();
ReadOnlyCollection<Cookie> count = options.Cookies.AllCookies;
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
driver.Url = url;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Contain(cookie1));
Assert.That(cookies, Does.Not.Contain(cookie2));
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("galaxy");
cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie1));
Assert.That(cookies, Does.Contain(cookie2));
}
[Test]
public void ShouldNotBeAbleToSetDomainToSomethingThatIsUnrelatedToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish", "cod");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html");
driver.Url = url;
Assert.That(options.Cookies.GetCookieNamed("fish"), Is.Null);
}
[Test]
public void GetCookieDoesNotRetriveBeyondCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish", "cod");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
String url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("");
driver.Url = url;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie1));
}
[Test]
public void ShouldAddCookieToCurrentDomainAndPath()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Homer", "Simpson", this.hostname, "/" + EnvironmentManager.Instance.UrlBuilder.Path, null);
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies.Contains(cookie), "Valid cookie was not returned");
}
[Test]
public void ShouldNotShowCookieAddedToDifferentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
Assert.Ignore("Not on a standard domain for cookies (localhost doesn't count).");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Bart", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName + ".com", EnvironmentManager.Instance.UrlBuilder.Path, null);
Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<WebDriverException>().Or.InstanceOf<InvalidOperationException>());
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned");
}
[Test]
public void ShouldNotShowCookieAddedToDifferentPath()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null);
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies, Does.Not.Contain(cookie), "Invalid cookie was returned");
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Driver throws generic WebDriverException")]
public void ShouldThrowExceptionWhenAddingCookieToNonExistingDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
driver.Url = "http://nonexistent-origin.seleniumhq-test.test";
IOptions options = driver.Manage();
Cookie cookie = new Cookie("question", "dunno");
Assert.That(() => options.Cookies.AddCookie(cookie), Throws.InstanceOf<InvalidCookieDomainException>().Or.InstanceOf<InvalidOperationException>());
}
[Test]
public void ShouldReturnNullBecauseCookieRetainsExpiry()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
Cookie addCookie = new Cookie("fish", "cod", "/common/animals", DateTime.Now.AddHours(-1));
IOptions options = driver.Manage();
options.Cookies.AddCookie(addCookie);
Cookie retrieved = options.Cookies.GetCookieNamed("fish");
Assert.That(retrieved, Is.Null);
}
[Test]
public void ShouldAddCookieToCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Marge", "Simpson", "/");
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies.Contains(cookie), "Valid cookie was not returned");
}
[Test]
public void ShouldDeleteCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookieToDelete = new Cookie("answer", "42");
Cookie cookieToKeep = new Cookie("canIHaz", "Cheeseburguer");
options.Cookies.AddCookie(cookieToDelete);
options.Cookies.AddCookie(cookieToKeep);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
options.Cookies.DeleteCookie(cookieToDelete);
ReadOnlyCollection<Cookie> cookies2 = options.Cookies.AllCookies;
Assert.That(cookies2, Does.Not.Contain(cookieToDelete), "Cookie was not deleted successfully");
Assert.That(cookies2.Contains(cookieToKeep), "Valid cookie was not returned");
}
//////////////////////////////////////////////
// Support functions
//////////////////////////////////////////////
private void GotoValidDomainAndClearCookies(string page)
{
this.hostname = null;
String hostname = EnvironmentManager.Instance.UrlBuilder.HostName;
if (IsValidHostNameForCookieTests(hostname))
{
this.isOnAlternativeHostName = false;
this.hostname = hostname;
}
hostname = EnvironmentManager.Instance.UrlBuilder.AlternateHostName;
if (this.hostname == null && IsValidHostNameForCookieTests(hostname))
{
this.isOnAlternativeHostName = true;
this.hostname = hostname;
}
GoToPage(page);
driver.Manage().Cookies.DeleteAllCookies();
}
private bool CheckIsOnValidHostNameForCookieTests()
{
bool correct = this.hostname != null && IsValidHostNameForCookieTests(this.hostname);
if (!correct)
{
System.Console.WriteLine("Skipping test: unable to find domain name to use");
}
return correct;
}
private void GoToPage(String pageName)
{
driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName);
}
private void GoToOtherPage(String pageName)
{
driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName);
}
private bool IsValidHostNameForCookieTests(string hostname)
{
// TODO(JimEvan): Some coverage is better than none, so we
// need to ignore the fact that localhost cookies are problematic.
// Reenable this when we have a better solution per DanielWagnerHall.
// ChromeDriver2 has trouble with localhost. IE and Firefox don't.
// return !IsIpv4Address(hostname) && "localhost" != hostname;
bool isLocalHostOkay = true;
if ("localhost" == hostname && TestUtilities.IsChrome(driver))
{
isLocalHostOkay = false;
}
return !IsIpv4Address(hostname) && isLocalHostOkay;
}
private static bool IsIpv4Address(string addrString)
{
return Regex.IsMatch(addrString, "\\d{1,3}(?:\\.\\d{1,3}){3}");
}
private string GenerateUniqueKey()
{
return string.Format("key_{0}", random.Next());
}
private string GetDocumentCookieOrNull()
{
IJavaScriptExecutor jsDriver = driver as IJavaScriptExecutor;
if (jsDriver == null)
{
return null;
}
try
{
return (string)jsDriver.ExecuteScript("return document.cookie");
}
catch (InvalidOperationException)
{
return null;
}
}
private void AssertNoCookiesArePresent()
{
Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.EqualTo(0), "Cookies were not empty");
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.AreEqual(string.Empty, documentCookie, "Cookies were not empty");
}
}
private void AssertSomeCookiesArePresent()
{
Assert.That(driver.Manage().Cookies.AllCookies.Count, Is.Not.EqualTo(0), "Cookies were empty");
String documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.AreNotEqual(string.Empty, documentCookie, "Cookies were empty");
}
}
private void AssertCookieIsNotPresentWithName(string key)
{
Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Null, "Cookie was present with name " + key);
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.That(documentCookie, Does.Not.Contain(key + "="));
}
}
private void AssertCookieIsPresentWithName(string key)
{
Assert.That(driver.Manage().Cookies.GetCookieNamed(key), Is.Not.Null, "Cookie was present with name " + key);
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.That(documentCookie, Does.Contain(key + "="));
}
}
private void AssertCookieHasValue(string key, string value)
{
Assert.AreEqual(value, driver.Manage().Cookies.GetCookieNamed(key).Value, "Cookie had wrong value");
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.That(documentCookie, Does.Contain(key + "=" + value));
}
}
private DateTime GetTimeInTheFuture()
{
return DateTime.Now.Add(TimeSpan.FromMilliseconds(100000));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
#if CLR2COMPATIBILITY
using Microsoft.Build.Shared.Concurrent;
#else
using System.Collections.Concurrent;
#endif
using System.IO;
using System.IO.Pipes;
using System.Threading;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
#if FEATURE_SECURITY_PERMISSIONS || FEATURE_PIPE_SECURITY
using System.Security.AccessControl;
#endif
#if FEATURE_PIPE_SECURITY && FEATURE_NAMED_PIPE_SECURITY_CONSTRUCTOR
using System.Security.Principal;
#endif
#if !FEATURE_APM
using System.Threading.Tasks;
#endif
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// This is an implementation of INodeEndpoint for the out-of-proc nodes. It acts only as a client.
/// </summary>
internal abstract class NodeEndpointOutOfProcBase : INodeEndpoint
{
#region Private Data
#if NETCOREAPP2_1_OR_GREATER || MONO
/// <summary>
/// The amount of time to wait for the client to connect to the host.
/// </summary>
private const int ClientConnectTimeout = 60000;
#endif // NETCOREAPP2_1 || MONO
/// <summary>
/// The size of the buffers to use for named pipes
/// </summary>
private const int PipeBufferSize = 131072;
/// <summary>
/// The current communication status of the node.
/// </summary>
private LinkStatus _status;
/// <summary>
/// The pipe client used by the nodes.
/// </summary>
private NamedPipeServerStream _pipeServer;
// The following private data fields are used only when the endpoint is in ASYNCHRONOUS mode.
/// <summary>
/// Object used as a lock source for the async data
/// </summary>
private object _asyncDataMonitor;
/// <summary>
/// Set when a packet is available in the packet queue
/// </summary>
private AutoResetEvent _packetAvailable;
/// <summary>
/// Set when the asynchronous packet pump should terminate
/// </summary>
private AutoResetEvent _terminatePacketPump;
/// <summary>
/// The thread which runs the asynchronous packet pump
/// </summary>
private Thread _packetPump;
/// <summary>
/// The factory used to create and route packets.
/// </summary>
private INodePacketFactory _packetFactory;
/// <summary>
/// The asynchronous packet queue.
/// </summary>
/// <remarks>
/// Operations on this queue must be synchronized since it is accessible by multiple threads.
/// Use a lock on the packetQueue itself.
/// </remarks>
private ConcurrentQueue<INodePacket> _packetQueue;
/// <summary>
/// Per-node shared read buffer.
/// </summary>
private SharedReadBuffer _sharedReadBuffer;
/// <summary>
/// A way to cache a byte array when writing out packets
/// </summary>
private MemoryStream _packetStream;
/// <summary>
/// A binary writer to help write into <see cref="_packetStream"/>
/// </summary>
private BinaryWriter _binaryWriter;
#endregion
#region INodeEndpoint Events
/// <summary>
/// Raised when the link status has changed.
/// </summary>
public event LinkStatusChangedDelegate OnLinkStatusChanged;
#endregion
#region INodeEndpoint Properties
/// <summary>
/// Returns the link status of this node.
/// </summary>
public LinkStatus LinkStatus
{
get { return _status; }
}
#endregion
#region Properties
#endregion
#region INodeEndpoint Methods
/// <summary>
/// Causes this endpoint to wait for the remote endpoint to connect
/// </summary>
/// <param name="factory">The factory used to create packets.</param>
public void Listen(INodePacketFactory factory)
{
ErrorUtilities.VerifyThrow(_status == LinkStatus.Inactive, "Link not inactive. Status is {0}", _status);
ErrorUtilities.VerifyThrowArgumentNull(factory, nameof(factory));
_packetFactory = factory;
InitializeAsyncPacketThread();
}
/// <summary>
/// Causes this node to connect to the matched endpoint.
/// </summary>
/// <param name="factory">The factory used to create packets.</param>
public void Connect(INodePacketFactory factory)
{
ErrorUtilities.ThrowInternalError("Connect() not valid on the out of proc endpoint.");
}
/// <summary>
/// Shuts down the link
/// </summary>
public void Disconnect()
{
InternalDisconnect();
}
/// <summary>
/// Sends data to the peer endpoint.
/// </summary>
/// <param name="packet">The packet to send.</param>
public void SendData(INodePacket packet)
{
// PERF: Set up a priority system so logging packets are sent only when all other packet types have been sent.
if (_status == LinkStatus.Active)
{
EnqueuePacket(packet);
}
}
#endregion
#region Construction
/// <summary>
/// Instantiates an endpoint to act as a client
/// </summary>
/// <param name="pipeName">The name of the pipe to which we should connect.</param>
internal void InternalConstruct(string pipeName)
{
ErrorUtilities.VerifyThrowArgumentLength(pipeName, nameof(pipeName));
_status = LinkStatus.Inactive;
_asyncDataMonitor = new object();
_sharedReadBuffer = InterningBinaryReader.CreateSharedBuffer();
_packetStream = new MemoryStream();
_binaryWriter = new BinaryWriter(_packetStream);
#if FEATURE_PIPE_SECURITY && FEATURE_NAMED_PIPE_SECURITY_CONSTRUCTOR
if (!NativeMethodsShared.IsMono)
{
SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
PipeSecurity security = new PipeSecurity();
// Restrict access to just this account. We set the owner specifically here, and on the
// pipe client side they will check the owner against this one - they must have identical
// SIDs or the client will reject this server. This is used to avoid attacks where a
// hacked server creates a less restricted pipe in an attempt to lure us into using it and
// then sending build requests to the real pipe client (which is the MSBuild Build Manager.)
PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite, AccessControlType.Allow);
security.AddAccessRule(rule);
security.SetOwner(identifier);
_pipeServer = new NamedPipeServerStream
(
pipeName,
PipeDirection.InOut,
1, // Only allow one connection at a time.
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.WriteThrough,
PipeBufferSize, // Default input buffer
PipeBufferSize, // Default output buffer
security,
HandleInheritability.None
);
}
else
#endif
{
_pipeServer = new NamedPipeServerStream
(
pipeName,
PipeDirection.InOut,
1, // Only allow one connection at a time.
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.WriteThrough,
PipeBufferSize, // Default input buffer
PipeBufferSize // Default output buffer
);
}
}
#endregion
/// <summary>
/// Returns the host handshake for this node endpoint
/// </summary>
protected abstract Handshake GetHandshake();
/// <summary>
/// Updates the current link status if it has changed and notifies any registered delegates.
/// </summary>
/// <param name="newStatus">The status the node should now be in.</param>
protected void ChangeLinkStatus(LinkStatus newStatus)
{
ErrorUtilities.VerifyThrow(_status != newStatus, "Attempting to change status to existing status {0}.", _status);
CommunicationsUtilities.Trace("Changing link status from {0} to {1}", _status.ToString(), newStatus.ToString());
_status = newStatus;
RaiseLinkStatusChanged(_status);
}
/// <summary>
/// Invokes the OnLinkStatusChanged event in a thread-safe manner.
/// </summary>
/// <param name="newStatus">The new status of the endpoint link.</param>
private void RaiseLinkStatusChanged(LinkStatus newStatus)
{
OnLinkStatusChanged?.Invoke(this, newStatus);
}
#region Private Methods
/// <summary>
/// This does the actual work of changing the status and shutting down any threads we may have for
/// disconnection.
/// </summary>
private void InternalDisconnect()
{
ErrorUtilities.VerifyThrow(_packetPump.ManagedThreadId != Thread.CurrentThread.ManagedThreadId, "Can't join on the same thread.");
_terminatePacketPump.Set();
_packetPump.Join();
#if CLR2COMPATIBILITY
_terminatePacketPump.Close();
#else
_terminatePacketPump.Dispose();
#endif
_pipeServer.Dispose();
_packetPump = null;
ChangeLinkStatus(LinkStatus.Inactive);
}
#region Asynchronous Mode Methods
/// <summary>
/// Adds a packet to the packet queue when asynchronous mode is enabled.
/// </summary>
/// <param name="packet">The packet to be transmitted.</param>
private void EnqueuePacket(INodePacket packet)
{
ErrorUtilities.VerifyThrowArgumentNull(packet, nameof(packet));
ErrorUtilities.VerifyThrow(_packetQueue != null, "packetQueue is null");
ErrorUtilities.VerifyThrow(_packetAvailable != null, "packetAvailable is null");
_packetQueue.Enqueue(packet);
_packetAvailable.Set();
}
/// <summary>
/// Initializes the packet pump thread and the supporting events as well as the packet queue.
/// </summary>
private void InitializeAsyncPacketThread()
{
lock (_asyncDataMonitor)
{
_packetPump = new Thread(PacketPumpProc);
_packetPump.IsBackground = true;
_packetPump.Name = "OutOfProc Endpoint Packet Pump";
_packetAvailable = new AutoResetEvent(false);
_terminatePacketPump = new AutoResetEvent(false);
_packetQueue = new ConcurrentQueue<INodePacket>();
_packetPump.Start();
}
}
/// <summary>
/// This method handles the asynchronous message pump. It waits for messages to show up on the queue
/// and calls FireDataAvailable for each such packet. It will terminate when the terminate event is
/// set.
/// </summary>
private void PacketPumpProc()
{
NamedPipeServerStream localPipeServer = _pipeServer;
AutoResetEvent localPacketAvailable = _packetAvailable;
AutoResetEvent localTerminatePacketPump = _terminatePacketPump;
ConcurrentQueue<INodePacket> localPacketQueue = _packetQueue;
DateTime originalWaitStartTime = DateTime.UtcNow;
bool gotValidConnection = false;
while (!gotValidConnection)
{
gotValidConnection = true;
DateTime restartWaitTime = DateTime.UtcNow;
// We only wait to wait the difference between now and the last original start time, in case we have multiple hosts attempting
// to attach. This prevents each attempt from resetting the timer.
TimeSpan usedWaitTime = restartWaitTime - originalWaitStartTime;
int waitTimeRemaining = Math.Max(0, CommunicationsUtilities.NodeConnectionTimeout - (int)usedWaitTime.TotalMilliseconds);
try
{
// Wait for a connection
#if FEATURE_APM
IAsyncResult resultForConnection = localPipeServer.BeginWaitForConnection(null, null);
CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);
bool connected = resultForConnection.AsyncWaitHandle.WaitOne(waitTimeRemaining, false);
#else
Task connectionTask = localPipeServer.WaitForConnectionAsync();
CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining);
bool connected = connectionTask.Wait(waitTimeRemaining);
#endif
if (!connected)
{
CommunicationsUtilities.Trace("Connection timed out waiting a host to contact us. Exiting comm thread.");
ChangeLinkStatus(LinkStatus.ConnectionFailed);
return;
}
CommunicationsUtilities.Trace("Parent started connecting. Reading handshake from parent");
#if FEATURE_APM
localPipeServer.EndWaitForConnection(resultForConnection);
#endif
// The handshake protocol is a series of int exchanges. The host sends us a each component, and we
// verify it. Afterwards, the host sends an "End of Handshake" signal, to which we respond in kind.
// Once the handshake is complete, both sides can be assured the other is ready to accept data.
Handshake handshake = GetHandshake();
try
{
int[] handshakeComponents = handshake.RetrieveHandshakeComponents();
for (int i = 0; i < handshakeComponents.Length; i++)
{
int handshakePart = _pipeServer.ReadIntForHandshake(i == 0 ? (byte?)CommunicationsUtilities.handshakeVersion : null /* this will disconnect a < 16.8 host; it expects leading 00 or F5 or 06. 0x00 is a wildcard */
#if NETCOREAPP2_1_OR_GREATER || MONO
, ClientConnectTimeout /* wait a long time for the handshake from this side */
#endif
);
if (handshakePart != handshakeComponents[i])
{
CommunicationsUtilities.Trace("Handshake failed. Received {0} from host not {1}. Probably the host is a different MSBuild build.", handshakePart, handshakeComponents[i]);
_pipeServer.WriteIntForHandshake(i + 1);
gotValidConnection = false;
break;
}
}
if (gotValidConnection)
{
// To ensure that our handshake and theirs have the same number of bytes, receive and send a magic number indicating EOS.
#if NETCOREAPP2_1_OR_GREATER || MONO
_pipeServer.ReadEndOfHandshakeSignal(false, ClientConnectTimeout); /* wait a long time for the handshake from this side */
#else
_pipeServer.ReadEndOfHandshakeSignal(false);
#endif
CommunicationsUtilities.Trace("Successfully connected to parent.");
_pipeServer.WriteEndOfHandshakeSignal();
#if FEATURE_SECURITY_PERMISSIONS
// We will only talk to a host that was started by the same user as us. Even though the pipe access is set to only allow this user, we want to ensure they
// haven't attempted to change those permissions out from under us. This ensures that the only way they can truly gain access is to be impersonating the
// user we were started by.
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsIdentity clientIdentity = null;
localPipeServer.RunAsClient(delegate () { clientIdentity = WindowsIdentity.GetCurrent(true); });
if (clientIdentity == null || !String.Equals(clientIdentity.Name, currentIdentity.Name, StringComparison.OrdinalIgnoreCase))
{
CommunicationsUtilities.Trace("Handshake failed. Host user is {0} but we were created by {1}.", (clientIdentity == null) ? "<unknown>" : clientIdentity.Name, currentIdentity.Name);
gotValidConnection = false;
continue;
}
#endif
}
}
catch (IOException e)
{
// We will get here when:
// 1. The host (OOP main node) connects to us, it immediately checks for user privileges
// and if they don't match it disconnects immediately leaving us still trying to read the blank handshake
// 2. The host is too old sending us bits we automatically reject in the handshake
// 3. We expected to read the EndOfHandshake signal, but we received something else
CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message);
gotValidConnection = false;
}
catch (InvalidOperationException)
{
gotValidConnection = false;
}
if (!gotValidConnection)
{
if (localPipeServer.IsConnected)
{
localPipeServer.Disconnect();
}
continue;
}
ChangeLinkStatus(LinkStatus.Active);
}
catch (Exception e)
{
if (ExceptionHandling.IsCriticalException(e))
{
throw;
}
CommunicationsUtilities.Trace("Client connection failed. Exiting comm thread. {0}", e);
if (localPipeServer.IsConnected)
{
localPipeServer.Disconnect();
}
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
return;
}
}
RunReadLoop(
new BufferedReadStream(_pipeServer),
_pipeServer,
localPacketQueue, localPacketAvailable, localTerminatePacketPump);
CommunicationsUtilities.Trace("Ending read loop");
try
{
if (localPipeServer.IsConnected)
{
#if NETCOREAPP // OperatingSystem.IsWindows() is new in .NET 5.0
if (OperatingSystem.IsWindows())
#endif
{
localPipeServer.WaitForPipeDrain();
}
localPipeServer.Disconnect();
}
}
catch (Exception)
{
// We don't really care if Disconnect somehow fails, but it gives us a chance to do the right thing.
}
}
private void RunReadLoop(Stream localReadPipe, Stream localWritePipe,
ConcurrentQueue<INodePacket> localPacketQueue, AutoResetEvent localPacketAvailable, AutoResetEvent localTerminatePacketPump)
{
// Ordering of the wait handles is important. The first signalled wait handle in the array
// will be returned by WaitAny if multiple wait handles are signalled. We prefer to have the
// terminate event triggered so that we cannot get into a situation where packets are being
// spammed to the endpoint and it never gets an opportunity to shutdown.
CommunicationsUtilities.Trace("Entering read loop.");
byte[] headerByte = new byte[5];
#if FEATURE_APM
IAsyncResult result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null);
#else
Task<int> readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length);
#endif
bool exitLoop = false;
do
{
// Ordering is important. We want packetAvailable to supercede terminate otherwise we will not properly wait for all
// packets to be sent by other threads which are shutting down, such as the logging thread.
WaitHandle[] handles = new WaitHandle[] {
#if FEATURE_APM
result.AsyncWaitHandle,
#else
((IAsyncResult)readTask).AsyncWaitHandle,
#endif
localPacketAvailable, localTerminatePacketPump };
int waitId = WaitHandle.WaitAny(handles);
switch (waitId)
{
case 0:
{
int bytesRead = 0;
try
{
#if FEATURE_APM
bytesRead = localReadPipe.EndRead(result);
#else
bytesRead = readTask.Result;
#endif
}
catch (Exception e)
{
// Lost communications. Abort (but allow node reuse)
CommunicationsUtilities.Trace("Exception reading from server. {0}", e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Inactive);
exitLoop = true;
break;
}
if (bytesRead != headerByte.Length)
{
// Incomplete read. Abort.
if (bytesRead == 0)
{
CommunicationsUtilities.Trace("Parent disconnected abruptly");
}
else
{
CommunicationsUtilities.Trace("Incomplete header read from server. {0} of {1} bytes read", bytesRead, headerByte.Length);
}
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
NodePacketType packetType = (NodePacketType)Enum.ToObject(typeof(NodePacketType), headerByte[0]);
try
{
_packetFactory.DeserializeAndRoutePacket(0, packetType, BinaryTranslator.GetReadTranslator(localReadPipe, _sharedReadBuffer));
}
catch (Exception e)
{
// Error while deserializing or handling packet. Abort.
CommunicationsUtilities.Trace("Exception while deserializing packet {0}: {1}", packetType, e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
#if FEATURE_APM
result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null);
#else
readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length);
#endif
}
break;
case 1:
case 2:
try
{
// Write out all the queued packets.
INodePacket packet;
while (localPacketQueue.TryDequeue(out packet))
{
var packetStream = _packetStream;
packetStream.SetLength(0);
ITranslator writeTranslator = BinaryTranslator.GetWriteTranslator(packetStream);
packetStream.WriteByte((byte)packet.Type);
// Pad for packet length
_binaryWriter.Write(0);
// Reset the position in the write buffer.
packet.Translate(writeTranslator);
int packetStreamLength = (int)packetStream.Position;
// Now write in the actual packet length
packetStream.Position = 1;
_binaryWriter.Write(packetStreamLength - 5);
localWritePipe.Write(packetStream.GetBuffer(), 0, packetStreamLength);
}
}
catch (Exception e)
{
// Error while deserializing or handling packet. Abort.
CommunicationsUtilities.Trace("Exception while serializing packets: {0}", e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
if (waitId == 2)
{
CommunicationsUtilities.Trace("Disconnecting voluntarily");
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
}
break;
default:
ErrorUtilities.ThrowInternalError("waitId {0} out of range.", waitId);
break;
}
}
while (!exitLoop);
}
#endregion
#endregion
}
}
| |
// 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.ComponentModel.MaskedTextProvider.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.ComponentModel
{
public partial class MaskedTextProvider : ICloneable
{
#region Methods and constructors
public bool Add(char input)
{
return default(bool);
}
public bool Add(char input, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-54)) <= Contract.ValueAtReturn(out resultHint));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool Add(string input)
{
return default(bool);
}
public bool Add(string input, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-54)) <= Contract.ValueAtReturn(out resultHint));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public void Clear()
{
}
public void Clear(out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(2)) <= Contract.ValueAtReturn(out resultHint));
Contract.Ensures(Contract.ValueAtReturn(out resultHint) <= ((System.ComponentModel.MaskedTextResultHint)(4)));
resultHint = default(MaskedTextResultHint);
}
public Object Clone()
{
return default(Object);
}
public int FindAssignedEditPositionFrom(int position, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public int FindAssignedEditPositionInRange(int startPosition, int endPosition, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public int FindEditPositionFrom(int position, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public int FindEditPositionInRange(int startPosition, int endPosition, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public int FindNonEditPositionFrom(int position, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public int FindNonEditPositionInRange(int startPosition, int endPosition, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public int FindUnassignedEditPositionFrom(int position, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public int FindUnassignedEditPositionInRange(int startPosition, int endPosition, bool direction)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public static bool GetOperationResultFromHint(MaskedTextResultHint hint)
{
Contract.Ensures(Contract.Result<bool>() == (hint > ((System.ComponentModel.MaskedTextResultHint)(0))));
return default(bool);
}
public bool InsertAt(string input, int position, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-55)) <= Contract.ValueAtReturn(out resultHint));
Contract.Ensures(Contract.ValueAtReturn(out resultHint) <= ((System.ComponentModel.MaskedTextResultHint)(4)));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool InsertAt(char input, int position)
{
return default(bool);
}
public bool InsertAt(string input, int position)
{
return default(bool);
}
public bool InsertAt(char input, int position, out int testPosition, out MaskedTextResultHint resultHint)
{
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool IsAvailablePosition(int position)
{
return default(bool);
}
public bool IsEditPosition(int position)
{
return default(bool);
}
public static bool IsValidInputChar(char c)
{
return default(bool);
}
public static bool IsValidMaskChar(char c)
{
return default(bool);
}
public static bool IsValidPasswordChar(char c)
{
return default(bool);
}
public MaskedTextProvider(string mask, System.Globalization.CultureInfo culture, bool restrictToAscii)
{
Contract.Requires(mask != null);
}
public MaskedTextProvider(string mask, System.Globalization.CultureInfo culture)
{
Contract.Requires(mask != null);
}
public MaskedTextProvider(string mask, char passwordChar, bool allowPromptAsInput)
{
Contract.Requires(mask != null);
}
public MaskedTextProvider(string mask, System.Globalization.CultureInfo culture, bool allowPromptAsInput, char promptChar, char passwordChar, bool restrictToAscii)
{
Contract.Requires(mask != null);
}
public MaskedTextProvider(string mask)
{
Contract.Requires(mask != null);
}
public MaskedTextProvider(string mask, System.Globalization.CultureInfo culture, char passwordChar, bool allowPromptAsInput)
{
Contract.Requires(mask != null);
}
public MaskedTextProvider(string mask, bool restrictToAscii)
{
Contract.Requires(mask != null);
}
public bool Remove(out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(2)) <= Contract.ValueAtReturn(out resultHint));
Contract.Ensures(0 <= Contract.ValueAtReturn(out testPosition));
Contract.Ensures(Contract.Result<bool>() == true);
Contract.Ensures(Contract.ValueAtReturn(out resultHint) <= ((System.ComponentModel.MaskedTextResultHint)(4)));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool Remove()
{
Contract.Ensures(Contract.Result<bool>() == true);
return default(bool);
}
public bool RemoveAt(int startPosition, int endPosition, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-55)) <= Contract.ValueAtReturn(out resultHint));
Contract.Ensures(Contract.ValueAtReturn(out resultHint) <= ((System.ComponentModel.MaskedTextResultHint)(4)));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool RemoveAt(int startPosition, int endPosition)
{
return default(bool);
}
public bool RemoveAt(int position)
{
return default(bool);
}
public bool Replace(char input, int startPosition, int endPosition, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-55)) <= Contract.ValueAtReturn(out resultHint));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool Replace(char input, int position, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-55)) <= Contract.ValueAtReturn(out resultHint));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool Replace(char input, int position)
{
return default(bool);
}
public bool Replace(string input, int startPosition, int endPosition, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-55)) <= Contract.ValueAtReturn(out resultHint));
Contract.Ensures(Contract.ValueAtReturn(out resultHint) <= ((System.ComponentModel.MaskedTextResultHint)(4)));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool Replace(string input, int position, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-55)) <= Contract.ValueAtReturn(out resultHint));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool Replace(string input, int position)
{
return default(bool);
}
public bool Set(string input, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-54)) <= Contract.ValueAtReturn(out resultHint));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool Set(string input)
{
return default(bool);
}
public string ToDisplayString()
{
return default(string);
}
public string ToString(bool ignorePasswordChar)
{
return default(string);
}
public override string ToString()
{
return default(string);
}
public string ToString(bool ignorePasswordChar, bool includePrompt, bool includeLiterals, int startPosition, int length)
{
return default(string);
}
public string ToString(int startPosition, int length)
{
return default(string);
}
public string ToString(bool includePrompt, bool includeLiterals, int startPosition, int length)
{
return default(string);
}
public string ToString(bool ignorePasswordChar, int startPosition, int length)
{
return default(string);
}
public string ToString(bool includePrompt, bool includeLiterals)
{
return default(string);
}
public bool VerifyChar(char input, int position, out MaskedTextResultHint hint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-55)) <= Contract.ValueAtReturn(out hint));
Contract.Ensures(Contract.ValueAtReturn(out hint) <= ((System.ComponentModel.MaskedTextResultHint)(4)));
hint = default(MaskedTextResultHint);
return default(bool);
}
public bool VerifyEscapeChar(char input, int position)
{
return default(bool);
}
public bool VerifyString(string input, out int testPosition, out MaskedTextResultHint resultHint)
{
Contract.Ensures(((System.ComponentModel.MaskedTextResultHint)(-54)) <= Contract.ValueAtReturn(out resultHint));
Contract.Ensures(Contract.ValueAtReturn(out resultHint) <= ((System.ComponentModel.MaskedTextResultHint)(4)));
testPosition = default(int);
resultHint = default(MaskedTextResultHint);
return default(bool);
}
public bool VerifyString(string input)
{
return default(bool);
}
#endregion
#region Properties and indexers
public bool AllowPromptAsInput
{
get
{
return default(bool);
}
}
public bool AsciiOnly
{
get
{
return default(bool);
}
}
public int AssignedEditPositionCount
{
get
{
return default(int);
}
}
public int AvailableEditPositionCount
{
get
{
return default(int);
}
}
public System.Globalization.CultureInfo Culture
{
get
{
return default(System.Globalization.CultureInfo);
}
}
public static char DefaultPasswordChar
{
get
{
Contract.Ensures(Contract.Result<char>() == 42);
return default(char);
}
}
public int EditPositionCount
{
get
{
return default(int);
}
}
public System.Collections.IEnumerator EditPositions
{
get
{
return default(System.Collections.IEnumerator);
}
}
public bool IncludeLiterals
{
get
{
return default(bool);
}
set
{
}
}
public bool IncludePrompt
{
get
{
return default(bool);
}
set
{
}
}
public static int InvalidIndex
{
get
{
Contract.Ensures(Contract.Result<int>() == -(1));
Contract.Ensures(Contract.Result<int>() == -1);
return default(int);
}
}
public bool IsPassword
{
get
{
return default(bool);
}
set
{
}
}
public char this [int index]
{
get
{
return default(char);
}
}
public int LastAssignedPosition
{
get
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
}
public int Length
{
get
{
return default(int);
}
}
public string Mask
{
get
{
return default(string);
}
}
public bool MaskCompleted
{
get
{
return default(bool);
}
}
public bool MaskFull
{
get
{
return default(bool);
}
}
public char PasswordChar
{
get
{
return default(char);
}
set
{
}
}
public char PromptChar
{
get
{
return default(char);
}
set
{
}
}
public bool ResetOnPrompt
{
get
{
return default(bool);
}
set
{
}
}
public bool ResetOnSpace
{
get
{
return default(bool);
}
set
{
}
}
public bool SkipLiterals
{
get
{
return default(bool);
}
set
{
}
}
#endregion
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.DirectoryServices;
using WebsitePanel.Setup.Web;
using System.IO;
using System.Management;
using WebsitePanel.Setup.Actions;
using Microsoft.Win32;
namespace WebsitePanel.Setup
{
public partial class ConfigurationCheckPage : BannerWizardPage
{
public const string AspNet40HasBeenInstalledMessage = "ASP.NET 4.0 has been installed.";
private Thread thread;
private List<ConfigurationCheck> checks;
public ConfigurationCheckPage()
{
InitializeComponent();
checks = new List<ConfigurationCheck>();
this.CustomCancelHandler = true;
}
public List<ConfigurationCheck> Checks
{
get
{
return checks;
}
}
protected override void InitializePageInternal()
{
base.InitializePageInternal();
this.Text = "System Configuration Check";
this.Description = "Wait while the system is checked for potential installation problems.";
this.imgError.Visible = false;
this.imgOk.Visible = false;
this.lblResult.Visible = false;
}
protected internal override void OnBeforeDisplay(EventArgs e)
{
base.OnBeforeDisplay(e);
this.AllowMoveBack = false;
this.AllowMoveNext = false;
}
protected internal override void OnAfterDisplay(EventArgs e)
{
base.OnAfterDisplay(e);
thread = new Thread(new ThreadStart(this.Start));
thread.Start();
}
/// <summary>
/// Displays process progress.
/// </summary>
public void Start()
{
bool pass = true;
try
{
lvCheck.Items.Clear();
this.imgError.Visible = false;
this.imgOk.Visible = false;
this.lblResult.Visible = false;
foreach (ConfigurationCheck check in Checks)
{
AddListViewItem(check);
}
this.Update();
CheckStatuses status = CheckStatuses.Success;
string details = string.Empty;
//
foreach (ListViewItem item in lvCheck.Items)
{
ConfigurationCheck check = (ConfigurationCheck)item.Tag;
item.ImageIndex = 0;
item.SubItems[2].Text = "Running";
this.Update();
#region Previous Prereq Verification
switch (check.CheckType)
{
case CheckTypes.OperationSystem:
status = CheckOS(check.SetupVariables, out details);
break;
case CheckTypes.IISVersion:
status = CheckIISVersion(check.SetupVariables, out details);
break;
case CheckTypes.ASPNET:
status = CheckASPNET(check.SetupVariables, out details);
break;
case CheckTypes.WPServer:
status = CheckWPServer(check.SetupVariables, out details);
break;
case CheckTypes.WPEnterpriseServer:
status = CheckWPEnterpriseServer(check.SetupVariables, out details);
break;
case CheckTypes.WPPortal:
status = CheckWPPortal(check.SetupVariables, out details);
break;
default:
status = CheckStatuses.Warning;
break;
}
#endregion
switch (status)
{
case CheckStatuses.Success:
item.ImageIndex = 1;
item.SubItems[2].Text = "Success";
break;
case CheckStatuses.Warning:
item.ImageIndex = 2;
item.SubItems[2].Text = "Warning";
break;
case CheckStatuses.Error:
item.ImageIndex = 3;
item.SubItems[2].Text = "Error";
pass = false;
break;
}
item.SubItems[3].Text = details;
this.Update();
}
//
//actionManager.PrerequisiteComplete += new EventHandler<ActionProgressEventArgs<bool>>((object sender, ActionProgressEventArgs<bool> e) =>
//{
//
//});
//
//actionManager.VerifyDistributivePrerequisites();
ShowResult(pass);
if (pass)
{
//unattended setup
if (!string.IsNullOrEmpty(Wizard.SetupVariables.SetupXml) && AllowMoveNext)
Wizard.GoNext();
}
}
catch (Exception ex)
{
if (Utils.IsThreadAbortException(ex))
return;
ShowError();
return;
}
}
private void ShowResult(bool success)
{
this.AllowMoveNext = success;
this.imgError.Visible = !success;
this.imgOk.Visible = success;
this.lblResult.Text = success ? "Success" : "Error";
this.lblResult.Visible = true;
Update();
}
private void AddListViewItem(ConfigurationCheck check)
{
lvCheck.BeginUpdate();
ListViewItem item = new ListViewItem(string.Empty);
item.SubItems.AddRange(new string[] { check.Action, string.Empty, string.Empty });
item.Tag = check;
lvCheck.Items.Add(item);
lvCheck.EndUpdate();
Update();
}
internal static CheckStatuses CheckOS(SetupVariables setupVariables, out string details)
{
details = string.Empty;
try
{
//check OS version
OS.WindowsVersion version = OS.GetVersion();
details = OS.GetName(version);
if (Utils.IsWin64())
details += " x64";
Log.WriteInfo(string.Format("OS check: {0}", details));
if (!(version == OS.WindowsVersion.WindowsServer2003 ||
version == OS.WindowsVersion.WindowsServer2008 ||
version == OS.WindowsVersion.WindowsServer2008R2 ||
version == OS.WindowsVersion.WindowsServer2012 ||
version == OS.WindowsVersion.WindowsServer2012R2 ||
version == OS.WindowsVersion.WindowsVista ||
version == OS.WindowsVersion.Windows7 ||
version == OS.WindowsVersion.Windows8 ))
{
details = "OS required: Windows Server 2008/2008 R2/2012 or Windows Vista/7/8.";
Log.WriteError(string.Format("OS check: {0}", details), null);
#if DEBUG
return CheckStatuses.Warning;
#endif
#if !DEBUG
return CheckStatuses.Error;
#endif
}
return CheckStatuses.Success;
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Check error", ex);
details = "Unexpected error";
return CheckStatuses.Error;
}
}
internal static CheckStatuses CheckIISVersion(SetupVariables setupVariables, out string details)
{
details = string.Empty;
try
{
details = string.Format("IIS {0}", setupVariables.IISVersion.ToString(2));
if (setupVariables.IISVersion.Major == 6 &&
Utils.IsWin64() && Utils.IIS32Enabled())
{
details += " (32-bit mode)";
}
Log.WriteInfo(string.Format("IIS check: {0}", details));
if (setupVariables.IISVersion.Major < 6)
{
details = "IIS 6.0 or greater required.";
Log.WriteError(string.Format("IIS check: {0}", details), null);
return CheckStatuses.Error;
}
return CheckStatuses.Success;
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Check error", ex);
details = "Unexpected error";
return CheckStatuses.Error;
}
}
internal static CheckStatuses CheckASPNET(SetupVariables setupVariables, out string details)
{
details = "ASP.NET 4.0 is installed.";
CheckStatuses ret = CheckStatuses.Success;
try
{
// IIS 6
if (setupVariables.IISVersion.Major == 6)
{
//
if (Utils.CheckAspNet40Registered(setupVariables) == false)
{
// Register ASP.NET 4.0
Utils.RegisterAspNet40(setupVariables);
//
ret = CheckStatuses.Warning;
details = AspNet40HasBeenInstalledMessage;
}
// Enable ASP.NET 4.0 Web Server Extension if it is prohibited
if (Utils.GetAspNetWebExtensionStatus_Iis6(setupVariables) == WebExtensionStatus.Prohibited)
{
Utils.EnableAspNetWebExtension_Iis6();
}
}
// IIS 7 on Windows 2008 and higher
else
{
if (!IsWebServerRoleInstalled())
{
details = "Web Server (IIS) role is not installed on your server. Run Server Manager to add Web Server (IIS) role.";
Log.WriteInfo(string.Format("ASP.NET check: {0}", details));
return CheckStatuses.Error;
}
if (!IsAspNetRoleServiceInstalled())
{
details = "ASP.NET role service is not installed on your server. Run Server Manager to add ASP.NET role service.";
Log.WriteInfo(string.Format("ASP.NET check: {0}", details));
return CheckStatuses.Error;
}
// Register ASP.NET 4.0
if (Utils.CheckAspNet40Registered(setupVariables) == false)
{
// Register ASP.NET 4.0
Utils.RegisterAspNet40(setupVariables);
//
ret = CheckStatuses.Warning;
details = AspNet40HasBeenInstalledMessage;
}
}
// Log details
Log.WriteInfo(string.Format("ASP.NET check: {0}", details));
//
return ret;
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Check error", ex);
details = "Unexpected error";
#if DEBUG
return CheckStatuses.Warning;
#endif
#if !DEBUG
return CheckStatuses.Error;
#endif
}
}
internal static CheckStatuses CheckIIS32Mode(SetupVariables setupVariables, out string details)
{
details = string.Empty;
CheckStatuses ret = CheckIISVersion(setupVariables, out details);
if (ret == CheckStatuses.Error)
return ret;
try
{
//IIS 6
if (setupVariables.IISVersion.Major == 6)
{
//x64
if (Utils.IsWin64())
{
if (!Utils.IIS32Enabled())
{
Log.WriteInfo("IIS 32-bit mode disabled");
EnableIIS32Mode();
details = "IIS 32-bit mode has been enabled.";
Log.WriteInfo(string.Format("IIS 32-bit mode check: {0}", details));
return CheckStatuses.Warning;
}
}
}
return CheckStatuses.Success;
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Check error", ex);
details = "Unexpected error";
return CheckStatuses.Error;
}
}
private bool SiteBindingsExist(SetupVariables setupVariables)
{
bool iis7 = (setupVariables.IISVersion.Major >= 7);
string ip = setupVariables.WebSiteIP;
string port = setupVariables.WebSitePort;
string domain = setupVariables.WebSiteDomain;
string siteId = iis7 ?
WebUtils.GetIIS7SiteIdByBinding(ip, port, domain) :
WebUtils.GetSiteIdByBinding(ip, port, domain);
return (siteId != null);
}
private bool AccountExists(SetupVariables setupVariables)
{
string domain = setupVariables.UserDomain;
string username = setupVariables.UserAccount;
return SecurityUtils.UserExists(domain, username);
}
private CheckStatuses CheckWPServer(SetupVariables setupVariables, out string details)
{
details = "";
try
{
if (SiteBindingsExist(setupVariables))
{
details = string.Format("Site with specified bindings already exists (ip: {0}, port: {1}, domain: {2})",
setupVariables.WebSiteIP, setupVariables.WebSitePort, setupVariables.WebSiteDomain);
Log.WriteError(string.Format("Site bindings check: {0}", details), null);
return CheckStatuses.Error;
}
if (AccountExists(setupVariables))
{
details = string.Format("Windows account already exists: {0}\\{1}",
setupVariables.UserDomain, setupVariables.UserAccount);
Log.WriteError(string.Format("Account check: {0}", details), null);
return CheckStatuses.Error;
}
if (!CheckDiskSpace(setupVariables, out details))
{
Log.WriteError(string.Format("Disk space check: {0}", details), null);
return CheckStatuses.Error;
}
return CheckStatuses.Success;
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Check error", ex);
details = "Unexpected error";
return CheckStatuses.Error;
}
}
private bool CheckDiskSpace(SetupVariables setupVariables, out string details)
{
details = string.Empty;
long spaceRequired = FileUtils.CalculateFolderSize(setupVariables.InstallerFolder);
if (string.IsNullOrEmpty(setupVariables.InstallationFolder))
{
details = "Installation folder is not specified.";
return false;
}
string drive = null;
try
{
drive = Path.GetPathRoot(Path.GetFullPath(setupVariables.InstallationFolder));
}
catch
{
details = "Installation folder is invalid.";
return false;
}
ulong freeBytesAvailable, totalBytes, freeBytes;
if (FileUtils.GetDiskFreeSpaceEx(drive, out freeBytesAvailable, out totalBytes, out freeBytes))
{
long freeSpace = Convert.ToInt64(freeBytesAvailable);
if (spaceRequired > freeSpace)
{
details = string.Format("There is not enough space on the disk ({0} required, {1} available)",
FileUtils.SizeToMB(spaceRequired), FileUtils.SizeToMB(freeSpace));
return false;
}
}
else
{
details = "I/O error";
return false;
}
return true;
}
private CheckStatuses CheckWPEnterpriseServer(SetupVariables setupVariables, out string details)
{
details = "";
try
{
if (SiteBindingsExist(setupVariables))
{
details = string.Format("Site with specified bindings already exists (ip: {0}, port: {1}, domain: {2})",
setupVariables.WebSiteIP, setupVariables.WebSitePort, setupVariables.WebSiteDomain);
Log.WriteError(string.Format("Site bindings check: {0}", details), null);
return CheckStatuses.Error;
}
if (AccountExists(setupVariables))
{
details = string.Format("Windows account already exists: {0}\\{1}",
setupVariables.UserDomain, setupVariables.UserAccount);
Log.WriteError(string.Format("Account check: {0}", details), null);
return CheckStatuses.Error;
}
if (!CheckDiskSpace(setupVariables, out details))
{
Log.WriteError(string.Format("Disk space check: {0}", details), null);
return CheckStatuses.Error;
}
return CheckStatuses.Success;
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Check error", ex);
details = "Unexpected error";
return CheckStatuses.Error;
}
}
private CheckStatuses CheckWPPortal(SetupVariables setupVariables, out string details)
{
details = "";
try
{
if (AccountExists(setupVariables))
{
details = string.Format("Windows account already exists: {0}\\{1}",
setupVariables.UserDomain, setupVariables.UserAccount);
Log.WriteError(string.Format("Account check: {0}", details), null);
return CheckStatuses.Error;
}
if (!CheckDiskSpace(setupVariables, out details))
{
Log.WriteError(string.Format("Disk space check: {0}", details), null);
return CheckStatuses.Error;
}
return CheckStatuses.Success;
}
catch (Exception ex)
{
if (!Utils.IsThreadAbortException(ex))
Log.WriteError("Check error", ex);
details = "Unexpected error";
return CheckStatuses.Error;
}
}
private static void EnableIIS32Mode()
{
Log.WriteStart("Enabling IIS 32-bit mode");
using (DirectoryEntry iisService = new DirectoryEntry("IIS://LocalHost/W3SVC/AppPools"))
{
Utils.SetObjectProperty(iisService, "Enable32bitAppOnWin64", true);
iisService.CommitChanges();
}
Log.WriteEnd("Enabled IIS 32-bit mode");
}
private static void InstallASPNET()
{
Log.WriteStart("Starting aspnet_regiis -i");
string util = (Utils.IsWin64() && !Utils.IIS32Enabled()) ?
@"Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe" :
@"Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe";
string path = Path.Combine(OS.GetWindowsDirectory(), util);
ProcessStartInfo info = new ProcessStartInfo(path, "-i");
info.WindowStyle = ProcessWindowStyle.Minimized;
Process process = Process.Start(info);
process.WaitForExit();
Log.WriteEnd("Finished aspnet_regiis -i");
}
private static bool IsWebServerRoleInstalled()
{
RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\InetStp");
if (regkey == null)
return false;
int value = (int)regkey.GetValue("MajorVersion", 0);
return value == 7 || value == 8;
}
private static bool IsAspNetRoleServiceInstalled()
{
return GetIsWebFeaturesInstalled();
}
private static bool GetIsWebFeaturesInstalled()
{ // See WebsitePanel.Installer\Sources\WebsitePanel.WIXInstaller\Common\Tool.cs
bool Result = false;
var LMKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
Result |= CheckAspNetRegValue(LMKey);
LMKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
Result |= CheckAspNetRegValue(LMKey);
return Result;
}
private static bool CheckAspNetRegValue(RegistryKey BaseKey)
{
var WebComponentsKey = "SOFTWARE\\Microsoft\\InetStp\\Components";
var AspNet = "ASPNET";
var AspNet45 = "ASPNET45";
RegistryKey Key = BaseKey.OpenSubKey(WebComponentsKey);
if (Key == null)
return false;
var Value = int.Parse(Key.GetValue(AspNet, 0).ToString());
if (Value != 1)
Value = int.Parse(Key.GetValue(AspNet45, 0).ToString());
return Value == 1;
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// Scheme with colors support.
/// </summary>
[Serializable]
public class ColorScheme : Scheme, IColorScheme
{
#region Fields
private ColorCategoryCollection _categories;
private float _opacity;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ColorScheme"/> class.
/// </summary>
public ColorScheme()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="ColorScheme"/> class using a predefined color scheme and the minimum and maximum specified
/// from the raster itself.
/// </summary>
/// <param name="schemeType">The predefined scheme to use</param>
/// <param name="raster">The raster to obtain the minimum and maximum settings from</param>
public ColorScheme(ColorSchemeType schemeType, IRaster raster)
{
Configure();
ApplyScheme(schemeType, raster);
}
/// <summary>
/// Initializes a new instance of the <see cref="ColorScheme"/> class, applying the specified color scheme, and using the minimum and maximum values indicated.
/// </summary>
/// <param name="schemeType">The predefined color scheme</param>
/// <param name="min">The minimum</param>
/// <param name="max">The maximum</param>
public ColorScheme(ColorSchemeType schemeType, double min, double max)
{
Configure();
ApplyScheme(schemeType, min, max);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the raster categories.
/// </summary>
[Serialize("Categories")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ColorCategoryCollection Categories
{
get
{
return _categories;
}
set
{
if (_categories != null) _categories.Scheme = null;
_categories = value;
if (_categories != null) _categories.Scheme = this;
}
}
/// <summary>
/// Gets or sets the raster editor settings associated with this scheme.
/// </summary>
[Serialize("EditorSettings")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new RasterEditorSettings EditorSettings
{
get
{
return base.EditorSettings as RasterEditorSettings;
}
set
{
base.EditorSettings = value;
}
}
/// <summary>
/// Gets or sets the floating point value for the opacity
/// </summary>
[Serialize("Opacity")]
public float Opacity
{
get
{
return _opacity;
}
set
{
_opacity = value;
}
}
#endregion
#region Methods
/// <summary>
/// Adds the specified category.
/// </summary>
/// <param name="category">Category that gets added.</param>
public override void AddCategory(ICategory category)
{
IColorCategory cc = category as IColorCategory;
if (cc != null) _categories.Add(cc);
}
/// <summary>
/// Applies the specified color scheme and uses the specified raster to define the
/// minimum and maximum to use for the scheme.
/// </summary>
/// <param name="schemeType">Color scheme that gets applied.</param>
/// <param name="raster">Raster that is used to define the minimum and maximum for the scheme.</param>
public void ApplyScheme(ColorSchemeType schemeType, IRaster raster)
{
double min, max;
if (!raster.IsInRam)
{
GetValues(raster);
min = Statistics.Minimum;
max = Statistics.Maximum;
}
else
{
min = raster.Minimum;
max = raster.Maximum;
}
ApplyScheme(schemeType, min, max);
}
/// <summary>
/// Applies the specified color scheme and uses the specified raster to define the
/// minimum and maximum to use for the scheme.
/// </summary>
/// <param name="schemeType">ColorSchemeType</param>
/// <param name="min">THe minimum value to use for the scheme</param>
/// <param name="max">THe maximum value to use for the scheme</param>
public void ApplyScheme(ColorSchemeType schemeType, double min, double max)
{
if (Categories == null)
{
Categories = new ColorCategoryCollection(this);
}
else
{
Categories.Clear();
}
IColorCategory eqCat = null, low = null, high = null;
if (min == max)
{
// Create one category
eqCat = new ColorCategory(min, max) { Range = { MaxIsInclusive = true, MinIsInclusive = true } };
eqCat.ApplyMinMax(EditorSettings);
Categories.Add(eqCat);
}
else
{
// Create two categories
low = new ColorCategory(min, (min + max) / 2) { Range = { MaxIsInclusive = true } };
high = new ColorCategory((min + max) / 2, max) { Range = { MaxIsInclusive = true } };
low.ApplyMinMax(EditorSettings);
high.ApplyMinMax(EditorSettings);
Categories.Add(low);
Categories.Add(high);
}
Color lowColor, midColor, highColor;
int alpha = Utils.ByteRange(Convert.ToInt32(_opacity * 255F));
switch (schemeType)
{
case ColorSchemeType.SummerMountains:
lowColor = Color.FromArgb(alpha, 10, 100, 10);
midColor = Color.FromArgb(alpha, 153, 125, 25);
highColor = Color.FromArgb(alpha, 255, 255, 255);
break;
case ColorSchemeType.FallLeaves:
lowColor = Color.FromArgb(alpha, 10, 100, 10);
midColor = Color.FromArgb(alpha, 199, 130, 61);
highColor = Color.FromArgb(alpha, 241, 220, 133);
break;
case ColorSchemeType.Desert:
lowColor = Color.FromArgb(alpha, 211, 206, 97);
midColor = Color.FromArgb(alpha, 139, 120, 112);
highColor = Color.FromArgb(alpha, 255, 255, 255);
break;
case ColorSchemeType.Glaciers:
lowColor = Color.FromArgb(alpha, 105, 171, 224);
midColor = Color.FromArgb(alpha, 162, 234, 240);
highColor = Color.FromArgb(alpha, 255, 255, 255);
break;
case ColorSchemeType.Meadow:
lowColor = Color.FromArgb(alpha, 68, 128, 71);
midColor = Color.FromArgb(alpha, 43, 91, 30);
highColor = Color.FromArgb(alpha, 167, 220, 168);
break;
case ColorSchemeType.ValleyFires:
lowColor = Color.FromArgb(alpha, 164, 0, 0);
midColor = Color.FromArgb(alpha, 255, 128, 64);
highColor = Color.FromArgb(alpha, 255, 255, 191);
break;
case ColorSchemeType.DeadSea:
lowColor = Color.FromArgb(alpha, 51, 137, 208);
midColor = Color.FromArgb(alpha, 226, 227, 166);
highColor = Color.FromArgb(alpha, 151, 146, 117);
break;
case ColorSchemeType.Highway:
lowColor = Color.FromArgb(alpha, 51, 137, 208);
midColor = Color.FromArgb(alpha, 214, 207, 124);
highColor = Color.FromArgb(alpha, 54, 152, 69);
break;
default:
lowColor = midColor = highColor = Color.Transparent;
break;
}
if (eqCat != null)
{
eqCat.LowColor = eqCat.HighColor = lowColor;
}
else
{
Debug.Assert(low != null, "low may not be null");
Debug.Assert(high != null, "high may not be null");
low.LowColor = lowColor;
low.HighColor = midColor;
high.LowColor = midColor;
high.HighColor = highColor;
}
OnItemChanged(this);
}
/// <summary>
/// Clears the categories
/// </summary>
public override void ClearCategories()
{
_categories.Clear();
}
/// <summary>
/// Creates the categories for this scheme based on statistics and values
/// sampled from the specified raster.
/// </summary>
/// <param name="raster">The raster to use when creating categories</param>
public void CreateCategories(IRaster raster)
{
GetValues(raster);
CreateBreakCategories();
OnItemChanged(this);
}
/// <summary>
/// Creates the category using a random fill color
/// </summary>
/// <param name="fillColor">The base color to use for creating the category</param>
/// <param name="size">For points this is the larger dimension, for lines this is the largest width</param>
/// <returns>A new IFeatureCategory that matches the type of this scheme</returns>
public override ICategory CreateNewCategory(Color fillColor, double size)
{
return new ColorCategory(null, null, fillColor, fillColor);
}
/// <summary>
/// Uses the settings on this scheme to create a random category.
/// </summary>
/// <returns>A new IFeatureCategory</returns>
public override ICategory CreateRandomCategory()
{
Random rnd = new Random(DateTime.Now.Millisecond);
return CreateNewCategory(CreateRandomColor(rnd), 20);
}
/// <summary>
/// Attempts to decrease the index value of the specified category, and returns
/// true if the move was successfull.
/// </summary>
/// <param name="category">The category to decrease the index of</param>
/// <returns>True, if the move was successfull.</returns>
public override bool DecreaseCategoryIndex(ICategory category)
{
IColorCategory cc = category as IColorCategory;
return cc != null && _categories.DecreaseIndex(cc);
}
/// <summary>
/// Draws the category in the specified location.
/// </summary>
/// <param name="index">Index of the category that gets drawn.</param>
/// <param name="g">graphics object used for drawing.</param>
/// <param name="bounds">Rectangle to draw the category to.</param>
public override void DrawCategory(int index, Graphics g, Rectangle bounds)
{
_categories[index].LegendSymbolPainted(g, bounds);
}
/// <summary>
/// Gets the values from the raster. If MaxSampleCount is less than the
/// number of cells, then it randomly samples the raster with MaxSampleCount
/// values. Otherwise it gets all the values in the raster.
/// </summary>
/// <param name="raster">The raster to sample</param>
public void GetValues(IRaster raster)
{
Values = raster.GetRandomValues(EditorSettings.MaxSampleCount);
var keepers = Values.Where(val => val != raster.NoDataValue).ToList();
Values = keepers;
Statistics.Calculate(Values);
}
/// <summary>
/// Attempts to increase the position of the specified category, and returns true
/// if the index increase was successful.
/// </summary>
/// <param name="category">The category to increase the position of</param>
/// <returns>Boolean, true if the item's position was increased</returns>
public override bool IncreaseCategoryIndex(ICategory category)
{
IColorCategory cc = category as IColorCategory;
return cc != null && _categories.IncreaseIndex(cc);
}
/// <summary>
/// Inserts the item at the specified index.
/// </summary>
/// <param name="index">Index where the category gets inserted.</param>
/// <param name="category">Category that gets inserted.</param>
public override void InsertCategory(int index, ICategory category)
{
IColorCategory cc = category as IColorCategory;
if (cc != null) _categories.Insert(index, cc);
}
/// <summary>
/// Removes the specified category.
/// </summary>
/// <param name="category">Category that gets removed.</param>
public override void RemoveCategory(ICategory category)
{
IColorCategory cc = category as IColorCategory;
if (cc != null) _categories.Remove(cc);
}
/// <summary>
/// Allows the ChangeItem event to get passed on when changes are made.
/// </summary>
public override void ResumeEvents()
{
_categories.ResumeEvents();
}
/// <summary>
/// Suspends the change item event from firing as the list is being changed.
/// </summary>
public override void SuspendEvents()
{
_categories.SuspendEvents();
}
/// <summary>
/// Occurs when setting the parent item and updates the parent item pointers.
/// </summary>
/// <param name="value">The parent item.</param>
protected override void OnSetParentItem(ILegendItem value)
{
base.OnSetParentItem(value);
_categories.UpdateItemParentPointers();
}
private void Configure()
{
_categories = new ColorCategoryCollection(this);
_opacity = 1;
EditorSettings = new RasterEditorSettings();
}
#endregion
}
}
| |
// Copyright (c) 2004-2010 Azavea, Inc.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using Azavea.Open.Common.Caching;
using Azavea.Open.Common.Collections;
using Azavea.Open.DAO.Criteria;
using Azavea.Open.DAO.Criteria.Grouping;
using Azavea.Open.DAO.Exceptions;
using Azavea.Open.DAO.Util;
namespace Azavea.Open.DAO.SQL
{
/// <summary>
/// A SQL-specific implementation of an IDaLayer.
/// Provided functionality to run data access function that are specific to data sources that take sql commands.
/// </summary>
public class SqlDaLayer : AbstractDaLayer
{
/// <summary>
/// The alias we use for "COUNT (*)".
/// </summary>
public const string COUNT_COL_ALIAS = "gb_count";
/// <summary>
/// From this class on down, we can always treat it as a SqlConnectionDescriptor.
/// </summary>
protected new AbstractSqlConnectionDescriptor _connDesc;
/// <summary>
/// Since there are different types of query for different dao layers,
/// each keeps their own cache.
/// </summary>
protected static readonly ClearingCache<SqlDaQuery> _sqlQueryCache = new ClearingCache<SqlDaQuery>();
/// <summary>
/// Tells us whether or not to fully qualify column names ("Table.Column") in the SQL.
/// This is generally harmless for actual databases, but may not always be desirable.
/// </summary>
protected Boolean _fullyQualifyColumnNames = true;
/// <summary>
/// Sometimes it is not desirable to fully qualify column names, even for a database,
/// e.g. when doing a query that is a join of foreign tables. This allows this value
/// to be set in those instances.
/// </summary>
/// <param name="fullyQualifyColumnNames">Whether or not to fully qualify column names.</param>
public void SetFullyQualifyColumnNames(bool fullyQualifyColumnNames)
{
_fullyQualifyColumnNames = fullyQualifyColumnNames;
}
/// <summary>
/// Instantiates the data access layer with the connection descriptor for the DB.
/// </summary>
/// <param name="connDesc">The connection descriptor that is being used by this FastDaoLayer.</param>
/// <param name="supportsNumRecords">If true, methods that return numbers of records affected will be
/// returning accurate numbers. If false, they will probably return
/// FastDAO.UNKNOWN_NUM_ROWS.</param>
public SqlDaLayer(AbstractSqlConnectionDescriptor connDesc, bool supportsNumRecords)
: base(connDesc, supportsNumRecords)
{
// We have a new _connDesc attribute, so make sure we set it here.
_connDesc = connDesc;
}
#region Members for children to override
/// <summary>
/// Override this method if you need to do any work to convert values from the
/// object's properties into normal SQL parameters. Default implementation
/// does nothing.
///
/// This is called prior to inserting or updating these values in the table.
/// </summary>
/// <param name="table">The table these values will be inserted or updated into.</param>
/// <param name="propValues">A dictionary of "column"/value pairs for the object to insert or update.</param>
protected virtual void PreProcessPropertyValues(string table,
IDictionary<string, object> propValues) { }
protected virtual IDictionary<string, string> GetValueStrings(string table,
IDictionary<string, object> propValues)
{
return null;
}
#endregion
#region IFastDaoLayer Members
/// <exclude/>
public override int Insert(ITransaction transaction, ClassMapping mapping, IDictionary<string, object> propValues)
{
List<object> sqlParams = DbCaches.ObjectLists.Get();
// This must be run BEFORE PreProcessPropertyValues, since PreProcessPropertyValues can mutate the collection
var valueStrings = GetValueStrings(mapping.Table, propValues);
PreProcessPropertyValues(mapping.Table, propValues);
string sql = SqlUtilities.MakeInsertStatement(mapping.Table, propValues, sqlParams, valueStrings);
int numRecs = SqlConnectionUtilities.XSafeCommand(_connDesc, (SqlTransaction)transaction, sql, sqlParams);
if (numRecs != 1)
{
throw new Exception("Should have inserted one record, but sql command returned " +
numRecs + " rows affected. SQL: " + SqlUtilities.SqlParamsToString(sql, sqlParams));
}
DbCaches.ObjectLists.Return(sqlParams);
return numRecs;
}
/// <exclude/>
public override int Update(ITransaction transaction, ClassMapping mapping, DaoCriteria crit, IDictionary<string, object> propValues)
{
// This must be run BEFORE PreProcessPropertyValues, since PreProcessPropertyValues can mutate the collection
var valueStrings = GetValueStrings(mapping.Table, propValues);
PreProcessPropertyValues(mapping.Table, propValues);
SqlDaQuery query = _sqlQueryCache.Get();
try
{
// Make the "update table set blah = something" part.
query.Sql.Append("UPDATE ");
query.Sql.Append(mapping.Table);
query.Sql.Append(" SET ");
bool first = true;
foreach (string key in propValues.Keys)
{
if (!first)
{
query.Sql.Append(", ");
}
else
{
first = false;
}
query.Sql.Append(key);
if (valueStrings != null && valueStrings.ContainsKey(key))
{
query.Sql.Append(" = " + valueStrings[key]);
}
else
{
query.Sql.Append(" = ?");
}
query.Params.Add(propValues[key]);
}
// Add the "where blah, blah, blah" part.
ExpressionsToQuery(query, crit, mapping);
return SqlConnectionUtilities.XSafeCommand(_connDesc, (SqlTransaction)transaction, query.Sql.ToString(), query.Params);
}
finally
{
_sqlQueryCache.Return(query);
}
}
/// <exclude/>
public override int Delete(ITransaction transaction, ClassMapping mapping, DaoCriteria crit)
{
SqlDaQuery query = _sqlQueryCache.Get();
query.Sql.Append("DELETE FROM ");
query.Sql.Append(mapping.Table);
ExpressionsToQuery(query, crit, mapping);
int retVal = SqlConnectionUtilities.XSafeCommand(_connDesc, (SqlTransaction)transaction, query.Sql.ToString(), query.Params);
DisposeOfQuery(query);
return retVal;
}
/// <exclude/>
public override int GetCount(ITransaction transaction, ClassMapping mapping, DaoCriteria crit)
{
SqlDaQuery query = _sqlQueryCache.Get();
query.Sql.Append("SELECT COUNT(*) FROM ");
query.Sql.Append(mapping.Table);
ExpressionsToQuery(query, crit, mapping);
int retVal = SqlConnectionUtilities.XSafeIntQuery(_connDesc, (SqlTransaction)transaction, query.Sql.ToString(), query.Params);
DisposeOfQuery(query);
return retVal;
}
/// <exclude/>
public override List<GroupCountResult> GetCount(ITransaction transaction,
ClassMapping mapping, DaoCriteria crit,
ICollection<AbstractGroupExpression> groupExpressions)
{
SqlDaQuery query = _sqlQueryCache.Get();
query.Sql.Append("SELECT COUNT(*) ");
if (_connDesc.NeedAsForColumnAliases())
{
query.Sql.Append("AS ");
}
query.Sql.Append(_connDesc.ColumnAliasPrefix()).
Append(COUNT_COL_ALIAS).Append(_connDesc.ColumnAliasSuffix());
GroupBysToStartOfQuery(query, groupExpressions, mapping);
query.Sql.Append(" FROM ");
query.Sql.Append(mapping.Table);
ExpressionsToQuery(query, crit, mapping);
GroupBysToEndOfQuery(query, groupExpressions, mapping);
OrdersToQuery(query, crit, mapping);
Hashtable parameters = DbCaches.Hashtables.Get();
parameters["groupBys"] = groupExpressions;
parameters["mapping"] = mapping;
SqlConnectionUtilities.XSafeQuery(_connDesc, (SqlTransaction)transaction,
query.Sql.ToString(), query.Params, ReadGroupByCount, parameters);
List<GroupCountResult> retVal = (List<GroupCountResult>) parameters["results"];
DisposeOfQuery(query);
DbCaches.Hashtables.Return(parameters);
return retVal;
}
/// <summary>
/// Reads the results from the data reader produced by the group by
/// query, creates the GroupCountResults, and returns them in the
/// parameters collection.
/// </summary>
/// <param name="parameters">Input and output parameters for the method.</param>
/// <param name="reader">Data reader to read from.</param>
protected virtual void ReadGroupByCount(Hashtable parameters, IDataReader reader)
{
ICollection<AbstractGroupExpression> groupExpressions =
(ICollection<AbstractGroupExpression>) parameters["groupBys"];
ClassMapping mapping = (ClassMapping) parameters["mapping"];
List<GroupCountResult> results = new List<GroupCountResult>();
parameters["results"] = results;
// Read each row and store it as a GroupCountResult.
while (reader.Read())
{
// We aliased the count as COUNT_COL_ALIAS.
// Some databases return other numeric types, like "decimal", so you can't
// just call reader.GetInt.
string colName = COUNT_COL_ALIAS;
int count = (int)CoerceType(typeof(int), reader.GetValue(reader.GetOrdinal(colName)));
IDictionary<string, object> values = new CheckedDictionary<string, object>();
int groupByNum = 0;
foreach (AbstractGroupExpression expr in groupExpressions)
{
values[expr.Name] = GetGroupByValue(mapping, reader, groupByNum, expr);
groupByNum++;
}
results.Add(new GroupCountResult(count, values));
}
}
/// <summary>
/// Reads a single "group by" field value from the data reader, coerces it
/// to the correct type if necessary/possible, and returns it.
/// </summary>
/// <param name="mapping">Mapping of class fields / names / etc.</param>
/// <param name="reader">Data reader to get the value from.</param>
/// <param name="number">Which group by field is this (0th, 1st, etc).</param>
/// <param name="expression">The group by expression we're reading the value for.</param>
/// <returns>The value to put in the GroupValues collection of the GroupCountResult.</returns>
protected virtual object GetGroupByValue(ClassMapping mapping, IDataReader reader,
int number, AbstractGroupExpression expression)
{
// We aliased the group bys in order as "gb_0", "gb_1", etc.
string colName = "gb_" + number;
int colNum = reader.GetOrdinal(colName);
object value = reader.IsDBNull(colNum) ? null : reader.GetValue(colNum);
if (expression is MemberGroupExpression)
{
// For group bys, we leave nulls as nulls even if the type would
// normally be non-nullable (I.E. int, float, etc).
if (value != null)
{
string memberName = ((MemberGroupExpression) expression).MemberName;
Type desiredType = null;
// If we actually have a member info, coerce the value to that type.
if (mapping.AllObjMemberInfosByObjAttr.ContainsKey(memberName))
{
MemberInfo info = mapping.AllObjMemberInfosByObjAttr[memberName];
// Don't call MemberType getter twice
MemberTypes type = info.MemberType;
if (type == MemberTypes.Field)
{
FieldInfo fInfo = ((FieldInfo) info);
desiredType = fInfo.FieldType;
}
else if (type == MemberTypes.Property)
{
PropertyInfo pInfo = ((PropertyInfo) info);
desiredType = pInfo.PropertyType;
}
}
else if (mapping.DataColTypesByObjAttr.ContainsKey(memberName))
{
// We don't have a memberinfo, but we do have a type in the mapping,
// so coerce to that type.
desiredType = mapping.DataColTypesByObjAttr[memberName];
}
// If we have a type to coerce it to, coerce it, otherwise return as-is.
if (desiredType != null)
{
value = CoerceType(desiredType, value);
}
}
}
else
{
throw new ArgumentException(
"Group expression '" + expression + "' is an unsupported type.",
"expression");
}
return value;
}
/// <summary>
/// Builds the query based on a serializable criteria.
/// </summary>
/// <param name="crit">The criteria to use for "where" comparisons.</param>
/// <param name="mapping">The mapping of the table for which to build the query string.</param>
/// <returns>A query that can be run by ExecureQuery.</returns>
public override IDaQuery CreateQuery(ClassMapping mapping, DaoCriteria crit)
{
SqlDaQuery retVal = _sqlQueryCache.Get();
retVal.Sql.Append("SELECT * FROM ");
retVal.Sql.Append(mapping.Table);
ExpressionsToQuery(retVal, crit, mapping);
OrdersToQuery(retVal, crit, mapping);
// Don't return the objects, we'll do that in DisposeOfQuery.
return retVal;
}
/// <summary>
/// Builds the query based on a string, such as a sql string.
/// NOTE: Not all FastDaoLayers are required to support this, if it is not
/// supported a NotSupportedException will be thrown.
/// TODO: This will be removed when FastDAO.QueryFor and IterateOverObjects
/// that take strings are removed.
/// </summary>
/// <param name="queryStr">The sql statement to execute that is expected to return a large
/// number of rows.</param>
/// <param name="queryParams">The parameters for the sql statement. If there are none, this
/// can be null.</param>
/// <param name="mapping">The mapping of the table for which to build the query string.</param>
/// <returns>A query that can be run by ExecureQuery.</returns>
public virtual IDaQuery CreateQuery(string queryStr, IEnumerable queryParams, ClassMapping mapping)
{
SqlDaQuery retVal = _sqlQueryCache.Get();
retVal.Sql.Append(queryStr);
if (queryParams != null)
{
foreach (object param in queryParams)
{
retVal.Params.Add(param);
}
}
// Don't return the param list or the query, we'll do that in DisposeOfQuery.
return retVal;
}
/// <summary>
/// Should be called when you're done with the query. Allows us to cache the
/// objects for reuse.
/// </summary>
/// <param name="query">Query you're done using.</param>
public override void DisposeOfQuery(IDaQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query", "Cannot dispose of null query.");
}
if (!(query is SqlDaQuery))
{
throw new ArgumentException("Cannot dispose of a query not created by me.");
}
SqlDaQuery sqlQuery = (SqlDaQuery) query;
_sqlQueryCache.Return(sqlQuery);
}
/// <summary>
/// Adds the group by fields to the "column" list ("column"
/// since they may not all be columns) in the beginning of the
/// select (I.E. "SELECT COUNT(*), Field1, Field2, etc).
/// </summary>
/// <param name="query">Query to append to.</param>
/// <param name="groupExpressions">Group by expressions.</param>
/// <param name="mapping">Class mapping for the class we're dealing with.</param>
public virtual void GroupBysToStartOfQuery(SqlDaQuery query,
ICollection<AbstractGroupExpression> groupExpressions, ClassMapping mapping)
{
int exprNum = 0;
foreach (AbstractGroupExpression expression in groupExpressions)
{
query.Sql.Append(", ");
if (expression is MemberGroupExpression)
{
query.Sql.Append(
mapping.AllDataColsByObjAttrs[((MemberGroupExpression)expression).MemberName]);
query.Sql.Append(_connDesc.NeedAsForColumnAliases() ? " AS " : " ")
.Append(_connDesc.ColumnAliasPrefix())
.Append("gb_").Append(exprNum).Append(_connDesc.ColumnAliasSuffix());
}
else
{
throw new ArgumentException(
"Group expression '" + expression + "' is an unsupported type.",
"groupExpressions");
}
exprNum++;
}
}
/// <summary>
/// Adds the group by fields to the end of the query, including
/// the keyword "GROUP BY" if necessary.
/// </summary>
/// <param name="query">Query to append to.</param>
/// <param name="groupExpressions">Group by expressions.</param>
/// <param name="mapping">Class mapping for the class we're dealing with.</param>
public virtual void GroupBysToEndOfQuery(SqlDaQuery query,
ICollection<AbstractGroupExpression> groupExpressions, ClassMapping mapping)
{
if (groupExpressions.Count > 0)
{
query.Sql.Append(" GROUP BY ");
}
bool first = true;
foreach (AbstractGroupExpression expression in groupExpressions)
{
if (first)
{
first = false;
}
else
{
query.Sql.Append(", ");
}
if (expression is MemberGroupExpression)
{
query.Sql.Append(
mapping.AllDataColsByObjAttrs[((MemberGroupExpression) expression).MemberName]);
}
else
{
throw new ArgumentException(
"Group expression '" + expression + "' is an unsupported type.",
"groupExpressions");
}
}
}
/// <summary>
/// Takes a DaoCriteria, converts it to a " WHERE ..." chunk of SQL.
/// The SQL will begin with a space if non-empty.
/// </summary>
/// <param name="queryToAddTo">Query we're adding the expression to.</param>
/// <param name="crit">Serializable critera to get the expressions from.</param>
/// <param name="mapping">Class mapping for the class we're dealing with.</param>
public virtual void ExpressionsToQuery(SqlDaQuery queryToAddTo, DaoCriteria crit,
ClassMapping mapping)
{
if (crit != null)
{
if (crit.Expressions.Count > 0)
{
string colPrefix = _fullyQualifyColumnNames ? mapping.Table + "." : null;
queryToAddTo.Sql.Append(" WHERE ");
ExpressionListToQuery(queryToAddTo, crit.BoolType, crit.Expressions,
mapping, colPrefix);
}
}
}
/// <summary>
/// Returns a nicely spaced AND or OR depending on the boolean type.
/// </summary>
/// <param name="boolType"></param>
/// <returns></returns>
protected static string BoolTypeToString(BooleanOperator boolType)
{
switch (boolType)
{
case BooleanOperator.And:
return " AND ";
case BooleanOperator.Or:
return " OR ";
default:
throw new NotSupportedException("Type of expression condition '" +
boolType + " not supported.");
}
}
/// <summary>
/// Converts the list of expressions from this criteria into SQL, and appends to the
/// given string builder.
/// </summary>
/// <param name="queryToAddTo">Query we're adding the expression to.</param>
/// <param name="boolType">Whether to AND or OR the expressions together.</param>
/// <param name="expressions">The expressions to add to the query.</param>
/// <param name="mapping">Class mapping for the class we're dealing with.</param>
/// <param name="colPrefix">What to prefix column names with, I.E. "Table." for "Table.Column".
/// May be null if no prefix is desired. May be something other than
/// the table name if the tables are being aliased.</param>
protected void ExpressionListToQuery(SqlDaQuery queryToAddTo,
BooleanOperator boolType,
IEnumerable<IExpression> expressions,
ClassMapping mapping, string colPrefix)
{
// starts out false for the first one.
bool needsBooleanOperator = false;
string boolText = BoolTypeToString(boolType);
foreach (IExpression expr in expressions)
{
try
{
if (expr == null)
{
throw new NullReferenceException("Can't convert a null expression to SQL.");
}
// After the first guy writes something, we need an operator.
if (ExpressionToQuery(queryToAddTo, expr, mapping, colPrefix,
needsBooleanOperator ? boolText : ""))
{
needsBooleanOperator = true;
}
}
catch (Exception e)
{
throw new UnableToConstructSqlException("Unable to add expression to query: " + expr, _connDesc, e);
}
}
}
/// <summary>
/// Converts a single Expression to SQL (mapping the columns as appropriate) and appends
/// to the given string builder.
///
/// Remember to wrap the SQL in parends if necessary.
/// </summary>
/// <param name="queryToAddTo">Query we're adding the expression to.</param>
/// <param name="expr">The expression. NOTE: It should NOT be null. This method does not check.</param>
/// <param name="mapping">Class mapping for the class we're dealing with.</param>
/// <param name="colPrefix">What to prefix column names with, I.E. "Table." for "Table.Column".
/// May be null if no prefix is desired. May be something other than
/// the table name if the tables are being aliased.</param>
/// <param name="booleanOperator">The boolean operator (AND or OR) to insert before
/// this expression. Blank ("") if we don't need one.</param>
/// <returns>Whether or not this expression modified the sql string.
/// Typically true, but may be false for special query types
/// that use other parameters for certain types of expressions.</returns>
protected virtual bool ExpressionToQuery(SqlDaQuery queryToAddTo, IExpression expr,
ClassMapping mapping, string colPrefix, string booleanOperator)
{
string col;
Type dbDataType;
bool trueOrNot = expr.TrueOrNot();
// add the operator if one was specified.
queryToAddTo.Sql.Append(booleanOperator);
// Add some parends.
queryToAddTo.Sql.Append("(");
if (expr is BetweenExpression)
{
BetweenExpression between = (BetweenExpression)expr;
col = colPrefix + mapping.AllDataColsByObjAttrs[between.Property];
dbDataType = mapping.DataColTypesByObjAttr[between.Property];
queryToAddTo.Sql.Append(col);
queryToAddTo.Sql.Append(trueOrNot ? " >= " : " < ");
AppendParameter(queryToAddTo, between.Min, dbDataType);
queryToAddTo.Sql.Append(trueOrNot ? " AND " : " OR ");
queryToAddTo.Sql.Append(col);
queryToAddTo.Sql.Append(trueOrNot ? " <= " : " > ");
AppendParameter(queryToAddTo, between.Max, dbDataType);
}
else if (expr is EqualExpression)
{
EqualExpression equal = (EqualExpression)expr;
col = colPrefix + mapping.AllDataColsByObjAttrs[equal.Property];
if (equal.Value == null)
{
queryToAddTo.Sql.Append(col);
queryToAddTo.Sql.Append(trueOrNot ? " IS NULL" : " IS NOT NULL");
}
else
{
queryToAddTo.Sql.Append(col);
queryToAddTo.Sql.Append(trueOrNot ? " = " : " <> ");
dbDataType = mapping.DataColTypesByObjAttr[equal.Property];
AppendParameter(queryToAddTo, equal.Value, dbDataType);
}
}
else if (expr is EqualInsensitiveExpression)
{
EqualInsensitiveExpression iequal = (EqualInsensitiveExpression)expr;
col = colPrefix + mapping.AllDataColsByObjAttrs[iequal.Property];
if (iequal.Value == null)
{
queryToAddTo.Sql.Append(col);
queryToAddTo.Sql.Append(trueOrNot ? " IS NULL" : " IS NOT NULL");
}
else
{
string lower = _connDesc.LowerCaseFunction();
queryToAddTo.Sql.Append(lower).Append("(");
queryToAddTo.Sql.Append(col).Append(") ");
queryToAddTo.Sql.Append(trueOrNot ? "= " : "<> ").Append(lower).Append("(");
dbDataType = mapping.DataColTypesByObjAttr[iequal.Property];
AppendParameter(queryToAddTo, iequal.Value, dbDataType);
queryToAddTo.Sql.Append(")");
}
}
else if (expr is GreaterExpression)
{
GreaterExpression greater = (GreaterExpression)expr;
queryToAddTo.Sql.Append(colPrefix);
queryToAddTo.Sql.Append(mapping.AllDataColsByObjAttrs[greater.Property]);
queryToAddTo.Sql.Append(trueOrNot ? " > " : " <= ");
dbDataType = mapping.DataColTypesByObjAttr[greater.Property];
AppendParameter(queryToAddTo, greater.Value, dbDataType);
}
else if (expr is LesserExpression)
{
LesserExpression lesser = (LesserExpression)expr;
queryToAddTo.Sql.Append(colPrefix);
queryToAddTo.Sql.Append(mapping.AllDataColsByObjAttrs[lesser.Property]);
queryToAddTo.Sql.Append(trueOrNot ? " < " : " >= ");
dbDataType = mapping.DataColTypesByObjAttr[lesser.Property];
AppendParameter(queryToAddTo, lesser.Value, dbDataType);
}
else if (expr is BitwiseAndExpression)
{
BitwiseAndExpression bitwise = (BitwiseAndExpression)expr;
string colName = colPrefix + mapping.AllDataColsByObjAttrs[bitwise.Property];
SqlClauseWithValue clause = _connDesc.MakeBitwiseAndClause(colName);
queryToAddTo.Sql.Append(clause.PartBeforeValue);
dbDataType = mapping.DataColTypesByObjAttr[bitwise.Property];
AppendParameter(queryToAddTo, bitwise.Value, dbDataType);
queryToAddTo.Sql.Append(clause.PartAfterValue);
DbCaches.Clauses.Return(clause);
queryToAddTo.Sql.Append(trueOrNot ? " = " : ") <> ");
AppendParameter(queryToAddTo, bitwise.Value, dbDataType);
}
else if (expr is LikeExpression)
{
LikeExpression like = (LikeExpression)expr;
queryToAddTo.Sql.Append(colPrefix);
queryToAddTo.Sql.Append(mapping.AllDataColsByObjAttrs[like.Property]);
queryToAddTo.Sql.Append(trueOrNot ? " LIKE " : " NOT LIKE ");
dbDataType = mapping.DataColTypesByObjAttr[like.Property];
AppendParameter(queryToAddTo, like.Value, dbDataType);
}
else if (expr is LikeInsensitiveExpression)
{
LikeInsensitiveExpression ilike = (LikeInsensitiveExpression)expr;
col = colPrefix + mapping.AllDataColsByObjAttrs[ilike.Property];
if (_connDesc.HasCaseInsensitiveLikeOperator())
{
string iLikeOperator = _connDesc.CaseInsensitiveLikeOperator();
queryToAddTo.Sql.Append(col);
queryToAddTo.Sql.Append(trueOrNot
? String.Format(" {0} ", iLikeOperator)
: String.Format(" NOT {0} ", iLikeOperator));
dbDataType = mapping.DataColTypesByObjAttr[ilike.Property];
AppendParameter(queryToAddTo, ilike.Value, dbDataType);
}
else
{
string lower = _connDesc.LowerCaseFunction();
queryToAddTo.Sql.Append(lower).Append("(");
queryToAddTo.Sql.Append(col).Append(") ");
queryToAddTo.Sql.Append(trueOrNot ? "LIKE " : "NOT LIKE ").Append(lower).Append("(");
dbDataType = mapping.DataColTypesByObjAttr[ilike.Property];
AppendParameter(queryToAddTo, ilike.Value, dbDataType);
queryToAddTo.Sql.Append(")");
}
}
else if (expr is PropertyInListExpression)
{
PropertyInListExpression inList = (PropertyInListExpression)expr;
IEnumerable listVals = inList.Values;
queryToAddTo.Sql.Append(colPrefix);
queryToAddTo.Sql.Append(mapping.AllDataColsByObjAttrs[inList.Property]);
dbDataType = mapping.DataColTypesByObjAttr[inList.Property];
queryToAddTo.Sql.Append(trueOrNot ? " IN (" : " NOT IN (");
bool firstIn = true;
foreach (object val in listVals)
{
if (val == null)
{
throw new NullReferenceException(
"Cannot include a null value in a list of possible values for " +
inList.Property + ".");
}
if (firstIn)
{
firstIn = false;
}
else
{
queryToAddTo.Sql.Append(", ");
}
AppendParameter(queryToAddTo, val, dbDataType);
}
if (firstIn)
{
throw new ArgumentException("Cannot query for " + inList.Property +
" values in an empty list.");
}
queryToAddTo.Sql.Append(")");
}
else if (expr is CriteriaExpression)
{
CriteriaExpression critExp = (CriteriaExpression)expr;
queryToAddTo.Sql.Append(trueOrNot ? "(" : " NOT (");
// This is slightly hacky, but basically even though we're now partway through
// assembling a SQL statement, we might have an empty nested expression. So rather
// than having "AND () AND" which isn't valid, we put "1=1" for empty nested criteria.
if ((critExp.NestedCriteria.Expressions != null) && (critExp.NestedCriteria.Expressions.Count > 0))
{
ExpressionListToQuery(queryToAddTo, critExp.NestedCriteria.BoolType,
critExp.NestedCriteria.Expressions, mapping, colPrefix);
}
else
{
queryToAddTo.Sql.Append("1=1");
}
queryToAddTo.Sql.Append(")");
}
else if (expr is HandWrittenExpression)
{
if (!trueOrNot)
{
throw new ArgumentException("You'll have to manually NOT your custom SQL.");
}
HandWrittenExpression hand = (HandWrittenExpression)expr;
// We'll assume it's SQL, hopefully parameterized.
queryToAddTo.Sql.Append(hand.Expression);
// If there are any parameters, add 'em.
if (hand.Parameters != null)
{
foreach (object aParam in hand.Parameters)
{
queryToAddTo.Params.Add(aParam);
}
}
}
else
{
throw new NotSupportedException("Expression type '" + expr.GetType() + "' is not supported.");
}
// Remember to close the parend.
queryToAddTo.Sql.Append(")");
return true;
}
/// <summary>
/// Takes a DaoCriteria, converts it to an " ORDER BY ..." chunk of SQL.
/// The SQL will begin with a space if non-empty.
/// </summary>
public virtual void OrdersToQuery(SqlDaQuery queryToAddTo, DaoCriteria crit,
ClassMapping mapping)
{
if (crit != null)
{
if (crit.Orders.Count > 0)
{
queryToAddTo.Sql.Append(" ORDER BY ");
OrderListToSql(queryToAddTo.Sql, crit, mapping);
}
}
}
/// <summary>
/// Converts the list of SortOrders from this criteria into SQL, and appends to the
/// given string builder.
/// </summary>
protected void OrderListToSql(StringBuilder orderClauseToAddTo, DaoCriteria crit,
ClassMapping mapping)
{
bool first = true;
foreach (SortOrder order in crit.Orders)
{
if (first)
{
first = false;
}
else
{
orderClauseToAddTo.Append(", ");
}
switch (order.Direction)
{
case SortType.Asc:
orderClauseToAddTo.Append(order is GroupCountSortOrder
? (_connDesc.CanUseAliasInOrderClause()
? (_connDesc.ColumnAliasPrefix() + COUNT_COL_ALIAS + _connDesc.ColumnAliasSuffix())
: "COUNT(*)")
: mapping.AllDataColsByObjAttrs[order.Property]);
orderClauseToAddTo.Append(" ASC");
break;
case SortType.Desc:
orderClauseToAddTo.Append(order is GroupCountSortOrder
? (_connDesc.CanUseAliasInOrderClause()
? (_connDesc.ColumnAliasPrefix() + COUNT_COL_ALIAS + _connDesc.ColumnAliasSuffix())
: "COUNT(*)")
: mapping.AllDataColsByObjAttrs[order.Property]);
orderClauseToAddTo.Append(" DESC");
break;
case SortType.Computed:
orderClauseToAddTo.Append(order.Property);
break;
default:
throw new NotSupportedException("Sort type '" + order.Direction + "' not supported.");
}
}
}
/// <exclude/>
public override void ExecuteQuery(ITransaction transaction, ClassMapping mapping, IDaQuery query,
DataReaderDelegate invokeMe, Hashtable parameters)
{
if (query == null)
{
throw new ArgumentNullException("query", "Cannot execute a null query.");
}
if (!(query is SqlDaQuery))
{
throw new ArgumentException("Cannot execute a query not created by me.");
}
SqlDaQuery sqlQuery = (SqlDaQuery)query;
SqlConnectionUtilities.XSafeQuery(_connDesc, (SqlTransaction)transaction, sqlQuery.Sql.ToString(),
sqlQuery.Params, invokeMe, parameters);
}
/// <exclude/>
public override void Truncate(ClassMapping classMap)
{
SqlConnectionUtilities.TruncateTable(_connDesc, classMap.Table);
}
/// <summary>
/// Since it is implementation-dependent whether to use the sql parameters collection
/// or not, this method should be implemented in each implementation.
/// </summary>
/// <param name="queryToAddTo">Query to add the parameter to.</param>
/// <param name="columnType">Type of data actually stored in the DB column. For example,
/// Enums may be stored as strings. May be null if no type cast
/// is necessary.</param>
/// <param name="value">Actual value that we need to append to our SQL.</param>
public virtual void AppendParameter(SqlDaQuery queryToAddTo, object value,
Type columnType)
{
queryToAddTo.Sql.Append("?");
if (columnType != null)
{
value = CoerceType(columnType, value);
}
queryToAddTo.Params.Add(value);
}
/// <exclude/>
public override object GetLastAutoGeneratedId(ITransaction transaction, ClassMapping mapping, string idCol)
{
string sql = _connDesc.MakeLastAutoGeneratedIdQuery(mapping.Table, idCol);
Hashtable parameters = new Hashtable();
SqlConnectionUtilities.XSafeQuery(_connDesc, (SqlTransaction)transaction, sql, null, ReadScalarValue, parameters);
return parameters[0];
}
/// <exclude/>
public override int GetNextSequenceValue(ITransaction transaction, string sequenceName)
{
return SqlConnectionUtilities.XSafeIntQuery(_connDesc, (SqlTransaction)transaction,
_connDesc.MakeSequenceValueQuery(sequenceName), null);
}
/// <exclude/>
public void ReadScalarValue(Hashtable parameters, IDataReader reader)
{
if (reader.Read())
{
object o = reader[0];
if (o is DBNull)
{
parameters.Add(0, null);
}
else
{
parameters.Add(0, o);
}
}
else
{
parameters.Add(0, null);
}
}
#endregion
}
}
| |
using EngineLayer;
using MassSpectrometry;
using OxyPlot;
using Proteomics.Fragmentation;
using Proteomics.ProteolyticDigestion;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using TaskLayer;
using ViewModels;
namespace MetaMorpheusGUI
{
/// <summary>
/// Interaction logic for MetaDraw.xaml
/// </summary>
public partial class MetaDraw : Window
{
private MetaDrawGraphicalSettings metaDrawGraphicalSettings;
private MetaDrawFilterSettings metaDrawFilterSettings;
private ItemsControlSampleViewModel itemsControlSampleViewModel;
private PsmAnnotationViewModel mainViewModel;
private MyFileManager spectraFileManager;
private MsDataFile MsDataFile;
private readonly ObservableCollection<PsmFromTsv> allPsms; // all loaded PSMs
private readonly ObservableCollection<PsmFromTsv> filteredListOfPsms; // this is the filtered list of PSMs to display (after q-value filter, etc.)
ICollectionView peptideSpectralMatchesView;
private readonly DataTable propertyView;
private string spectraFilePath;
private string tsvResultsFilePath;
private Dictionary<ProductType, double> productTypeToYOffset;
private Dictionary<ProductType, Color> productTypeToColor;
private Color variantCrossColor;
private SolidColorBrush modificationAnnotationColor;
private Regex illegalInFileName = new Regex(@"[\\/:*?""<>|]");
private ObservableCollection<string> plotTypes;
public MetaDraw()
{
UsefulProteomicsDatabases.Loaders.LoadElements();
InitializeComponent();
itemsControlSampleViewModel = new ItemsControlSampleViewModel();
DataContext = itemsControlSampleViewModel;
mainViewModel = new PsmAnnotationViewModel();
plotView.DataContext = mainViewModel;
allPsms = new ObservableCollection<PsmFromTsv>();
filteredListOfPsms = new ObservableCollection<PsmFromTsv>();
propertyView = new DataTable();
propertyView.Columns.Add("Name", typeof(string));
propertyView.Columns.Add("Value", typeof(string));
peptideSpectralMatchesView = CollectionViewSource.GetDefaultView(filteredListOfPsms);
dataGridScanNums.DataContext = peptideSpectralMatchesView;
dataGridProperties.DataContext = propertyView.DefaultView;
Title = "MetaDraw: version " + GlobalVariables.MetaMorpheusVersion;
spectraFileManager = new MyFileManager(true);
SetUpDictionaries();
variantCrossColor = Colors.Green;
modificationAnnotationColor = Brushes.Orange;
metaDrawGraphicalSettings = new MetaDrawGraphicalSettings();
metaDrawFilterSettings = new MetaDrawFilterSettings();
base.Closing += this.OnClosing;
ParentChildScanView.Visibility = Visibility.Collapsed;
ParentScanView.Visibility = Visibility.Collapsed;
plotTypes = new ObservableCollection<string>();
SetUpPlots();
//plotsListBox.ItemsSource = plotTypes;
}
private void SetUpDictionaries()
{
// colors of each fragment to annotate on base sequence
productTypeToColor = ((ProductType[])Enum.GetValues(typeof(ProductType))).ToDictionary(p => p, p => Colors.Aqua);
productTypeToColor[ProductType.b] = Colors.Blue;
productTypeToColor[ProductType.y] = Colors.Purple;
productTypeToColor[ProductType.zDot] = Colors.Orange;
productTypeToColor[ProductType.c] = Colors.Gold;
// offset for annotation on base sequence
productTypeToYOffset = ((ProductType[])Enum.GetValues(typeof(ProductType))).ToDictionary(p => p, p => 0.0);
productTypeToYOffset[ProductType.b] = 50;
productTypeToYOffset[ProductType.y] = 0;
productTypeToYOffset[ProductType.c] = 50;
productTypeToYOffset[ProductType.zDot] = 0;
}
private void Window_Drop(object sender, DragEventArgs e)
{
string[] files = ((string[])e.Data.GetData(DataFormats.FileDrop)).OrderBy(p => p).ToArray();
if (files != null)
{
foreach (var draggedFilePath in files)
{
if (File.Exists(draggedFilePath))
{
LoadFile(draggedFilePath);
}
}
}
}
private void LoadFile(string filePath)
{
var theExtension = Path.GetExtension(filePath).ToLower();
switch (theExtension)
{
case ".raw":
case ".mzml":
case ".mgf":
spectraFilePath = filePath;
spectraFileNameLabel.Text = filePath;
break;
case ".psmtsv":
case ".tsv":
tsvResultsFilePath = filePath;
psmFileNameLabel.Text = filePath;
//psmFileNameLabelStat.Text = filePath;
break;
default:
MessageBox.Show("Cannot read file type: " + theExtension);
break;
}
}
private void LoadPsms(string filename)
{
allPsms.Clear();
string fileNameWithExtension = Path.GetFileName(spectraFilePath);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(spectraFilePath);
try
{
// TODO: print warnings
foreach (var psm in PsmTsvReader.ReadTsv(filename, out List<string> warnings))
{
if (spectraFilePath == null || psm.Filename == fileNameWithExtension || psm.Filename == fileNameWithoutExtension || psm.Filename.Contains(fileNameWithoutExtension))
{
allPsms.Add(psm);
}
}
}
catch (Exception e)
{
MessageBox.Show("Could not open PSM file:\n" + e.Message);
}
}
private void DisplayLoadedAndFilteredPsms()
{
filteredListOfPsms.Clear();
var filteredList = allPsms.Where(p =>
p.QValue <= metaDrawFilterSettings.QValueFilter
&& (p.QValueNotch < metaDrawFilterSettings.QValueFilter || p.QValueNotch == null)
&& (p.DecoyContamTarget == "T" || (p.DecoyContamTarget == "D" && metaDrawFilterSettings.ShowDecoys) || (p.DecoyContamTarget == "C" && metaDrawFilterSettings.ShowContaminants)));
foreach (PsmFromTsv psm in filteredList)
{
filteredListOfPsms.Add(psm);
}
}
private void DrawPsm(int oneBasedScanNumber, string fullSequence = null, string fileName = null)
{
MsDataScan msDataScanToDraw = MsDataFile.GetOneBasedScan(oneBasedScanNumber);
IEnumerable<PsmFromTsv> scanPsms = filteredListOfPsms.Where(p => p.Ms2ScanNumber == oneBasedScanNumber);
if (fullSequence != null)
{
scanPsms = scanPsms.Where(p => p.FullSequence == fullSequence);
}
PsmFromTsv psmToDraw = scanPsms.FirstOrDefault();
// if this spectrum has child scans, draw them in the "advanced" tab
if ((psmToDraw.ChildScanMatchedIons != null && psmToDraw.ChildScanMatchedIons.Count > 0)
|| (psmToDraw.BetaPeptideChildScanMatchedIons != null && psmToDraw.BetaPeptideChildScanMatchedIons.Count > 0))
{
ParentChildScanView.Visibility = Visibility.Visible;
ParentScanView.Visibility = Visibility.Visible;
// draw parent scans
var parentPsmModel = new PsmAnnotationViewModel();
MsDataScan parentScan = MsDataFile.GetOneBasedScan(psmToDraw.Ms2ScanNumber);
parentPsmModel.DrawPeptideSpectralMatch(parentScan, psmToDraw);
string parentAnnotation = "Scan: " + parentScan.OneBasedScanNumber.ToString()
+ " Dissociation Type: " + parentScan.DissociationType.ToString()
+ " MsOrder: " + parentScan.MsnOrder.ToString()
+ " Selected Mz: " + parentScan.SelectedIonMZ.Value.ToString("0.##")
+ " Retention Time: " + parentScan.RetentionTime.ToString("0.##");
itemsControlSampleViewModel.AddNewRow(parentPsmModel, parentAnnotation);
// draw child scans
HashSet<int> scansDrawn = new HashSet<int>();
foreach (var childScanMatchedIons in psmToDraw.ChildScanMatchedIons.Concat(psmToDraw.BetaPeptideChildScanMatchedIons))
{
int scanNumber = childScanMatchedIons.Key;
if (scansDrawn.Contains(scanNumber))
{
continue;
}
scansDrawn.Add(scanNumber);
List<MatchedFragmentIon> matchedIons = childScanMatchedIons.Value;
var childPsmModel = new PsmAnnotationViewModel();
MsDataScan childScan = MsDataFile.GetOneBasedScan(scanNumber);
childPsmModel.DrawPeptideSpectralMatch(childScan, psmToDraw, metaDrawGraphicalSettings.ShowMzValues,
metaDrawGraphicalSettings.ShowAnnotationCharges, metaDrawGraphicalSettings.AnnotatedFontSize, metaDrawGraphicalSettings.BoldText);
string childAnnotation = "Scan: " + scanNumber.ToString()
+ " Dissociation Type: " + childScan.DissociationType.ToString()
+ " MsOrder: " + childScan.MsnOrder.ToString()
+ " Selected Mz: " + childScan.SelectedIonMZ.Value.ToString("0.##")
+ " RetentionTime: " + childScan.RetentionTime.ToString("0.##");
itemsControlSampleViewModel.AddNewRow(childPsmModel, childAnnotation);
}
}
else
{
ParentChildScanView.Visibility = Visibility.Collapsed;
ParentScanView.Visibility = Visibility.Collapsed;
}
// if this is a crosslink spectrum match, there are two base sequence annotations to draw
// this makes the canvas taller to fit both of these peptide sequences
if (psmToDraw.BetaPeptideBaseSequence != null)
{
int height = 150;
canvas.Height = height;
PsmAnnotationGrid.RowDefinitions[1].Height = new GridLength(height);
}
else
{
int height = 60;
canvas.Height = height;
PsmAnnotationGrid.RowDefinitions[1].Height = new GridLength(height);
}
// draw annotated spectrum
mainViewModel.DrawPeptideSpectralMatch(msDataScanToDraw, psmToDraw, metaDrawGraphicalSettings.ShowMzValues,
metaDrawGraphicalSettings.ShowAnnotationCharges, metaDrawGraphicalSettings.AnnotatedFontSize, metaDrawGraphicalSettings.BoldText);
// draw annotated base sequence
DrawAnnotatedBaseSequence(psmToDraw);
}
/// <summary>
/// Event triggers when a different cell is selected in the PSM data grid
/// </summary>
private void dataGridScanNums_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
OnSelectionChanged();
}
private void OnSelectionChanged()
{
if (dataGridScanNums.SelectedItem == null)
{
return;
}
// draw the selected PSM
propertyView.Clear();
PsmFromTsv row = (PsmFromTsv)dataGridScanNums.SelectedItem;
System.Reflection.PropertyInfo[] temp = row.GetType().GetProperties();
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Name == nameof(row.MatchedIons))
{
propertyView.Rows.Add(temp[i].Name, string.Join(", ", row.MatchedIons.Select(p => p.Annotation)));
}
else
{
propertyView.Rows.Add(temp[i].Name, temp[i].GetValue(row, null));
}
}
dataGridProperties.Items.Refresh();
itemsControlSampleViewModel.Data.Clear();
DrawPsm(row.Ms2ScanNumber, row.FullSequence);
}
private void selectSpectraFileButton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog
{
Filter = "Spectra Files(*.raw;*.mzML)|*.raw;*.mzML",
FilterIndex = 1,
RestoreDirectory = true,
Multiselect = false
};
if (openFileDialog1.ShowDialog() == true)
{
foreach (var filePath in openFileDialog1.FileNames.OrderBy(p => p))
{
LoadFile(filePath);
}
}
}
private void selectPsmFileButton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog
{
Filter = "Result Files(*.psmtsv)|*.psmtsv",
FilterIndex = 1,
RestoreDirectory = true,
Multiselect = false
};
if (openFileDialog1.ShowDialog() == true)
{
foreach (var filePath in openFileDialog1.FileNames.OrderBy(p => p))
{
LoadFile(filePath);
}
}
}
private void OnClosing(object sender, CancelEventArgs e)
{
metaDrawGraphicalSettings.Close();
metaDrawFilterSettings.Close();
}
private void graphicalSettings_Click(object sender, RoutedEventArgs e)
{
metaDrawGraphicalSettings.MZCheckBox.IsChecked = metaDrawGraphicalSettings.ShowMzValues;
metaDrawGraphicalSettings.ChargesCheckBox.IsChecked = metaDrawGraphicalSettings.ShowAnnotationCharges;
metaDrawGraphicalSettings.BoldTextCheckBox.IsChecked = metaDrawGraphicalSettings.BoldText;
metaDrawGraphicalSettings.TextSizeBox.Text = metaDrawGraphicalSettings.AnnotatedFontSize.ToString();
metaDrawGraphicalSettings.ShowDialog();
OnSelectionChanged();
}
private void filterSettings_Click(object sender, RoutedEventArgs e)
{
metaDrawFilterSettings.DecoysCheckBox.IsChecked = metaDrawFilterSettings.ShowDecoys;
metaDrawFilterSettings.ContaminantsCheckBox.IsChecked = metaDrawFilterSettings.ShowContaminants;
metaDrawFilterSettings.qValueBox.Text = metaDrawFilterSettings.QValueFilter.ToString();
var result = metaDrawFilterSettings.ShowDialog();
DisplayLoadedAndFilteredPsms();
}
private async void loadFilesButton_Click(object sender, RoutedEventArgs e)
{
// check for validity
propertyView.Clear();
if (spectraFilePath == null)
{
MessageBox.Show("Please add a spectra file.");
return;
}
if (tsvResultsFilePath == null)
{
MessageBox.Show("Please add a search result file.");
return;
}
// load the spectra file
(sender as Button).IsEnabled = false;
selectSpectraFileButton.IsEnabled = false;
selectPsmFileButton.IsEnabled = false;
prgsFeed.IsOpen = true;
prgsText.Content = "Loading spectra file...";
var slowProcess = Task<MsDataFile>.Factory.StartNew(() => spectraFileManager.LoadFile(spectraFilePath, new CommonParameters(trimMsMsPeaks: false)));
await slowProcess;
MsDataFile = slowProcess.Result;
// load the PSMs
this.prgsText.Content = "Loading PSMs...";
LoadPsms(tsvResultsFilePath);
DisplayLoadedAndFilteredPsms();
// done loading - restore controls
this.prgsFeed.IsOpen = false;
(sender as Button).IsEnabled = true;
selectSpectraFileButton.IsEnabled = true;
selectPsmFileButton.IsEnabled = true;
}
//private void loadFilesButtonStat_Click(object sender, RoutedEventArgs e)
//{
// // check for validity
// if (tsvResultsFilePath == null)
// {
// MessageBox.Show("Please add a search result file.");
// return;
// }
// (sender as Button).IsEnabled = false;
// selectPsmFileButtonStat.IsEnabled = false;
// prgsFeedStat.IsOpen = true;
// // load the PSMs
// this.prgsTextStat.Content = "Loading PSMs...";
// LoadPsmsStat(tsvResultsFilePath);
// // done loading - restore controls
// this.prgsFeedStat.IsOpen = false;
// (sender as Button).IsEnabled = true;
// selectPsmFileButtonStat.IsEnabled = true;
//}
private void LoadPsmsStat(string filepath)
{
LoadPsms(filepath);
DisplayLoadedAndFilteredPsms();
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
string txt = (sender as TextBox).Text;
if (txt == "")
{
peptideSpectralMatchesView.Filter = null;
}
else
{
peptideSpectralMatchesView.Filter = obj =>
{
PsmFromTsv psm = obj as PsmFromTsv;
return ((psm.Ms2ScanNumber.ToString()).StartsWith(txt) || psm.FullSequence.ToUpper().Contains(txt.ToUpper()));
};
}
}
private void DrawAnnotatedBaseSequence(PsmFromTsv psm)
{
double spacing = 22;
BaseDraw.clearCanvas(canvas);
// don't draw ambiguous sequences
if (psm.FullSequence.Contains("|"))
{
return;
}
// draw base sequence
for (int r = 0; r < psm.BaseSeq.Length; r++)
{
BaseDraw.txtDrawing(canvas, new Point(r * spacing + 10, 10), psm.BaseSeq[r].ToString(), Brushes.Black);
}
// draw the fragment ion annotations on the base sequence
foreach (var ion in psm.MatchedIons)
{
int residue = ion.NeutralTheoreticalProduct.TerminusFragment.AminoAcidPosition;
string annotation = ion.NeutralTheoreticalProduct.ProductType + "" + ion.NeutralTheoreticalProduct.TerminusFragment.FragmentNumber;
Color color = psm.VariantCrossingIons.Contains(ion) ? variantCrossColor : productTypeToColor[ion.NeutralTheoreticalProduct.ProductType];
if (ion.NeutralTheoreticalProduct.NeutralLoss != 0)
{
annotation += "-" + ion.NeutralTheoreticalProduct.NeutralLoss;
}
if (ion.NeutralTheoreticalProduct.TerminusFragment.Terminus == FragmentationTerminus.C)
{
BaseDraw.topSplittingDrawing(canvas, new Point(residue * spacing + 8,
productTypeToYOffset[ion.NeutralTheoreticalProduct.ProductType]), color, annotation);
}
else if (ion.NeutralTheoreticalProduct.TerminusFragment.Terminus == FragmentationTerminus.N)
{
BaseDraw.botSplittingDrawing(canvas, new Point(residue * spacing + 8,
productTypeToYOffset[ion.NeutralTheoreticalProduct.ProductType]), color, annotation);
}
// don't draw diagnostic ions, precursor ions, etc
}
// draw modifications
var peptide = new PeptideWithSetModifications(psm.FullSequence, GlobalVariables.AllModsKnownDictionary);
foreach (var mod in peptide.AllModsOneIsNterminus)
{
BaseDraw.circledTxtDraw(canvas, new Point((mod.Key - 1) * spacing - 17, 12), modificationAnnotationColor);
}
if (psm.BetaPeptideBaseSequence != null)
{
for (int r = 0; r < psm.BetaPeptideBaseSequence.Length; r++)
{
BaseDraw.txtDrawing(canvas, new Point(r * spacing + 10, 100), psm.BetaPeptideBaseSequence[r].ToString(), Brushes.Black);
}
foreach (var ion in psm.BetaPeptideMatchedIons)
{
int residue = ion.NeutralTheoreticalProduct.TerminusFragment.AminoAcidPosition;
string annotation = ion.NeutralTheoreticalProduct.ProductType + "" + ion.NeutralTheoreticalProduct.TerminusFragment.FragmentNumber;
if (ion.NeutralTheoreticalProduct.NeutralLoss != 0)
{
annotation += "-" + ion.NeutralTheoreticalProduct.NeutralLoss;
}
if (ion.NeutralTheoreticalProduct.TerminusFragment.Terminus == FragmentationTerminus.C)
{
BaseDraw.topSplittingDrawing(canvas, new Point(residue * spacing + 8,
productTypeToYOffset[ion.NeutralTheoreticalProduct.ProductType] + 90), productTypeToColor[ion.NeutralTheoreticalProduct.ProductType], annotation);
}
else if (ion.NeutralTheoreticalProduct.TerminusFragment.Terminus == FragmentationTerminus.N)
{
BaseDraw.botSplittingDrawing(canvas, new Point(residue * spacing + 8,
productTypeToYOffset[ion.NeutralTheoreticalProduct.ProductType] + 90), productTypeToColor[ion.NeutralTheoreticalProduct.ProductType], annotation);
}
// don't draw diagnostic ions, precursor ions, etc
}
var betaPeptide = new PeptideWithSetModifications(psm.BetaPeptideFullSequence, GlobalVariables.AllModsKnownDictionary);
foreach (var mod in betaPeptide.AllModsOneIsNterminus)
{
BaseDraw.circledTxtDraw(canvas, new Point((mod.Key - 1) * spacing - 17, 12 + 90), modificationAnnotationColor);
}
int alphaSite = Int32.Parse(Regex.Match(psm.FullSequence, @"\d+").Value);
int betaSite = Int32.Parse(Regex.Match(psm.BetaPeptideFullSequence, @"\d+").Value);
BaseDraw.DrawCrosslinker(canvas, new Point(alphaSite * spacing, 50), new Point(betaSite * spacing, 90), Colors.Black);
}
}
private void SetUpPlots()
{
foreach (var plot in PlotModelStat.PlotNames)
{
plotTypes.Add(plot);
}
}
private void dataGridProperties_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
(sender as DataGrid).UnselectAll();
}
//private void CreatePlotPdf_Click(object sender, RoutedEventArgs e)
//{
// var selectedItem = plotsListBox.SelectedItem;
// if (selectedItem == null)
// {
// MessageBox.Show("Select a plot type to export!");
// return;
// }
// if (!filteredListOfPsms.Any())
// {
// MessageBox.Show("No PSMs are loaded!");
// return;
// }
// var plotName = selectedItem as string;
// PlotModelStat plot = new PlotModelStat(plotName, filteredListOfPsms);
// var fileDirectory = Directory.GetParent(tsvResultsFilePath).ToString();
// var fileName = String.Concat(plotName, ".pdf");
// using (Stream writePDF = File.Create(Path.Combine(fileDirectory, fileName)))
// {
// PdfExporter.Export(plot.Model, writePDF, 1000, 700);
// }
// MessageBox.Show("PDF Created at " + Path.Combine(fileDirectory, fileName) + "!");
//}
private void PDFButton_Click(object sender, RoutedEventArgs e)
{
PsmFromTsv tempPsm = null;
if (dataGridScanNums.SelectedCells.Count == 0)
{
MessageBox.Show("Please select at least one scan to export");
}
else
{
int numberOfScansToExport = dataGridScanNums.SelectedItems.Count;
foreach (object selectedItem in dataGridScanNums.SelectedItems)
{
PsmFromTsv psm = (PsmFromTsv)selectedItem;
if (tempPsm == null)
{
tempPsm = psm;
}
MsDataScan msDataScanToDraw = MsDataFile.GetOneBasedScan(psm.Ms2ScanNumber);
string myString = illegalInFileName.Replace(psm.FullSequence, "");
if (myString.Length > 30)
{
myString = myString.Substring(0, 30);
}
string filePath = Path.Combine(Path.GetDirectoryName(tsvResultsFilePath), "MetaDrawExport", psm.Ms2ScanNumber + "_" + myString + ".pdf");
string dir = Path.GetDirectoryName(filePath);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
DrawPdfAnnotatedBaseSequence(psm, canvas, filePath); // captures the annotation for the pdf
mainViewModel.DrawPeptideSpectralMatchPdf(msDataScanToDraw, psm, filePath, numberOfScansToExport > 1);
}
dataGridScanNums.SelectedItem = dataGridScanNums.SelectedItem;
DrawPsm(tempPsm.Ms2ScanNumber, tempPsm.FullSequence);
MessageBox.Show(string.Format("{0} PDFs exported", numberOfScansToExport));
}
}
private void DrawPdfAnnotatedBaseSequence(PsmFromTsv psm, Canvas canvas, string path)
{
if (psm.CrossType == null)
{
DrawAnnotatedBaseSequence(psm);
}
canvas.Measure(new Size((int)canvas.Width, 600));
canvas.Arrange(new Rect(new Size((int)canvas.Width, 600)));
RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)(canvas.Width), 600, 96, 96, PixelFormats.Pbgra32);
renderBitmap.Render(canvas);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
string tempPath = Path.Combine(Path.GetDirectoryName(tsvResultsFilePath), "MetaDrawExport", "annotation.png");
using (FileStream file = File.Create(tempPath))
{
encoder.Save(file);
}
}
//private async void PlotSelected(object sender, SelectionChangedEventArgs e)
//{
// var listview = sender as ListView;
// var plotName = listview.SelectedItem as string;
// if (filteredListOfPsms.Count == 0)
// {
// MessageBox.Show("There are no PSMs to analyze.\n\nLoad the current file or choose a new file.");
// return;
// }
// PlotModelStat plot = await Task.Run(() => new PlotModelStat(plotName, filteredListOfPsms));
// plotViewStat.DataContext = plot;
//}
private void BtnChangeGridColumns_Click(object sender, RoutedEventArgs e)
{
itemsControlSampleViewModel.MyColumnCount++;
if (itemsControlSampleViewModel.MyColumnCount > itemsControlSampleViewModel.Data.Count / 3)
{
itemsControlSampleViewModel.MyColumnCount = 1;
}
}
}
}
| |
using System.Collections.Immutable;
using System.Reflection;
using NQuery.Symbols;
namespace NQuery
{
public sealed class Conversion
{
private const string ImplicitMethodName = "op_Implicit";
private const string ExplicitMethodName = "op_Explicit";
private const BindingFlags ConversionMethodBindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
private const bool N = false;
private const bool Y = true;
private static readonly bool[,] ImplicitNumericConversions =
{
/* SByte Byte Short UShort Int UInt Long ULong Char Float Double*/
/* SByte */ { N, N, Y, N, Y, N, Y, N, N, Y, Y},
/* Byte */ { N, N, Y, Y, Y, Y, Y, Y, N, Y, Y},
/* Short */ { N, N, N, N, Y, N, Y, N, N, Y, Y},
/* UShort */ { N, N, N, N, Y, Y, Y, Y, N, Y, Y},
/* Int */ { N, N, N, N, N, N, Y, N, N, Y, Y},
/* UInt */ { N, N, N, N, N, N, Y, Y, N, Y, Y},
/* Long */ { N, N, N, N, N, N, N, N, N, Y, Y},
/* ULong */ { N, N, N, N, N, N, N, N, N, Y, Y},
/* Char */ { N, N, N, Y, Y, Y, Y, Y, N, Y, Y},
/* Float */ { N, N, N, N, N, N, N, N, N, N, Y},
/* Double */ { N, N, N, N, N, N, N, N, N, N, N}
};
private readonly bool _isBoxingOrUnboxing;
private Conversion(bool exists, bool isIdentity, bool isImplicit, bool isBoxingOrUnboxing, bool isReference, IEnumerable<MethodInfo> conversionMethods)
{
Exists = exists;
IsIdentity = isIdentity;
IsImplicit = isImplicit;
_isBoxingOrUnboxing = isBoxingOrUnboxing;
IsReference = isReference;
ConversionMethods = conversionMethods?.ToImmutableArray() ?? ImmutableArray<MethodInfo>.Empty;
}
private static readonly Conversion None = new(false, false, false, false, false, null);
private static readonly Conversion Null = new(true, false, true, false, false, null);
private static readonly Conversion Identity = new(true, true, true, false, false, null);
private static readonly Conversion Implicit = new(true, false, true, false, false, null);
private static readonly Conversion Explicit = new(true, false, false, false, false, null);
private static readonly Conversion Boxing = new(true, false, true, true, false, null);
private static readonly Conversion Unboxing = new(true, false, false, true, false, null);
private static readonly Conversion UpCast = new(true, false, true, false, true, null);
private static readonly Conversion DownCast = new(true, false, false, false, true, null);
public bool Exists { get; }
public bool IsIdentity { get; }
public bool IsImplicit { get; }
public bool IsExplicit => Exists && !IsImplicit;
public bool IsBoxing => _isBoxingOrUnboxing && IsImplicit;
public bool IsUnboxing => _isBoxingOrUnboxing && IsExplicit;
public bool IsReference { get; }
public ImmutableArray<MethodInfo> ConversionMethods { get; }
internal static Conversion Classify(Type sourceType, Type targetType)
{
if (sourceType == targetType)
return Identity;
var knownSourceType = sourceType.GetKnownType();
var knownTargetType = targetType.GetKnownType();
if (knownSourceType is not null && knownTargetType is not null)
{
if (HasImplicitNumericConversion(knownSourceType.Value, knownTargetType.Value))
return Implicit;
if (HasExplicitNumericConversion(knownSourceType.Value, knownTargetType.Value))
return Explicit;
}
if (sourceType.IsValueType && knownTargetType == KnownType.Object)
{
// Converting a value type to object is always possible (AKA 'boxing').
return Boxing;
}
if (knownSourceType == KnownType.Object && targetType.IsValueType)
{
// Converting object to a value type is always possible (AKA 'unboxing').
return Unboxing;
}
if (sourceType.IsNull() || targetType.IsNull())
{
// If either side is the null type, we have an implicit conversion to or from NULL.
return Null;
}
if (!sourceType.IsValueType && !targetType.IsValueType)
{
// If both are reference types, let's check whether target is a base type
// of source. In that case it's an implicit upcast.
if (targetType.IsAssignableFrom(sourceType))
return UpCast;
// The reverse would be an explicit downcast.
if (sourceType.IsAssignableFrom(targetType))
return DownCast;
}
// TODO: The implementation of user defined conversions (UDC) is incomplete.
//
// For instance, the following is considered valid in C#:
//
// class SomeType
// {
// public static implicit operator sbyte (SomeType argument)
// {
// return 42;
// }
// }
//
// class Program
// {
// static void Main()
// {
// float x = new SomeType();
// var y = - new SomeType(); // Uses unary minus on int
// }
// }
//
// In other words, the conversions SomeType -> float and SomeType -> int
// are considered valid because SomeType has a UDC from SomeType -> sbyte.
//
// Also, C# considers UDC that are on base types.
//
// Implementing this isn't that easy because we also need to apply the
// usual betterness rules in order to find the best UDC among a set of
// candidates. For instance, if we'd add an implicit conversion to
// SomeType -> int, that's the one it would use instead of the one
// that returns an sbyte.
var implicitConversions = GetConversionMethods(sourceType, targetType, true);
if (implicitConversions.Length > 0)
return ImplicitViaConversionMethod(implicitConversions);
var explicitConversions = GetConversionMethods(sourceType, targetType, false);
if (explicitConversions.Length > 0)
return ExplicitViaConversionMethod(explicitConversions);
return None;
}
private static Conversion ImplicitViaConversionMethod(IEnumerable<MethodInfo> implicitConversions)
{
return new Conversion(true, false, true, false, false, implicitConversions);
}
private static Conversion ExplicitViaConversionMethod(IEnumerable<MethodInfo> implicitConversions)
{
return new Conversion(true, false, false, false, false, implicitConversions);
}
private static bool HasImplicitNumericConversion(KnownType sourceType, KnownType targetType)
{
if (sourceType.IsIntrinsicNumericType() && targetType.IsIntrinsicNumericType())
{
var sourceIndex = (int)sourceType;
var targetIndex = (int)targetType;
return ImplicitNumericConversions[sourceIndex, targetIndex];
}
return false;
}
private static bool HasExplicitNumericConversion(KnownType sourceType, KnownType targetType)
{
if (sourceType.IsIntrinsicNumericType() && targetType.IsIntrinsicNumericType())
return !HasImplicitNumericConversion(sourceType, targetType);
return false;
}
private static ImmutableArray<MethodInfo> GetConversionMethods(Type sourceType, Type targetType, bool isImplicit)
{
var methodName = isImplicit ? ImplicitMethodName : ExplicitMethodName;
var sourceMethods = sourceType.GetMethods(ConversionMethodBindingFlags);
var targetMethods = targetType.GetMethods(ConversionMethodBindingFlags);
var methods = sourceMethods.Concat(targetMethods);
return (from m in methods
where m.Name.Equals(methodName, StringComparison.Ordinal) &&
HasConversionSignature(m, sourceType, targetType)
select m).ToImmutableArray();
}
private static bool HasConversionSignature(MethodInfo methodInfo, Type sourceType, Type targetType)
{
if (methodInfo.ReturnType != targetType)
return false;
var parameterInfos = methodInfo.GetParameters();
if (parameterInfos.Length != 1)
return false;
return parameterInfos[0].ParameterType == sourceType;
}
internal static int Compare(Type xType, Conversion xConversion, Type yType, Conversion yConversion)
{
if (xConversion.IsIdentity && !yConversion.IsIdentity ||
xConversion.IsImplicit && yConversion.IsExplicit)
return -1;
if (!xConversion.IsIdentity && yConversion.IsIdentity ||
xConversion.IsExplicit && yConversion.IsImplicit)
return 1;
var xTypeToYType = Classify(xType, yType);
var yTypeToXType = Classify(yType, xType);
if (xTypeToYType.IsImplicit && yTypeToXType.IsExplicit)
return -1;
if (xTypeToYType.IsExplicit && yTypeToXType.IsImplicit)
return 1;
var xKnown = xType.GetKnownType();
var yKnown = yType.GetKnownType();
if (xKnown is not null && yKnown is not null)
{
var x = xKnown.Value;
var y = yKnown.Value;
if (x.IsSignedNumericType() && y.IsUnsignedNumericType())
return -1;
if (x.IsUnsignedNumericType() && y.IsSignedNumericType())
return 1;
}
return 0;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace LevelDb
{
internal delegate void PutAction(IntPtr state, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] key, ulong keyLength, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] value, ulong valueLength);
internal delegate void DeleteAction(IntPtr state, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] key, ulong keyLength);
internal delegate void DestructorAction(IntPtr state);
internal delegate int ComparatorAction(IntPtr state, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] firstKey, ulong firstKeyLength, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] secondKey, ulong secondKeyLength);
[return: MarshalAs(UnmanagedType.LPStr)] internal delegate string GetNameAction(IntPtr state);
[return: MarshalAs(UnmanagedType.LPArray)] internal delegate byte[] CreateFilterAction(IntPtr state, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[][] keys, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysUInt, SizeParamIndex = 3)] ulong[] keyLengths, int numberOfKeys, out ulong filterLength);
[return: MarshalAs(UnmanagedType.U1)] internal delegate bool CheckFilterAction(IntPtr state, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] key, ulong keyLength, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] filter, ulong filterLength);
/// <summary>
/// Native method P/Invoke declarations for LevelDB
/// </summary>
internal static class NativeMethods
{
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_open(IntPtr options,
[MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern void leveldb_close(IntPtr db);
[DllImport("leveldb-native")]
public static extern void leveldb_put(IntPtr db,
IntPtr writeOptions,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] key,
ulong keyLength,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] value,
ulong valueLength,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern void leveldb_delete(IntPtr db,
IntPtr writeOptions,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] key,
ulong keyLength,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern void leveldb_write(IntPtr db,
IntPtr writeOptions,
IntPtr writeBatch,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_get(IntPtr db,
IntPtr readOptions,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] key,
ulong keyLength,
out ulong valueLength,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_create_iterator(IntPtr db,
IntPtr readOptions);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_create_snapshot(IntPtr db);
[DllImport("leveldb-native")]
public static extern void leveldb_release_snapshot(IntPtr db,
IntPtr snapshot);
[DllImport("leveldb-native")]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string leveldb_property_value(IntPtr db,
[MarshalAs(UnmanagedType.LPStr)] string propertyName);
[DllImport("leveldb-native")]
public static extern void leveldb_approximate_sizes(IntPtr db,
int num_ranges,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] rangeStartKey,
ulong rangeStartKeyLength,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)] byte[] rangeLimitKey,
ulong rangeLimitKeyLength,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysUInt)] ulong[] sizes);
[DllImport("leveldb-native")]
public static extern void leveldb_compact_range(IntPtr db,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] startKey,
ulong startKeyLength,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] limitKey,
ulong limitKeyLength);
[DllImport("leveldb-native")]
public static extern void leveldb_destroy_db(IntPtr options,
[MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern void leveldb_repair_db(IntPtr options,
[MarshalAs(UnmanagedType.LPStr)] string name,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern void leveldb_iter_destroy(IntPtr iter);
[DllImport("leveldb-native")]
public static extern bool leveldb_iter_valid(IntPtr iter);
[DllImport("leveldb-native")]
public static extern void leveldb_iter_seek_to_first(IntPtr iter);
[DllImport("leveldb-native")]
public static extern void leveldb_iter_seek_to_last(IntPtr iter);
[DllImport("leveldb-native")]
public static extern void leveldb_iter_seek(IntPtr iter,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] key,
ulong keyLength);
[DllImport("leveldb-native")]
public static extern void leveldb_iter_next(IntPtr iter);
[DllImport("leveldb-native")]
public static extern void leveldb_iter_prev(IntPtr iter);
[DllImport("leveldb-native")]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string leveldb_iter_key(IntPtr iter,
out ulong keyLength);
[DllImport("leveldb-native")]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string leveldb_iter_value(IntPtr iter,
out ulong valueLength);
[DllImport("leveldb-native")]
public static extern void leveldb_iter_get_error(IntPtr iter,
[MarshalAs(UnmanagedType.LPStr)] out string error);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_writebatch_create();
[DllImport("leveldb-native")]
public static extern void leveldb_writebatch_destroy(IntPtr writeBatch);
[DllImport("leveldb-native")]
public static extern void leveldb_writebatch_clear(IntPtr writeBatch);
[DllImport("leveldb-native")]
public static extern void leveldb_writebatch_put(IntPtr writeBatch,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] key,
ulong keyLength,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] value,
ulong valueLength);
[DllImport("leveldb-native")]
public static extern void leveldb_writebatch_delete(IntPtr writeBatch,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] key,
ulong keyLength);
[DllImport("leveldb-native")]
public static extern void leveldb_writebatch_iterate(IntPtr writeBatch,
IntPtr handle,
[MarshalAs(UnmanagedType.FunctionPtr)] PutAction putCallback,
[MarshalAs(UnmanagedType.FunctionPtr)] DeleteAction deleteCallback);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_options_create();
[DllImport("leveldb-native")]
public static extern void leveldb_options_destroy(IntPtr options);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_comparator(IntPtr options,
IntPtr comparator);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_filter_policy(IntPtr options,
IntPtr filterPolicy);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_create_if_missing(IntPtr options,
[MarshalAs(UnmanagedType.U1)] bool value);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_error_if_exists(IntPtr options,
[MarshalAs(UnmanagedType.U1)] bool value);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_paranoid_checks(IntPtr options,
[MarshalAs(UnmanagedType.U1)] bool value);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_env(IntPtr options,
IntPtr env);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_info_log(IntPtr options,
IntPtr logger);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_write_buffer_size(IntPtr options,
ulong size);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_max_open_files(IntPtr options,
int value);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_cache(IntPtr options,
IntPtr cache);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_block_size(IntPtr options,
ulong size);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_block_restart_interval(IntPtr options,
int interval);
[DllImport("leveldb-native")]
public static extern void leveldb_options_set_compression(IntPtr options,
CompressionOption value);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_comparator_create(IntPtr handle,
[MarshalAs(UnmanagedType.FunctionPtr)] DestructorAction destructor,
[MarshalAs(UnmanagedType.FunctionPtr)] ComparatorAction comparator,
[MarshalAs(UnmanagedType.FunctionPtr)] GetNameAction nameGetter);
[DllImport("leveldb-native")]
public static extern void leveldb_comparator_destroy(IntPtr comparator);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_filterpolicy_create(IntPtr handle,
[MarshalAs(UnmanagedType.FunctionPtr)] DestructorAction destructor,
[MarshalAs(UnmanagedType.FunctionPtr)] GetNameAction nameGetter,
[MarshalAs(UnmanagedType.FunctionPtr)] CreateFilterAction createAction,
[MarshalAs(UnmanagedType.FunctionPtr)] CheckFilterAction checkAction);
[DllImport("leveldb-native")]
public static extern void leveldb_filterpolicy_destroy(IntPtr filterPolicy);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_filterpolicy_create_bloom(int bitsPerKey);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_readoptions_create();
[DllImport("leveldb-native")]
public static extern void leveldb_readoptions_destroy(IntPtr readOptions);
[DllImport("leveldb-native")]
public static extern void leveldb_readoptions_set_verify_checksums(IntPtr readOptions,
[MarshalAs(UnmanagedType.U1)] bool value);
[DllImport("leveldb-native")]
public static extern void leveldb_readoptions_set_fill_cache(IntPtr readOptions,
[MarshalAs(UnmanagedType.U1)] bool value);
[DllImport("leveldb-native")]
public static extern void leveldb_readoptions_set_snapshot(IntPtr readOptions,
IntPtr snapshot);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_writeoptions_create();
[DllImport("leveldb-native")]
public static extern void leveldb_writeoptions_destroy(IntPtr writeOptions);
[DllImport("leveldb-native")]
public static extern void leveldb_writeoptions_set_sync(IntPtr writeOptions,
[MarshalAs(UnmanagedType.U1)] bool value);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_cache_create_lru(ulong capacity);
[DllImport("leveldb-native")]
public static extern void leveldb_cache_destroy(IntPtr cache);
[DllImport("leveldb-native")]
public static extern IntPtr leveldb_create_default_env();
[DllImport("leveldb-native")]
public static extern void leveldb_env_destroy(IntPtr env);
[DllImport("leveldb-native")]
public static extern void leveldb_free(IntPtr ptr);
[DllImport("leveldb-native")]
public static extern int leveldb_major_version();
[DllImport("leveldb-native")]
public static extern int leveldb_minor_version();
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsTalking = false;
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
[SerializeField] private HARTOTuningv3Script m_HARTO;
public SphereCollider personalSpace;
public Collider npcAstridIsTalkingTo;
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
personalSpace = GetComponent<SphereCollider>();
m_HARTO = GameObject.Find ("HARTOUI").GetComponent<HARTOTuningv3Script> ();
}
// Update is called once per frame
private void Update()
{
//if (!GameManager.gm.thirdPersonActive && !GameManager.gm.disableInput) {
RotateView ();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump && !m_IsTalking) {
m_Jump = CrossPlatformInputManager.GetButtonDown ("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded) {
StartCoroutine (m_JumpBob.DoBobCycle ());
PlayLandingSound ();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded) {
m_MoveDir.y = 0f;
}
//}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
//if (!GameManager.gm.thirdPersonActive && !GameManager.gm.disableInput) {
float speed;
GetInput (out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast (transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane (desiredMove, hitInfo.normal).normalized;
if (!m_IsTalking) {
m_MoveDir.x = desiredMove.x * speed;
m_MoveDir.z = desiredMove.z * speed;
if (m_CharacterController.isGrounded) {
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump) {
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound ();
m_Jump = false;
m_Jumping = true;
}
} else {
m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move (m_MoveDir * Time.fixedDeltaTime);
ProgressStepCycle (speed);
}
UpdateCameraPosition (speed);
m_MouseLook.UpdateCursorLock ();
//}
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
//if (!GameManager.gm.disableInput)
//{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
//}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("NPC"))
{
npcAstridIsTalkingTo = other;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag ("NPC"))
{
npcAstridIsTalkingTo = null;
}
}
public void setTalking (bool b) {
m_IsTalking = b;
}
}
}
| |
#region License
// /*
// See license included in this library folder.
// */
#endregion
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using Sqloogle.Libs.NLog.Common;
using Sqloogle.Libs.NLog.Internal.NetworkSenders;
using Sqloogle.Libs.NLog.Layouts;
namespace Sqloogle.Libs.NLog.Targets
{
/// <summary>
/// Sends log messages over the network.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/Network_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/Network/NLog.config" />
/// <p>
/// This assumes 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/Network/Simple/Example.cs" />
/// <p>
/// To print the results, use any application that's able to receive messages over
/// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is
/// a simple but very powerful command-line tool that can be used for that. This image
/// demonstrates the NetCat tool receiving log messages from Network target.
/// </p>
/// <img src="examples/targets/Screenshots/Network/Output.gif" />
/// <p>
/// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol
/// or you'll get TCP timeouts and your application will be very slow.
/// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target
/// so that your application threads will not be blocked by the timing-out connection attempts.
/// </p>
/// <p>
/// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a>
/// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer
/// or NLogViewer application respectively.
/// </p>
/// </example>
[Target("Network")]
public class NetworkTarget : TargetWithLayout
{
private readonly Dictionary<string, NetworkSender> currentSenderCache = new Dictionary<string, NetworkSender>();
private readonly List<NetworkSender> openNetworkSenders = new List<NetworkSender>();
/// <summary>
/// Initializes a new instance of the <see cref="NetworkTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public NetworkTarget()
{
SenderFactory = NetworkSenderFactory.Default;
Encoding = Encoding.UTF8;
OnOverflow = NetworkTargetOverflowAction.Split;
KeepConnection = true;
MaxMessageSize = 65000;
ConnectionCacheSize = 5;
}
/// <summary>
/// Gets or sets the network address.
/// </summary>
/// <remarks>
/// The network address can be:
/// <ul>
/// <li>tcp://host:port - TCP (auto select IPv4/IPv6) (not supported on Windows Phone 7.0)</li>
/// <li>tcp4://host:port - force TCP/IPv4 (not supported on Windows Phone 7.0)</li>
/// <li>tcp6://host:port - force TCP/IPv6 (not supported on Windows Phone 7.0)</li>
/// <li>udp://host:port - UDP (auto select IPv4/IPv6, not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>udp4://host:port - force UDP/IPv4 (not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>udp6://host:port - force UDP/IPv6 (not supported on Silverlight and on Windows Phone 7.0)</li>
/// <li>http://host:port/pageName - HTTP using POST verb</li>
/// <li>https://host:port/pageName - HTTPS using POST verb</li>
/// </ul>
/// For SOAP-based webservice support over HTTP use WebService target.
/// </remarks>
/// <docgen category='Connection Options' order='10' />
public Layout Address { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep connection open whenever possible.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(true)]
public bool KeepConnection { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to append newline at the end of log message.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue(false)]
public bool NewLine { get; set; }
/// <summary>
/// Gets or sets the maximum message size in bytes.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue(65000)]
public int MaxMessageSize { get; set; }
/// <summary>
/// Gets or sets the size of the connection cache (number of connections which are kept alive).
/// </summary>
/// <docgen category="Connection Options" order="10" />
[DefaultValue(5)]
public int ConnectionCacheSize { get; set; }
/// <summary>
/// Gets or sets the action that should be taken if the message is larger than
/// maxMessageSize.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public NetworkTargetOverflowAction OnOverflow { get; set; }
/// <summary>
/// Gets or sets the encoding to be used.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[DefaultValue("utf-8")]
public Encoding Encoding { get; set; }
internal INetworkSenderFactory SenderFactory { get; set; }
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
var remainingCount = 0;
AsyncContinuation continuation =
ex =>
{
// ignore exception
if (Interlocked.Decrement(ref remainingCount) == 0)
{
asyncContinuation(null);
}
};
lock (openNetworkSenders)
{
remainingCount = openNetworkSenders.Count;
if (remainingCount == 0)
{
// nothing to flush
asyncContinuation(null);
}
else
{
// otherwise call FlushAsync() on all senders
// and invoke continuation at the very end
foreach (var openSender in openNetworkSenders)
{
openSender.FlushAsync(continuation);
}
}
}
}
/// <summary>
/// Closes the target.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
lock (openNetworkSenders)
{
foreach (var openSender in openNetworkSenders)
{
openSender.Close(ex => { });
}
openNetworkSenders.Clear();
}
}
/// <summary>
/// Sends the
/// rendered logging event over the network optionally concatenating it with a newline character.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
var address = Address.Render(logEvent.LogEvent);
var bytes = GetBytesToWrite(logEvent.LogEvent);
if (KeepConnection)
{
var sender = GetCachedNetworkSender(address);
ChunkedSend(
sender,
bytes,
ex =>
{
if (ex != null)
{
InternalLogger.Error("Error when sending {0}", ex);
ReleaseCachedConnection(sender);
}
logEvent.Continuation(ex);
});
}
else
{
var sender = SenderFactory.Create(address);
sender.Initialize();
lock (openNetworkSenders)
{
openNetworkSenders.Add(sender);
ChunkedSend(
sender,
bytes,
ex =>
{
lock (openNetworkSenders)
{
openNetworkSenders.Remove(sender);
}
if (ex != null)
{
InternalLogger.Error("Error when sending {0}", ex);
}
sender.Close(ex2 => { });
logEvent.Continuation(ex);
});
}
}
}
/// <summary>
/// Gets the bytes to be written.
/// </summary>
/// <param name="logEvent">Log event.</param>
/// <returns>Byte array.</returns>
protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent)
{
string text;
if (NewLine)
{
text = Layout.Render(logEvent) + "\r\n";
}
else
{
text = Layout.Render(logEvent);
}
return Encoding.GetBytes(text);
}
private NetworkSender GetCachedNetworkSender(string address)
{
lock (currentSenderCache)
{
NetworkSender sender;
// already have address
if (currentSenderCache.TryGetValue(address, out sender))
{
return sender;
}
if (currentSenderCache.Count >= ConnectionCacheSize)
{
// make room in the cache by closing the least recently used connection
var minAccessTime = int.MaxValue;
NetworkSender leastRecentlyUsed = null;
foreach (var kvp in currentSenderCache)
{
if (kvp.Value.LastSendTime < minAccessTime)
{
minAccessTime = kvp.Value.LastSendTime;
leastRecentlyUsed = kvp.Value;
}
}
if (leastRecentlyUsed != null)
{
ReleaseCachedConnection(leastRecentlyUsed);
}
}
sender = SenderFactory.Create(address);
sender.Initialize();
lock (openNetworkSenders)
{
openNetworkSenders.Add(sender);
}
currentSenderCache.Add(address, sender);
return sender;
}
}
private void ReleaseCachedConnection(NetworkSender sender)
{
lock (currentSenderCache)
{
lock (openNetworkSenders)
{
if (openNetworkSenders.Remove(sender))
{
// only remove it once
sender.Close(ex => { });
}
}
NetworkSender sender2;
// make sure the current sender for this address is the one we want to remove
if (currentSenderCache.TryGetValue(sender.Address, out sender2))
{
if (ReferenceEquals(sender, sender2))
{
currentSenderCache.Remove(sender.Address);
}
}
}
}
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")]
private void ChunkedSend(NetworkSender sender, byte[] buffer, AsyncContinuation continuation)
{
var tosend = buffer.Length;
var pos = 0;
AsyncContinuation sendNextChunk = null;
sendNextChunk = ex =>
{
if (ex != null)
{
continuation(ex);
return;
}
if (tosend <= 0)
{
continuation(null);
return;
}
var chunksize = tosend;
if (chunksize > MaxMessageSize)
{
if (OnOverflow == NetworkTargetOverflowAction.Discard)
{
continuation(null);
return;
}
if (OnOverflow == NetworkTargetOverflowAction.Error)
{
continuation(new OverflowException("Attempted to send a message larger than MaxMessageSize (" + MaxMessageSize + "). Actual size was: " + buffer.Length + ". Adjust OnOverflow and MaxMessageSize parameters accordingly."));
return;
}
chunksize = MaxMessageSize;
}
var pos0 = pos;
tosend -= chunksize;
pos += chunksize;
sender.Send(buffer, pos0, chunksize, sendNextChunk);
};
sendNextChunk(null);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\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.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt641()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt641();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt641
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector128<UInt64> value = Vector128.Create(values[0], values[1]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt64 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt64.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
Vector128<UInt64> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt64.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt64[] values = new UInt64[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt64();
}
Vector128<UInt64> value = Vector128.Create(values[0], values[1]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.GetElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt64)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt64.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt64 insertedValue = TestLibrary.Generator.GetUInt64();
try
{
object result2 = typeof(Vector128)
.GetMethod(nameof(Vector128.WithElement))
.MakeGenericMethod(typeof(UInt64))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector128<UInt64>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt64.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt64 result, UInt64[] values, [CallerMemberName] string method = "")
{
if (result != values[1])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector128<UInt64.GetElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector128<UInt64> result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
UInt64[] resultElements = new UInt64[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt64[] result, UInt64[] values, UInt64 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 1) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[1] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt64.WithElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Xml.Tests
{
public class InsertAfterTests
{
private XmlDocument CreateDocumentWithElement()
{
var doc = new XmlDocument();
doc.AppendChild(doc.CreateElement("root"));
return doc;
}
[Fact]
public void InsertAfterWithSameRefAttrKeepsOrderIntactAndReturnsTheArgument()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute attr1, attr2, attr3;
attr1 = element.Attributes.Append(doc.CreateAttribute("attr1"));
attr2 = element.Attributes.Append(doc.CreateAttribute("attr2"));
attr3 = element.Attributes.Append(doc.CreateAttribute("attr3"));
XmlAttributeCollection target = element.Attributes;
XmlAttribute result = target.InsertAfter(attr2, attr2);
Assert.Equal(3, target.Count);
Assert.Same(attr1, target[0]);
Assert.Same(attr2, target[1]);
Assert.Same(attr3, target[2]);
Assert.Same(attr2, result);
}
[Fact]
public void InsertAfterWithNullRefAttrAddsToTheBeginning()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute attr1, attr2, attr3;
attr1 = element.Attributes.Append(doc.CreateAttribute("attr1"));
attr2 = element.Attributes.Append(doc.CreateAttribute("attr2"));
attr3 = doc.CreateAttribute("attr3");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(attr3, null);
Assert.Equal(3, target.Count);
Assert.Same(attr3, target[0]);
Assert.Same(attr1, target[1]);
Assert.Same(attr2, target[2]);
}
[Fact]
public void InsertAfterWithRefAttrWithAnotherOwnerElementThrows()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlElement anotherElement = doc.CreateElement("anotherElement");
XmlAttribute anotherOwnerElementAttr = anotherElement.SetAttributeNode("anotherOwnerElementAttr", string.Empty);
XmlAttributeCollection target = element.Attributes;
Assert.Throws<ArgumentException>(() => target.InsertAfter(newAttr, anotherOwnerElementAttr));
}
[Fact]
public void InsertAfterWithAttrWithAnotherOwnerDocumentThrows()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute existingAttr = doc.CreateAttribute("existingAttr");
element.Attributes.Append(existingAttr);
XmlAttribute anotherOwnerDocumentAttr = new XmlDocument().CreateAttribute("anotherOwnerDocumentAttr");
XmlAttributeCollection target = element.Attributes;
Assert.Throws<ArgumentException>(() => target.InsertAfter(anotherOwnerDocumentAttr, existingAttr));
}
[Fact]
public void InsertAfterDetachesAttrFromCurrentOwnerElement()
{
const string attributeName = "movingAttr";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute attr = element.Attributes.Append(doc.CreateAttribute(attributeName));
// assert on implicitly set preconditions
Assert.Same(element, attr.OwnerElement);
Assert.True(element.HasAttribute(attributeName));
XmlElement destinationElement = doc.CreateElement("anotherElement");
XmlAttribute refAttr = destinationElement.Attributes.Append(doc.CreateAttribute("anotherAttr"));
XmlAttributeCollection target = destinationElement.Attributes;
target.InsertAfter(attr, refAttr);
Assert.Same(destinationElement, attr.OwnerElement);
Assert.False(element.HasAttribute(attributeName));
}
[Fact]
public void InsertAfterCanInsertAfterTheFirst()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[0]);
Assert.Same(newAttr, target[1]);
}
[Fact]
public void InsertAfterCanInsertAfterTheLast()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[2]);
Assert.Same(newAttr, target[3]);
}
[Fact]
public void InsertAfterCanInsertInTheMiddle()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute("newAttr");
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[1]);
Assert.Same(newAttr, target[2]);
}
[Fact]
public void InsertAfterRemovesDupAttrAfterTheRef()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(3, target.Count);
Assert.Same(refAttr, target[0]);
Assert.Same(newAttr, target[1]);
Assert.Same(anotherAttr, target[2]);
}
[Fact]
public void InsertAfterRemovesDupAttrBeforeTheRef()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(3, target.Count);
Assert.Same(anotherAttr, target[0]);
Assert.Same(refAttr, target[1]);
Assert.Same(newAttr, target[2]);
}
[Fact]
public void InsertAfterReturnsInsertedAttr()
{
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute newAttr = doc.CreateAttribute("attr2", "some:uri2");
XmlAttributeCollection target = element.Attributes;
Assert.Same(newAttr, target.InsertAfter(newAttr, refAttr));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] //Fix for this edge case was only made in NetCore
public void InsertAfterRemovesDupRefAttrAtTheEnd()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(3, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
Assert.Same(newAttr, target[2]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public void InsertAfterThrowsArgumentOutOfRangeExceptionForDupRefAttrAtTheEnd_OldBehavior()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
Assert.Throws<ArgumentOutOfRangeException> (() => target.InsertAfter(newAttr, refAttr));
Assert.Equal(2, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] //Fix for this edge case was only made in NetCore
public void InsertAfterReplacesDupRefAttr()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr3 = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
Assert.Same(newAttr, target[2]);
Assert.Same(anotherAttr3, target[3]);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public void InsertAfterDoesNotReplaceDupRefAttr_OldBehavior()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute anotherAttr1 = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr3 = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(anotherAttr1, target[0]);
Assert.Same(anotherAttr2, target[1]);
Assert.Same(anotherAttr3, target[2]);
Assert.Same(newAttr, target[3]);
}
[Fact]
public void InsertAfterRemovesDupRefAttrAfterAttrAndTheRef()
{
const string attributeName = "existingAttr";
const string attributeUri = "some:existingUri";
XmlDocument doc = CreateDocumentWithElement();
XmlElement element = doc.DocumentElement;
XmlAttribute refAttr = element.Attributes.Append(doc.CreateAttribute("attr1", "some:uri1"));
XmlAttribute anotherAttr2 = element.Attributes.Append(doc.CreateAttribute("attr2", "some:uri2"));
element.Attributes.Append(doc.CreateAttribute(attributeName, attributeUri)); //dup
XmlAttribute anotherAttr3 = element.Attributes.Append(doc.CreateAttribute("attr3", "some:uri3"));
XmlAttribute newAttr = doc.CreateAttribute(attributeName, attributeUri);
XmlAttributeCollection target = element.Attributes;
target.InsertAfter(newAttr, refAttr);
Assert.Equal(4, target.Count);
Assert.Same(refAttr, target[0]);
Assert.Same(newAttr, target[1]);
Assert.Same(anotherAttr2, target[2]);
Assert.Same(anotherAttr3, target[3]);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for JobOperations.
/// </summary>
public static partial class JobOperationsExtensions
{
/// <summary>
/// Gets lifetime summary statistics for all of the jobs in the specified
/// account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all jobs that have ever existed in the
/// account, from account creation to the last update time of the statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
public static JobStatistics GetAllLifetimeStatistics(this IJobOperations operations, JobGetAllLifetimeStatisticsOptions jobGetAllLifetimeStatisticsOptions = default(JobGetAllLifetimeStatisticsOptions))
{
return operations.GetAllLifetimeStatisticsAsync(jobGetAllLifetimeStatisticsOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets lifetime summary statistics for all of the jobs in the specified
/// account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all jobs that have ever existed in the
/// account, from account creation to the last update time of the statistics.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobStatistics> GetAllLifetimeStatisticsAsync(this IJobOperations operations, JobGetAllLifetimeStatisticsOptions jobGetAllLifetimeStatisticsOptions = default(JobGetAllLifetimeStatisticsOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAllLifetimeStatisticsWithHttpMessagesAsync(jobGetAllLifetimeStatisticsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a job.
/// </summary>
/// <remarks>
/// Deleting a job also deletes all tasks that are part of that job, and all
/// job statistics. This also overrides the retention period for task data;
/// that is, if the job contains tasks which are still retained on compute
/// nodes, the Batch services deletes those tasks' working directories and all
/// their contents. When a Delete Job request is received, the Batch service
/// sets the job to the deleting state. All update operations on a job that is
/// in deleting state will fail with status code 409 (Conflict), with
/// additional information indicating that the job is being deleted.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to delete.
/// </param>
/// <param name='jobDeleteOptions'>
/// Additional parameters for the operation
/// </param>
public static JobDeleteHeaders Delete(this IJobOperations operations, string jobId, JobDeleteOptions jobDeleteOptions = default(JobDeleteOptions))
{
return operations.DeleteAsync(jobId, jobDeleteOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a job.
/// </summary>
/// <remarks>
/// Deleting a job also deletes all tasks that are part of that job, and all
/// job statistics. This also overrides the retention period for task data;
/// that is, if the job contains tasks which are still retained on compute
/// nodes, the Batch services deletes those tasks' working directories and all
/// their contents. When a Delete Job request is received, the Batch service
/// sets the job to the deleting state. All update operations on a job that is
/// in deleting state will fail with status code 409 (Conflict), with
/// additional information indicating that the job is being deleted.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to delete.
/// </param>
/// <param name='jobDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobDeleteHeaders> DeleteAsync(this IJobOperations operations, string jobId, JobDeleteOptions jobDeleteOptions = default(JobDeleteOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(jobId, jobDeleteOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets information about the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobGetOptions'>
/// Additional parameters for the operation
/// </param>
public static CloudJob Get(this IJobOperations operations, string jobId, JobGetOptions jobGetOptions = default(JobGetOptions))
{
return operations.GetAsync(jobId, jobGetOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<CloudJob> GetAsync(this IJobOperations operations, string jobId, JobGetOptions jobGetOptions = default(JobGetOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(jobId, jobGetOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This replaces only the job properties specified in the request. For
/// example, if the job has constraints, and a request does not specify the
/// constraints element, then the job keeps the existing constraints.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobPatchOptions'>
/// Additional parameters for the operation
/// </param>
public static JobPatchHeaders Patch(this IJobOperations operations, string jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions = default(JobPatchOptions))
{
return operations.PatchAsync(jobId, jobPatchParameter, jobPatchOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This replaces only the job properties specified in the request. For
/// example, if the job has constraints, and a request does not specify the
/// constraints element, then the job keeps the existing constraints.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobPatchHeaders> PatchAsync(this IJobOperations operations, string jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions = default(JobPatchOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(jobId, jobPatchParameter, jobPatchOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the job. For example,
/// if the job has constraints associated with it and if constraints is not
/// specified with this request, then the Batch service will remove the
/// existing constraints.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobUpdateOptions'>
/// Additional parameters for the operation
/// </param>
public static JobUpdateHeaders Update(this IJobOperations operations, string jobId, JobUpdateParameter jobUpdateParameter, JobUpdateOptions jobUpdateOptions = default(JobUpdateOptions))
{
return operations.UpdateAsync(jobId, jobUpdateParameter, jobUpdateOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the job. For example,
/// if the job has constraints associated with it and if constraints is not
/// specified with this request, then the Batch service will remove the
/// existing constraints.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobUpdateHeaders> UpdateAsync(this IJobOperations operations, string jobId, JobUpdateParameter jobUpdateParameter, JobUpdateOptions jobUpdateOptions = default(JobUpdateOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(jobId, jobUpdateParameter, jobUpdateOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Disables the specified job, preventing new tasks from running.
/// </summary>
/// <remarks>
/// The Batch Service immediately moves the job to the disabling state. Batch
/// then uses the disableTasks parameter to determine what to do with the
/// currently running tasks of the job. The job remains in the disabling state
/// until the disable operation is completed and all tasks have been dealt with
/// according to the disableTasks option; the job then moves to the disabled
/// state. No new tasks are started under the job until it moves back to active
/// state. If you try to disable a job that is in any state other than active,
/// disabling, or disabled, the request fails with status code 409.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to disable.
/// </param>
/// <param name='disableTasks'>
/// What to do with active tasks associated with the job. Values are:
///
/// requeue - Terminate running tasks and requeue them. The tasks will run
/// again when the job is enabled.
/// terminate - Terminate running tasks. The tasks will not run again.
/// wait - Allow currently running tasks to complete. Possible values include:
/// 'requeue', 'terminate', 'wait'
/// </param>
/// <param name='jobDisableOptions'>
/// Additional parameters for the operation
/// </param>
public static JobDisableHeaders Disable(this IJobOperations operations, string jobId, DisableJobOption disableTasks, JobDisableOptions jobDisableOptions = default(JobDisableOptions))
{
return operations.DisableAsync(jobId, disableTasks, jobDisableOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Disables the specified job, preventing new tasks from running.
/// </summary>
/// <remarks>
/// The Batch Service immediately moves the job to the disabling state. Batch
/// then uses the disableTasks parameter to determine what to do with the
/// currently running tasks of the job. The job remains in the disabling state
/// until the disable operation is completed and all tasks have been dealt with
/// according to the disableTasks option; the job then moves to the disabled
/// state. No new tasks are started under the job until it moves back to active
/// state. If you try to disable a job that is in any state other than active,
/// disabling, or disabled, the request fails with status code 409.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to disable.
/// </param>
/// <param name='disableTasks'>
/// What to do with active tasks associated with the job. Values are:
///
/// requeue - Terminate running tasks and requeue them. The tasks will run
/// again when the job is enabled.
/// terminate - Terminate running tasks. The tasks will not run again.
/// wait - Allow currently running tasks to complete. Possible values include:
/// 'requeue', 'terminate', 'wait'
/// </param>
/// <param name='jobDisableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobDisableHeaders> DisableAsync(this IJobOperations operations, string jobId, DisableJobOption disableTasks, JobDisableOptions jobDisableOptions = default(JobDisableOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DisableWithHttpMessagesAsync(jobId, disableTasks, jobDisableOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Enables the specified job, allowing new tasks to run.
/// </summary>
/// <remarks>
/// When you call this API, the Batch service sets a disabled job to the
/// enabling state. After the this operation is completed, the job moves to the
/// active state, and scheduling of new tasks under the job resumes. The Batch
/// service does not allow a task to remain in the active state for more than 7
/// days. Therefore, if you enable a job containing active tasks which were
/// added more than 7 days ago, those tasks will not run.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to enable.
/// </param>
/// <param name='jobEnableOptions'>
/// Additional parameters for the operation
/// </param>
public static JobEnableHeaders Enable(this IJobOperations operations, string jobId, JobEnableOptions jobEnableOptions = default(JobEnableOptions))
{
return operations.EnableAsync(jobId, jobEnableOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Enables the specified job, allowing new tasks to run.
/// </summary>
/// <remarks>
/// When you call this API, the Batch service sets a disabled job to the
/// enabling state. After the this operation is completed, the job moves to the
/// active state, and scheduling of new tasks under the job resumes. The Batch
/// service does not allow a task to remain in the active state for more than 7
/// days. Therefore, if you enable a job containing active tasks which were
/// added more than 7 days ago, those tasks will not run.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to enable.
/// </param>
/// <param name='jobEnableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobEnableHeaders> EnableAsync(this IJobOperations operations, string jobId, JobEnableOptions jobEnableOptions = default(JobEnableOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.EnableWithHttpMessagesAsync(jobId, jobEnableOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Terminates the specified job, marking it as completed.
/// </summary>
/// <remarks>
/// When a Terminate Job request is received, the Batch service sets the job to
/// the terminating state. The Batch service then terminates any active or
/// running tasks associated with the job, and runs any required Job Release
/// tasks. The job then moves into the completed state.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to terminate.
/// </param>
/// <param name='terminateReason'>
/// The text you want to appear as the job's TerminateReason. The default is
/// 'UserTerminate'.
/// </param>
/// <param name='jobTerminateOptions'>
/// Additional parameters for the operation
/// </param>
public static JobTerminateHeaders Terminate(this IJobOperations operations, string jobId, string terminateReason = default(string), JobTerminateOptions jobTerminateOptions = default(JobTerminateOptions))
{
return operations.TerminateAsync(jobId, terminateReason, jobTerminateOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Terminates the specified job, marking it as completed.
/// </summary>
/// <remarks>
/// When a Terminate Job request is received, the Batch service sets the job to
/// the terminating state. The Batch service then terminates any active or
/// running tasks associated with the job, and runs any required Job Release
/// tasks. The job then moves into the completed state.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job to terminate.
/// </param>
/// <param name='terminateReason'>
/// The text you want to appear as the job's TerminateReason. The default is
/// 'UserTerminate'.
/// </param>
/// <param name='jobTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobTerminateHeaders> TerminateAsync(this IJobOperations operations, string jobId, string terminateReason = default(string), JobTerminateOptions jobTerminateOptions = default(JobTerminateOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.TerminateWithHttpMessagesAsync(jobId, terminateReason, jobTerminateOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Adds a job to the specified account.
/// </summary>
/// <remarks>
/// The Batch service supports two ways to control the work done as part of a
/// job. In the first approach, the user specifies a Job Manager task. The
/// Batch service launches this task when it is ready to start the job. The Job
/// Manager task controls all other tasks that run under this job, by using the
/// Task APIs. In the second approach, the user directly controls the execution
/// of tasks under an active job, by using the Task APIs. Also note: when
/// naming jobs, avoid including sensitive information such as user names or
/// secret project names. This information may appear in telemetry logs
/// accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='job'>
/// The job to be added.
/// </param>
/// <param name='jobAddOptions'>
/// Additional parameters for the operation
/// </param>
public static JobAddHeaders Add(this IJobOperations operations, JobAddParameter job, JobAddOptions jobAddOptions = default(JobAddOptions))
{
return operations.AddAsync(job, jobAddOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Adds a job to the specified account.
/// </summary>
/// <remarks>
/// The Batch service supports two ways to control the work done as part of a
/// job. In the first approach, the user specifies a Job Manager task. The
/// Batch service launches this task when it is ready to start the job. The Job
/// Manager task controls all other tasks that run under this job, by using the
/// Task APIs. In the second approach, the user directly controls the execution
/// of tasks under an active job, by using the Task APIs. Also note: when
/// naming jobs, avoid including sensitive information such as user names or
/// secret project names. This information may appear in telemetry logs
/// accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='job'>
/// The job to be added.
/// </param>
/// <param name='jobAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobAddHeaders> AddAsync(this IJobOperations operations, JobAddParameter job, JobAddOptions jobAddOptions = default(JobAddOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddWithHttpMessagesAsync(job, jobAddOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobListOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<CloudJob> List(this IJobOperations operations, JobListOptions jobListOptions = default(JobListOptions))
{
return operations.ListAsync(jobListOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<CloudJob>> ListAsync(this IJobOperations operations, JobListOptions jobListOptions = default(JobListOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(jobListOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the jobs that have been created under the specified job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule from which you want to get a list of jobs.
/// </param>
/// <param name='jobListFromJobScheduleOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<CloudJob> ListFromJobSchedule(this IJobOperations operations, string jobScheduleId, JobListFromJobScheduleOptions jobListFromJobScheduleOptions = default(JobListFromJobScheduleOptions))
{
return operations.ListFromJobScheduleAsync(jobScheduleId, jobListFromJobScheduleOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the jobs that have been created under the specified job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobScheduleId'>
/// The ID of the job schedule from which you want to get a list of jobs.
/// </param>
/// <param name='jobListFromJobScheduleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<CloudJob>> ListFromJobScheduleAsync(this IJobOperations operations, string jobScheduleId, JobListFromJobScheduleOptions jobListFromJobScheduleOptions = default(JobListFromJobScheduleOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListFromJobScheduleWithHttpMessagesAsync(jobScheduleId, jobListFromJobScheduleOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release task for
/// the specified job across the compute nodes where the job has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on all
/// compute nodes that have run the Job Preparation or Job Release task. This
/// includes nodes which have since been removed from the pool. If this API is
/// invoked on a job which has no Job Preparation or Job Release task, the
/// Batch service returns HTTP status code 409 (Conflict) with an error code of
/// JobPreparationTaskNotSpecified.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<JobPreparationAndReleaseTaskExecutionInformation> ListPreparationAndReleaseTaskStatus(this IJobOperations operations, string jobId, JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions = default(JobListPreparationAndReleaseTaskStatusOptions))
{
return operations.ListPreparationAndReleaseTaskStatusAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release task for
/// the specified job across the compute nodes where the job has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on all
/// compute nodes that have run the Job Preparation or Job Release task. This
/// includes nodes which have since been removed from the pool. If this API is
/// invoked on a job which has no Job Preparation or Job Release task, the
/// Batch service returns HTTP status code 409 (Conflict) with an error code of
/// JobPreparationTaskNotSpecified.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<JobPreparationAndReleaseTaskExecutionInformation>> ListPreparationAndReleaseTaskStatusAsync(this IJobOperations operations, string jobId, JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions = default(JobListPreparationAndReleaseTaskStatusOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListPreparationAndReleaseTaskStatusWithHttpMessagesAsync(jobId, jobListPreparationAndReleaseTaskStatusOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the task counts for the specified job.
/// </summary>
/// <remarks>
/// Task counts provide a count of the tasks by active, running or completed
/// task state, and a count of tasks which succeeded or failed. Tasks in the
/// preparing state are counted as running. If the validationStatus is
/// unvalidated, then the Batch service has not been able to check state counts
/// against the task states as reported in the List Tasks API. The
/// validationStatus may be unvalidated if the job contains more than 200,000
/// tasks.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobGetTaskCountsOptions'>
/// Additional parameters for the operation
/// </param>
public static TaskCounts GetTaskCounts(this IJobOperations operations, string jobId, JobGetTaskCountsOptions jobGetTaskCountsOptions = default(JobGetTaskCountsOptions))
{
return operations.GetTaskCountsAsync(jobId, jobGetTaskCountsOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the task counts for the specified job.
/// </summary>
/// <remarks>
/// Task counts provide a count of the tasks by active, running or completed
/// task state, and a count of tasks which succeeded or failed. Tasks in the
/// preparing state are counted as running. If the validationStatus is
/// unvalidated, then the Batch service has not been able to check state counts
/// against the task states as reported in the List Tasks API. The
/// validationStatus may be unvalidated if the job contains more than 200,000
/// tasks.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobGetTaskCountsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TaskCounts> GetTaskCountsAsync(this IJobOperations operations, string jobId, JobGetTaskCountsOptions jobGetTaskCountsOptions = default(JobGetTaskCountsOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetTaskCountsWithHttpMessagesAsync(jobId, jobGetTaskCountsOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<CloudJob> ListNext(this IJobOperations operations, string nextPageLink, JobListNextOptions jobListNextOptions = default(JobListNextOptions))
{
return operations.ListNextAsync(nextPageLink, jobListNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<CloudJob>> ListNextAsync(this IJobOperations operations, string nextPageLink, JobListNextOptions jobListNextOptions = default(JobListNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, jobListNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the jobs that have been created under the specified job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListFromJobScheduleNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<CloudJob> ListFromJobScheduleNext(this IJobOperations operations, string nextPageLink, JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions = default(JobListFromJobScheduleNextOptions))
{
return operations.ListFromJobScheduleNextAsync(nextPageLink, jobListFromJobScheduleNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the jobs that have been created under the specified job schedule.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListFromJobScheduleNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<CloudJob>> ListFromJobScheduleNextAsync(this IJobOperations operations, string nextPageLink, JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions = default(JobListFromJobScheduleNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListFromJobScheduleNextWithHttpMessagesAsync(nextPageLink, jobListFromJobScheduleNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release task for
/// the specified job across the compute nodes where the job has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on all
/// compute nodes that have run the Job Preparation or Job Release task. This
/// includes nodes which have since been removed from the pool. If this API is
/// invoked on a job which has no Job Preparation or Job Release task, the
/// Batch service returns HTTP status code 409 (Conflict) with an error code of
/// JobPreparationTaskNotSpecified.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<JobPreparationAndReleaseTaskExecutionInformation> ListPreparationAndReleaseTaskStatusNext(this IJobOperations operations, string nextPageLink, JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = default(JobListPreparationAndReleaseTaskStatusNextOptions))
{
return operations.ListPreparationAndReleaseTaskStatusNextAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release task for
/// the specified job across the compute nodes where the job has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on all
/// compute nodes that have run the Job Preparation or Job Release task. This
/// includes nodes which have since been removed from the pool. If this API is
/// invoked on a job which has no Job Preparation or Job Release task, the
/// Batch service returns HTTP status code 409 (Conflict) with an error code of
/// JobPreparationTaskNotSpecified.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<JobPreparationAndReleaseTaskExecutionInformation>> ListPreparationAndReleaseTaskStatusNextAsync(this IJobOperations operations, string nextPageLink, JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = default(JobListPreparationAndReleaseTaskStatusNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListPreparationAndReleaseTaskStatusNextWithHttpMessagesAsync(nextPageLink, jobListPreparationAndReleaseTaskStatusNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Controls.Templates;
using Avalonia.Interactivity;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.VisualTree;
namespace Avalonia.Controls.Primitives
{
/// <summary>
/// A lookless control whose visual appearance is defined by its <see cref="Template"/>.
/// </summary>
public class TemplatedControl : Control, ITemplatedControl
{
/// <summary>
/// Defines the <see cref="Background"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> BackgroundProperty =
Border.BackgroundProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="BorderBrush"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> BorderBrushProperty =
Border.BorderBrushProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="BorderThickness"/> property.
/// </summary>
public static readonly StyledProperty<Thickness> BorderThicknessProperty =
Border.BorderThicknessProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="FontFamily"/> property.
/// </summary>
public static readonly StyledProperty<string> FontFamilyProperty =
TextBlock.FontFamilyProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="FontSize"/> property.
/// </summary>
public static readonly StyledProperty<double> FontSizeProperty =
TextBlock.FontSizeProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="FontStyle"/> property.
/// </summary>
public static readonly StyledProperty<FontStyle> FontStyleProperty =
TextBlock.FontStyleProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="FontWeight"/> property.
/// </summary>
public static readonly StyledProperty<FontWeight> FontWeightProperty =
TextBlock.FontWeightProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="Foreground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> ForegroundProperty =
TextBlock.ForegroundProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="Padding"/> property.
/// </summary>
public static readonly StyledProperty<Thickness> PaddingProperty =
Decorator.PaddingProperty.AddOwner<TemplatedControl>();
/// <summary>
/// Defines the <see cref="Template"/> property.
/// </summary>
public static readonly StyledProperty<IControlTemplate> TemplateProperty =
AvaloniaProperty.Register<TemplatedControl, IControlTemplate>(nameof(Template));
/// <summary>
/// Defines the IsTemplateFocusTarget attached property.
/// </summary>
public static readonly AttachedProperty<bool> IsTemplateFocusTargetProperty =
AvaloniaProperty.RegisterAttached<TemplatedControl, Control, bool>("IsTemplateFocusTarget");
/// <summary>
/// Defines the <see cref="TemplateApplied"/> routed event.
/// </summary>
public static readonly RoutedEvent<TemplateAppliedEventArgs> TemplateAppliedEvent =
RoutedEvent.Register<TemplatedControl, TemplateAppliedEventArgs>(
"TemplateApplied",
RoutingStrategies.Direct);
private IControlTemplate _appliedTemplate;
/// <summary>
/// Initializes static members of the <see cref="TemplatedControl"/> class.
/// </summary>
static TemplatedControl()
{
ClipToBoundsProperty.OverrideDefaultValue<TemplatedControl>(true);
TemplateProperty.Changed.AddClassHandler<TemplatedControl>(x => x.OnTemplateChanged);
}
/// <summary>
/// Raised when the control's template is applied.
/// </summary>
public event EventHandler<TemplateAppliedEventArgs> TemplateApplied
{
add { AddHandler(TemplateAppliedEvent, value); }
remove { RemoveHandler(TemplateAppliedEvent, value); }
}
/// <summary>
/// Gets or sets the brush used to draw the control's background.
/// </summary>
public IBrush Background
{
get { return GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
/// <summary>
/// Gets or sets the brush used to draw the control's border.
/// </summary>
public IBrush BorderBrush
{
get { return GetValue(BorderBrushProperty); }
set { SetValue(BorderBrushProperty, value); }
}
/// <summary>
/// Gets or sets the thickness of the control's border.
/// </summary>
public Thickness BorderThickness
{
get { return GetValue(BorderThicknessProperty); }
set { SetValue(BorderThicknessProperty, value); }
}
/// <summary>
/// Gets or sets the font family used to draw the control's text.
/// </summary>
public string FontFamily
{
get { return GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
/// <summary>
/// Gets or sets the size of the control's text in points.
/// </summary>
public double FontSize
{
get { return GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
/// <summary>
/// Gets or sets the font style used to draw the control's text.
/// </summary>
public FontStyle FontStyle
{
get { return GetValue(FontStyleProperty); }
set { SetValue(FontStyleProperty, value); }
}
/// <summary>
/// Gets or sets the font weight used to draw the control's text.
/// </summary>
public FontWeight FontWeight
{
get { return GetValue(FontWeightProperty); }
set { SetValue(FontWeightProperty, value); }
}
/// <summary>
/// Gets or sets the brush used to draw the control's text and other foreground elements.
/// </summary>
public IBrush Foreground
{
get { return GetValue(ForegroundProperty); }
set { SetValue(ForegroundProperty, value); }
}
/// <summary>
/// Gets or sets the padding placed between the border of the control and its content.
/// </summary>
public Thickness Padding
{
get { return GetValue(PaddingProperty); }
set { SetValue(PaddingProperty, value); }
}
/// <summary>
/// Gets or sets the template that defines the control's appearance.
/// </summary>
public IControlTemplate Template
{
get { return GetValue(TemplateProperty); }
set { SetValue(TemplateProperty, value); }
}
/// <summary>
/// Gets the value of the IsTemplateFocusTargetProperty attached property on a control.
/// </summary>
/// <param name="control">The control.</param>
/// <returns>The property value.</returns>
/// <see cref="SetIsTemplateFocusTarget(Control, bool)"/>
public static bool GetIsTemplateFocusTarget(Control control)
{
return control.GetValue(IsTemplateFocusTargetProperty);
}
/// <summary>
/// Sets the value of the IsTemplateFocusTargetProperty attached property on a control.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="value">The property value.</param>
/// <remarks>
/// When a control is navigated to using the keyboard, a focus adorner is shown - usually
/// around the control itself. However if the TemplatedControl.IsTemplateFocusTarget
/// attached property is set to true on an element in the control template, then the focus
/// adorner will be shown around that control instead.
/// </remarks>
public static void SetIsTemplateFocusTarget(Control control, bool value)
{
control.SetValue(IsTemplateFocusTargetProperty, value);
}
/// <inheritdoc/>
public sealed override void ApplyTemplate()
{
var template = Template;
var logical = (ILogical)this;
// Apply the template if it is not the same as the template already applied - except
// for in the case that the template is null and we're not attached to the logical
// tree. In that case, the template has probably been cleared because the style setting
// the template has been detached, so we want to wait until it's re-attached to the
// logical tree as if it's re-attached to the same tree the template will be the same
// and we don't need to do anything.
if (_appliedTemplate != template && (template != null || logical.IsAttachedToLogicalTree))
{
if (VisualChildren.Count > 0)
{
foreach (var child in this.GetTemplateChildren())
{
child.SetValue(TemplatedParentProperty, null);
}
VisualChildren.Clear();
}
if (template != null)
{
Logger.Verbose(LogArea.Control, this, "Creating control template");
var child = template.Build(this);
var nameScope = new NameScope();
NameScope.SetNameScope((Control)child, nameScope);
child.SetValue(TemplatedParentProperty, this);
RegisterNames(child, nameScope);
((ISetLogicalParent)child).SetParent(this);
VisualChildren.Add(child);
OnTemplateApplied(new TemplateAppliedEventArgs(nameScope));
}
_appliedTemplate = template;
}
}
/// <inheritdoc/>
protected override IControl GetTemplateFocusTarget()
{
foreach (Control child in this.GetTemplateChildren())
{
if (GetIsTemplateFocusTarget(child))
{
return child;
}
}
return this;
}
/// <inheritdoc/>
protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
if (VisualChildren.Count > 0)
{
((ILogical)VisualChildren[0]).NotifyAttachedToLogicalTree(e);
}
base.OnAttachedToLogicalTree(e);
}
/// <inheritdoc/>
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
if (VisualChildren.Count > 0)
{
((ILogical)VisualChildren[0]).NotifyDetachedFromLogicalTree(e);
}
base.OnDetachedFromLogicalTree(e);
}
/// <summary>
/// Called when the control's template is applied.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnTemplateApplied(TemplateAppliedEventArgs e)
{
RaiseEvent(e);
}
/// <summary>
/// Called when the <see cref="Template"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnTemplateChanged(AvaloniaPropertyChangedEventArgs e)
{
InvalidateMeasure();
}
/// <summary>
/// Registers each control with its name scope.
/// </summary>
/// <param name="control">The control.</param>
/// <param name="nameScope">The name scope.</param>
private void RegisterNames(IControl control, INameScope nameScope)
{
if (control.Name != null)
{
nameScope.Register(control.Name, control);
}
if (control.TemplatedParent == this)
{
foreach (IControl child in control.GetVisualChildren())
{
RegisterNames(child, nameScope);
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Portable.IO
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Text;
/// <summary>
/// Base class for managed and unmanaged data streams.
/// </summary>
internal unsafe abstract class PortableAbstractStream : IPortableStream
{
/// <summary>
/// Array copy delegate.
/// </summary>
delegate void MemCopy(byte* a1, byte* a2, int len);
/** memcpy function handle. */
private static readonly MemCopy Memcpy;
/** Whether src and dest arguments are inverted. */
private static readonly bool MemcpyInverted;
/** Byte: zero. */
protected const byte ByteZero = 0;
/** Byte: one. */
protected const byte ByteOne = 1;
/** LITTLE_ENDIAN flag. */
protected static readonly bool LittleEndian = BitConverter.IsLittleEndian;
/** Position. */
protected int Pos;
/** Disposed flag. */
private bool _disposed;
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
static PortableAbstractStream()
{
Type type = typeof(Buffer);
const BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic;
Type[] paramTypes = { typeof(byte*), typeof(byte*), typeof(int) };
// Assume .Net 4.5.
MethodInfo mthd = type.GetMethod("Memcpy", flags, null, paramTypes, null);
MemcpyInverted = true;
if (mthd == null)
{
// Assume .Net 4.0.
mthd = type.GetMethod("memcpyimpl", flags, null, paramTypes, null);
MemcpyInverted = false;
if (mthd == null)
throw new InvalidOperationException("Unable to get memory copy function delegate.");
}
Memcpy = (MemCopy)Delegate.CreateDelegate(typeof(MemCopy), mthd);
}
/// <summary>
/// Write byte.
/// </summary>
/// <param name="val">Byte value.</param>
public abstract void WriteByte(byte val);
/// <summary>
/// Read byte.
/// </summary>
/// <returns>
/// Byte value.
/// </returns>
public abstract byte ReadByte();
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
public abstract void WriteByteArray(byte[] val);
/// <summary>
/// Internal routine to write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
/// <param name="data">Data pointer.</param>
protected void WriteByteArray0(byte[] val, byte* data)
{
fixed (byte* val0 = val)
{
CopyMemory(val0, data, val.Length);
}
}
/// <summary>
/// Read byte array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Byte array.
/// </returns>
public abstract byte[] ReadByteArray(int cnt);
/// <summary>
/// Internal routine to read byte array.
/// </summary>
/// <param name="len">Array length.</param>
/// <param name="data">Data pointer.</param>
/// <returns>Byte array</returns>
protected byte[] ReadByteArray0(int len, byte* data)
{
byte[] res = new byte[len];
fixed (byte* res0 = res)
{
CopyMemory(data, res0, len);
}
return res;
}
/// <summary>
/// Write bool.
/// </summary>
/// <param name="val">Bool value.</param>
public void WriteBool(bool val)
{
WriteByte(val ? ByteOne : ByteZero);
}
/// <summary>
/// Read bool.
/// </summary>
/// <returns>
/// Bool value.
/// </returns>
public bool ReadBool()
{
return ReadByte() == ByteOne;
}
/// <summary>
/// Write bool array.
/// </summary>
/// <param name="val">Bool array.</param>
public abstract void WriteBoolArray(bool[] val);
/// <summary>
/// Internal routine to write bool array.
/// </summary>
/// <param name="val">Bool array.</param>
/// <param name="data">Data pointer.</param>
protected void WriteBoolArray0(bool[] val, byte* data)
{
fixed (bool* val0 = val)
{
CopyMemory((byte*)val0, data, val.Length);
}
}
/// <summary>
/// Read bool array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Bool array.
/// </returns>
public abstract bool[] ReadBoolArray(int cnt);
/// <summary>
/// Internal routine to read bool array.
/// </summary>
/// <param name="len">Array length.</param>
/// <param name="data">Data pointer.</param>
/// <returns>Bool array</returns>
protected bool[] ReadBoolArray0(int len, byte* data)
{
bool[] res = new bool[len];
fixed (bool* res0 = res)
{
CopyMemory(data, (byte*)res0, len);
}
return res;
}
/// <summary>
/// Write short.
/// </summary>
/// <param name="val">Short value.</param>
public abstract void WriteShort(short val);
/// <summary>
/// Internal routine to write short value.
/// </summary>
/// <param name="val">Short value.</param>
/// <param name="data">Data pointer.</param>
protected void WriteShort0(short val, byte* data)
{
if (LittleEndian)
*((short*)data) = val;
else
{
byte* valPtr = (byte*)&val;
data[0] = valPtr[1];
data[1] = valPtr[0];
}
}
/// <summary>
/// Read short.
/// </summary>
/// <returns>
/// Short value.
/// </returns>
public abstract short ReadShort();
/// <summary>
/// Internal routine to read short value.
/// </summary>
/// <param name="data">Data pointer.</param>
/// <returns>Short value</returns>
protected short ReadShort0(byte* data)
{
short val;
if (LittleEndian)
val = *((short*)data);
else
{
byte* valPtr = (byte*)&val;
valPtr[0] = data[1];
valPtr[1] = data[0];
}
return val;
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="val">Short array.</param>
public abstract void WriteShortArray(short[] val);
/// <summary>
/// Internal routine to write short array.
/// </summary>
/// <param name="val">Short array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected void WriteShortArray0(short[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (short* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
short val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read short array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Short array.
/// </returns>
public abstract short[] ReadShortArray(int cnt);
/// <summary>
/// Internal routine to read short array.
/// </summary>
/// <param name="len">Array length.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Short array</returns>
protected short[] ReadShortArray0(int len, byte* data, int cnt)
{
short[] res = new short[len];
if (LittleEndian)
{
fixed (short* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
short val;
byte* valPtr = (byte*)&val;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write char.
/// </summary>
/// <param name="val">Char value.</param>
public void WriteChar(char val)
{
WriteShort(*(short*)(&val));
}
/// <summary>
/// Read char.
/// </summary>
/// <returns>
/// Char value.
/// </returns>
public char ReadChar()
{
short val = ReadShort();
return *(char*)(&val);
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="val">Char array.</param>
public abstract void WriteCharArray(char[] val);
/// <summary>
/// Internal routine to write char array.
/// </summary>
/// <param name="val">Char array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected void WriteCharArray0(char[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (char* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
char val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read char array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Char array.
/// </returns>
public abstract char[] ReadCharArray(int cnt);
/// <summary>
/// Internal routine to read char array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Char array</returns>
protected char[] ReadCharArray0(int len, byte* data, int cnt)
{
char[] res = new char[len];
if (LittleEndian)
{
fixed (char* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
char val;
byte* valPtr = (byte*)&val;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write int.
/// </summary>
/// <param name="val">Int value.</param>
public abstract void WriteInt(int val);
/// <summary>
/// Write int to specific position.
/// </summary>
/// <param name="writePos">Position.</param>
/// <param name="val">Value.</param>
public abstract void WriteInt(int writePos, int val);
/// <summary>
/// Internal routine to write int value.
/// </summary>
/// <param name="val">Int value.</param>
/// <param name="data">Data pointer.</param>
protected void WriteInt0(int val, byte* data)
{
if (LittleEndian)
*((int*)data) = val;
else
{
byte* valPtr = (byte*)&val;
data[0] = valPtr[3];
data[1] = valPtr[2];
data[2] = valPtr[1];
data[3] = valPtr[0];
}
}
/// <summary>
/// Read int.
/// </summary>
/// <returns>
/// Int value.
/// </returns>
public abstract int ReadInt();
/// <summary>
/// Internal routine to read int value.
/// </summary>
/// <param name="data">Data pointer.</param>
/// <returns>Int value</returns>
protected int ReadInt0(byte* data) {
int val;
if (LittleEndian)
val = *((int*)data);
else
{
byte* valPtr = (byte*)&val;
valPtr[0] = data[3];
valPtr[1] = data[2];
valPtr[2] = data[1];
valPtr[3] = data[0];
}
return val;
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="val">Int array.</param>
public abstract void WriteIntArray(int[] val);
/// <summary>
/// Internal routine to write int array.
/// </summary>
/// <param name="val">Int array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected void WriteIntArray0(int[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (int* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
int val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read int array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Int array.
/// </returns>
public abstract int[] ReadIntArray(int cnt);
/// <summary>
/// Internal routine to read int array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Int array</returns>
protected int[] ReadIntArray0(int len, byte* data, int cnt)
{
int[] res = new int[len];
if (LittleEndian)
{
fixed (int* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
int val;
byte* valPtr = (byte*)&val;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write float.
/// </summary>
/// <param name="val">Float value.</param>
public void WriteFloat(float val)
{
int val0 = *(int*)(&val);
WriteInt(val0);
}
/// <summary>
/// Read float.
/// </summary>
/// <returns>
/// Float value.
/// </returns>
public float ReadFloat()
{
int val = ReadInt();
return *(float*)(&val);
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="val">Float array.</param>
public abstract void WriteFloatArray(float[] val);
/// <summary>
/// Internal routine to write float array.
/// </summary>
/// <param name="val">Int array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected void WriteFloatArray0(float[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (float* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
float val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read float array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Float array.
/// </returns>
public abstract float[] ReadFloatArray(int cnt);
/// <summary>
/// Internal routine to read float array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Float array</returns>
protected float[] ReadFloatArray0(int len, byte* data, int cnt)
{
float[] res = new float[len];
if (LittleEndian)
{
fixed (float* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
int val;
byte* valPtr = (byte*)&val;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write long.
/// </summary>
/// <param name="val">Long value.</param>
public abstract void WriteLong(long val);
/// <summary>
/// Internal routine to write long value.
/// </summary>
/// <param name="val">Long value.</param>
/// <param name="data">Data pointer.</param>
protected void WriteLong0(long val, byte* data)
{
if (LittleEndian)
*((long*)data) = val;
else
{
byte* valPtr = (byte*)&val;
data[0] = valPtr[7];
data[1] = valPtr[6];
data[2] = valPtr[5];
data[3] = valPtr[4];
data[4] = valPtr[3];
data[5] = valPtr[2];
data[6] = valPtr[1];
data[7] = valPtr[0];
}
}
/// <summary>
/// Read long.
/// </summary>
/// <returns>
/// Long value.
/// </returns>
public abstract long ReadLong();
/// <summary>
/// Internal routine to read long value.
/// </summary>
/// <param name="data">Data pointer.</param>
/// <returns>Long value</returns>
protected long ReadLong0(byte* data)
{
long val;
if (LittleEndian)
val = *((long*)data);
else
{
byte* valPtr = (byte*)&val;
valPtr[0] = data[7];
valPtr[1] = data[6];
valPtr[2] = data[5];
valPtr[3] = data[4];
valPtr[4] = data[3];
valPtr[5] = data[2];
valPtr[6] = data[1];
valPtr[7] = data[0];
}
return val;
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="val">Long array.</param>
public abstract void WriteLongArray(long[] val);
/// <summary>
/// Internal routine to write long array.
/// </summary>
/// <param name="val">Long array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected void WriteLongArray0(long[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (long* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
long val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[7];
*curPos++ = valPtr[6];
*curPos++ = valPtr[5];
*curPos++ = valPtr[4];
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read long array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Long array.
/// </returns>
public abstract long[] ReadLongArray(int cnt);
/// <summary>
/// Internal routine to read long array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Long array</returns>
protected long[] ReadLongArray0(int len, byte* data, int cnt)
{
long[] res = new long[len];
if (LittleEndian)
{
fixed (long* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
long val;
byte* valPtr = (byte*)&val;
valPtr[7] = *data++;
valPtr[6] = *data++;
valPtr[5] = *data++;
valPtr[4] = *data++;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write double.
/// </summary>
/// <param name="val">Double value.</param>
public void WriteDouble(double val)
{
long val0 = *(long*)(&val);
WriteLong(val0);
}
/// <summary>
/// Read double.
/// </summary>
/// <returns>
/// Double value.
/// </returns>
public double ReadDouble()
{
long val = ReadLong();
return *(double*)(&val);
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="val">Double array.</param>
public abstract void WriteDoubleArray(double[] val);
/// <summary>
/// Internal routine to write double array.
/// </summary>
/// <param name="val">Double array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected void WriteDoubleArray0(double[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (double* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
double val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[7];
*curPos++ = valPtr[6];
*curPos++ = valPtr[5];
*curPos++ = valPtr[4];
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read double array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Double array.
/// </returns>
public abstract double[] ReadDoubleArray(int cnt);
/// <summary>
/// Internal routine to read double array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Double array</returns>
protected double[] ReadDoubleArray0(int len, byte* data, int cnt)
{
double[] res = new double[len];
if (LittleEndian)
{
fixed (double* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
double val;
byte* valPtr = (byte*)&val;
valPtr[7] = *data++;
valPtr[6] = *data++;
valPtr[5] = *data++;
valPtr[4] = *data++;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write string.
/// </summary>
/// <param name="chars">Characters.</param>
/// <param name="charCnt">Char count.</param>
/// <param name="byteCnt">Byte count.</param>
/// <param name="encoding">Encoding.</param>
/// <returns>
/// Amounts of bytes written.
/// </returns>
public abstract int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding);
/// <summary>
/// Internal string write routine.
/// </summary>
/// <param name="chars">Chars.</param>
/// <param name="charCnt">Chars count.</param>
/// <param name="byteCnt">Bytes count.</param>
/// <param name="enc">Encoding.</param>
/// <param name="data">Data.</param>
/// <returns>Amount of bytes written.</returns>
protected int WriteString0(char* chars, int charCnt, int byteCnt, Encoding enc, byte* data)
{
return enc.GetBytes(chars, charCnt, data, byteCnt);
}
/// <summary>
/// Write arbitrary data.
/// </summary>
/// <param name="src">Source array.</param>
/// <param name="off">Offset</param>
/// <param name="cnt">Count.</param>
public void Write(byte[] src, int off, int cnt)
{
fixed (byte* src0 = src)
{
Write(src0 + off, cnt);
}
}
/// <summary>
/// Read arbitrary data.
/// </summary>
/// <param name="dest">Destination array.</param>
/// <param name="off">Offset.</param>
/// <param name="cnt">Count.</param>
/// <returns>
/// Amount of bytes read.
/// </returns>
public void Read(byte[] dest, int off, int cnt)
{
fixed (byte* dest0 = dest)
{
Read(dest0 + off, cnt);
}
}
/// <summary>
/// Write arbitrary data.
/// </summary>
/// <param name="src">Source.</param>
/// <param name="cnt">Count.</param>
public abstract void Write(byte* src, int cnt);
/// <summary>
/// Internal write routine.
/// </summary>
/// <param name="src">Source.</param>
/// <param name="cnt">Count.</param>
/// <param name="data">Data (dsetination).</param>
protected void WriteInternal(byte* src, int cnt, byte* data)
{
CopyMemory(src, data + Pos, cnt);
}
/// <summary>
/// Read arbitrary data.
/// </summary>
/// <param name="dest">Destination.</param>
/// <param name="cnt">Count.</param>
/// <returns></returns>
public abstract void Read(byte* dest, int cnt);
/// <summary>
/// Internal read routine.
/// </summary>
/// <param name="dest">Destination.</param>
/// <param name="cnt">Count.</param>
/// <param name="data">Data (source).</param>
/// <returns>Amount of bytes written.</returns>
protected void ReadInternal(byte* dest, int cnt, byte* data)
{
int cnt0 = Math.Min(Remaining(), cnt);
CopyMemory(data + Pos, dest, cnt0);
ShiftRead(cnt0);
}
/// <summary>
/// Position.
/// </summary>
public int Position
{
get { return Pos; }
}
/// <summary>
/// Gets remaining bytes in the stream.
/// </summary>
/// <returns>
/// Remaining bytes.
/// </returns>
public abstract int Remaining();
/// <summary>
/// Gets underlying array, avoiding copying if possible.
/// </summary>
/// <returns>
/// Underlying array.
/// </returns>
public abstract byte[] Array();
/// <summary>
/// Gets underlying data in a new array.
/// </summary>
/// <returns>
/// New array with data.
/// </returns>
public abstract byte[] ArrayCopy();
/// <summary>
/// Check whether array passed as argument is the same as the stream hosts.
/// </summary>
/// <param name="arr">Array.</param>
/// <returns>
/// <c>True</c> if they are same.
/// </returns>
public virtual bool IsSameArray(byte[] arr)
{
return false;
}
/// <summary>
/// Seek to the given positoin.
/// </summary>
/// <param name="offset">Offset.</param>
/// <param name="origin">Seek origin.</param>
/// <returns>
/// Position.
/// </returns>
/// <exception cref="System.ArgumentException">
/// Unsupported seek origin: + origin
/// or
/// Seek before origin: + newPos
/// </exception>
public int Seek(int offset, SeekOrigin origin)
{
int newPos;
switch (origin)
{
case SeekOrigin.Begin:
{
newPos = offset;
break;
}
case SeekOrigin.Current:
{
newPos = Pos + offset;
break;
}
default:
throw new ArgumentException("Unsupported seek origin: " + origin);
}
if (newPos < 0)
throw new ArgumentException("Seek before origin: " + newPos);
EnsureWriteCapacity(newPos);
Pos = newPos;
return Pos;
}
/** <inheritdoc /> */
public void Dispose()
{
if (_disposed)
return;
Dispose(true);
GC.SuppressFinalize(this);
_disposed = true;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected abstract void Dispose(bool disposing);
/// <summary>
/// Ensure capacity for write.
/// </summary>
/// <param name="cnt">Bytes count.</param>
protected abstract void EnsureWriteCapacity(int cnt);
/// <summary>
/// Ensure capacity for write and shift position.
/// </summary>
/// <param name="cnt">Bytes count.</param>
/// <returns>Position before shift.</returns>
protected int EnsureWriteCapacityAndShift(int cnt)
{
int pos0 = Pos;
EnsureWriteCapacity(Pos + cnt);
ShiftWrite(cnt);
return pos0;
}
/// <summary>
/// Ensure capacity for read.
/// </summary>
/// <param name="cnt">Bytes count.</param>
protected abstract void EnsureReadCapacity(int cnt);
/// <summary>
/// Ensure capacity for read and shift position.
/// </summary>
/// <param name="cnt">Bytes count.</param>
/// <returns>Position before shift.</returns>
protected int EnsureReadCapacityAndShift(int cnt)
{
int pos0 = Pos;
EnsureReadCapacity(cnt);
ShiftRead(cnt);
return pos0;
}
/// <summary>
/// Shift position due to write
/// </summary>
/// <param name="cnt">Bytes count.</param>
protected void ShiftWrite(int cnt)
{
Pos += cnt;
}
/// <summary>
/// Shift position due to read.
/// </summary>
/// <param name="cnt">Bytes count.</param>
protected void ShiftRead(int cnt)
{
Pos += cnt;
}
/// <summary>
/// Calculate new capacity.
/// </summary>
/// <param name="curCap">Current capacity.</param>
/// <param name="reqCap">Required capacity.</param>
/// <returns>New capacity.</returns>
protected static int Capacity(int curCap, int reqCap)
{
int newCap;
if (reqCap < 256)
newCap = 256;
else
{
newCap = curCap << 1;
if (newCap < reqCap)
newCap = reqCap;
}
return newCap;
}
/// <summary>
/// Unsafe memory copy routine.
/// </summary>
/// <param name="src">Source.</param>
/// <param name="dest">Destination.</param>
/// <param name="len">Length.</param>
public static void CopyMemory(byte* src, byte* dest, int len)
{
if (MemcpyInverted)
Memcpy.Invoke(dest, src, len);
else
Memcpy.Invoke(src, dest, len);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias PDB;
using System;
using System.Collections.Immutable;
using System.Diagnostics.SymbolStore;
using System.IO;
using System.Reflection.Metadata;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.VisualStudio.SymReaderInterop;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal sealed class SymReader : ISymUnmanagedReader
{
private readonly ISymUnmanagedReader _reader;
private readonly ImmutableDictionary<string, byte[]> _constantSignaturesOpt;
internal SymReader(byte[] pdbBytes, ImmutableDictionary<string, byte[]> constantSignaturesOpt = null)
{
_reader = SymUnmanagedReaderExtensions.CreateReader(
new MemoryStream(pdbBytes),
PDB::Roslyn.Test.PdbUtilities.DummyMetadataImport.Instance);
_constantSignaturesOpt = constantSignaturesOpt;
}
public int GetDocuments(int cDocs, out int pcDocs, ISymUnmanagedDocument[] pDocs)
{
throw new NotImplementedException();
}
public int GetMethod(SymbolToken methodToken, out ISymUnmanagedMethod retVal)
{
// The EE should never be calling ISymUnmanagedReader.GetMethod. In order to account
// for EnC updates, it should always be calling GetMethodByVersion instead.
throw ExceptionUtilities.Unreachable;
}
public int GetMethodByVersion(SymbolToken methodToken, int version, out ISymUnmanagedMethod retVal)
{
var hr = _reader.GetMethodByVersion(methodToken, version, out retVal);
if (retVal != null)
{
retVal = new SymMethod(this, retVal);
}
return hr;
}
public int GetSymAttribute(SymbolToken token, string name, int sizeBuffer, out int lengthBuffer, byte[] buffer)
{
return _reader.GetSymAttribute(token, name, sizeBuffer, out lengthBuffer, buffer);
}
public int Initialize(object importer, string filename, string searchPath, IStream stream)
{
throw new NotImplementedException();
}
public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument retVal)
{
throw new NotImplementedException();
}
public int GetDocumentVersion(ISymUnmanagedDocument pDoc, out int version, out bool pbCurrent)
{
throw new NotImplementedException();
}
public int GetGlobalVariables(int cVars, out int pcVars, ISymUnmanagedVariable[] vars)
{
throw new NotImplementedException();
}
public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod retVal)
{
throw new NotImplementedException();
}
public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int cMethod, out int pcMethod, ISymUnmanagedMethod[] pRetVal)
{
throw new NotImplementedException();
}
public int GetMethodVersion(ISymUnmanagedMethod pMethod, out int version)
{
throw new NotImplementedException();
}
public int GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
throw new NotImplementedException();
}
public int GetSymbolStoreFileName(int cchName, out int pcchName, char[] szName)
{
throw new NotImplementedException();
}
public int GetUserEntryPoint(out SymbolToken EntryPoint)
{
throw new NotImplementedException();
}
public int GetVariables(SymbolToken parent, int cVars, out int pcVars, ISymUnmanagedVariable[] vars)
{
throw new NotImplementedException();
}
public int ReplaceSymbolStore(string filename, IStream stream)
{
throw new NotImplementedException();
}
public int UpdateSymbolStore(string filename, IStream stream)
{
throw new NotImplementedException();
}
private sealed class SymMethod : ISymUnmanagedMethod
{
private readonly SymReader _reader;
private readonly ISymUnmanagedMethod _method;
internal SymMethod(SymReader reader, ISymUnmanagedMethod method)
{
_reader = reader;
_method = method;
}
public int GetRootScope(out ISymUnmanagedScope retVal)
{
_method.GetRootScope(out retVal);
if (retVal != null)
{
retVal = new SymScope(_reader, retVal);
}
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal)
{
throw new NotImplementedException();
}
public int GetSequencePointCount(out int retVal)
{
return _method.GetSequencePointCount(out retVal);
}
public int GetToken(out SymbolToken token)
{
throw new NotImplementedException();
}
public int GetNamespace(out ISymUnmanagedNamespace retVal)
{
throw new NotImplementedException();
}
public int GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal)
{
throw new NotImplementedException();
}
public int GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms)
{
throw new NotImplementedException();
}
public int GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges)
{
throw new NotImplementedException();
}
public int GetSequencePoints(
int cPoints,
out int pcPoints,
int[] offsets,
ISymUnmanagedDocument[] documents,
int[] lines,
int[] columns,
int[] endLines,
int[] endColumns)
{
_method.GetSequencePoints(cPoints, out pcPoints, offsets, documents, lines, columns, endLines, endColumns);
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal)
{
throw new NotImplementedException();
}
}
private sealed class SymScope : ISymUnmanagedScope, ISymUnmanagedScope2
{
private readonly SymReader _reader;
private readonly ISymUnmanagedScope _scope;
internal SymScope(SymReader reader, ISymUnmanagedScope scope)
{
_reader = reader;
_scope = scope;
}
public int GetChildren(int cChildren, out int pcChildren, ISymUnmanagedScope[] children)
{
_scope.GetChildren(cChildren, out pcChildren, children);
if (children != null)
{
for (int i = 0; i < pcChildren; i++)
{
children[i] = new SymScope(_reader, children[i]);
}
}
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetConstantCount(out int pRetVal)
{
throw new NotImplementedException();
}
public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants)
{
((ISymUnmanagedScope2)_scope).GetConstants(cConstants, out pcConstants, constants);
if (constants != null)
{
for (int i = 0; i < pcConstants; i++)
{
var c = constants[i];
var signaturesOpt = _reader._constantSignaturesOpt;
byte[] signature = null;
if (signaturesOpt != null)
{
int length;
int hresult = c.GetName(0, out length, null);
SymUnmanagedReaderExtensions.ThrowExceptionForHR(hresult);
var chars = new char[length];
hresult = c.GetName(length, out length, chars);
SymUnmanagedReaderExtensions.ThrowExceptionForHR(hresult);
var name = new string(chars, 0, length - 1);
signaturesOpt.TryGetValue(name, out signature);
}
constants[i] = new SymConstant(c, signature);
}
}
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetEndOffset(out int pRetVal)
{
return _scope.GetEndOffset(out pRetVal);
}
public int GetLocalCount(out int pRetVal)
{
return _scope.GetLocalCount(out pRetVal);
}
public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals)
{
return _scope.GetLocals(cLocals, out pcLocals, locals);
}
public int GetMethod(out ISymUnmanagedMethod pRetVal)
{
throw new NotImplementedException();
}
public int GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces)
{
return _scope.GetNamespaces(cNameSpaces, out pcNameSpaces, namespaces);
}
public int GetParent(out ISymUnmanagedScope pRetVal)
{
throw new NotImplementedException();
}
public int GetStartOffset(out int pRetVal)
{
return _scope.GetStartOffset(out pRetVal);
}
public void _VtblGap1_9()
{
throw new NotImplementedException();
}
}
private sealed class SymConstant : ISymUnmanagedConstant
{
private readonly ISymUnmanagedConstant _constant;
private readonly byte[] _signatureOpt;
internal SymConstant(ISymUnmanagedConstant constant, byte[] signatureOpt)
{
_constant = constant;
_signatureOpt = signatureOpt;
}
public int GetName(int cchName, out int pcchName, char[] name)
{
return _constant.GetName(cchName, out pcchName, name);
}
public int GetSignature(int cSig, out int pcSig, byte[] sig)
{
if (_signatureOpt == null)
{
pcSig = 1;
if (sig != null)
{
object value;
_constant.GetValue(out value);
sig[0] = (byte)GetSignatureTypeCode(value);
}
}
else
{
pcSig = _signatureOpt.Length;
if (sig != null)
{
Array.Copy(_signatureOpt, sig, cSig);
}
}
return SymUnmanagedReaderExtensions.S_OK;
}
public int GetValue(out object value)
{
return _constant.GetValue(out value);
}
private static SignatureTypeCode GetSignatureTypeCode(object value)
{
if (value == null)
{
// Note: We never reach here since PdbWriter uses
// (int)0 for (object)null. This is just an issue with
// this implementation of GetSignature however.
return SignatureTypeCode.Object;
}
var typeCode = Type.GetTypeCode(value.GetType());
switch (typeCode)
{
case TypeCode.Int32:
return SignatureTypeCode.Int32;
case TypeCode.String:
return SignatureTypeCode.String;
case TypeCode.Double:
return SignatureTypeCode.Double;
default:
// Only a few TypeCodes handled currently.
throw new NotImplementedException();
}
}
}
}
}
| |
// Copyright (c) 2013, SIL International.
// Distributable under the terms of the MIT license (http://opensource.org/licenses/MIT).
#if __MonoCS__
using System;
using System.Windows.Forms;
using IBusDotNet;
namespace SIL.Windows.Forms.Keyboarding.Linux
{
/// <summary>Normal implementation of IIbusCommunicator</summary>
internal class IbusCommunicator : IIbusCommunicator
{
// see https://github.com/ibus/ibus/blob/1.4.y/src/ibustypes.h for ibus modifier values
private enum IbusModifiers
{
Shift = 1 << 0,
ShiftLock = 1 << 1,
Control = 1 << 2,
}
#region protected fields
/// <summary>
/// stores Dbus Connection to ibus
/// </summary>
protected IBusConnection m_connection;
/// <summary>
/// the input Context created
/// </summary>
protected IInputContext m_inputContext;
/// <summary>
/// Ibus helper class
/// </summary>
protected InputBus m_ibus;
#endregion
/// <summary>
/// Create a Connection to Ibus. If successfull Connected property is true.
/// </summary>
public IbusCommunicator()
{
m_connection = IBusConnectionFactory.Create();
if (m_connection == null)
return;
// Prevent hanging on exit issues caused by missing dispose calls, or strange interaction
// between ComObjects and managed object.
Application.ThreadExit += (sender, args) =>
{
if (m_connection != null)
m_connection.Dispose();
m_connection = null;
};
m_ibus = new InputBus(m_connection);
}
#region Disposable stuff
#if DEBUG
/// <summary/>
~IbusCommunicator()
{
Dispose(false);
}
#endif
/// <summary/>
public bool IsDisposed
{
get;
private set;
}
/// <summary/>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary/>
protected virtual void Dispose(bool fDisposing)
{
System.Diagnostics.Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + ". *******");
if (fDisposing && !IsDisposed)
{
// dispose managed and unmanaged objects
if (m_connection != null)
m_connection.Dispose();
}
m_connection = null;
IsDisposed = true;
}
#endregion
/// <summary>
/// Wrap an ibus with protection incase DBus connection is dropped.
/// </summary>
protected void ProtectedIBusInvoke(Action action)
{
try
{
action();
}
catch (NDesk.DBus.DBusConectionErrorException)
{
m_ibus = null;
m_inputContext = null;
NotifyUserOfIBusConnectionDropped();
}
catch (System.NullReferenceException)
{
}
}
/// <summary>
/// Inform users of IBus problem.
/// </summary>
protected void NotifyUserOfIBusConnectionDropped()
{
MessageBox.Show(Form.ActiveForm, "Please restart IBus and the application.", "IBus connection has stopped.");
}
private int ConvertToIbusModifiers(Keys modifierKeys, char charUserTyped)
{
int ibusModifiers = 0;
if ((modifierKeys & Keys.Shift) != 0)
ibusModifiers |= (int)IbusModifiers.Shift;
if ((modifierKeys & Keys.Control) != 0)
ibusModifiers |= (int)IbusModifiers.Control;
// modifierKeys don't contain CapsLock and Control.IsKeyLocked(Keys.CapsLock)
// doesn't work on mono. So we guess the caps state by unicode value and the shift
// state. This is far from ideal.
if ((char.IsUpper(charUserTyped) && (modifierKeys & Keys.Shift) == 0) ||
(char.IsLower(charUserTyped) && (modifierKeys & Keys.Shift) != 0))
ibusModifiers |= (int)IbusModifiers.ShiftLock;
return ibusModifiers;
}
#region IIBusCommunicator Implementation
/// <summary>
/// Returns true if we have a connection to Ibus.
/// </summary>
public bool Connected
{
get { return m_connection != null; }
}
/// <summary>
/// Gets the connection to IBus.
/// </summary>
public IBusConnection Connection
{
get { return m_connection; }
}
/// <summary>
/// If we have a valid inputContext Focus it. Also set the GlobalCachedInputContext.
/// </summary>
public void FocusIn()
{
if (InputContext == null)
return;
ProtectedIBusInvoke(() => m_inputContext.FocusIn());
// For performance reasons we store the active inputContext
GlobalCachedInputContext.InputContext = m_inputContext;
}
/// <summary>
/// If we have a valid inputContext call FocusOut ibus method.
/// </summary>
public void FocusOut()
{
if (m_inputContext == null)
return;
ProtectedIBusInvoke(() => m_inputContext.FocusOut());
GlobalCachedInputContext.Clear();
}
/// <summary>
/// Tells IBus the location and height of the selection
/// </summary>
public void NotifySelectionLocationAndHeight(int x, int y, int height)
{
if (m_inputContext == null)
return;
ProtectedIBusInvoke(() => m_inputContext.SetCursorLocation(x, y, 0, height));
}
/// <summary>
/// Sends a key Event to the ibus current input context. This method will be called by
/// the IbusKeyboardAdapter on some KeyDown and all KeyPress events.
/// </summary>
/// <param name="keySym">The X11 key symbol (for special keys) or the key code</param>
/// <param name="scanCode">The X11 scan code</param>
/// <param name="state">The modifier state, i.e. shift key etc.</param>
/// <returns><c>true</c> if the key event is handled by ibus.</returns>
/// <seealso cref="IBusKeyboardAdaptor.HandleKeyPress"/>
public bool ProcessKeyEvent(int keySym, int scanCode, Keys state)
{
if (m_inputContext == null)
return false;
try
{
// m_inputContext.IsEnabled() is no longer contained in IBus 1.5. However,
// ibusdotnet >= 1.9.1 deals with that and always returns true so that we still
// can use this method.
if (!m_inputContext.IsEnabled())
return false;
var modifiers = ConvertToIbusModifiers(state, (char)keySym);
return m_inputContext.ProcessKeyEvent(keySym, scanCode, modifiers);
}
catch (NDesk.DBus.DBusConectionErrorException e)
{
Console.WriteLine("IbusCommunicator.ProcessKeyEvent({0},{1},{2}): caught DBusConectionErrorException: {3}", keySym, scanCode, state, e);
m_ibus = null;
m_inputContext = null;
NotifyUserOfIBusConnectionDropped();
}
catch (System.NullReferenceException e)
{
Console.WriteLine("IbusCommunicator.ProcessKeyEvent({0},{1},{2}): caught NullReferenceException: {3}", keySym, scanCode, state, e);
}
return false;
}
/// <summary>
/// Reset the Current ibus inputContext.
/// </summary>
public void Reset()
{
if (m_inputContext == null)
return;
ProtectedIBusInvoke(m_inputContext.Reset);
}
private bool m_contextCreated;
/// <summary>
/// Create an input context and setup callback handlers.
/// </summary>
public void CreateInputContext()
{
System.Diagnostics.Debug.Assert(!m_contextCreated);
if (m_ibus == null)
{
// This seems to be needed for tests on TeamCity.
// It also seems that it shouldn't be necessary to run IBus to use Linux keyboarding!
return;
}
// A previous version of this code that seems to have worked on Saucy had the following
// comment: "For IBus 1.5, we must use the current InputContext because there is no
// way to enable one we create ourselves. (InputContext.Enable() has turned
// into a no-op.) For IBus 1.4, we must create one ourselves because
// m_ibus.CurrentInputContext() throws an exception."
// However as of 2015-08-11 this no longer seems to be true: when we use the existing
// input context then typing with an IPA KMFL keyboard doesn't work in the
// SIL.Windows.Forms.TestApp on Trusty with unity desktop although the keyboard
// indicator correctly shows the IPA keyboard. I don't know what changed or why it is
// suddenly behaving differently.
//
// if (KeyboardController.CombinedKeyboardHandling)
// {
// var path = m_ibus.CurrentInputContext();
// m_inputContext = new InputContext(m_connection, path);
// }
// else
m_inputContext = m_ibus.CreateInputContext("IbusCommunicator");
AttachContextMethods(m_inputContext);
m_contextCreated = true;
}
private void AttachContextMethods(IInputContext context)
{
ProtectedIBusInvoke(() =>
{
context.SetCapabilities(Capabilities.Focus | Capabilities.PreeditText | Capabilities.SurroundingText);
context.CommitText += OnCommitText;
context.UpdatePreeditText += OnUpdatePreeditText;
context.HidePreeditText += OnHidePreeditText;
context.ForwardKeyEvent += OnKeyEvent;
context.DeleteSurroundingText += OnDeleteSurroundingText;
context.Enable(); // not needed for IBus 1.5, but doesn't hurt.
});
}
/// <summary>
/// Get the ibus input context, creating it if necessary.
/// </summary>
/// <remarks>
/// This must be called after the KeyboardController.CombinedKeyboardHandling has been set.
/// </remarks>
protected IInputContext InputContext
{
get
{
if (m_inputContext != null)
return m_inputContext;
if (m_contextCreated || !Connected)
return null; // we must have had an error that cleared m_inputContext
CreateInputContext();
return m_inputContext;
}
}
/// <summary>
/// Return the DBUS 'path' name for the currently focused InputContext
/// </summary>
/// <exception cref="System.Exception">Throws: System.Exception with message
/// 'org.freedesktop.DBus.Error.Failed: No input context focused' if nothing is currently
/// focused.</exception>
public string GetFocusedInputContext()
{
return m_ibus.CurrentInputContext();
}
/// <summary></summary>
public event Action<object> CommitText;
/// <summary></summary>
public event Action<object, int> UpdatePreeditText;
/// <summary></summary>
public event Action<int, int> DeleteSurroundingText;
/// <summary></summary>
public event Action HidePreeditText;
/// <summary></summary>
public event Action<int, int, int> KeyEvent;
#endregion
#region private methods
private void OnCommitText(object text)
{
if (CommitText != null)
{
CommitText(IBusText.FromObject(text));
}
}
private void OnUpdatePreeditText(object text, uint cursor_pos, bool visible)
{
if (UpdatePreeditText != null && visible)
{
UpdatePreeditText(IBusText.FromObject(text), (int)cursor_pos);
}
}
private void OnDeleteSurroundingText(int offset, uint nChars)
{
if (DeleteSurroundingText != null)
DeleteSurroundingText(offset, (int)nChars);
}
private void OnHidePreeditText()
{
if (HidePreeditText != null)
HidePreeditText();
}
private void OnKeyEvent(uint keyval, uint keycode, uint modifiers)
{
if (KeyEvent != null)
KeyEvent((int)keyval, (int)keycode, (int)modifiers);
}
#endregion
}
}
#endif
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const bool CheckOperationsRequiresSetHandle = true;
private ThreadPoolBoundHandle _threadPoolBinding;
internal static string GetPipePath(string serverName, string pipeName)
{
string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (String.Equals(normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException("pipeName", SR.ArgumentOutOfRange_AnonymousReserved);
}
return normalizedPipePath;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
// Check that this handle is infact a handle to a pipe.
if (Interop.mincore.GetFileType(safePipeHandle) != Interop.mincore.FileTypes.FILE_TYPE_PIPE)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// If the handle is of async type, bind the handle to the ThreadPool so that we can use
// the async operations (it's needed so that our native callbacks get called).
_threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle);
}
private void UninitializeAsyncHandle()
{
if (_threadPoolBinding != null)
_threadPoolBinding.Dispose();
}
[SecurityCritical]
private unsafe int ReadCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginReadCore(buffer, offset, count, null, null);
return EndRead(result);
}
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
// If the other side has broken the connection, set state to Broken and return 0
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
r = 0;
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty);
}
}
_isMessageComplete = (errorCode != Interop.mincore.Errors.ERROR_MORE_DATA);
Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");
return r;
}
[SecuritySafeCritical]
private Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync<int>(BeginRead, EndRead, state);
}
[SecurityCritical]
private unsafe void WriteCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginWriteCore(buffer, offset, count, null, null);
EndWrite(result);
return;
}
int errorCode = 0;
int r = WriteFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
WinIOError(errorCode);
}
Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
return;
}
[SecuritySafeCritical]
private Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync(BeginWrite, EndWrite, state);
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
// Block until other end of the pipe has read everything.
if (!Interop.mincore.FlushFileBuffers(_handle))
{
WinIOError(Marshal.GetLastWin32Error());
}
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (_isFromExistingHandle)
{
int pipeFlags;
if (!Interop.mincore.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((pipeFlags & Interop.mincore.PipeOptions.PIPE_TYPE_MESSAGE) != 0)
{
return PipeTransmissionMode.Message;
}
else
{
return PipeTransmissionMode.Byte;
}
}
else
{
return _transmissionMode;
}
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
int inBufferSize;
if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
return inBufferSize;
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
int outBufferSize;
// Use cached value if direction is out; otherwise get fresh version
if (_pipeDirection == PipeDirection.Out)
{
outBufferSize = _outBufferSize;
}
else if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize,
IntPtr.Zero, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
return outBufferSize;
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
// get fresh value if it could be stale
if (_isFromExistingHandle || IsHandleExposed)
{
UpdateReadMode();
}
return _readMode;
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
// Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream
// and the AnonymousPipeStreams override this.
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
unsafe
{
int pipeReadType = (int)value << 1;
if (!Interop.mincore.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
else
{
_readMode = value;
}
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private class ReadWriteAsyncParams
{
public ReadWriteAsyncParams() { }
public ReadWriteAsyncParams(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
this.Buffer = buffer;
this.Offset = offset;
this.Count = count;
this.CancellationHelper = cancellationToken.CanBeCanceled ? new IOCancellationHelper(cancellationToken) : null;
}
public byte[] Buffer { get; set; }
public int Offset { get; set; }
public int Count { get; set; }
public IOCancellationHelper CancellationHelper { get; private set; }
}
[SecurityCritical]
private unsafe static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(PipeStream.AsyncPSCallback);
[SecurityCritical]
private IAsyncResult BeginWrite(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
CheckWriteOperations();
if (!_isAsync)
{
return _streamAsyncHelper.BeginWrite(buffer, offset, count, callback, state);
}
else
{
return BeginWriteCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginWriteCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginWriteCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = true;
asyncResult._handle = _handle;
// fixed doesn't work well with zero length arrays. Set the zero-byte flag in case
// caller needs to do any cleanup
if (buffer.Length == 0)
{
//intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using the managed
// Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
NativeOverlapped* intOverlapped = _threadPoolBinding.AllocateNativeOverlapped(s_IOCallback, asyncResult, buffer);
asyncResult._overlapped = intOverlapped;
int errorCode = 0;
// Queue an async WriteFile operation and pass in a packed overlapped
int r = WriteFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
// wrapper returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer written back from this
// call when using overlapped structures! You must not pass in a non-null
// lpNumBytesWritten to WriteFile when using overlapped structures! This is by design
// NT behavior.
if (r == -1 && errorCode != Interop.mincore.Errors.ERROR_IO_PENDING)
{
// Clean up
if (intOverlapped != null) _threadPoolBinding.FreeNativeOverlapped(intOverlapped);
WinIOError(errorCode);
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
_streamAsyncHelper.EndWrite(asyncResult);
return;
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || !afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice. --
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndWriteCalledTwice();
}
ReadWriteAsyncParams readWriteParams = afsar.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
cancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true, "PipeStream::EndWrite - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
_threadPoolBinding.FreeNativeOverlapped(overlappedPtr);
}
// Now check for any error during the write.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// Number of buffer written is afsar._numBytes.
return;
}
[SecurityCritical]
private unsafe int ReadFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesRead = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginReadCore won't return an
// IAsyncResult that will cause EndRead to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
// In message mode, the ReadFile can inform us that there is more data to come.
if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA)
{
return numBytesRead;
}
return -1;
}
else
{
errorCode = 0;
}
return numBytesRead;
}
[SecurityCritical]
private unsafe int WriteFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int numBytesWritten = 0;
int r = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginWriteCore won't return an
// IAsyncResult that will cause EndWrite to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
return -1;
}
else
{
errorCode = 0;
}
return numBytesWritten;
}
[SecurityCritical]
private IAsyncResult BeginRead(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanRead)
{
throw __Error.GetReadNotSupported();
}
CheckReadOperations();
if (!_isAsync)
{
// special case when this is called for sync broken pipes because otherwise Stream's
// Begin/EndRead hang. Reads return 0 bytes in this case so we can call the user's
// callback immediately
if (_state == PipeState.Broken)
{
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
asyncResult.CallUserCallback();
return asyncResult;
}
else
{
return _streamAsyncHelper.BeginRead(buffer, offset, count, callback, state);
}
}
else
{
return BeginReadCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginReadCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginReadCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
// handle zero-length buffers separately; fixed keyword ReadFileNative doesn't like
// 0-length buffers. Call user callback and we're done
if (buffer.Length == 0)
{
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using
// the managed Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
NativeOverlapped* intOverlapped = _threadPoolBinding.AllocateNativeOverlapped(s_IOCallback, asyncResult, buffer);
asyncResult._overlapped = intOverlapped;
// Queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
// returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer read back from this call
// when using overlapped structures! You must not pass in a non-null lpNumBytesRead to
// ReadFile when using overlapped structures! This is by design NT behavior.
if (r == -1)
{
// One side has closed its handle or server disconnected. Set the state to Broken
// and do some cleanup work
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
// Clear the overlapped status bit for this special case. Failure to do so looks
// like we are freeing a pending overlapped.
intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else if (errorCode != Interop.mincore.Errors.ERROR_IO_PENDING)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe int EndRead(IAsyncResult asyncResult)
{
// There are 3 significantly different IAsyncResults we'll accept
// here. One is from Stream::BeginRead. The other two are variations
// on our PipeStreamAsyncResult. One is from BeginReadCore,
// while the other is from the BeginRead buffering wrapper.
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
return _streamAsyncHelper.EndRead(asyncResult);
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice.
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndReadCalledTwice();
}
ReadWriteAsyncParams readWriteParams = asyncResult.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
readWriteParams.CancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true,
"FileStream::EndRead - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
_threadPoolBinding.FreeNativeOverlapped(overlappedPtr);
}
// Now check for any error during the read.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// set message complete to true if the pipe is broken as well; need this to signal to readers
// to stop reading
_isMessageComplete = _state == PipeState.Broken ||
afsar._isMessageComplete;
return afsar._numBytes;
}
[SecurityCritical]
internal static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)Marshal.SizeOf(secAttrs);
secAttrs.bInheritHandle = true;
}
return secAttrs;
}
// When doing IO asynchronously (i.e., _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
[SecurityCritical]
unsafe private static void AsyncPSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Extract async result from overlapped
PipeStreamAsyncResult asyncResult = (PipeStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
asyncResult._numBytes = (int)numBytes;
// Allow async read to finish
if (!asyncResult._isWrite)
{
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.mincore.Errors.ERROR_NO_DATA)
{
errorCode = 0;
numBytes = 0;
}
}
// For message type buffer.
if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA)
{
errorCode = 0;
asyncResult._isMessageComplete = false;
}
else
{
asyncResult._isMessageComplete = true;
}
asyncResult._errorCode = (int)errorCode;
// Call the user-provided callback. It can and often should
// call EndRead or EndWrite. There's no reason to use an async
// delegate here - we're already on a threadpool thread.
// IAsyncResult's completedSynchronously property must return
// false here, saying the user callback was called on another thread.
asyncResult._completedSynchronously = false;
asyncResult._isComplete = true;
// The OS does not signal this event. We must do it ourselves.
ManualResetEvent wh = asyncResult._waitHandle;
if (wh != null)
{
Debug.Assert(!wh.GetSafeWaitHandle().IsClosed, "ManualResetEvent already closed!");
bool r = wh.Set();
Debug.Assert(r, "ManualResetEvent::Set failed!");
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
AsyncCallback callback = asyncResult._userCallback;
if (callback != null)
{
callback(asyncResult);
}
}
/// <summary>
/// Determine pipe read mode from Win32
/// </summary>
[SecurityCritical]
private void UpdateReadMode()
{
int flags;
if (!Interop.mincore.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero, 0))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((flags & Interop.mincore.PipeOptions.PIPE_READMODE_MESSAGE) != 0)
{
_readMode = PipeTransmissionMode.Message;
}
else
{
_readMode = PipeTransmissionMode.Byte;
}
}
/// <summary>
/// Filter out all pipe related errors and do some cleanup before calling __Error.WinIOError.
/// </summary>
/// <param name="errorCode"></param>
[SecurityCritical]
internal void WinIOError(int errorCode)
{
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.mincore.Errors.ERROR_NO_DATA
)
{
// Other side has broken the connection
_state = PipeState.Broken;
throw new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));
}
else if (errorCode == Interop.mincore.Errors.ERROR_HANDLE_EOF)
{
throw __Error.GetEndOfFile();
}
else
{
// For invalid handles, detect the error and mark our handle
// as invalid to give slightly better error messages. Also
// help ensure we avoid handle recycling bugs.
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_HANDLE)
{
_handle.SetHandleAsInvalid();
_state = PipeState.Broken;
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
}
| |
namespace Nancy.Diagnostics
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.Cookies;
using Nancy.Cryptography;
using Nancy.Culture;
using Nancy.Localization;
using Nancy.ModelBinding;
using Nancy.Responses;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Routing.Constraints;
using Nancy.Routing.Trie;
public static class DiagnosticsHook
{
private static readonly CancellationToken CancellationToken = new CancellationToken();
private const string PipelineKey = "__Diagnostics";
internal const string ItemsKey = "DIAGS_REQUEST";
public static void Enable(IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable<IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment)
{
var diagnosticsConfiguration =
environment.GetValue<DiagnosticsConfiguration>();
var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration);
var diagnosticsRouteCache = new RouteCache(
diagnosticsModuleCatalog,
new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource),
new DefaultRouteSegmentExtractor(),
new DefaultRouteDescriptionProvider(),
cultureService,
routeMetadataProviders);
var diagnosticsRouteResolver = new DefaultRouteResolver(
diagnosticsModuleCatalog,
new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, environment),
diagnosticsRouteCache,
new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)));
var serializer = new DefaultObjectSerializer();
pipelines.BeforeRequest.AddItemToStartOfPipeline(
new PipelineItem<Func<NancyContext, Response>>(
PipelineKey,
ctx =>
{
if (!ctx.ControlPanelEnabled)
{
return null;
}
if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
{
return null;
}
ctx.Items[ItemsKey] = true;
var resourcePrefix =
string.Concat(diagnosticsConfiguration.Path, "/Resources/");
if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
{
var resourceNamespace = "Nancy.Diagnostics.Resources";
var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
if (!string.IsNullOrEmpty(path))
{
resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.'));
}
return new EmbeddedFileResponse(
typeof(DiagnosticsHook).Assembly,
resourceNamespace,
Path.GetFileName(ctx.Request.Url.Path));
}
RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);
return ValidateConfiguration(diagnosticsConfiguration)
? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer)
: GetDiagnosticsHelpView(ctx);
}));
}
private static bool ValidateConfiguration(DiagnosticsConfiguration configuration)
{
return !string.IsNullOrWhiteSpace(configuration.Password) &&
!string.IsNullOrWhiteSpace(configuration.CookieName) &&
!string.IsNullOrWhiteSpace(configuration.Path) &&
configuration.SlidingTimeout != 0;
}
public static void Disable(IPipelines pipelines)
{
pipelines.BeforeRequest.RemoveByName(PipelineKey);
}
private static Response GetDiagnosticsHelpView(NancyContext ctx)
{
return (StaticConfiguration.IsRunningDebug)
? new DiagnosticsViewRenderer(ctx)["help"]
: HttpStatusCode.NotFound;
}
private static Response GetDiagnosticsLoginView(NancyContext ctx)
{
var renderer = new DiagnosticsViewRenderer(ctx);
return renderer["login"];
}
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
var session = GetSession(ctx, diagnosticsConfiguration, serializer);
if (session == null)
{
var view = GetDiagnosticsLoginView(ctx);
view.WithCookie(
new NancyCookie(diagnosticsConfiguration.CookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) });
return view;
}
var resolveResult = routeResolver.Resolve(ctx);
ctx.Parameters = resolveResult.Parameters;
ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before);
if (ctx.Response == null)
{
// Don't care about async here, so just get the result
var task = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken);
task.Wait();
ctx.Response = task.Result;
}
if (ctx.Request.Method.ToUpperInvariant() == "HEAD")
{
ctx.Response = new HeadResponse(ctx.Response);
}
if (resolveResult.After != null)
{
resolveResult.After.Invoke(ctx, CancellationToken);
}
AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer);
return ctx.Response;
}
private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
if (context.Response == null)
{
return;
}
session.Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout);
var serializedSession = serializer.Serialize(session);
var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession);
var hmacBytes = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
var hmacString = Convert.ToBase64String(hmacBytes);
var cookie = new NancyCookie(diagnosticsConfiguration.CookieName, String.Format("{1}{0}", encryptedSession, hmacString), true);
context.Response.WithCookie(cookie);
}
private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
if (context.Request == null)
{
return null;
}
if (IsLoginRequest(context, diagnosticsConfiguration))
{
return ProcessLogin(context, diagnosticsConfiguration, serializer);
}
if (!context.Request.Cookies.ContainsKey(diagnosticsConfiguration.CookieName))
{
return null;
}
var encryptedValue = context.Request.Cookies[diagnosticsConfiguration.CookieName];
var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
var encryptedSession = encryptedValue.Substring(hmacStringLength);
var hmacString = encryptedValue.Substring(0, hmacStringLength);
var hmacBytes = Convert.FromBase64String(hmacString);
var newHmac = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
if (!hmacValid)
{
return null;
}
var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession);
var session = serializer.Deserialize(decryptedValue) as DiagnosticsSession;
if (session == null || session.Expiry < DateTime.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password))
{
return null;
}
return session;
}
private static bool SessionPasswordValid(DiagnosticsSession session, string realPassword)
{
var newHash = DiagnosticsSession.GenerateSaltedHash(realPassword, session.Salt);
return (newHash.Length == session.Hash.Length && newHash.SequenceEqual(session.Hash));
}
private static DiagnosticsSession ProcessLogin(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
string password = context.Request.Form.Password;
if (!string.Equals(password, diagnosticsConfiguration.Password, StringComparison.Ordinal))
{
return null;
}
var salt = DiagnosticsSession.GenerateRandomSalt();
var hash = DiagnosticsSession.GenerateSaltedHash(password, salt);
var session = new DiagnosticsSession
{
Hash = hash,
Salt = salt,
Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout)
};
return session;
}
private static bool IsLoginRequest(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration)
{
return context.Request.Method == "POST" &&
context.Request.Url.BasePath.TrimEnd(new[] { '/' }).EndsWith(diagnosticsConfiguration.Path) &&
context.Request.Url.Path == "/";
}
private static void ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)
{
if (resolveResultPreReq == null)
{
return;
}
var resolveResultPreReqResponse = resolveResultPreReq.Invoke(context, cancellationToken).Result;
if (resolveResultPreReqResponse != null)
{
context.Response = resolveResultPreReqResponse;
}
}
private static void RewriteDiagnosticsUrl(DiagnosticsConfiguration diagnosticsConfiguration, NancyContext ctx)
{
ctx.Request.Url.BasePath =
string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path);
ctx.Request.Url.Path =
ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length);
if (ctx.Request.Url.Path.Length.Equals(0))
{
ctx.Request.Url.Path = "/";
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using Newtonsoft.Json;
using NFluent;
using WireMock.Handlers;
using WireMock.Models;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Xunit;
#if NET452
using Microsoft.Owin;
#else
using Microsoft.AspNetCore.Http;
#endif
namespace WireMock.Net.Tests.ResponseBuilders
{
public class ResponseWithTransformerTests
{
private readonly WireMockServerSettings _settings = new WireMockServerSettings();
private const string ClientIp = "::1";
public ResponseWithTransformerTests()
{
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("abc");
_settings.FileSystemHandler = filesystemHandlerMock.Object;
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithNullBody_ShouldNotThrowException(TransformerType transformerType)
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, "GET", ClientIp);
var responseBuilder = Response.Create().WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
response.Message.BodyData.Should().BeNull();
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_UrlPathVerb(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "whatever",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POSt", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test {{request.Url}} {{request.Path}} {{request.Method}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost/foo /foo POSt");
}
[Theory]
[InlineData(TransformerType.Handlebars, "Get")]
[InlineData(TransformerType.Handlebars, "Post")]
[InlineData(TransformerType.Scriban, "Get")]
[InlineData(TransformerType.Scriban, "Post")]
[InlineData(TransformerType.ScribanDotLiquid, "Get")]
[InlineData(TransformerType.ScribanDotLiquid, "Post")]
public async Task Response_ProvideResponse_Transformer_UrlPath(TransformerType transformerType, string httpMethod)
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, httpMethod, ClientIp);
var responseBuilder = Response.Create()
.WithBody("url={{request.Url}} absoluteurl={{request.AbsoluteUrl}} path={{request.Path}} absolutepath={{request.AbsolutePath}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("url=http://localhost/a/b absoluteurl=http://localhost/wiremock/a/b path=/a/b absolutepath=/wiremock/a/b");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_PathSegments()
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, "POST", ClientIp);
var responseBuilder = Response.Create()
.WithBody("{{request.PathSegments.[0]}} {{request.AbsolutePathSegments.[0]}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("a wiremock");
}
[Theory(Skip = "Invalid token `OpenBracket`")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_PathSegments(TransformerType transformerType)
{
// Assign
var urlDetails = UrlUtils.Parse(new Uri("http://localhost/wiremock/a/b"), new PathString("/wiremock"));
var request = new RequestMessage(urlDetails, "POST", ClientIp);
var responseBuilder = Response.Create()
.WithBody("{{request.PathSegments.[0]}} {{request.AbsolutePathSegments.[0]}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("a wiremock");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Query()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test keya=1,2 idx=1 idx=2 keyb=5");
}
[Theory(Skip = "Invalid token `OpenBracket`")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_Query(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=1&a=2&b=5"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test keya=1 idx=1 idx=2 keyb=5");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_StatusCode()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=400"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithStatusCode("{{request.query.a}}")
.WithBody("test")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals("400");
}
[Theory(Skip = "WireMockList is not supported by Scriban")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_StatusCode(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=400"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithStatusCode("{{request.Query.a}}")
.WithBody("test")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals("400");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_StatusCodeIsNull(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo?a=400"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.StatusCode).Equals(null);
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Header()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var responseBuilder = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}").WithBody("test").WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).ContainsExactly("text/plain");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_Headers()
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var responseBuilder = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}", "{{request.url}}").WithBody("test").WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).Contains("text/plain");
Check.That(response.Message.Headers["x"]).Contains("http://localhost/foo");
}
[Theory(Skip = "WireMockList is not supported by Scriban")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_Headers(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, body, new Dictionary<string, string[]> { { "Content-Type", new[] { "text/plain" } } });
var responseBuilder = Response.Create().WithHeader("x", "{{request.Headers[\"Content-Type\"]}}", "{{request.Url}}").WithBody("test").WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test");
Check.That(response.Message.Headers).ContainsKey("x");
Check.That(response.Message.Headers["x"]).Contains("text/plain");
Check.That(response.Message.Headers["x"]).Contains("http://localhost/foo");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_Origin_Port_Protocol_Host(TransformerType transformerType)
{
// Assign
var body = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String
};
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "POST", ClientIp, body);
var responseBuilder = Response.Create()
.WithBody("test {{request.Origin}} {{request.Port}} {{request.Protocol}} {{request.Host}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsString).Equals("test http://localhost:1234 1234 http localhost");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsObject(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"WireMock\" } ] }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new { x = "test {{request.Path}}" })
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}");
}
//[Theory]
//[InlineData(TransformerType.Handlebars, "a")]
//[InlineData(TransformerType.Handlebars, "42")]
//[InlineData(TransformerType.Handlebars, "{")]
//[InlineData(TransformerType.Handlebars, "]")]
//[InlineData(TransformerType.Handlebars, " ")]
//public async Task Response_ProvideResponse_Transformer_WithBodyAsJsonWithExtraQuotes_AndSpecialOption_MakesAString_ResultAsObject(TransformerType transformerType, string text)
//{
// string jsonString = $"{{ \"x\": \"{text}\" }}";
// var bodyData = new BodyData
// {
// BodyAsJson = JsonConvert.DeserializeObject(jsonString),
// DetectedBodyType = BodyType.Json,
// Encoding = Encoding.UTF8
// };
// var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
// var responseBuilder = Response.Create()
// .WithBodyAsJson(new { text = "\"{{request.bodyAsJson.x}}\"" })
// .WithTransformer(transformerType, false, ReplaceNodeOptions.Default);
// // Act
// var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// // Assert
// JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be($"{{\"text\":\"{text}\"}}");
//}
[Theory]
[InlineData(TransformerType.Handlebars, "\"\"", "\"\"")]
[InlineData(TransformerType.Handlebars, "\"a\"", "\"a\"")]
[InlineData(TransformerType.Handlebars, "\" \"", "\" \"")]
[InlineData(TransformerType.Handlebars, "\"'\"", "\"'\"")]
[InlineData(TransformerType.Handlebars, "\"false\"", "false")] // bool is special
[InlineData(TransformerType.Handlebars, "false", "false")]
[InlineData(TransformerType.Handlebars, "\"true\"", "true")] // bool is special
[InlineData(TransformerType.Handlebars, "true", "true")]
[InlineData(TransformerType.Handlebars, "\"-42\"", "-42")] // todo
[InlineData(TransformerType.Handlebars, "-42", "-42")]
[InlineData(TransformerType.Handlebars, "\"2147483647\"", "2147483647")] // todo
[InlineData(TransformerType.Handlebars, "2147483647", "2147483647")]
[InlineData(TransformerType.Handlebars, "\"9223372036854775807\"", "9223372036854775807")] // todo
[InlineData(TransformerType.Handlebars, "9223372036854775807", "9223372036854775807")]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_And_ReplaceNodeOptionsKeep(TransformerType transformerType, string value, string expected)
{
string jsonString = $"{{ \"x\": {value} }}";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new { text = "{{request.bodyAsJson.x}}" })
.WithTransformer(transformerType, false, ReplaceNodeOptions.None);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be($"{{\"text\":{expected}}}");
}
[Theory]
[InlineData(TransformerType.Handlebars, "\"\"", "\"\"")]
[InlineData(TransformerType.Handlebars, "\"a\"", "\"a\"")]
[InlineData(TransformerType.Handlebars, "\" \"", "\" \"")]
[InlineData(TransformerType.Handlebars, "\"'\"", "\"'\"")]
[InlineData(TransformerType.Handlebars, "\"false\"", "false")] // bool is special
[InlineData(TransformerType.Handlebars, "false", "false")]
[InlineData(TransformerType.Handlebars, "\"true\"", "true")] // bool is special
[InlineData(TransformerType.Handlebars, "true", "true")]
[InlineData(TransformerType.Handlebars, "\"-42\"", "\"-42\"")]
[InlineData(TransformerType.Handlebars, "-42", "\"-42\"")]
[InlineData(TransformerType.Handlebars, "\"2147483647\"", "\"2147483647\"")]
[InlineData(TransformerType.Handlebars, "2147483647", "\"2147483647\"")]
[InlineData(TransformerType.Handlebars, "\"9223372036854775807\"", "\"9223372036854775807\"")]
[InlineData(TransformerType.Handlebars, "9223372036854775807", "\"9223372036854775807\"")]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJsonWithExtraQuotes_AlwaysMakesString(TransformerType transformerType, string value, string expected)
{
string jsonString = $"{{ \"x\": {value} }}";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new { text = "\"{{request.bodyAsJson.x}}\"" })
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson).Should().Be($"{{\"text\":{expected}}}");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
//[InlineData(TransformerType.Scriban)] Scriban cannot access dynamic Json Objects
//[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsArray(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"a\": \"test 1\", \"b\": \"test 2\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_array"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson(new[] { "first", "{{request.path}}", "{{request.bodyAsJson.a}}", "{{request.bodyAsJson.b}}", "last" })
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("[\"first\",\"/foo_array\",\"test 1\",\"test 2\",\"last\"]");
}
[Fact]
public async Task Response_ProvideResponse_Handlebars_WithBodyAsFile()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithTransformer()
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
}
[Theory(Skip = @"Does not work in Scriban --> c:\\[""1""]\\test.xml")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_WithBodyAsFile(TransformerType transformerType)
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithTransformer(transformerType)
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
//[InlineData(TransformerType.Scriban)] ["c:\\["1"]\\test.xml"]
//[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsFile_And_TransformContentFromBodyAsFile(TransformerType transformerType)
{
// Assign
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
filesystemHandlerMock.Setup(fs => fs.ReadResponseBodyAsString(It.IsAny<string>())).Returns("<xml MyUniqueNumber=\"{{request.query.MyUniqueNumber}}\"></xml>");
_settings.FileSystemHandler = filesystemHandlerMock.Object;
var request = new RequestMessage(new UrlDetails("http://localhost/foo?MyUniqueNumber=1"), "GET", ClientIp);
var responseBuilder = Response.Create()
.WithTransformer(transformerType, true)
.WithBodyFromFile(@"c:\\{{request.query.MyUniqueNumber}}\\test.xml");
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(response.Message.BodyData.BodyAsFile).Equals(@"c:\1\test.xml");
Check.That(response.Message.BodyData.DetectedBodyType).Equals(BodyType.String);
Check.That(response.Message.BodyData.BodyAsString).Equals("<xml MyUniqueNumber=\"1\"></xml>");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsJson_ResultAsNormalString(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"name\": \"WireMock\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson("test")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("\"test\"");
}
[Fact(Skip = "todo...")]
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsTemplatedString()
{
// Assign
string jsonString = "{ \"name\": \"WireMock\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson("{{{request.BodyAsJson}}}")
.WithTransformer();
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("{\"name\":\"WireMock\"}");
}
[Theory(Skip = "{{{ }}} Does not work in Scriban")]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Scriban_WithBodyAsJson_ResultAsTemplatedString(TransformerType transformerType)
{
// Assign
string jsonString = "{ \"name\": \"WireMock\" }";
var bodyData = new BodyData
{
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
DetectedBodyType = BodyType.Json,
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBodyAsJson("{{{request.BodyAsJson}}}")
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
Check.That(JsonConvert.SerializeObject(response.Message.BodyData.BodyAsJson)).Equals("{\"name\":\"WireMock\"}");
}
[Theory]
[InlineData(TransformerType.Handlebars)]
[InlineData(TransformerType.Scriban)]
[InlineData(TransformerType.ScribanDotLiquid)]
public async Task Response_ProvideResponse_Transformer_WithBodyAsString_KeepsEncoding(TransformerType transformerType)
{
// Assign
const string text = "my-text";
Encoding enc = Encoding.Unicode;
var bodyData = new BodyData
{
BodyAsString = text,
DetectedBodyType = BodyType.String,
Encoding = enc
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var responseBuilder = Response.Create()
.WithBody("{{request.Body}}", BodyDestinationFormat.SameAsSource, enc)
.WithTransformer(transformerType);
// Act
var response = await responseBuilder.ProvideResponseAsync(request, _settings).ConfigureAwait(false);
// Assert
response.Message.BodyData.BodyAsString.Should().Be(text);
response.Message.BodyData.Encoding.Should().Be(enc);
}
}
}
| |
/*
* MinIO .NET Library for Amazon S3 Compatible Cloud Storage,
* (C) 2017-2021 MinIO, 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.IO;
using System.Threading;
using System.Threading.Tasks;
using Minio.DataModel;
using Minio.DataModel.Tags;
using Minio.DataModel.ObjectLock;
using Minio.Exceptions;
namespace Minio
{
public interface IObjectOperations
{
/// <summary>
/// Get the configuration object for Legal Hold Status
/// </summary>
/// <param name="args">GetObjectLegalHoldArgs Arguments Object which has object identifier information - bucket name, object name, version ID</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation </param>
/// <returns> True if Legal Hold is ON, false otherwise </returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MissingObjectLockConfigurationException">When object lock configuration on bucket is not set</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task<bool> GetObjectLegalHoldAsync(GetObjectLegalHoldArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Set the configuration for Legal Hold Status
/// </summary>
/// <param name="args">SetObjectLegalHoldArgs Arguments Object which has object identifier information - bucket name, object name, version ID and the status (ON/OFF) of legal-hold</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation </param>
/// <returns> Task </returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MissingObjectLockConfigurationException">When object lock configuration on bucket is not set</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task SetObjectLegalHoldAsync(SetObjectLegalHoldArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Set the Retention using the configuration object
/// </summary>
/// <param name="args">SetObjectRetentionArgs Arguments Object which has object identifier information - bucket name, object name, version ID</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns> Task </returns>
/// <exception cref="AuthorizationException">When access or secret key provided is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MissingObjectLockConfigurationException">When object lock configuration on bucket is not set</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task SetObjectRetentionAsync(SetObjectRetentionArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the Retention configuration for the object
/// </summary>
/// <param name="args">GetObjectRetentionArgs Arguments Object which has object identifier information - bucket name, object name, version ID</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns> ObjectRetentionConfiguration object which contains the Retention configuration </returns>
/// <exception cref="AuthorizationException">When access or secret key provided is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="MissingObjectLockConfigurationException">When object lock configuration on bucket is not set</exception>
Task<ObjectRetentionConfiguration> GetObjectRetentionAsync(GetObjectRetentionArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Clears the Retention configuration for the object
/// </summary>
/// <param name="args">ClearObjectRetentionArgs Arguments Object which has object identifier information - bucket name, object name, version ID</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns> Task </returns>
/// <exception cref="AuthorizationException">When access or secret key provided is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MissingObjectLockConfigurationException">When object lock configuration on bucket is not set</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task ClearObjectRetentionAsync(ClearObjectRetentionArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes an object with given name in specific bucket
/// </summary>
/// <param name="args">RemoveObjectArgs Arguments Object encapsulates information like - bucket name, object name, whether delete all versions</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
/// <exception cref="AuthorizationException">When access or secret key provided is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
Task RemoveObjectAsync(RemoveObjectArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes list of objects from bucket
/// </summary>
/// <param name="args">RemoveObjectsArgs Arguments Object encapsulates information like - bucket name, List of objects, optional list of versions (for each object) to be deleted</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>Observable that returns delete error while deleting objects if any</returns>
/// <exception cref="AuthorizationException">When access or secret key provided is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
Task<IObservable<DeleteError>> RemoveObjectsAsync(RemoveObjectsArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Copy a source object into a new destination object.
/// </summary>
/// <param name="args">CopyObjectArgs Arguments Object which encapsulates bucket name, object name, destination bucket, destination object names, Copy conditions object, metadata, SSE source, destination objects</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="AccessDeniedException">For encrypted copy operation, Access is denied if the key is wrong</exception>
Task CopyObjectAsync(CopyObjectArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get an object. The object will be streamed to the callback given by the user.
/// </summary>
/// <param name="args">GetObjectArgs Arguments Object encapsulates information like - bucket name, object name, server-side encryption object, action stream, length, offset</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="DirectoryNotFoundException">If the directory to copy to is not found</exception>
Task<ObjectStat> GetObjectAsync(GetObjectArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates object in a bucket fom input stream or filename.
/// </summary>
/// <param name="args">PutObjectArgs Arguments object encapsulating bucket name, object name, file name, object data stream, object size, content type.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="FileNotFoundException">If the file to copy from not found</exception>
/// <exception cref="ObjectDisposedException">The file stream has been disposed</exception>
/// <exception cref="NotSupportedException">The file stream cannot be read from</exception>
/// <exception cref="InvalidOperationException">The file stream is currently in a read operation</exception>
/// <exception cref="AccessDeniedException">For encrypted PUT operation, Access is denied if the key is wrong</exception>
Task PutObjectAsync(PutObjectArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Select an object's content. The object will be streamed to the callback given by the user.
/// </summary>
/// <param name="args">SelectObjectContentArgs Arguments Object which encapsulates bucket name, object name, Select Object Options</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <exception cref="AuthorizationException">When access or secret key provided is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
Task<SelectResponseStream> SelectObjectContentAsync(SelectObjectContentArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all incomplete uploads in a given bucket and prefix recursively
/// </summary>
/// <param name="args">ListIncompleteUploadsArgs Arguments Object which encapsulates bucket name, prefix, recursive</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>A lazily populated list of incomplete uploads</returns>
/// <exception cref="AuthorizationException">When access or secret key provided is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
IObservable<Upload> ListIncompleteUploads(ListIncompleteUploadsArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Remove incomplete uploads from a given bucket and objectName
/// </summary>
/// <param name="args">RemoveIncompleteUploadArgs Arguments Object which encapsulates bucket, object names</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task RemoveIncompleteUploadAsync(RemoveIncompleteUploadArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Presigned get url - returns a presigned url to access an object's data without credentials.URL can have a maximum expiry of
/// up to 7 days or a minimum of 1 second.Additionally, you can override a set of response headers using reqParams.
/// </summary>
/// <param name="args">PresignedGetObjectArgs Arguments object encapsulating bucket and object names, expiry time, response headers, request date</param>
/// <returns></returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
Task<string> PresignedGetObjectAsync(PresignedGetObjectArgs args);
/// <summary>
/// Presigned post policy
/// </summary>
/// <param name="args">PresignedPostPolicyArgs Arguments object encapsulating Policy, Expiry, Region, </param>
/// <returns>Tuple of URI and Policy Form data</returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task<(Uri, Dictionary<string, string>)> PresignedPostPolicyAsync(PresignedPostPolicyArgs args);
/// <summary>
/// Presigned Put url -returns a presigned url to upload an object without credentials.URL can have a maximum expiry of
/// upto 7 days or a minimum of 1 second.
/// </summary>
/// <param name="args">PresignedPutObjectArgs Arguments Object which encapsulates bucket, object names, expiry</param>
/// <returns></returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task<string> PresignedPutObjectAsync(PresignedPutObjectArgs args);
/// <summary>
/// Get an object. The object will be streamed to the callback given by the user.
/// </summary>
/// <param name="bucketName">Bucket to retrieve object from</param>
/// <param name="objectName">Name of object to retrieve</param>
/// <param name="callback">A stream will be passed to the callback</param>
/// <param name="sse">Optional Server-side encryption option. Defaults to null.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
[Obsolete("Use GetObjectAsync method with GetObjectArgs object. Refer GetObject, GetObjectVersion & GetObjectQuery example code.")]
Task GetObjectAsync(string bucketName, string objectName, Action<Stream> callback, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get an object. The object will be streamed to the callback given by the user.
/// </summary>
/// <param name="bucketName">Bucket to retrieve object from</param>
/// <param name="objectName">Name of object to retrieve</param>
/// <param name="offset">offset of the object from where stream will start </param>
/// <param name="length">length of object to read in from the stream</param>
/// <param name="cb">A stream will be passed to the callback</param>
/// <param name="sse">Optional Server-side encryption option. Defaults to null.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
[Obsolete("Use GetObjectAsync method with GetObjectArgs object. Refer GetObject, GetObjectVersion & GetObjectQuery example code.")]
Task GetObjectAsync(string bucketName, string objectName, long offset, long length, Action<Stream> cb, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Select an object's content. The object will be streamed to the callback given by the user.
/// </summary>
/// <param name="bucketName">Bucket to retrieve object from</param>
/// <param name="objectName">Name of object to retrieve</param>
/// <param name="opts">Select Object options</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
[Obsolete("Use SelectObjectContentAsync method with SelectObjectContentsArgs object. Refer SelectObjectContent example code.")]
Task<SelectResponseStream> SelectObjectContentAsync(string bucketName, string objectName, SelectObjectOptions opts, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates an object from file input stream
/// </summary>
/// <param name="bucketName">Bucket to create object in</param>
/// <param name="objectName">Key of the new object</param>
/// <param name="data">Stream of file to upload</param>
/// <param name="size">Size of stream</param>
/// <param name="contentType">Content type of the new object, null defaults to "application/octet-stream"</param>
/// <param name="metaData">Optional Object metadata to be stored. Defaults to null.</param>
/// <param name="sse">Optional Server-side encryption option. Defaults to null.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
[Obsolete("Use PutObjectAsync method with PutObjectArgs object. Refer PutObject example code.")]
Task PutObjectAsync(string bucketName, string objectName, Stream data, long size, string contentType = null, Dictionary<string, string> metaData = null, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes an object with given name in specific bucket
/// </summary>
/// <param name="bucketName">Bucket to remove object from</param>
/// <param name="objectName">Key of object to remove</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
[Obsolete("Use RemoveObjectAsync method with RemoveObjectArgs object. Refer RemoveObject example code.")]
Task RemoveObjectAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes objects in the list from specific bucket
/// </summary>
/// <param name="bucketName">Bucket to remove objects from</param>
/// <param name="objectsList">List of object keys to remove</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
[Obsolete("Use RemoveObjectsAsync method with RemoveObjectsArgs object. Refer RemoveObjects example code.")]
Task<IObservable<DeleteError>> RemoveObjectAsync(string bucketName, IEnumerable<string> objectsList, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Tests the object's existence and returns metadata about existing objects.
/// </summary>
/// <param name="bucketName">Bucket to test object in</param>
/// <param name="objectName">Name of the object to stat</param>
/// <param name="sse">Optional Server-side encryption option. Defaults to null.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>Facts about the object</returns>
[Obsolete("Use StatObjectAsync method with StatObjectArgs object. Refer StatObject & StatObjectQuery example code.")]
Task<ObjectStat> StatObjectAsync(string bucketName, string objectName, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all incomplete uploads in a given bucket and prefix recursively
/// </summary>
/// <param name="bucketName">Bucket to list all incomplete uploads from</param>
/// <param name="prefix">prefix to list all incomplete uploads</param>
/// <param name="recursive">Set to true to recursively list all incomplete uploads</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>A lazily populated list of incomplete uploads</returns>
[Obsolete("Use ListIncompleteUploads method with ListIncompleteUploadsArgs object. Refer ListIncompleteUploads example code.")]
IObservable<Upload> ListIncompleteUploads(string bucketName, string prefix = "", bool recursive = false, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Remove incomplete uploads from a given bucket and objectName
/// </summary>
/// <param name="bucketName">Bucket to remove incomplete uploads from</param>
/// <param name="objectName">Key to remove incomplete uploads from</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
[Obsolete("Use RemoveIncompleteUploadAsync method with RemoveIncompleteUploadArgs object. Refer RemoveIncompleteUpload example code.")]
Task RemoveIncompleteUploadAsync(string bucketName, string objectName, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Copy a source object into a new destination object.
/// </summary>
/// <param name="bucketName"> Bucket name where the object to be copied exists.</param>
/// <param name="objectName">Object name source to be copied.</param>
/// <param name="destBucketName">Bucket name where the object will be copied to.</param>
/// <param name="destObjectName">Object name to be created, if not provided uses source object name as destination object name.</param>
/// <param name="copyConditions">optionally can take a key value CopyConditions as well for conditionally attempting copyObject.</param>
/// <param name="metadata">Optional Object metadata to be stored. Defaults to null.</param>
/// <param name="sseSrc">Optional Server-side encryption option for source. Defaults to null.</param>
/// <param name="sseDest">Optional Server-side encryption option for destination. Defaults to null.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
[Obsolete("Use CopyObjectAsync method with CopyObjectArgs object. Refer CopyObject example code.")]
Task CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null, CopyConditions copyConditions = null, Dictionary<string, string> metadata = null, ServerSideEncryption sseSrc = null, ServerSideEncryption sseDest = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates an object from file
/// </summary>
/// <param name="bucketName">Bucket to create object in</param>
/// <param name="objectName">Key of the new object</param>
/// <param name="filePath">Path of file to upload</param>
/// <param name="contentType">Content type of the new object, null defaults to "application/octet-stream"</param>
/// <param name="metaData">Optional Object metadata to be stored. Defaults to null.</param>
/// <param name="sse">Optional Server-side encryption option. Defaults to null.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
[Obsolete("Use PutObjectAsync method with PutObjectArgs object. Refer PutObject example code.")]
Task PutObjectAsync(string bucketName, string objectName, string filePath, string contentType = null, Dictionary<string, string> metaData = null, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get an object. The object will be streamed to the callback given by the user.
/// </summary>
/// <param name="bucketName">Bucket to retrieve object from</param>
/// <param name="objectName">Name of object to retrieve</param>
/// <param name="filePath">string with file path</param>
/// <param name="sse">Optional Server-side encryption option. Defaults to null.</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
[Obsolete("Use GetObjectAsync method with GetObjectArgs object. Refer GetObject, GetObjectVersion & GetObjectQuery example code.")]
Task GetObjectAsync(string bucketName, string objectName, string filePath, ServerSideEncryption sse = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Presigned get url - returns a presigned url to access an object's data without credentials.URL can have a maximum expiry of
/// upto 7 days or a minimum of 1 second.Additionally, you can override a set of response headers using reqParams.
/// </summary>
/// <param name="bucketName">Bucket to retrieve object from</param>
/// <param name="objectName">Key of object to retrieve</param>
/// <param name="expiresInt">Expiration time in seconds.</param>
/// <param name="reqParams">Optional override response headers</param>
/// <param name="reqDate">Optional request date and time in UTC</param>
[Obsolete("Use PresignedGetObjectAsync method with PresignedGetObjectArgs object.")]
Task<string> PresignedGetObjectAsync(string bucketName, string objectName, int expiresInt, Dictionary<string, string> reqParams = null, DateTime? reqDate = null);
/// <summary>
/// Presigned Put url - returns a presigned url to upload an object without credentials.URL can have a maximum expiry of
/// upto 7 days or a minimum of 1 second.
/// </summary>
/// <param name="bucketName">Bucket to retrieve object from</param>
/// <param name="objectName">Key of object to retrieve</param>
/// <param name="expiresInt">Expiration time in seconds</param>
[Obsolete("Use PresignedPutObjectAsync method with PresignedPutObjectArgs object.")]
Task<string> PresignedPutObjectAsync(string bucketName, string objectName, int expiresInt);
/// <summary>
/// Presigned post policy
/// </summary>
/// <param name="policy"></param>
/// <returns></returns>
Task<(Uri, Dictionary<string, string>)> PresignedPostPolicyAsync(PostPolicy policy);
/// <summary>
/// Gets Tagging values set for this object
/// </summary>
/// <param name="args"> GetObjectTagsArgs Arguments Object with information like Bucket, Object name, (optional)version Id</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns>Tagging Object with key-value tag pairs</returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
Task<Tagging> GetObjectTagsAsync(GetObjectTagsArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Sets the Tagging values for this object
/// </summary>
/// <param name="args">SetObjectTagsArgs Arguments Object with information like Bucket name,Object name, (optional)version Id, tag key-value pairs</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task SetObjectTagsAsync(SetObjectTagsArgs args, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Removes Tagging values stored for the object
/// </summary>
/// <param name="args">RemoveObjectTagsArgs Arguments Object with information like Bucket name</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the operation</param>
/// <returns></returns>
/// <exception cref="AuthorizationException">When access or secret key is invalid</exception>
/// <exception cref="InvalidBucketNameException">When bucket name is invalid</exception>
/// <exception cref="InvalidObjectNameException">When object name is invalid</exception>
/// <exception cref="BucketNotFoundException">When bucket is not found</exception>
/// <exception cref="NotImplementedException">When a functionality or extension is not implemented</exception>
/// <exception cref="ObjectNotFoundException">When object is not found</exception>
/// <exception cref="MalFormedXMLException">When configuration XML provided is invalid</exception>
Task RemoveObjectTagsAsync(RemoveObjectTagsArgs args, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
namespace Humidifier.ApiGateway
{
using System.Collections.Generic;
using StageTypes;
public class Stage : Humidifier.Resource
{
public override string AWSTypeName
{
get
{
return @"AWS::ApiGateway::Stage";
}
}
/// <summary>
/// AccessLogSetting
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-accesslogsetting
/// Required: False
/// UpdateType: Mutable
/// Type: AccessLogSetting
/// </summary>
public AccessLogSetting AccessLogSetting
{
get;
set;
}
/// <summary>
/// CacheClusterEnabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-cacheclusterenabled
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic CacheClusterEnabled
{
get;
set;
}
/// <summary>
/// CacheClusterSize
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-cacheclustersize
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic CacheClusterSize
{
get;
set;
}
/// <summary>
/// CanarySetting
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-canarysetting
/// Required: False
/// UpdateType: Mutable
/// Type: CanarySetting
/// </summary>
public CanarySetting CanarySetting
{
get;
set;
}
/// <summary>
/// ClientCertificateId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-clientcertificateid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ClientCertificateId
{
get;
set;
}
/// <summary>
/// DeploymentId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-deploymentid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DeploymentId
{
get;
set;
}
/// <summary>
/// Description
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-description
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Description
{
get;
set;
}
/// <summary>
/// DocumentationVersion
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-documentationversion
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DocumentationVersion
{
get;
set;
}
/// <summary>
/// MethodSettings
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-methodsettings
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: MethodSetting
/// </summary>
public List<MethodSetting> MethodSettings
{
get;
set;
}
/// <summary>
/// RestApiId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-restapiid
/// Required: True
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic RestApiId
{
get;
set;
}
/// <summary>
/// StageName
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-stagename
/// Required: False
/// UpdateType: Immutable
/// PrimitiveType: String
/// </summary>
public dynamic StageName
{
get;
set;
}
/// <summary>
/// Tags
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-tags
/// Required: False
/// UpdateType: Mutable
/// Type: List
/// ItemType: Tag
/// </summary>
public List<Tag> Tags
{
get;
set;
}
/// <summary>
/// TracingEnabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-tracingenabled
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic TracingEnabled
{
get;
set;
}
/// <summary>
/// Variables
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-variables
/// Required: False
/// UpdateType: Mutable
/// Type: Map
/// PrimitiveItemType: String
/// </summary>
public Dictionary<string, dynamic> Variables
{
get;
set;
}
}
namespace StageTypes
{
public class CanarySetting
{
/// <summary>
/// DeploymentId
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-canarysetting.html#cfn-apigateway-stage-canarysetting-deploymentid
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DeploymentId
{
get;
set;
}
/// <summary>
/// PercentTraffic
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-canarysetting.html#cfn-apigateway-stage-canarysetting-percenttraffic
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Double
/// </summary>
public dynamic PercentTraffic
{
get;
set;
}
/// <summary>
/// StageVariableOverrides
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-canarysetting.html#cfn-apigateway-stage-canarysetting-stagevariableoverrides
/// Required: False
/// UpdateType: Mutable
/// Type: Map
/// PrimitiveItemType: String
/// </summary>
public Dictionary<string, dynamic> StageVariableOverrides
{
get;
set;
}
/// <summary>
/// UseStageCache
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-canarysetting.html#cfn-apigateway-stage-canarysetting-usestagecache
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic UseStageCache
{
get;
set;
}
}
public class AccessLogSetting
{
/// <summary>
/// DestinationArn
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-accesslogsetting.html#cfn-apigateway-stage-accesslogsetting-destinationarn
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic DestinationArn
{
get;
set;
}
/// <summary>
/// Format
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-stage-accesslogsetting.html#cfn-apigateway-stage-accesslogsetting-format
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic Format
{
get;
set;
}
}
public class MethodSetting
{
/// <summary>
/// CacheDataEncrypted
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-cachedataencrypted
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic CacheDataEncrypted
{
get;
set;
}
/// <summary>
/// CacheTtlInSeconds
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-cachettlinseconds
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic CacheTtlInSeconds
{
get;
set;
}
/// <summary>
/// CachingEnabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-cachingenabled
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic CachingEnabled
{
get;
set;
}
/// <summary>
/// DataTraceEnabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-datatraceenabled
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic DataTraceEnabled
{
get;
set;
}
/// <summary>
/// HttpMethod
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-httpmethod
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic HttpMethod
{
get;
set;
}
/// <summary>
/// LoggingLevel
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-logginglevel
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic LoggingLevel
{
get;
set;
}
/// <summary>
/// MetricsEnabled
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-metricsenabled
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Boolean
/// </summary>
public dynamic MetricsEnabled
{
get;
set;
}
/// <summary>
/// ResourcePath
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-resourcepath
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: String
/// </summary>
public dynamic ResourcePath
{
get;
set;
}
/// <summary>
/// ThrottlingBurstLimit
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-throttlingburstlimit
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Integer
/// </summary>
public dynamic ThrottlingBurstLimit
{
get;
set;
}
/// <summary>
/// ThrottlingRateLimit
/// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-throttlingratelimit
/// Required: False
/// UpdateType: Mutable
/// PrimitiveType: Double
/// </summary>
public dynamic ThrottlingRateLimit
{
get;
set;
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Project31.CoreServices;
namespace Project31.ApplicationFramework
{
/// <summary>
/// Provides a "tracking indicator" for use in splitter bars.
/// </summary>
internal class SplitterTrackingIndicator
{
/// <summary>
/// SRCCOPY ROP.
/// </summary>
private const int SRCCOPY = 0x00cc0020;
/// <summary>
/// DCX_PARENTCLIP option for GetDCEx.
/// </summary>
private const int DCX_PARENTCLIP = 0x00000020;
/// <summary>
/// Valid indicator. Used to ensure that calls to Begin, Update and End are valid when
/// they are made.
/// </summary>
private bool valid = false;
/// <summary>
/// Control into which the tracking indicator will be drawn.
/// </summary>
private Control control;
/// <summary>
/// Graphics object for the control into which the tracking indicator will be drawn.
/// </summary>
private Graphics controlGraphics;
/// <summary>
/// DC for the control into which the tracking indicator will be drawn.
/// </summary>
private IntPtr controlDC;
/// <summary>
/// The capture bitmap. Used to capture the portion of the control that is being
/// overwritten by the tracking indicator so that it can be restored when the
/// tracking indicator is moved to a new location.
/// </summary>
private Bitmap captureBitmap;
/// <summary>
/// Last capture location where the tracking indicator was drawn.
/// </summary>
private Point lastCaptureLocation;
/// <summary>
/// The tracking indicator bitmap.
/// </summary>
private Bitmap trackingIndicatorBitmap;
/// <summary>
/// DllImport of Win32 GetDCEx.
/// </summary>
[DllImport("user32.dll")]
public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr region, System.Int32 dw);
/// <summary>
/// DllImport of GDI BitBlt.
/// </summary>
[DllImport("gdi32.dll")]
private static extern bool BitBlt( IntPtr hdcDest, // handle to destination DC (device context)
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop);// raster operation code
/// <summary>
/// DllImport of Win32 ReleaseDC.
/// </summary>
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
private static extern bool ReleaseDC(IntPtr hWnd, IntPtr dc);
/// <summary>
/// Initializes a new instance of the SplitterTrackingIndicator class.
/// </summary>
public SplitterTrackingIndicator()
{
}
/// <summary>
/// Begin a tracking indicator in the specified control using the specified rectangle.
/// </summary>
/// <param name="control">The control into which the tracking indicator will be drawn.</param>
/// <param name="rectangle">Rectangle structure that represents the tracking indicator rectangle, relative to the upper-left corner of the control into which it will be drawn.</param>
public void Begin(Control control, Rectangle rectangle)
{
// Can't Begin twice.
Debug.Assert(!valid, "Invalid nested Begin", "You must first call the End method of a SplitterTrackingIndicator before calling its Begin method again.");
if (valid)
End();
// Save away the control. We need this so we can call ReleaseDC later on.
this.control = control;
// Get a DC for the "visible region" the specified control. Children are not clipped
// for this DC, which allows us to draw the tracking indicator over them.
controlDC = GetDCEx(control.Handle, System.IntPtr.Zero, DCX_PARENTCLIP);
// Get a graphics object for the DC.
controlGraphics = Graphics.FromHdc(controlDC);
// Instantiate the capture bitmap.
captureBitmap = new Bitmap(rectangle.Width, rectangle.Height);
// Instantiate and paint the tracking indicator bitmap.
trackingIndicatorBitmap = new Bitmap(rectangle.Width, rectangle.Height);
Graphics trackingIndicatorBitmapGraphics = Graphics.FromImage(trackingIndicatorBitmap);
HatchBrush hatchBrush = new HatchBrush( HatchStyle.Percent50,
Color.FromArgb(128, Color.Black),
Color.FromArgb(128, Color.White));
trackingIndicatorBitmapGraphics.FillRectangle(hatchBrush, new Rectangle(0, 0, rectangle.Width, rectangle.Height));
hatchBrush.Dispose();
trackingIndicatorBitmapGraphics.Dispose();
// Draw the new tracking indicator.
DrawTrackingIndicator(rectangle.Location);
// Valid now.
valid = true;
}
/// <summary>
/// Update the location of the tracking indicator.
/// </summary>
/// <param name="location">The new location of the tracking indicator.</param>
public void Update(Point location)
{
// Can't Update without a Begin.
Debug.Assert(valid, "Invalid Update", "You must first call the Begin method of a SplitterTrackingIndicator before calling its Update method.");
if (!valid)
return;
// Undraw the last tracking indicator.
UndrawLastTrackingIndicator();
// Draw the new tracking indicator.
DrawTrackingIndicator(location);
}
/// <summary>
/// End the tracking indicator.
/// </summary>
public void End()
{
// Can't Update without a Begin.
Debug.Assert(valid, "Invalid End", "You must first call the Begin method of a SplitterTrackingIndicator before calling its End method.");
if (!valid)
return;
// Undraw the last tracking indicator.
UndrawLastTrackingIndicator();
// Cleanup the capture bitmap.
captureBitmap.Dispose();
// Dispose of the graphics context and DC for the control.
controlGraphics.Dispose();
ReleaseDC(control.Handle, controlDC);
// Not valid anymore.
valid = false;
}
/// <summary>
/// "Undraw" the last tracking indicator.
/// </summary>
private void UndrawLastTrackingIndicator()
{
controlGraphics.DrawImageUnscaled(captureBitmap, lastCaptureLocation);
}
/// <summary>
/// Draw the tracking indicator.
/// </summary>
private void DrawTrackingIndicator(Point location)
{
// BitBlt the contents of the specified rectangle of the control to the capture bitmap.
Graphics captureBitmapGraphics = Graphics.FromImage(captureBitmap);
System.IntPtr captureBitmapDC = captureBitmapGraphics.GetHdc();
BitBlt( captureBitmapDC, // handle to destination DC (device context)
0, // x-coord of destination upper-left corner
0, // y-coord of destination upper-left corner
captureBitmap.Width, // width of destination rectangle
captureBitmap.Height, // height of destination rectangle
controlDC, // handle to source DC
location.X, // x-coordinate of source upper-left corner
location.Y, // y-coordinate of source upper-left corner
SRCCOPY); // raster operation code
captureBitmapGraphics.ReleaseHdc(captureBitmapDC);
captureBitmapGraphics.Dispose();
// Draw the tracking indicator bitmap.
controlGraphics.DrawImageUnscaled(trackingIndicatorBitmap, location);
// Remember the last capture location. UndrawLastTrackingIndicator uses this value
// to undraw this tracking indicator at this location.
lastCaptureLocation = location;
}
}
}
| |
using System;
using ToolBelt;
using System.Collections.Generic;
using Cairo;
using System.IO;
namespace Playroom
{
public enum ImageRotation
{
None,
Left,
Right,
UpsideDown
}
public class ImagePlacement
{
public ImagePlacement(ParsedPath pngPath, Cairo.Rectangle targetRectangle)
{
this.ImageFile = pngPath;
this.TargetRectangle = targetRectangle;
}
public ParsedPath ImageFile { get; set; }
public Cairo.Rectangle TargetRectangle { get; set; }
}
public static class ImageTools
{
public static void SvgToPngWithInkscape(string svgFile, string pngFile, int width, int height)
{
string output;
string command = string.Format("\"{0}\" --export-png=\"{4}\" --export-width={2} --export-height={3} --export-dpi=96 --file=\"{1}\"",
ToolPaths.Inkscape, // 0
svgFile, // 1
width.ToString(), // 2
height.ToString(), // 3
pngFile // 4
);
int ret = Command.Run(command, out output);
if (ret != 0 || output.IndexOf("CRITICAL **") != -1)
{
throw new ContentFileException("Error running Inkscape on '{0}': {1}".CultureFormat(svgFile, output));
}
}
public static void SvgToPngWithRSvg(string svgFile, string pngFile, int width, int height)
{
string output;
string command = string.Format("\"{0}\" \"{1}\" --format=png --dpi-x=96 --dpi-y=96 --width={2} --height={3} --output \"{4}\"",
ToolPaths.RSvgConvert, // 0
svgFile, // 1
width.ToString(), // 2
height.ToString(), // 3
pngFile // 4
);
int ret = Command.Run(command, out output);
if (ret != 0)
throw new InvalidOperationException("Error running RSVG-Convert on '{0}': {1}".CultureFormat(svgFile, output));
}
public static void SvgToPdfWithInkscape(string svgFile, string pdfFile)
{
string output;
string command = string.Format("\"{0}\" --export-pdf=\"{2}\" --file=\"{1}\"",
ToolPaths.Inkscape, // 0
svgFile, // 1
pdfFile); // 2
int ret = Command.Run(command, out output);
if (ret != 0 || output.IndexOf("CRITICAL **") != -1)
{
throw new InvalidOperationException("Error running Inkscape on '{0}': {1}".CultureFormat(svgFile, output));
}
}
public static void CombinePngs(List<ImagePlacement> placements, ParsedPath pngPath)
{
try
{
int w = 0;
int h = 0;
foreach (var placement in placements)
{
int wt = (int)placement.TargetRectangle.Width;
int ht = (int)placement.TargetRectangle.Height;
if (wt > w)
w = wt;
if (ht > h)
h = ht;
}
using (ImageSurface combinedImage = new ImageSurface(Format.Argb32, w, h))
{
using (Cairo.Context g = new Cairo.Context(combinedImage))
{
foreach (var placement in placements)
{
using (ImageSurface image = new ImageSurface(placement.ImageFile))
{
int x = (int)placement.TargetRectangle.X;
int y = (int)placement.TargetRectangle.Y;
g.SetSourceSurface(image, x, y);
g.Paint();
}
}
}
combinedImage.WriteToPng(pngPath);
}
}
catch (Exception e)
{
throw new ArgumentException("Unable to combine images into file '{0}'".CultureFormat(pngPath), e);
}
}
public static void RotatePng(ParsedPath pngPath, ImageRotation rotation)
{
if (rotation == ImageRotation.None)
return;
using (ImageSurface originalImage = new ImageSurface(pngPath))
{
int w;
int h;
if (rotation == ImageRotation.Left || rotation == ImageRotation.Right)
{
w = originalImage.Height;
h = originalImage.Width;
}
else
{
w = originalImage.Width;
h = originalImage.Height;
}
double[] rotationRadians = {0, -Math.PI / 2, Math.PI / 2, Math.PI };
using (ImageSurface rotatedImage = new ImageSurface(Format.Argb32, w, h))
{
using (Cairo.Context g = new Cairo.Context(rotatedImage))
{
g.Translate(rotatedImage.Width / 2.0, rotatedImage.Height / 2.0);
g.Rotate(rotationRadians[(int)rotation]);
g.Translate(-originalImage.Width / 2.0, -originalImage.Height / 2.0);
g.SetSourceSurface(originalImage, 0, 0);
g.Paint();
}
rotatedImage.WriteToPng(pngPath);
}
}
}
public static void ExportPngToDxt(ParsedPath pngFileName, ParsedPath dxtFileName)
{
PngFile pngFile = PngFileReader.ReadFile(pngFileName);
SquishMethod? squishMethod = null;
switch (dxtFileName.Extension)
{
case ".dxt1":
squishMethod = SquishMethod.Dxt1;
break;
case ".dxt3":
squishMethod = SquishMethod.Dxt3;
break;
case ".dxt5":
squishMethod = SquishMethod.Dxt5;
break;
default:
break;
}
byte[] rgbaData;
if (squishMethod.HasValue)
{
rgbaData = Squish.CompressImage(
pngFile.RgbaData, pngFile.Width, pngFile.Height,
squishMethod.Value, SquishFit.IterativeCluster, SquishMetric.Default, SquishExtra.None);
}
else
{
rgbaData = null;
}
using (BinaryWriter writer = new BinaryWriter(new FileStream(dxtFileName, FileMode.Create)))
{
writer.Write(pngFile.Width);
writer.Write(pngFile.Height);
writer.Write(rgbaData);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Threading;
using System.Transactions;
using Common.Logging;
using Rhino.Queues.Internal;
using Rhino.Queues.Model;
using Rhino.Queues.Monitoring;
using Rhino.Queues.Protocol;
using Rhino.Queues.Storage;
using System.Linq;
#pragma warning disable 420
namespace Rhino.Queues
{
using Exceptions;
using Utils;
public class QueueManager : IQueueManager, ITransactionalQueueManager
{
[ThreadStatic]
private static TransactionEnlistment Enlistment;
[ThreadStatic]
private static Transaction CurrentlyEnslistedTransaction;
private volatile bool wasStarted;
private volatile bool wasDisposed;
private volatile bool enableEndpointPortAutoSelection;
private volatile int currentlyInCriticalReceiveStatus;
private volatile int currentlyInsideTransaction;
private readonly IPEndPoint endpoint;
private readonly object newMessageArrivedLock = new object();
private readonly string path;
private Timer purgeOldDataTimer;
private readonly QueueStorage queueStorage;
private Receiver receiver;
private Thread sendingThread;
private QueuedMessagesSender queuedMessagesSender;
private readonly ILog logger = LogManager.GetLogger(typeof(QueueManager));
private PerformanceMonitor monitor;
private volatile bool waitingForAllMessagesToBeSent;
private readonly ThreadSafeSet<MessageId> receivedMsgs = new ThreadSafeSet<MessageId>();
private bool disposing;
public QueueManagerConfiguration Configuration { get; set; }
public int CurrentlySendingCount
{
get { return queuedMessagesSender.CurrentlySendingCount; }
}
public int CurrentlyConnectingCount
{
get { return queuedMessagesSender.CurrentlyConnectingCount; }
}
public event Action<Endpoint> FailedToSendMessagesTo;
public event Action<object, MessageEventArgs> MessageQueuedForSend;
public event Action<object, MessageEventArgs> MessageSent;
public event Action<object, MessageEventArgs> MessageQueuedForReceive;
public event Action<object, MessageEventArgs> MessageReceived;
public QueueManager(IPEndPoint endpoint, string path)
: this(endpoint, path, new QueueManagerConfiguration())
{
}
public QueueManager(IPEndPoint endpoint, string path, QueueManagerConfiguration configuration)
{
Configuration = configuration;
this.endpoint = endpoint;
this.path = path;
queueStorage = new QueueStorage(path, configuration);
queueStorage.Initialize();
queueStorage.Global(actions =>
{
receivedMsgs.Add(actions.GetAlreadyReceivedMessageIds());
actions.Commit();
});
HandleRecovery();
}
public void Start()
{
AssertNotDisposedOrDisposing();
if (wasStarted)
throw new InvalidOperationException("The Start method may not be invoked more than once.");
receiver = new Receiver(endpoint, enableEndpointPortAutoSelection, AcceptMessages);
receiver.Start();
queuedMessagesSender = new QueuedMessagesSender(queueStorage, this);
sendingThread = new Thread(queuedMessagesSender.Send)
{
IsBackground = true,
Name = "Rhino Queue Sender Thread for " + path
};
sendingThread.Start();
purgeOldDataTimer = new Timer(_ => PurgeOldData(), null,
TimeSpan.FromMinutes(3),
TimeSpan.FromMinutes(3));
wasStarted = true;
}
public void PurgeOldData()
{
logger.Info("Starting to purge old data");
try
{
PurgeProcessedMessages();
PurgeOutgoingHistory();
PurgeOldestReceivedMessageIds();
}
catch (Exception exception)
{
logger.Warn("Failed to purge old data from the system", exception);
}
}
private void PurgeProcessedMessages()
{
if (!Configuration.EnableProcessedMessageHistory)
return;
foreach (string queue in Queues)
{
PurgeProcessedMessagesInQueue(queue);
}
}
private void PurgeProcessedMessagesInQueue(string queue)
{
// To make this batchable:
// 1: Move to the end of the history (to the newest messages) and seek
// backword by NumberOfMessagesToKeepInProcessedHistory.
// 2: Save a bookmark of the current position.
// 3: Delete from the beginning of the table (oldest messages) in batches until
// a) we reach the bookmark or b) we hit OldestMessageInProcessedHistory.
MessageBookmark purgeLimit = null;
int numberOfMessagesToKeep = Configuration.NumberOfMessagesToKeepInProcessedHistory;
if (numberOfMessagesToKeep > 0)
{
queueStorage.Global(actions =>
{
var queueActions = actions.GetQueue(queue);
purgeLimit = queueActions.GetMessageHistoryBookmarkAtPosition(numberOfMessagesToKeep);
actions.Commit();
});
if (purgeLimit == null)
return;
}
bool foundMessages = false;
do
{
foundMessages = false;
queueStorage.Global(actions =>
{
var queueActions = actions.GetQueue(queue);
var messages = queueActions.GetAllProcessedMessages(batchSize: 250)
.TakeWhile(x => (purgeLimit == null || !x.Bookmark.Equals(purgeLimit))
&& (DateTime.Now - x.SentAt) > Configuration.OldestMessageInProcessedHistory);
foreach (var message in messages)
{
foundMessages = true;
logger.DebugFormat("Purging message {0} from queue {1}/{2}", message.Id, message.Queue, message.SubQueue);
queueActions.DeleteHistoric(message.Bookmark);
}
actions.Commit();
});
} while (foundMessages);
}
private void PurgeOutgoingHistory()
{
// Outgoing messages are still stored in the history in case the sender
// needs to revert, so there will still be messages to purge even when
// the QueueManagerConfiguration has disabled outgoing history.
//
// To make this batchable:
// 1: Move to the end of the history (to the newest messages) and seek
// backword by NumberOfMessagesToKeepInOutgoingHistory.
// 2: Save a bookmark of the current position.
// 3: Delete from the beginning of the table (oldest messages) in batches until
// a) we reach the bookmark or b) we hit OldestMessageInOutgoingHistory.
MessageBookmark purgeLimit = null;
int numberOfMessagesToKeep = Configuration.NumberOfMessagesToKeepInOutgoingHistory;
if (numberOfMessagesToKeep > 0 && Configuration.EnableOutgoingMessageHistory)
{
queueStorage.Global(actions =>
{
purgeLimit = actions.GetSentMessageBookmarkAtPosition(numberOfMessagesToKeep);
actions.Commit();
});
if (purgeLimit == null)
return;
}
bool foundMessages = false;
do
{
foundMessages = false;
queueStorage.Global(actions =>
{
IEnumerable<PersistentMessageToSend> sentMessages = actions.GetSentMessages(batchSize: 250)
.TakeWhile(x => (purgeLimit == null || !x.Bookmark.Equals(purgeLimit))
&& (!Configuration.EnableOutgoingMessageHistory || (DateTime.Now - x.SentAt) > Configuration.OldestMessageInOutgoingHistory));
foreach (var sentMessage in sentMessages)
{
foundMessages = true;
logger.DebugFormat("Purging sent message {0} to {1}/{2}/{3}", sentMessage.Id, sentMessage.Endpoint,
sentMessage.Queue, sentMessage.SubQueue);
actions.DeleteMessageToSendHistoric(sentMessage.Bookmark);
}
actions.Commit();
});
} while (foundMessages);
}
private void PurgeOldestReceivedMessageIds()
{
int totalCount = 0;
List<MessageId> deletedMessageIds = null;
do
{
queueStorage.Global(actions =>
{
deletedMessageIds = actions.DeleteOldestReceivedMessageIds(
Configuration.NumberOfReceivedMessageIdsToKeep, numberOfItemsToDelete: 250)
.ToList();
actions.Commit();
});
receivedMsgs.Remove(deletedMessageIds);
totalCount += deletedMessageIds.Count;
} while (deletedMessageIds.Count > 0);
logger.InfoFormat("Purged {0} message ids", totalCount);
}
private void HandleRecovery()
{
var recoveryRequired = false;
queueStorage.Global(actions =>
{
actions.MarkAllOutgoingInFlightMessagesAsReadyToSend();
actions.MarkAllProcessedMessagesWithTransactionsNotRegisterForRecoveryAsReadyToDeliver();
foreach (var bytes in actions.GetRecoveryInformation())
{
recoveryRequired = true;
TransactionManager.Reenlist(queueStorage.Id, bytes,
new TransactionEnlistment(queueStorage, () => { }, () => { }));
}
actions.Commit();
});
if (recoveryRequired)
TransactionManager.RecoveryComplete(queueStorage.Id);
}
public ITransactionalScope BeginTransactionalScope()
{
return new TransactionalScope(this, new QueueTransaction(queueStorage, OnTransactionComplete, AssertNotDisposed));
}
public void EnablePerformanceCounters()
{
if (wasStarted)
throw new InvalidOperationException("Performance counters cannot be enabled after the queue has been started.");
monitor = new PerformanceMonitor(this);
}
public void EnableEndpointPortAutoSelection()
{
if (wasStarted)
throw new InvalidOperationException("Endpoint auto-port-selection cannot be enabled after the queue has been started.");
enableEndpointPortAutoSelection = true;
}
public string Path
{
get { return path; }
}
public IPEndPoint Endpoint
{
get { return endpoint; }
}
#region IDisposable Members
public void Dispose()
{
if (wasDisposed)
return;
DisposeResourcesWhoseDisposalCannotFail();
if (monitor != null)
monitor.Dispose();
queueStorage.Dispose();
// only after we finish incoming recieves, and finish processing
// active transactions can we mark it as disposed
wasDisposed = true;
}
public void DisposeRudely()
{
if (wasDisposed)
return;
DisposeResourcesWhoseDisposalCannotFail();
queueStorage.DisposeRudely();
// only after we finish incoming recieves, and finish processing
// active transactions can we mark it as disposed
wasDisposed = true;
}
private void DisposeResourcesWhoseDisposalCannotFail()
{
disposing = true;
lock (newMessageArrivedLock)
{
Monitor.PulseAll(newMessageArrivedLock);
}
if (wasStarted)
{
purgeOldDataTimer.Dispose();
queuedMessagesSender.Stop();
sendingThread.Join();
receiver.Dispose();
}
while (currentlyInCriticalReceiveStatus > 0)
{
logger.WarnFormat("Waiting for {0} messages that are currently in critical receive status", currentlyInCriticalReceiveStatus);
Thread.Sleep(TimeSpan.FromSeconds(1));
}
while (currentlyInsideTransaction > 0)
{
logger.WarnFormat("Waiting for {0} transactions currently running", currentlyInsideTransaction);
Thread.Sleep(TimeSpan.FromSeconds(1));
}
}
#endregion
private void OnTransactionComplete()
{
lock (newMessageArrivedLock)
{
Monitor.PulseAll(newMessageArrivedLock);
}
Interlocked.Decrement(ref currentlyInsideTransaction);
}
private void AssertNotDisposed()
{
if (wasDisposed)
throw new ObjectDisposedException("QueueManager");
}
private void AssertNotDisposedOrDisposing()
{
if (disposing || wasDisposed)
throw new ObjectDisposedException("QueueManager");
}
public void WaitForAllMessagesToBeSent()
{
waitingForAllMessagesToBeSent = true;
try
{
var hasMessagesToSend = true;
do
{
queueStorage.Send(actions =>
{
hasMessagesToSend = actions.HasMessagesToSend();
actions.Commit();
});
if (hasMessagesToSend)
Thread.Sleep(100);
} while (hasMessagesToSend);
}
finally
{
waitingForAllMessagesToBeSent = false;
}
}
public IQueue GetQueue(string queue)
{
return new Queue(this, queue);
}
public PersistentMessage[] GetAllMessages(string queueName, string subqueue)
{
AssertNotDisposedOrDisposing();
PersistentMessage[] messages = null;
queueStorage.Global(actions =>
{
messages = actions.GetQueue(queueName).GetAllMessages(subqueue).ToArray();
actions.Commit();
});
return messages;
}
public HistoryMessage[] GetAllProcessedMessages(string queueName)
{
AssertNotDisposedOrDisposing();
HistoryMessage[] messages = null;
queueStorage.Global(actions =>
{
messages = actions.GetQueue(queueName).GetAllProcessedMessages().ToArray();
actions.Commit();
});
return messages;
}
public PersistentMessageToSend[] GetAllSentMessages()
{
AssertNotDisposedOrDisposing();
PersistentMessageToSend[] msgs = null;
queueStorage.Global(actions =>
{
msgs = actions.GetSentMessages().ToArray();
actions.Commit();
});
return msgs;
}
public PersistentMessageToSend[] GetMessagesCurrentlySending()
{
AssertNotDisposedOrDisposing();
PersistentMessageToSend[] msgs = null;
queueStorage.Send(actions =>
{
msgs = actions.GetMessagesToSend().ToArray();
actions.Commit();
});
return msgs;
}
public Message Peek(string queueName)
{
return Peek(queueName, null, TimeSpan.FromDays(1));
}
public Message Peek(string queueName, TimeSpan timeout)
{
return Peek(queueName, null, timeout);
}
public Message Peek(string queueName, string subqueue)
{
return Peek(queueName, subqueue, TimeSpan.FromDays(1));
}
public Message Peek(string queueName, string subqueue, TimeSpan timeout)
{
var remaining = timeout;
while (true)
{
var message = PeekMessageFromQueue(queueName, subqueue);
if (message != null)
return message;
lock (newMessageArrivedLock)
{
message = PeekMessageFromQueue(queueName, subqueue);
if (message != null)
return message;
var sp = Stopwatch.StartNew();
if (Monitor.Wait(newMessageArrivedLock, remaining) == false)
throw new TimeoutException("No message arrived in the specified timeframe " + timeout);
remaining = Max(TimeSpan.Zero, remaining - sp.Elapsed);
}
}
}
private static TimeSpan Max(TimeSpan x, TimeSpan y)
{
return x >= y ? x : y;
}
public Message Receive(string queueName)
{
return Receive(queueName, null, TimeSpan.FromDays(1));
}
public Message Receive(string queueName, TimeSpan timeout)
{
return Receive(queueName, null, timeout);
}
public Message Receive(string queueName, string subqueue)
{
return Receive(queueName, subqueue, TimeSpan.FromDays(1));
}
public Message Receive(string queueName, string subqueue, TimeSpan timeout)
{
EnsureEnlistment();
return Receive(Enlistment, queueName, subqueue, timeout);
}
public MessageId Send(Uri uri, MessagePayload payload)
{
if (waitingForAllMessagesToBeSent)
throw new CannotSendWhileWaitingForAllMessagesToBeSentException("Currently waiting for all messages to be sent, so we cannot send. You probably have a race condition in your application.");
EnsureEnlistment();
return Send(Enlistment, uri, payload);
}
private void EnsureEnlistment()
{
AssertNotDisposedOrDisposing();
if (Transaction.Current == null)
throw new InvalidOperationException("You must use TransactionScope when using Rhino.Queues");
if (CurrentlyEnslistedTransaction == Transaction.Current)
return;
// need to change the enlistment
Interlocked.Increment(ref currentlyInsideTransaction);
Enlistment = new TransactionEnlistment(queueStorage, OnTransactionComplete, AssertNotDisposed);
CurrentlyEnslistedTransaction = Transaction.Current;
}
private PersistentMessage GetMessageFromQueue(ITransaction transaction, string queueName, string subqueue)
{
AssertNotDisposedOrDisposing();
PersistentMessage message = null;
queueStorage.Global(actions =>
{
message = actions.GetQueue(queueName).Dequeue(subqueue);
if (message != null)
{
actions.RegisterUpdateToReverse(
transaction.Id,
message.Bookmark,
MessageStatus.ReadyToDeliver,
subqueue);
}
actions.Commit();
});
return message;
}
private PersistentMessage PeekMessageFromQueue(string queueName, string subqueue)
{
AssertNotDisposedOrDisposing();
PersistentMessage message = null;
queueStorage.Global(actions =>
{
message = actions.GetQueue(queueName).Peek(subqueue);
actions.Commit();
});
if (message != null)
{
logger.DebugFormat("Peeked message with id '{0}' from '{1}/{2}'",
message.Id, queueName, subqueue);
}
return message;
}
protected virtual IMessageAcceptance AcceptMessages(Message[] msgs)
{
var bookmarks = new List<MessageBookmark>();
queueStorage.Global(actions =>
{
foreach (var msg in receivedMsgs.Filter(msgs, message => message.Id))
{
var queue = actions.GetQueue(msg.Queue);
var bookmark = queue.Enqueue(msg);
bookmarks.Add(bookmark);
}
actions.Commit();
});
return new MessageAcceptance(this, bookmarks, msgs, queueStorage);
}
#region Nested type: MessageAcceptance
private class MessageAcceptance : IMessageAcceptance
{
private readonly IList<MessageBookmark> bookmarks;
private readonly IEnumerable<Message> messages;
private readonly QueueManager parent;
private readonly QueueStorage queueStorage;
public MessageAcceptance(QueueManager parent,
IList<MessageBookmark> bookmarks,
IEnumerable<Message> messages,
QueueStorage queueStorage)
{
this.parent = parent;
this.bookmarks = bookmarks;
this.messages = messages;
this.queueStorage = queueStorage;
Interlocked.Increment(ref parent.currentlyInCriticalReceiveStatus);
}
#region IMessageAcceptance Members
public void Commit()
{
try
{
parent.AssertNotDisposed();
queueStorage.Global(actions =>
{
foreach (var bookmark in bookmarks)
{
actions.GetQueue(bookmark.QueueName)
.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver);
}
foreach (var msg in messages)
{
actions.MarkReceived(msg.Id);
}
actions.Commit();
});
parent.receivedMsgs.Add(messages.Select(m => m.Id));
foreach (var msg in messages)
{
parent.OnMessageQueuedForReceive(msg);
}
lock (parent.newMessageArrivedLock)
{
Monitor.PulseAll(parent.newMessageArrivedLock);
}
}
finally
{
Interlocked.Decrement(ref parent.currentlyInCriticalReceiveStatus);
}
}
public void Abort()
{
try
{
parent.AssertNotDisposed();
queueStorage.Global(actions =>
{
foreach (var bookmark in bookmarks)
{
actions.GetQueue(bookmark.QueueName)
.Discard(bookmark);
}
actions.Commit();
});
}
finally
{
Interlocked.Decrement(ref parent.currentlyInCriticalReceiveStatus);
}
}
#endregion
}
#endregion
public void CreateQueues(params string[] queueNames)
{
AssertNotDisposedOrDisposing();
queueStorage.Global(actions =>
{
foreach (var queueName in queueNames)
{
actions.CreateQueueIfDoesNotExists(queueName);
}
actions.Commit();
});
}
public string[] Queues
{
get
{
AssertNotDisposedOrDisposing();
string[] queues = null;
queueStorage.Global(actions =>
{
queues = actions.GetAllQueuesNames();
actions.Commit();
});
return queues;
}
}
public void MoveTo(string subqueue, Message message)
{
AssertNotDisposedOrDisposing();
EnsureEnlistment();
queueStorage.Global(actions =>
{
var queue = actions.GetQueue(message.Queue);
var bookmark = queue.MoveTo(subqueue, (PersistentMessage)message);
actions.RegisterUpdateToReverse(Enlistment.Id,
bookmark, MessageStatus.ReadyToDeliver,
message.SubQueue
);
actions.Commit();
});
if (((PersistentMessage)message).Status == MessageStatus.ReadyToDeliver)
OnMessageReceived(message);
var updatedMessage = new Message
{
Id = message.Id,
Data = message.Data,
Headers = message.Headers,
Queue = message.Queue,
SubQueue = subqueue,
SentAt = message.SentAt
};
OnMessageQueuedForReceive(updatedMessage);
}
public void EnqueueDirectlyTo(string queue, string subqueue, MessagePayload payload)
{
EnsureEnlistment();
var message = new PersistentMessage
{
Data = payload.Data,
Headers = payload.Headers,
Id = new MessageId
{
SourceInstanceId = queueStorage.Id,
MessageIdentifier = GuidCombGenerator.Generate()
},
Queue = queue,
SentAt = DateTime.Now,
SubQueue = subqueue,
Status = MessageStatus.EnqueueWait
};
queueStorage.Global(actions =>
{
var queueActions = actions.GetQueue(queue);
var bookmark = queueActions.Enqueue(message);
actions.RegisterUpdateToReverse(Enlistment.Id, bookmark, MessageStatus.EnqueueWait, subqueue);
actions.Commit();
});
OnMessageQueuedForReceive(message);
lock (newMessageArrivedLock)
{
Monitor.PulseAll(newMessageArrivedLock);
}
}
public PersistentMessage PeekById(string queueName, MessageId id)
{
PersistentMessage message = null;
queueStorage.Global(actions =>
{
var queue = actions.GetQueue(queueName);
message = queue.PeekById(id);
actions.Commit();
});
return message;
}
public string[] GetSubqueues(string queueName)
{
string[] result = null;
queueStorage.Global(actions =>
{
var queue = actions.GetQueue(queueName);
result = queue.Subqueues;
actions.Commit();
});
return result;
}
public int GetNumberOfMessages(string queueName)
{
int numberOfMsgs = 0;
queueStorage.Global(actions =>
{
numberOfMsgs = actions.GetNumberOfMessages(queueName);
actions.Commit();
});
return numberOfMsgs;
}
public void FailedToSendTo(Endpoint endpointThatWeFailedToSendTo)
{
var action = FailedToSendMessagesTo;
if (action != null)
action(endpointThatWeFailedToSendTo);
}
public void OnMessageQueuedForSend(MessageEventArgs messageEventArgs)
{
var action = MessageQueuedForSend;
if (action != null) action(this, messageEventArgs);
}
public void OnMessageSent(MessageEventArgs messageEventArgs)
{
var action = MessageSent;
if (action != null) action(this, messageEventArgs);
}
private void OnMessageQueuedForReceive(Message message)
{
OnMessageQueuedForReceive(new MessageEventArgs(null, message));
}
public void OnMessageQueuedForReceive(MessageEventArgs messageEventArgs)
{
var action = MessageQueuedForReceive;
if (action != null) action(this, messageEventArgs);
}
private void OnMessageReceived(Message message)
{
OnMessageReceived(new MessageEventArgs(null, message));
}
public void OnMessageReceived(MessageEventArgs messageEventArgs)
{
var action = MessageReceived;
if (action != null) action(this, messageEventArgs);
}
public Message Receive(ITransaction transaction, string queueName)
{
return Receive(transaction, queueName, null, TimeSpan.FromDays(1));
}
public Message Receive(ITransaction transaction, string queueName, TimeSpan timeout)
{
return Receive(transaction, queueName, null, timeout);
}
public Message Receive(ITransaction transaction, string queueName, string subqueue)
{
return Receive(transaction, queueName, subqueue, TimeSpan.FromDays(1));
}
public Message Receive(ITransaction transaction, string queueName, string subqueue, TimeSpan timeout)
{
var remaining = timeout;
while (true)
{
var message = GetMessageFromQueue(transaction, queueName, subqueue);
if (message != null)
{
OnMessageReceived(message);
return message;
}
lock (newMessageArrivedLock)
{
message = GetMessageFromQueue(transaction, queueName, subqueue);
if (message != null)
{
OnMessageReceived(message);
return message;
}
var sp = Stopwatch.StartNew();
if (Monitor.Wait(newMessageArrivedLock, remaining) == false)
throw new TimeoutException("No message arrived in the specified timeframe " + timeout);
var newRemaining = remaining - sp.Elapsed;
remaining = newRemaining >= TimeSpan.Zero ? newRemaining : TimeSpan.Zero;
}
}
}
public MessageId Send(ITransaction transaction, Uri uri, MessagePayload payload)
{
if (waitingForAllMessagesToBeSent)
throw new CannotSendWhileWaitingForAllMessagesToBeSentException("Currently waiting for all messages to be sent, so we cannot send. You probably have a race condition in your application.");
var parts = uri.AbsolutePath.Substring(1).Split('/');
var queue = parts[0];
string subqueue = null;
if (parts.Length > 1)
{
subqueue = string.Join("/", parts.Skip(1).ToArray());
}
Guid msgId = Guid.Empty;
var port = uri.Port;
if (port == -1)
port = 2200;
var destination = new Endpoint(uri.Host, port);
queueStorage.Global(actions =>
{
msgId = actions.RegisterToSend(destination, queue,
subqueue, payload, transaction.Id);
actions.Commit();
});
var messageId = new MessageId
{
SourceInstanceId = queueStorage.Id,
MessageIdentifier = msgId
};
var message = new Message
{
Id = messageId,
Data = payload.Data,
Headers = payload.Headers,
Queue = queue,
SubQueue = subqueue
};
OnMessageQueuedForSend(new MessageEventArgs(destination, message));
return messageId;
}
}
}
#pragma warning restore 420
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//============================================================
//
// File: HttpStreams.cs
//
// Summary: Defines streams used by HTTP channels
//
//============================================================
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Globalization;
namespace System.Runtime.Remoting.Channels.Http
{
internal abstract class HttpServerResponseStream : Stream
{
public override bool CanRead { get { return false; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return true; } }
public override long Length { get { throw new NotSupportedException(); } }
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
} // HttpServerResponseStream
internal sealed class HttpFixedLengthResponseStream : HttpServerResponseStream
{
private Stream _outputStream = null; // funnel http data into here
private static int _length;
internal HttpFixedLengthResponseStream(Stream outputStream, int length)
{
_outputStream = outputStream;
_length = length;
} // HttpFixedLengthResponseStream
protected override void Dispose(bool disposing)
{
try {
if (disposing)
_outputStream.Flush();
}
finally {
base.Dispose(disposing);
}
} // Close
public override void Flush()
{
_outputStream.Flush();
} // Flush
public override void Write(byte[] buffer, int offset, int count)
{
_outputStream.Write(buffer, offset, count);
} // Write
public override void WriteByte(byte value)
{
_outputStream.WriteByte(value);
} // WriteByte
} // class HttpFixedLengthResponseStream
internal sealed class HttpChunkedResponseStream : HttpServerResponseStream
{
private static byte[] _trailer = Encoding.ASCII.GetBytes("0\r\n\r\n"); // 0-length, no trailer, end chunked
private static byte[] _endChunk = Encoding.ASCII.GetBytes("\r\n");
private Stream _outputStream = null; // funnel chunked http data into here
private byte[] _chunk; // chunk of data to write
private int _chunkSize; // size of chunk
private int _chunkOffset; // next byte to write in to chunk
private byte[] _byteBuffer = new byte[1]; // buffer for writing bytes
internal HttpChunkedResponseStream(Stream outputStream)
{
_outputStream = outputStream;
_chunk = CoreChannel.BufferPool.GetBuffer();
_chunkSize = _chunk.Length - 2; // reserve space for _endChunk directly in buffer
_chunkOffset = 0;
// write end chunk bytes at end of buffer (avoids extra socket write)
_chunk[_chunkSize - 2] = (byte)'\r';
_chunk[_chunkSize - 1] = (byte)'\n';
} // HttpChunkedResponseStream
protected override void Dispose(bool disposing)
{
try {
if (disposing) {
if (_chunkOffset > 0)
FlushChunk();
_outputStream.Write(_trailer, 0, _trailer.Length);
_outputStream.Flush();
}
CoreChannel.BufferPool.ReturnBuffer(_chunk);
_chunk = null;
}
finally {
base.Dispose(disposing);
}
} // Close
public override void Flush()
{
if (_chunkOffset > 0)
FlushChunk();
_outputStream.Flush();
} // Flush
public override void Write(byte[] buffer, int offset, int count)
{
while (count > 0)
{
if ((_chunkOffset == 0) && (count >= _chunkSize))
{
// just write the rest as a chunk directly to the wire
WriteChunk(buffer, offset, count);
break;
}
else
{
// write bytes to current chunk buffer
int writeCount = Math.Min(_chunkSize - _chunkOffset, count);
Array.Copy(buffer, offset, _chunk, _chunkOffset, writeCount);
_chunkOffset += writeCount;
count -= writeCount;
offset += writeCount;
// see if we need to terminate the chunk
if (_chunkOffset == _chunkSize)
FlushChunk();
}
}
} // Write
public override void WriteByte(byte value)
{
_byteBuffer[0] = value;
Write(_byteBuffer, 0, 1);
} // WriteByte
private void FlushChunk()
{
WriteChunk(_chunk, 0, _chunkOffset);
_chunkOffset = 0;
}
private void WriteChunk(byte[] buffer, int offset, int count)
{
byte[] size = IntToHexChars(count);
_outputStream.Write(size, 0, size.Length);
if (buffer == _chunk)
{
// _chunk already has end chunk encoding at end
_outputStream.Write(_chunk, offset, count + 2);
}
else
{
_outputStream.Write(buffer, offset, count);
_outputStream.Write(_endChunk, 0, _endChunk.Length);
}
} // WriteChunk
private byte[] IntToHexChars(int i)
{
String str = "";
while (i > 0)
{
int val = i % 16;
switch (val)
{
case 15: str = 'F' + str; break;
case 14: str = 'E' + str; break;
case 13: str = 'D' + str; break;
case 12: str = 'C' + str; break;
case 11: str = 'B' + str; break;
case 10: str = 'A' + str; break;
default: str = (char)(val + (int)'0') + str; break;
}
i = i / 16;
}
str += "\r\n";
return Encoding.ASCII.GetBytes(str);
} // IntToHexChars
} // HttpChunkedResponseStream
internal abstract class HttpReadingStream : Stream
{
public virtual bool ReadToEnd()
{
// This will never be called at a point where it is valid
// for someone to use the remaining data, so we don't
// need to buffer it.
byte[] buffer = new byte[16];
int bytesRead = 0;
do
{
bytesRead = Read(buffer, 0, 16);
} while (bytesRead > 0);
return bytesRead == 0;
}
public virtual bool FoundEnd { get { return false; } }
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return false; } }
public override bool CanWrite { get { return false; } }
public override long Length { get { throw new NotSupportedException(); } }
public override long Position
{
get{ throw new NotSupportedException(); }
set{ throw new NotSupportedException(); }
}
public override void Flush() { throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
} // HttpReadingStream
internal sealed class HttpFixedLengthReadingStream : HttpReadingStream
{
private HttpSocketHandler _inputStream = null; // read content data from here
private int _bytesLeft; // bytes left in current chunk
internal HttpFixedLengthReadingStream(HttpSocketHandler inputStream, int contentLength)
{
_inputStream = inputStream;
_bytesLeft = contentLength;
} // HttpFixedLengthReadingStream
public override bool FoundEnd { get { return _bytesLeft == 0; } }
protected override void Dispose(bool disposing)
{
try {
//
}
finally {
base.Dispose(disposing);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_bytesLeft == 0)
return 0;
int readCount = _inputStream.Read(buffer, offset, Math.Min(_bytesLeft, count));
if (readCount > 0)
_bytesLeft -= readCount;
return readCount;
} // Read
public override int ReadByte()
{
if (_bytesLeft == 0)
return -1;
_bytesLeft -= 1;
return _inputStream.ReadByte();
} // ReadByte
} // HttpFixedLengthReadingStream
// Stream class to read chunked data for HTTP
// (assumes that provided outputStream will be positioned for
// reading the body)
internal sealed class HttpChunkedReadingStream : HttpReadingStream
{
private static byte[] _trailer = Encoding.ASCII.GetBytes("0\r\n\r\n\r\n"); // 0-length, null trailer, end chunked
private static byte[] _endChunk = Encoding.ASCII.GetBytes("\r\n");
private HttpSocketHandler _inputStream = null; // read chunked http data from here
private int _bytesLeft; // bytes left in current chunk
private bool _bFoundEnd = false; // has end of stream been reached?
private byte[] _byteBuffer = new byte[1]; // buffer for reading bytes
internal HttpChunkedReadingStream(HttpSocketHandler inputStream)
{
_inputStream = inputStream;
_bytesLeft = 0;
} // HttpChunkedReadingStream
public override bool FoundEnd { get { return _bFoundEnd; } }
protected override void Dispose(bool disposing)
{
try {
//
}
finally {
base.Dispose(disposing);
}
} // Close
public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = 0;
while (!_bFoundEnd && (count > 0))
{
// see if we need to start reading a new chunk
if (_bytesLeft == 0)
{
// this loop stops when the end of line is found
for (;;)
{
byte b = (byte)_inputStream.ReadByte();
// see if this is the end of the length
if (b == '\r')
{
// This had better be '\n'
if ((char)_inputStream.ReadByte() != '\n')
{
throw new RemotingException(
CoreChannel.GetResourceString(
"Remoting_Http_ChunkedEncodingError"));
}
else
break; // we've finished reading the length
}
else
{
int value = HttpChannelHelper.CharacterHexDigitToDecimal(b);
// make sure value is a hex-digit
if ((value < 0) || (value > 15))
{
throw new RemotingException(
CoreChannel.GetResourceString(
"Remoting_Http_ChunkedEncodingError"));
}
// update _bytesLeft value to account for new digit on the right
_bytesLeft = (_bytesLeft * 16) + value;
}
}
if (_bytesLeft == 0)
{
// read off trailing headers and end-line
String trailerHeader;
do
{
trailerHeader = _inputStream.ReadToEndOfLine();
} while (!(trailerHeader.Length == 0));
_bFoundEnd = true;
}
}
if (!_bFoundEnd)
{
int readCount = Math.Min(_bytesLeft, count);
int bytesReadThisTime = _inputStream.Read(buffer, offset, readCount);
if (bytesReadThisTime <= 0)
{
throw new RemotingException(
CoreChannel.GetResourceString(
"Remoting_Http_ChunkedEncodingError"));
}
_bytesLeft -= bytesReadThisTime;
count -= bytesReadThisTime;
offset += bytesReadThisTime;
bytesRead += bytesReadThisTime;
// see if the end of the chunk was found
if (_bytesLeft == 0)
{
// read off "\r\n"
char ch = (char)_inputStream.ReadByte();
if (ch != '\r')
{
throw new RemotingException(
CoreChannel.GetResourceString(
"Remoting_Http_ChunkedEncodingError"));
}
ch = (char)_inputStream.ReadByte();
if (ch != '\n')
{
throw new RemotingException(
CoreChannel.GetResourceString(
"Remoting_Http_ChunkedEncodingError"));
}
}
}
} // while (count > 0)
return bytesRead;
} // Read
public override int ReadByte()
{
int readCount = Read(_byteBuffer, 0, 1);
if (readCount == 0)
return -1;
return _byteBuffer[0];
} // ReadByte
} // class HttpChunkedReadingStream
[Serializable]
internal enum HttpVersion
{
V1_0,
V1_1
} // HttpVersion
// Maintains control of a socket connection.
internal sealed class HttpServerSocketHandler : HttpSocketHandler
{
// Used to make sure verb characters are valid
private static ValidateByteDelegate s_validateVerbDelegate =
new ValidateByteDelegate(HttpServerSocketHandler.ValidateVerbCharacter);
// Used to keep track of socket connections
private static Int64 _connectionIdCounter = 0;
// primed buffer data
private static byte[] _bufferhttpContinue = Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n");
// stream manager data
private HttpReadingStream _requestStream = null; // request stream we handed out.
private HttpServerResponseStream _responseStream = null; // response stream we handed out.
private Int64 _connectionId; // id for this connection
// request state flags
private HttpVersion _version; // http version used by client
private int _contentLength = 0; // Content-Length value if found
private bool _chunkedEncoding = false; // does request stream use chunked encoding?
private bool _keepAlive = false; // does the client want to keep the connection alive?
internal HttpServerSocketHandler(Socket socket, RequestQueue requestQueue, Stream stream) : base(socket, requestQueue, stream)
{
_connectionId = Interlocked.Increment(ref _connectionIdCounter);
} // HttpServerSocketHandler
//
public bool AllowChunkedResponse { get { return false; } }
// Determine if it's possible to service another request
public bool CanServiceAnotherRequest()
{
if (_keepAlive && (_requestStream != null))
{
if (_requestStream.FoundEnd || _requestStream.ReadToEnd())
return true;
}
return false;
} // CanServiceAnotherRequest
// Prepare for reading a new request off of the same socket
protected override void PrepareForNewMessage()
{
_requestStream = null;
_responseStream = null;
_contentLength = 0;
_chunkedEncoding = false;
_keepAlive = false;
} // PrepareForNewRequest
string GenerateFaultString(Exception e) {
//If the user has specified it's a development server (versus a production server) in remoting config,
//then we should just return e.ToString instead of extracting the list of messages.
if (!CustomErrorsEnabled())
return e.ToString();
else {
return CoreChannel.GetResourceString("Remoting_InternalError");
}
}
protected override void SendErrorMessageIfPossible(Exception e)
{
// If we haven't started sending a response back, we can do the following.
if ((_responseStream == null) && !(e is SocketException))
{
Stream outputStream = new MemoryStream();
StreamWriter writer = new StreamWriter(outputStream, new UTF8Encoding(false));
writer.WriteLine(GenerateFaultString(e));
writer.Flush();
SendResponse(outputStream, "500", CoreChannel.GetResourceString("Remoting_InternalError"), null);
}
} // SendErrorMessageIfPossible
private static bool ValidateVerbCharacter(byte b)
{
if (Char.IsLetter((char)b) ||
(b == '-'))
{
return true;
}
return false;
} // ValidateVerbCharacter
// read headers
public BaseTransportHeaders ReadHeaders()
{
bool bSendContinue = false;
BaseTransportHeaders headers = new BaseTransportHeaders();
// read first line
String verb, requestURI, version;
ReadFirstLine(out verb, out requestURI, out version);
if ((verb == null) || (requestURI == null) || (version == null))
{
throw new RemotingException(
CoreChannel.GetResourceString(
"Remoting_Http_UnableToReadFirstLine"));
}
if (version.Equals("HTTP/1.1")) // most common case
_version = HttpVersion.V1_1;
else
if (version.Equals("HTTP/1.0"))
_version = HttpVersion.V1_0;
else
_version = HttpVersion.V1_1; // (assume it will understand 1.1)
if (_version == HttpVersion.V1_1)
{
_keepAlive = true;
}
else // it's a 1.0 client
{
_keepAlive = false;
}
// update request uri to be sure that it has no channel data
String channelURI;
String objectURI;
channelURI = HttpChannelHelper.ParseURL(requestURI, out objectURI);
if (channelURI == null)
{
objectURI = requestURI;
}
headers["__RequestVerb"] = verb;
headers.RequestUri = objectURI;
headers["__HttpVersion"] = version;
// check to see if we must send continue
if ((_version == HttpVersion.V1_1) &&
(verb.Equals("POST") || verb.Equals("PUT")))
{
bSendContinue = true;
}
ReadToEndOfHeaders(headers, out _chunkedEncoding, out _contentLength,
ref _keepAlive, ref bSendContinue);
if (bSendContinue && (_version != HttpVersion.V1_0))
SendContinue();
// add IP address and Connection Id to headers
headers[CommonTransportKeys.IPAddress] = ((IPEndPoint)NetSocket.RemoteEndPoint).Address;
headers[CommonTransportKeys.ConnectionId] = _connectionId;
return headers;
} // ReadHeaders
public Stream GetRequestStream()
{
if (_chunkedEncoding)
_requestStream = new HttpChunkedReadingStream(this);
else
_requestStream = new HttpFixedLengthReadingStream(this, _contentLength);
return _requestStream;
} // GetRequestStream
public Stream GetResponseStream(String statusCode, String reasonPhrase,
ITransportHeaders headers)
{
bool contentLengthPresent = false;
bool useChunkedEncoding = false;
int contentLength = 0;
// check for custom user status code and reason phrase
Object userStatusCode = headers["__HttpStatusCode"]; // someone might have stored an int
String userReasonPhrase = headers["__HttpReasonPhrase"] as String;
if (userStatusCode != null)
statusCode = userStatusCode.ToString();
if (userReasonPhrase != null)
reasonPhrase = userReasonPhrase;
// see if we can handle any more requests on this socket
if (!CanServiceAnotherRequest())
{
headers["Connection"] = "Close";
}
// check for content length
Object contentLengthEntry = headers["Content-Length"];
if (contentLengthEntry != null)
{
contentLengthPresent = true;
if (contentLengthEntry is int)
contentLength = (int)contentLengthEntry;
else
contentLength = Convert.ToInt32(contentLengthEntry, CultureInfo.InvariantCulture);
}
// see if we are going to use chunked-encoding
useChunkedEncoding = AllowChunkedResponse && !contentLengthPresent;
if (useChunkedEncoding)
headers["Transfer-Encoding"] = "chunked";
// write headers to stream
ChunkedMemoryStream headerStream = new ChunkedMemoryStream(CoreChannel.BufferPool);
WriteResponseFirstLine(statusCode, reasonPhrase, headerStream);
WriteHeaders(headers, headerStream);
headerStream.WriteTo(NetStream);
headerStream.Close();
// return stream ready for content
if (useChunkedEncoding)
_responseStream = new HttpChunkedResponseStream(NetStream);
else
_responseStream = new HttpFixedLengthResponseStream(NetStream, contentLength);
return _responseStream;
} // GetResponseStream
private bool ReadFirstLine(out String verb, out String requestURI, out String version)
{
verb = null;
requestURI = null;
version = null;
verb = ReadToChar(' ', s_validateVerbDelegate);
byte[] requestUriBytes = ReadToByte((byte)' ');
int decodedUriLength;
HttpChannelHelper.DecodeUriInPlace(requestUriBytes, out decodedUriLength);
requestURI = Encoding.UTF8.GetString(requestUriBytes, 0, decodedUriLength);
version = ReadToEndOfLine();
return true;
} // ReadFirstLine
private void SendContinue()
{
// Output:
// HTTP/1.1 100 Continue
// Send the continue response back to the client
NetStream.Write(_bufferhttpContinue, 0, _bufferhttpContinue.Length);
} // SendContinue
public void SendResponse(Stream httpContentStream,
String statusCode, String reasonPhrase,
ITransportHeaders headers)
{
if (_responseStream != null)
{
_responseStream.Close();
if (_responseStream != httpContentStream)
{
throw new RemotingException(
CoreChannel.GetResourceString("Remoting_Http_WrongResponseStream"));
}
// we are done with the response stream
_responseStream = null;
}
else
{
if (headers == null)
headers = new TransportHeaders();
String serverHeader = (String)headers["Server"];
if (serverHeader != null)
serverHeader = HttpServerTransportSink.ServerHeader + ", " + serverHeader;
else
serverHeader = HttpServerTransportSink.ServerHeader;
headers["Server"] = serverHeader;
// Add length to response headers if necessary
if (!AllowChunkedResponse && (httpContentStream != null))
headers["Content-Length"] = httpContentStream.Length.ToString(CultureInfo.InvariantCulture);
else
if (httpContentStream == null)
headers["Content-Length"] = "0";
GetResponseStream(statusCode, reasonPhrase, headers);
// write HTTP content
if(httpContentStream != null)
{
StreamHelper.CopyStream(httpContentStream, _responseStream);
_responseStream.Close();
httpContentStream.Close();
}
// we are done with the response stream
_responseStream = null;
}
} // SendResponse
} // class HttpServerSocketHandler
} // namespace System.Runtime.Remoting.Channels.Http
| |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
using ChargeBee.Filters.Enums;
namespace ChargeBee.Models
{
public class PortalSession : Resource
{
public PortalSession() { }
public PortalSession(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
}
public PortalSession(TextReader reader)
{
JObj = JToken.Parse(reader.ReadToEnd());
apiVersionCheck (JObj);
}
public PortalSession(String jsonString)
{
JObj = JToken.Parse(jsonString);
apiVersionCheck (JObj);
}
#region Methods
public static CreateRequest Create()
{
string url = ApiUtil.BuildUrl("portal_sessions");
return new CreateRequest(url, HttpMethod.POST);
}
public static EntityRequest<Type> Retrieve(string id)
{
string url = ApiUtil.BuildUrl("portal_sessions", CheckNull(id));
return new EntityRequest<Type>(url, HttpMethod.GET);
}
public static EntityRequest<Type> Logout(string id)
{
string url = ApiUtil.BuildUrl("portal_sessions", CheckNull(id), "logout");
return new EntityRequest<Type>(url, HttpMethod.POST);
}
public static ActivateRequest Activate(string id)
{
string url = ApiUtil.BuildUrl("portal_sessions", CheckNull(id), "activate");
return new ActivateRequest(url, HttpMethod.POST);
}
#endregion
#region Properties
public string Id
{
get { return GetValue<string>("id", true); }
}
public string Token
{
get { return GetValue<string>("token", true); }
}
public string AccessUrl
{
get { return GetValue<string>("access_url", true); }
}
public string RedirectUrl
{
get { return GetValue<string>("redirect_url", false); }
}
public StatusEnum Status
{
get { return GetEnum<StatusEnum>("status", true); }
}
public DateTime CreatedAt
{
get { return (DateTime)GetDateTime("created_at", true); }
}
public DateTime? ExpiresAt
{
get { return GetDateTime("expires_at", false); }
}
public string CustomerId
{
get { return GetValue<string>("customer_id", true); }
}
public DateTime? LoginAt
{
get { return GetDateTime("login_at", false); }
}
public DateTime? LogoutAt
{
get { return GetDateTime("logout_at", false); }
}
public string LoginIpaddress
{
get { return GetValue<string>("login_ipaddress", false); }
}
public string LogoutIpaddress
{
get { return GetValue<string>("logout_ipaddress", false); }
}
public List<PortalSessionLinkedCustomer> LinkedCustomers
{
get { return GetResourceList<PortalSessionLinkedCustomer>("linked_customers"); }
}
#endregion
#region Requests
public class CreateRequest : EntityRequest<CreateRequest>
{
public CreateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public CreateRequest RedirectUrl(string redirectUrl)
{
m_params.AddOpt("redirect_url", redirectUrl);
return this;
}
public CreateRequest ForwardUrl(string forwardUrl)
{
m_params.AddOpt("forward_url", forwardUrl);
return this;
}
public CreateRequest CustomerId(string customerId)
{
m_params.Add("customer[id]", customerId);
return this;
}
}
public class ActivateRequest : EntityRequest<ActivateRequest>
{
public ActivateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public ActivateRequest Token(string token)
{
m_params.Add("token", token);
return this;
}
}
#endregion
public enum StatusEnum
{
UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a
dotnet-client version incompatibility. We suggest you to upgrade to the latest version */
[EnumMember(Value = "created")]
Created,
[EnumMember(Value = "logged_in")]
LoggedIn,
[EnumMember(Value = "logged_out")]
LoggedOut,
[EnumMember(Value = "not_yet_activated")]
NotYetActivated,
[EnumMember(Value = "activated")]
Activated,
}
#region Subclasses
public class PortalSessionLinkedCustomer : Resource
{
public string CustomerId {
get { return GetValue<string>("customer_id", true); }
}
public string Email {
get { return GetValue<string>("email", false); }
}
public bool HasBillingAddress {
get { return GetValue<bool>("has_billing_address", true); }
}
public bool HasPaymentMethod {
get { return GetValue<bool>("has_payment_method", true); }
}
public bool HasActiveSubscription {
get { return GetValue<bool>("has_active_subscription", true); }
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace XWG.Laboratory.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.Setup;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Logging;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Notifications;
using QuantConnect.Statistics;
namespace QuantConnect.Lean.Engine.Results
{
/// <summary>
/// Console local resulthandler passes messages back to the console/local GUI display.
/// </summary>
public class ConsoleResultHandler : IResultHandler
{
private bool _isActive;
private bool _exitTriggered;
private DateTime _updateTime;
private DateTime _lastSampledTimed;
private IAlgorithm _algorithm;
private readonly object _chartLock;
private IConsoleStatusHandler _algorithmNode;
private IMessagingHandler _messagingHandler;
//Sampling Periods:
private DateTime _nextSample;
private TimeSpan _resamplePeriod;
private readonly TimeSpan _notificationPeriod;
private string _chartDirectory;
private readonly Dictionary<string, List<string>> _equityResults;
/// <summary>
/// A dictionary containing summary statistics
/// </summary>
public Dictionary<string, string> FinalStatistics { get; private set; }
/// <summary>
/// Messaging to store notification messages for processing.
/// </summary>
public ConcurrentQueue<Packet> Messages
{
get;
set;
}
/// <summary>
/// Local object access to the algorithm for the underlying Debug and Error messaging.
/// </summary>
public IAlgorithm Algorithm
{
get
{
return _algorithm;
}
set
{
_algorithm = value;
}
}
/// <summary>
/// Charts collection for storing the master copy of user charting data.
/// </summary>
public ConcurrentDictionary<string, Chart> Charts
{
get;
set;
}
/// <summary>
/// Boolean flag indicating the result hander thread is busy.
/// False means it has completely finished and ready to dispose.
/// </summary>
public bool IsActive {
get
{
return _isActive;
}
}
/// <summary>
/// Sampling period for timespans between resamples of the charting equity.
/// </summary>
/// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks>
public TimeSpan ResamplePeriod
{
get
{
return _resamplePeriod;
}
}
/// <summary>
/// How frequently the backtests push messages to the browser.
/// </summary>
/// <remarks>Update frequency of notification packets</remarks>
public TimeSpan NotificationPeriod
{
get
{
return _notificationPeriod;
}
}
/// <summary>
/// Console result handler constructor.
/// </summary>
public ConsoleResultHandler()
{
Messages = new ConcurrentQueue<Packet>();
Charts = new ConcurrentDictionary<string, Chart>();
FinalStatistics = new Dictionary<string, string>();
_chartLock = new Object();
_isActive = true;
_notificationPeriod = TimeSpan.FromSeconds(5);
_equityResults = new Dictionary<string, List<string>>();
}
/// <summary>
/// Initialize the result handler with this result packet.
/// </summary>
/// <param name="packet">Algorithm job packet for this result handler</param>
/// <param name="messagingHandler"></param>
/// <param name="api"></param>
/// <param name="dataFeed"></param>
/// <param name="setupHandler"></param>
/// <param name="transactionHandler"></param>
public void Initialize(AlgorithmNodePacket packet, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler)
{
// we expect one of two types here, the backtest node packet or the live node packet
var job = packet as BacktestNodePacket;
if (job != null)
{
_algorithmNode = new BacktestConsoleStatusHandler(job);
}
else
{
var live = packet as LiveNodePacket;
if (live == null)
{
throw new ArgumentException("Unexpected AlgorithmNodeType: " + packet.GetType().Name);
}
_algorithmNode = new LiveConsoleStatusHandler(live);
}
_resamplePeriod = _algorithmNode.ComputeSampleEquityPeriod();
var time = DateTime.Now.ToString("yyyy-MM-dd-HH-mm");
_chartDirectory = Path.Combine("../../../Charts/", packet.AlgorithmId, time);
if (Directory.Exists(_chartDirectory))
{
foreach (var file in Directory.EnumerateFiles(_chartDirectory, "*.csv", SearchOption.AllDirectories))
{
File.Delete(file);
}
Directory.Delete(_chartDirectory, true);
}
Directory.CreateDirectory(_chartDirectory);
_messagingHandler = messagingHandler;
}
/// <summary>
/// Entry point for console result handler thread.
/// </summary>
public void Run()
{
try
{
while ( !_exitTriggered || Messages.Count > 0 )
{
Thread.Sleep(100);
var now = DateTime.UtcNow;
if (now > _updateTime)
{
_updateTime = now.AddSeconds(5);
_algorithmNode.LogAlgorithmStatus(_lastSampledTimed);
}
}
// Write Equity and EquityPerformance files in charts directory
foreach (var fileName in _equityResults.Keys)
{
File.WriteAllLines(fileName, _equityResults[fileName]);
}
}
catch (Exception err)
{
// unexpected error, we need to close down shop
Log.Error(err);
// quit the algorithm due to error
_algorithm.RunTimeError = err;
}
Log.Trace("ConsoleResultHandler: Ending Thread...");
_isActive = false;
}
/// <summary>
/// Send a debug message back to the browser console.
/// </summary>
/// <param name="message">Message we'd like shown in console.</param>
public void DebugMessage(string message)
{
Log.Trace(_algorithm.Time + ": Debug >> " + message);
}
/// <summary>
/// Send a logging message to the log list for storage.
/// </summary>
/// <param name="message">Message we'd in the log.</param>
public void LogMessage(string message)
{
Log.Trace(_algorithm.Time + ": Log >> " + message);
}
/// <summary>
/// Send a runtime error message back to the browser highlighted with in red
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="stacktrace">Stacktrace information string</param>
public void RuntimeError(string message, string stacktrace = "")
{
Log.Error(_algorithm.Time + ": Error >> " + message + (!string.IsNullOrEmpty(stacktrace) ? (" >> ST: " + stacktrace) : ""));
}
/// <summary>
/// Send an error message back to the console highlighted in red with a stacktrace.
/// </summary>
/// <param name="message">Error message we'd like shown in console.</param>
/// <param name="stacktrace">Stacktrace information string</param>
public void ErrorMessage(string message, string stacktrace = "")
{
Log.Error(_algorithm.Time + ": Error >> " + message + (!string.IsNullOrEmpty(stacktrace) ? (" >> ST: " + stacktrace) : ""));
}
/// <summary>
/// Add a sample to the chart specified by the chartName, and seriesName.
/// </summary>
/// <param name="chartName">String chart name to place the sample.</param>
/// <param name="chartType">Type of chart we should create if it doesn't already exist.</param>
/// <param name="seriesName">Series name for the chart.</param>
/// <param name="seriesType">Series type for the chart.</param>
/// <param name="time">Time for the sample</param>
/// <param name="value">Value for the chart sample.</param>
/// <param name="unit">Unit for the sample axis</param>
/// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks>
public void Sample(string chartName, ChartType chartType, string seriesName, SeriesType seriesType, DateTime time, decimal value, string unit = "$")
{
var chartFilename = Path.Combine(_chartDirectory, chartName + "-" + seriesName + ".csv");
lock (_chartLock)
{
// Add line to list in dictionary, will be written to file at the end
List<string> rows;
if (!_equityResults.TryGetValue(chartFilename, out rows))
{
rows = new List<string>();
_equityResults[chartFilename] = rows;
}
rows.Add(time + "," + value.ToString("F2", CultureInfo.InvariantCulture));
//Add a copy locally:
if (!Charts.ContainsKey(chartName))
{
Charts.AddOrUpdate<string, Chart>(chartName, new Chart(chartName, chartType));
}
//Add the sample to our chart:
if (!Charts[chartName].Series.ContainsKey(seriesName))
{
Charts[chartName].Series.Add(seriesName, new Series(seriesName, seriesType));
}
//Add our value:
Charts[chartName].Series[seriesName].Values.Add(new ChartPoint(time, value));
}
}
/// <summary>
/// Sample the strategy equity at this moment in time.
/// </summary>
/// <param name="time">Current time</param>
/// <param name="value">Current equity value</param>
public void SampleEquity(DateTime time, decimal value)
{
Sample("Strategy Equity", ChartType.Stacked, "Equity", SeriesType.Candle, time, value);
_lastSampledTimed = time;
}
/// <summary>
/// Sample today's algorithm daily performance value.
/// </summary>
/// <param name="time">Current time.</param>
/// <param name="value">Value of the daily performance.</param>
public void SamplePerformance(DateTime time, decimal value)
{
Sample("Strategy Equity", ChartType.Overlay, "Daily Performance", SeriesType.Line, time, value, "%");
}
/// <summary>
/// Sample the current benchmark performance directly with a time-value pair.
/// </summary>
/// <param name="time">Current backtest date.</param>
/// <param name="value">Current benchmark value.</param>
/// <seealso cref="IResultHandler.Sample"/>
public void SampleBenchmark(DateTime time, decimal value)
{
Sample("Benchmark", ChartType.Stacked, "Benchmark", SeriesType.Line, time, value);
}
/// <summary>
/// Analyse the algorithm and determine its security types.
/// </summary>
/// <param name="types">List of security types in the algorithm</param>
public void SecurityType(List<SecurityType> types)
{
//NOP
}
/// <summary>
/// Send an algorithm status update to the browser.
/// </summary>
/// <param name="algorithmId">Algorithm id for the status update.</param>
/// <param name="status">Status enum value.</param>
/// <param name="message">Additional optional status message.</param>
/// <remarks>In backtesting we do not send the algorithm status updates.</remarks>
public void SendStatusUpdate(string algorithmId, AlgorithmStatus status, string message = "")
{
Log.Trace("ConsoleResultHandler.SendStatusUpdate(): Algorithm Status: " + status + " : " + message);
}
/// <summary>
/// Sample the asset prices to generate plots.
/// </summary>
/// <param name="symbol">Symbol we're sampling.</param>
/// <param name="time">Time of sample</param>
/// <param name="value">Value of the asset price</param>
public void SampleAssetPrices(Symbol symbol, DateTime time, decimal value)
{
//NOP. Don't sample asset prices in console.
}
/// <summary>
/// Add a range of samples to the store.
/// </summary>
/// <param name="updates">Charting updates since the last sample request.</param>
public void SampleRange(List<Chart> updates)
{
lock (_chartLock)
{
foreach (var update in updates)
{
//Create the chart if it doesn't exist already:
if (!Charts.ContainsKey(update.Name))
{
Charts.AddOrUpdate(update.Name, new Chart(update.Name, update.ChartType));
}
//Add these samples to this chart.
foreach (var series in update.Series.Values)
{
//If we don't already have this record, its the first packet
if (!Charts[update.Name].Series.ContainsKey(series.Name))
{
Charts[update.Name].Series.Add(series.Name, new Series(series.Name, series.SeriesType));
}
//We already have this record, so just the new samples to the end:
Charts[update.Name].Series[series.Name].Values.AddRange(series.Values);
}
}
}
}
/// <summary>
/// Algorithm final analysis results dumped to the console.
/// </summary>
/// <param name="job">Lean AlgorithmJob task</param>
/// <param name="orders">Collection of orders from the algorithm</param>
/// <param name="profitLoss">Collection of time-profit values for the algorithm</param>
/// <param name="holdings">Current holdings state for the algorithm</param>
/// <param name="statisticsResults">Statistics information for the algorithm (empty if not finished)</param>
/// <param name="banner">Runtime statistics banner information</param>
public void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, StatisticsResults statisticsResults, Dictionary<string, string> banner)
{
// uncomment these code traces to help write regression tests
//Console.WriteLine("var statistics = new Dictionary<string, string>();");
// Bleh. Nicely format statistical analysis on your algorithm results. Save to file etc.
foreach (var pair in statisticsResults.Summary)
{
Log.Trace("STATISTICS:: " + pair.Key + " " + pair.Value);
//Console.WriteLine(string.Format("statistics.Add(\"{0}\",\"{1}\");", pair.Key, pair.Value));
}
//foreach (var pair in statisticsResults.RollingPerformances)
//{
// Log.Trace("ROLLINGSTATS:: " + pair.Key + " SharpeRatio: " + Math.Round(pair.Value.PortfolioStatistics.SharpeRatio, 3));
//}
FinalStatistics = statisticsResults.Summary;
}
/// <summary>
/// Set the Algorithm instance for ths result.
/// </summary>
/// <param name="algorithm">Algorithm we're working on.</param>
/// <remarks>While setting the algorithm the backtest result handler.</remarks>
public void SetAlgorithm(IAlgorithm algorithm)
{
_algorithm = algorithm;
}
/// <summary>
/// Terminate the result thread and apply any required exit proceedures.
/// </summary>
public void Exit()
{
_exitTriggered = true;
}
/// <summary>
/// Send a new order event to the browser.
/// </summary>
/// <remarks>In backtesting the order events are not sent because it would generate a high load of messaging.</remarks>
/// <param name="newEvent">New order event details</param>
public void OrderEvent(OrderEvent newEvent)
{
Log.Debug("ConsoleResultHandler.OrderEvent(): id:" + newEvent.OrderId + " >> Status:" + newEvent.Status + " >> Fill Price: " + newEvent.FillPrice.ToString("C") + " >> Fill Quantity: " + newEvent.FillQuantity);
}
/// <summary>
/// Set the current runtime statistics of the algorithm
/// </summary>
/// <param name="key">Runtime headline statistic name</param>
/// <param name="value">Runtime headline statistic value</param>
public void RuntimeStatistic(string key, string value)
{
Log.Trace("ConsoleResultHandler.RuntimeStatistic(): " + key + " : " + value);
}
/// <summary>
/// Clear the outstanding message queue to exit the thread.
/// </summary>
public void PurgeQueue()
{
Messages.Clear();
}
/// <summary>
/// Store result on desktop.
/// </summary>
/// <param name="packet">Packet of data to store.</param>
/// <param name="async">Store the packet asyncronously to speed up the thread.</param>
/// <remarks>Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now.</remarks>
public void StoreResult(Packet packet, bool async = false)
{
// Do nothing.
}
/// <summary>
/// Provides an abstraction layer for live vs backtest packets to provide status/sampling to the AlgorithmManager
/// </summary>
/// <remarks>
/// Since we can run both live and back test from the console, we need two implementations of what to do
/// at certain times
/// </remarks>
private interface IConsoleStatusHandler
{
void LogAlgorithmStatus(DateTime current);
TimeSpan ComputeSampleEquityPeriod();
}
// uses a const 2 second sample equity period and does nothing for logging algorithm status
private class LiveConsoleStatusHandler : IConsoleStatusHandler
{
private readonly LiveNodePacket _job;
public LiveConsoleStatusHandler(LiveNodePacket _job)
{
this._job = _job;
}
public void LogAlgorithmStatus(DateTime current)
{
// later we can log daily %Gain if possible
}
public TimeSpan ComputeSampleEquityPeriod()
{
return TimeSpan.FromSeconds(2);
}
}
// computes sample equity period from 4000 samples evenly spaced over the backtest interval and logs %complete to log file
private class BacktestConsoleStatusHandler : IConsoleStatusHandler
{
private readonly BacktestNodePacket _job;
private double? _backtestSpanInDays;
public BacktestConsoleStatusHandler(BacktestNodePacket _job)
{
this._job = _job;
}
public void LogAlgorithmStatus(DateTime current)
{
if (!_backtestSpanInDays.HasValue)
{
_backtestSpanInDays = Math.Round((_job.PeriodFinish - _job.PeriodStart).TotalDays);
if (_backtestSpanInDays == 0.0)
{
_backtestSpanInDays = null;
}
}
// we need to wait until we've called initialize on the algorithm
// this is not ideal at all
if (_backtestSpanInDays.HasValue)
{
var daysProcessed = (current - _job.PeriodStart).TotalDays;
if (daysProcessed < 0) daysProcessed = 0;
if (daysProcessed > _backtestSpanInDays.Value) daysProcessed = _backtestSpanInDays.Value;
Log.Trace("Progress: " + (daysProcessed * 100 / _backtestSpanInDays.Value).ToString("F2") + "% Processed: " + daysProcessed.ToString("0.000") + " days of total: " + (int)_backtestSpanInDays.Value);
}
else
{
Log.Trace("Initializing...");
}
}
public TimeSpan ComputeSampleEquityPeriod()
{
const double samples = 4000;
const double minimumSamplePeriod = 4 * 60;
double resampleMinutes = minimumSamplePeriod;
var totalMinutes = (_job.PeriodFinish - _job.PeriodStart).TotalMinutes;
// before initialize is called this will be zero
if (totalMinutes > 0.0)
{
resampleMinutes = (totalMinutes < (minimumSamplePeriod * samples)) ? minimumSamplePeriod : (totalMinutes / samples);
}
// set max value
if (resampleMinutes < minimumSamplePeriod)
{
resampleMinutes = minimumSamplePeriod;
}
return TimeSpan.FromMinutes(resampleMinutes);
}
}
/// <summary>
/// Not used
/// </summary>
public void SetChartSubscription(string symbol)
{
//
}
/// <summary>
/// Process the synchronous result events, sampling and message reading.
/// This method is triggered from the algorithm manager thread.
/// </summary>
/// <remarks>Prime candidate for putting into a base class. Is identical across all result handlers.</remarks>
public void ProcessSynchronousEvents(bool forceProcess = false)
{
var time = _algorithm.Time;
if (time > _nextSample || forceProcess)
{
//Set next sample time: 4000 samples per backtest
_nextSample = time.Add(ResamplePeriod);
//Sample the portfolio value over time for chart.
SampleEquity(time, Math.Round(_algorithm.Portfolio.TotalPortfolioValue, 4));
//Also add the user samples / plots to the result handler tracking:
SampleRange(_algorithm.GetChartUpdates());
//Sample the asset pricing:
foreach (var security in _algorithm.Securities.Values)
{
SampleAssetPrices(security.Symbol, time, security.Price);
}
}
//Send out the debug messages:
_algorithm.DebugMessages.ForEach(x => DebugMessage(x));
_algorithm.DebugMessages.Clear();
//Send out the error messages:
_algorithm.ErrorMessages.ForEach(x => ErrorMessage(x));
_algorithm.ErrorMessages.Clear();
//Send out the log messages:
_algorithm.LogMessages.ForEach(x => LogMessage(x));
_algorithm.LogMessages.Clear();
//Set the running statistics:
foreach (var pair in _algorithm.RuntimeStatistics)
{
RuntimeStatistic(pair.Key, pair.Value);
}
// Dequeue and processes notification messages
//Send all the notification messages but timeout within a second
var start = DateTime.Now;
while (_algorithm.Notify.Messages.Count > 0 && DateTime.Now < start.AddSeconds(1))
{
Notification message;
if (_algorithm.Notify.Messages.TryDequeue(out message))
{
//Process the notification messages:
Log.Trace("ConsoleResultHandler.ProcessSynchronousEvents(): Processing Notification...");
switch (message.GetType().Name)
{
case "NotificationEmail":
_messagingHandler.Email(message as NotificationEmail);
break;
case "NotificationSms":
_messagingHandler.Sms(message as NotificationSms);
break;
case "NotificationWeb":
_messagingHandler.Web(message as NotificationWeb);
break;
default:
try
{
//User code.
message.Send();
}
catch (Exception err)
{
Log.Error(err, "Custom send notification:");
ErrorMessage("Custom send notification: " + err.Message, err.StackTrace);
}
break;
}
}
}
}
} // End Result Handler Thread:
} // End Namespace
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
/// <summary>
/// Named pipe server
/// </summary>
public sealed partial class NamedPipeServerStream : PipeStream
{
[SecurityCritical]
private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
HandleInheritability inheritability)
{
Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);
// Make sure the pipe name isn't one of our reserved names for anonymous pipes.
if (String.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException("pipeName", SR.ArgumentOutOfRange_AnonymousReserved);
}
int openMode = ((int)direction) |
(maxNumberOfServerInstances == 1 ? Interop.mincore.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
(int)options;
// We automatically set the ReadMode to match the TransmissionMode.
int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;
// Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
if (maxNumberOfServerInstances == MaxAllowedServerInstances)
{
maxNumberOfServerInstances = 255;
}
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
SafePipeHandle handle = Interop.mincore.CreateNamedPipe(fullPipeName, openMode, pipeModes,
maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);
if (handle.IsInvalid)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
}
// This will wait until the client calls Connect(). If we return from this method, we guarantee that
// the client has returned from its Connect call. The client may have done so before this method
// was called (but not before this server is been created, or, if we were servicing another client,
// not before we called Disconnect), in which case, there may be some buffer already in the pipe waiting
// for us to read. See NamedPipeClientStream.Connect for more information.
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
public void WaitForConnection()
{
CheckConnectOperationsServerWithHandle();
if (IsAsync)
{
IAsyncResult result = BeginWaitForConnection(null, null);
EndWaitForConnection(result);
}
else
{
if (!Interop.mincore.ConnectNamedPipe(InternalHandle, IntPtr.Zero))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != Interop.mincore.Errors.ERROR_PIPE_CONNECTED)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
// pipe already connected
if (errorCode == Interop.mincore.Errors.ERROR_PIPE_CONNECTED && State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
// If we reach here then a connection has been established. This can happen if a client
// connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe.
// In this situation, there is still a good connection between client and server, even though
// ConnectNamedPipe returns zero.
}
State = PipeState.Connected;
}
}
public Task WaitForConnectionAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
if (!IsAsync)
{
return Task.Factory.StartNew(s => ((NamedPipeServerStream)s).WaitForConnection(),
this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
return Task.Factory.FromAsync(
BeginWaitForConnection, EndWaitForConnection,
cancellationToken.CanBeCanceled ? new IOCancellationHelper(cancellationToken) : null);
}
[SecurityCritical]
public void Disconnect()
{
CheckDisconnectOperations();
// Disconnect the pipe.
if (!Interop.mincore.DisconnectNamedPipe(InternalHandle))
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
State = PipeState.Disconnected;
}
// Gets the username of the connected client. Not that we will not have access to the client's
// username until it has written at least once to the pipe (and has set its impersonationLevel
// argument appropriately).
[SecurityCritical]
public String GetImpersonationUserName()
{
CheckWriteOperations();
StringBuilder userName = new StringBuilder(Interop.mincore.CREDUI_MAX_USERNAME_LENGTH + 1);
if (!Interop.mincore.GetNamedPipeHandleState(InternalHandle, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero, userName, userName.Capacity))
{
WinIOError(Marshal.GetLastWin32Error());
}
return userName.ToString();
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
[SecurityCritical]
private unsafe static readonly IOCompletionCallback s_WaitForConnectionCallback =
new IOCompletionCallback(NamedPipeServerStream.AsyncWaitForConnectionCallback);
#if RunAs
// This method calls a delegate while impersonating the client. Note that we will not have
// access to the client's security token until it has written at least once to the pipe
// (and has set its impersonationLevel argument appropriately).
[SecurityCritical]
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlPrincipal)]
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker)
{
CheckWriteOperations();
ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle);
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(tryCode, cleanupCode, execHelper);
// now handle win32 impersonate/revert specific errors by throwing corresponding exceptions
if (execHelper._impersonateErrorCode != 0)
{
WinIOError(execHelper._impersonateErrorCode);
}
else if (execHelper._revertImpersonateErrorCode != 0)
{
WinIOError(execHelper._revertImpersonateErrorCode);
}
}
// the following are needed for CER
private static RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(ImpersonateAndTryCode);
private static RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(RevertImpersonationOnBackout);
[SecurityCritical]
private static void ImpersonateAndTryCode(Object helper)
{
ExecuteHelper execHelper = (ExecuteHelper)helper;
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
if (UnsafeNativeMethods.ImpersonateNamedPipeClient(execHelper._handle))
{
execHelper._mustRevert = true;
}
else
{
execHelper._impersonateErrorCode = Marshal.GetLastWin32Error();
}
}
if (execHelper._mustRevert)
{ // impersonate passed so run user code
execHelper._userCode();
}
}
[SecurityCritical]
[PrePrepareMethod]
private static void RevertImpersonationOnBackout(Object helper, bool exceptionThrown)
{
ExecuteHelper execHelper = (ExecuteHelper)helper;
if (execHelper._mustRevert)
{
if (!UnsafeNativeMethods.RevertToSelf())
{
execHelper._revertImpersonateErrorCode = Marshal.GetLastWin32Error();
}
}
}
internal class ExecuteHelper
{
internal PipeStreamImpersonationWorker _userCode;
internal SafePipeHandle _handle;
internal bool _mustRevert;
internal int _impersonateErrorCode;
internal int _revertImpersonateErrorCode;
[SecurityCritical]
internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle handle)
{
_userCode = userCode;
_handle = handle;
}
}
#endif
// Async version of WaitForConnection. See the comments above for more info.
[SecurityCritical]
private unsafe IAsyncResult BeginWaitForConnection(AsyncCallback callback, Object state)
{
CheckConnectOperationsServerWithHandle();
if (!IsAsync)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotAsync);
}
// Create and store async stream class library specific data in the
// async result
PipeAsyncResult asyncResult = new PipeAsyncResult();
asyncResult._handle = InternalHandle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
IOCancellationHelper cancellationHelper = state as IOCancellationHelper;
// Create wait handle and store in async result
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
// Create a managed overlapped class
// We will set the file offsets later
Overlapped overlapped = new Overlapped();
overlapped.OffsetLow = 0;
overlapped.OffsetHigh = 0;
overlapped.AsyncResult = asyncResult;
// Pack the Overlapped class, and store it in the async result
NativeOverlapped* intOverlapped = overlapped.Pack(s_WaitForConnectionCallback, null);
asyncResult._overlapped = intOverlapped;
if (!Interop.mincore.ConnectNamedPipe(InternalHandle, intOverlapped))
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.mincore.Errors.ERROR_IO_PENDING)
{
if (cancellationHelper != null)
{
cancellationHelper.AllowCancellation(InternalHandle, intOverlapped);
}
return asyncResult;
}
// WaitForConnectionCallback will not be called because we completed synchronously.
// Either the pipe is already connected, or there was an error. Unpin and free the overlapped again.
Overlapped.Free(intOverlapped);
asyncResult._overlapped = null;
// Did the client already connect to us?
if (errorCode == Interop.mincore.Errors.ERROR_PIPE_CONNECTED)
{
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
asyncResult.CallUserCallback();
return asyncResult;
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
// will set state to Connected when EndWait is called
if (cancellationHelper != null)
{
cancellationHelper.AllowCancellation(InternalHandle, intOverlapped);
}
return asyncResult;
}
// Async version of WaitForConnection. See comments for WaitForConnection for more info.
[SecurityCritical]
private unsafe void EndWaitForConnection(IAsyncResult asyncResult)
{
CheckConnectOperationsServerWithHandle();
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!IsAsync)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotAsync);
}
PipeAsyncResult afsar = asyncResult as PipeAsyncResult;
if (afsar == null)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice. --
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndWaitForConnectionCalledTwice();
}
IOCancellationHelper cancellationHelper = afsar.AsyncState as IOCancellationHelper;
if (cancellationHelper != null)
{
cancellationHelper.SetOperationCompleted();
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that ConnectionIOCallback has completed,
// and we should close the WaitHandle in here. AsyncFSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true, "NamedPipeServerStream::EndWaitForConnection - AsyncFSCallback didn't set _isComplete to true!");
}
}
// We should have freed the overlapped and set it to null either in the Begin
// method (if ConnectNamedPipe completed synchronously) or in AsyncWaitForConnectionCallback.
// If it is not nulled out, we should not be past the above wait:
Debug.Assert(afsar._overlapped == null);
// Now check for any error during the read.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
throw Win32Marshal.GetExceptionForWin32Error(afsar._errorCode);
}
// Success
State = PipeState.Connected;
}
// Callback to be called by the OS when completing the async WaitForConnection operation.
[SecurityCritical]
unsafe private static void AsyncWaitForConnectionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Unpack overlapped
Overlapped overlapped = Overlapped.Unpack(pOverlapped);
// Extract async result from overlapped
PipeAsyncResult asyncResult = (PipeAsyncResult)overlapped.AsyncResult;
// Free the pinned overlapped:
Debug.Assert(asyncResult._overlapped == pOverlapped);
Overlapped.Free(pOverlapped);
asyncResult._overlapped = null;
// Special case for when the client has already connected to us.
if (errorCode == Interop.mincore.Errors.ERROR_PIPE_CONNECTED)
{
errorCode = 0;
}
asyncResult._errorCode = (int)errorCode;
// Call the user-provided callback. It can and often should
// call EndWaitForConnection. There's no reason to use an async
// delegate here - we're already on a threadpool thread.
// IAsyncResult's completedSynchronously property must return
// false here, saying the user callback was called on another thread.
asyncResult._completedSynchronously = false;
asyncResult._isComplete = true;
// The OS does not signal this event. We must do it ourselves.
ManualResetEvent wh = asyncResult._waitHandle;
if (wh != null)
{
Debug.Assert(!wh.GetSafeWaitHandle().IsClosed, "ManualResetEvent already closed!");
bool r = wh.Set();
Debug.Assert(r, "ManualResetEvent::Set failed!");
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
AsyncCallback userCallback = asyncResult._userCallback;
if (userCallback != null)
{
userCallback(asyncResult);
}
}
private void CheckConnectOperationsServerWithHandle()
{
if (InternalHandle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
CheckConnectOperationsServer();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Semantics;
namespace Microsoft.CSharp.RuntimeBinder
{
internal class ExpressionTreeCallRewriter : ExprVisitorBase
{
/////////////////////////////////////////////////////////////////////////////////
// Members
private class ExpressionEXPR : EXPR
{
public Expression Expression;
public ExpressionEXPR(Expression e)
{
Expression = e;
}
}
private Dictionary<EXPRCALL, Expression> _DictionaryOfParameters;
private IEnumerable<Expression> _ListOfParameters;
private TypeManager _typeManager;
// Counts how many EXPRSAVEs we've encountered so we know which index into the
// parameter list we should be taking.
private int _currentParameterIndex;
/////////////////////////////////////////////////////////////////////////////////
protected ExpressionTreeCallRewriter(TypeManager typeManager, IEnumerable<Expression> listOfParameters)
{
_typeManager = typeManager;
_DictionaryOfParameters = new Dictionary<EXPRCALL, Expression>();
_ListOfParameters = listOfParameters;
}
/////////////////////////////////////////////////////////////////////////////////
public static Expression Rewrite(TypeManager typeManager, EXPR pExpr, IEnumerable<Expression> listOfParameters)
{
ExpressionTreeCallRewriter rewriter = new ExpressionTreeCallRewriter(typeManager, listOfParameters);
// We should have a EXPRBINOP thats an EK_SEQUENCE. The RHS of our sequence
// should be a call to PM_EXPRESSION_LAMBDA. The LHS of our sequence is the
// set of declarations for the parameters that we'll need.
// Assert all of these first, and then unwrap them.
Debug.Assert(pExpr != null);
Debug.Assert(pExpr.isBIN());
Debug.Assert(pExpr.kind == ExpressionKind.EK_SEQUENCE);
Debug.Assert(pExpr.asBIN().GetOptionalRightChild() != null);
Debug.Assert(pExpr.asBIN().GetOptionalRightChild().isCALL());
Debug.Assert(pExpr.asBIN().GetOptionalRightChild().asCALL().PredefinedMethod == PREDEFMETH.PM_EXPRESSION_LAMBDA);
Debug.Assert(pExpr.asBIN().GetOptionalLeftChild() != null);
// Visit the left to generate the parameter construction.
rewriter.Visit(pExpr.asBIN().GetOptionalLeftChild());
EXPRCALL call = pExpr.asBIN().GetOptionalRightChild().asCALL();
ExpressionEXPR e = rewriter.Visit(call) as ExpressionEXPR;
return e.Expression;
}
/////////////////////////////////////////////////////////////////////////////////
protected override EXPR VisitSAVE(EXPRBINOP pExpr)
{
// Saves should have a LHS that is a CALL to PM_EXPRESSION_PARAMETER
// and a RHS that is a WRAP of that call.
Debug.Assert(pExpr.GetOptionalLeftChild() != null);
Debug.Assert(pExpr.GetOptionalLeftChild().isCALL());
Debug.Assert(pExpr.GetOptionalLeftChild().asCALL().PredefinedMethod == PREDEFMETH.PM_EXPRESSION_PARAMETER);
Debug.Assert(pExpr.GetOptionalRightChild() != null);
Debug.Assert(pExpr.GetOptionalRightChild().isWRAP());
EXPRCALL call = pExpr.GetOptionalLeftChild().asCALL();
EXPRTYPEOF TypeOf = call.GetOptionalArguments().asLIST().GetOptionalElement().asTYPEOF();
Expression parameter = _ListOfParameters.ElementAt(_currentParameterIndex++);
_DictionaryOfParameters.Add(call, parameter);
return null;
}
/////////////////////////////////////////////////////////////////////////////////
protected override EXPR VisitCAST(EXPRCAST pExpr)
{
return base.VisitCAST(pExpr);
}
/////////////////////////////////////////////////////////////////////////////////
protected override EXPR VisitCALL(EXPRCALL pExpr)
{
if (pExpr.PredefinedMethod != PREDEFMETH.PM_FIRST)
{
switch (pExpr.PredefinedMethod)
{
case PREDEFMETH.PM_EXPRESSION_LAMBDA:
return GenerateLambda(pExpr);
case PREDEFMETH.PM_EXPRESSION_CALL:
return GenerateCall(pExpr);
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX:
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2:
return GenerateArrayIndex(pExpr);
case PREDEFMETH.PM_EXPRESSION_CONVERT:
case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED:
return GenerateConvert(pExpr);
case PREDEFMETH.PM_EXPRESSION_PROPERTY:
return GenerateProperty(pExpr);
case PREDEFMETH.PM_EXPRESSION_FIELD:
return GenerateField(pExpr);
case PREDEFMETH.PM_EXPRESSION_INVOKE:
return GenerateInvoke(pExpr);
case PREDEFMETH.PM_EXPRESSION_NEW:
return GenerateNew(pExpr);
case PREDEFMETH.PM_EXPRESSION_ADD:
case PREDEFMETH.PM_EXPRESSION_AND:
case PREDEFMETH.PM_EXPRESSION_DIVIDE:
case PREDEFMETH.PM_EXPRESSION_EQUAL:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_MODULO:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
case PREDEFMETH.PM_EXPRESSION_OR:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
case PREDEFMETH.PM_EXPRESSION_ORELSE:
case PREDEFMETH.PM_EXPRESSION_ANDALSO:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
return GenerateBinaryOperator(pExpr);
case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
return GenerateUserDefinedBinaryOperator(pExpr);
case PREDEFMETH.PM_EXPRESSION_NEGATE:
case PREDEFMETH.PM_EXPRESSION_NOT:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
return GenerateUnaryOperator(pExpr);
case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
return GenerateUserDefinedUnaryOperator(pExpr);
case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE:
return GenerateConstantType(pExpr);
case PREDEFMETH.PM_EXPRESSION_ASSIGN:
return GenerateAssignment(pExpr);
default:
Debug.Assert(false, "Invalid Predefined Method in VisitCALL");
throw Error.InternalCompilerError();
}
}
return pExpr;
}
#region Generators
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateLambda(EXPRCALL pExpr)
{
// We always call Lambda(body, arrayinit) where the arrayinit
// is the initialization of the parameters.
ExpressionEXPR body = Visit(pExpr.GetOptionalArguments().asLIST().GetOptionalElement()) as ExpressionEXPR;
Expression e = body.Expression;
/*
* // Do we need to do this?
if (e.Type.IsValueType)
{
// If we have a value type, convert it to object so that boxing
// can happen.
e = Expression.Convert(body.Expression, typeof(object));
}
* */
return new ExpressionEXPR(e);
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateCall(EXPRCALL pExpr)
{
// Our arguments are: object, methodinfo, parameters.
// The object is either an EXPRWRAP of a CALL, or a CALL that is a PM_CONVERT, whose
// argument is the WRAP of a CALL. Deal with that first.
EXPRMETHODINFO methinfo;
EXPRARRINIT arrinit;
EXPRLIST list = pExpr.GetOptionalArguments().asLIST();
if (list.GetOptionalNextListNode().isLIST())
{
methinfo = list.GetOptionalNextListNode().asLIST().GetOptionalElement().asMETHODINFO();
arrinit = list.GetOptionalNextListNode().asLIST().GetOptionalNextListNode().asARRINIT();
}
else
{
methinfo = list.GetOptionalNextListNode().asMETHODINFO();
arrinit = null;
}
Expression obj = null;
MethodInfo m = GetMethodInfoFromExpr(methinfo);
Expression[] arguments = GetArgumentsFromArrayInit(arrinit);
if (m == null)
{
Debug.Assert(false, "How did we get a call that doesn't have a methodinfo?");
throw Error.InternalCompilerError();
}
// The DLR is expecting the instance for a static invocation to be null. If we have
// an instance method, fetch the object.
if (!m.IsStatic)
{
obj = GetExpression(pExpr.GetOptionalArguments().asLIST().GetOptionalElement());
}
return new ExpressionEXPR(Expression.Call(obj, m, arguments));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateArrayIndex(EXPRCALL pExpr)
{
// We have two possibilities here - we're either a single index array, in which
// case we'll be PM_EXPRESSION_ARRAYINDEX, or we have multiple dimensions,
// in which case we are PM_EXPRESSION_ARRAYINDEX2.
//
// Our arguments then, are: object, index or object, indicies.
EXPRLIST list = pExpr.GetOptionalArguments().asLIST();
Expression obj = GetExpression(list.GetOptionalElement());
Expression[] indicies;
if (pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX)
{
indicies = new Expression[] { GetExpression(list.GetOptionalNextListNode()) };
}
else
{
Debug.Assert(pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2);
indicies = GetArgumentsFromArrayInit(list.GetOptionalNextListNode().asARRINIT());
}
return new ExpressionEXPR(Expression.ArrayAccess(obj, indicies));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateConvert(EXPRCALL pExpr)
{
PREDEFMETH pm = pExpr.PredefinedMethod;
Expression e;
Type t;
if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED)
{
// If we have a user defined conversion, then we'll have the object
// as the first element, and another list as a second element. This list
// contains a TYPEOF as the first element, and the METHODINFO for the call
// as the second.
EXPRLIST list = pExpr.asCALL().GetOptionalArguments().asLIST();
EXPRLIST list2 = list.GetOptionalNextListNode().asLIST();
e = GetExpression(list.GetOptionalElement());
t = list2.GetOptionalElement().asTYPEOF().SourceType.type.AssociatedSystemType;
if (e.Type.MakeByRefType() == t)
{
// We're trying to convert from a type to its by ref type. Dont do that.
return new ExpressionEXPR(e);
}
Debug.Assert((pExpr.flags & EXPRFLAG.EXF_UNBOXRUNTIME) == 0);
MethodInfo m = GetMethodInfoFromExpr(list2.GetOptionalNextListNode().asMETHODINFO());
if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED)
{
return new ExpressionEXPR(Expression.Convert(e, t, m));
}
return new ExpressionEXPR(Expression.ConvertChecked(e, t, m));
}
else
{
Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED);
// If we have a standard conversion, then we'll have some object as
// the first list element (ie a WRAP or a CALL), and then a TYPEOF
// as the second list element.
EXPRLIST list = pExpr.asCALL().GetOptionalArguments().asLIST();
e = GetExpression(list.GetOptionalElement());
t = list.GetOptionalNextListNode().asTYPEOF().SourceType.type.AssociatedSystemType;
if (e.Type.MakeByRefType() == t)
{
// We're trying to convert from a type to its by ref type. Dont do that.
return new ExpressionEXPR(e);
}
if ((pExpr.flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0)
{
// If we want to unbox this thing, return that instead of the convert.
return new ExpressionEXPR(Expression.Unbox(e, t));
}
if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT)
{
return new ExpressionEXPR(Expression.Convert(e, t));
}
return new ExpressionEXPR(Expression.ConvertChecked(e, t));
}
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateProperty(EXPRCALL pExpr)
{
EXPRLIST list = pExpr.asCALL().GetOptionalArguments().asLIST();
EXPR instance = list.GetOptionalElement();
EXPRPropertyInfo propinfo = list.GetOptionalNextListNode().isLIST() ?
list.GetOptionalNextListNode().asLIST().GetOptionalElement().asPropertyInfo() :
list.GetOptionalNextListNode().asPropertyInfo();
EXPRARRINIT arguments = list.GetOptionalNextListNode().isLIST() ?
list.GetOptionalNextListNode().asLIST().GetOptionalNextListNode().asARRINIT() : null;
PropertyInfo p = GetPropertyInfoFromExpr(propinfo);
if (p == null)
{
Debug.Assert(false, "How did we get a prop that doesn't have a propinfo?");
throw Error.InternalCompilerError();
}
if (arguments == null)
{
return new ExpressionEXPR(Expression.Property(GetExpression(instance), p));
}
return new ExpressionEXPR(Expression.Property(GetExpression(instance), p, GetArgumentsFromArrayInit(arguments)));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateField(EXPRCALL pExpr)
{
EXPRLIST list = pExpr.asCALL().GetOptionalArguments().asLIST();
Type t = list.GetOptionalNextListNode().asFIELDINFO().FieldType().AssociatedSystemType;
FieldInfo f = list.GetOptionalNextListNode().asFIELDINFO().Field().AssociatedFieldInfo;
// This is to ensure that for embedded nopia types, we have the
// appropriate local type from the member itself; this is possible
// because nopia types are not generic or nested.
if (!t.GetTypeInfo().IsGenericType && !t.GetTypeInfo().IsNested)
{
t = f.DeclaringType;
}
// Now find the generic'ed one if we're generic.
if (t.GetTypeInfo().IsGenericType)
{
f = t.GetField(f.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
}
return new ExpressionEXPR(Expression.Field(GetExpression(list.GetOptionalElement()), f));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateInvoke(EXPRCALL pExpr)
{
EXPRLIST list = pExpr.asCALL().GetOptionalArguments().asLIST();
return new ExpressionEXPR(Expression.Invoke(
GetExpression(list.GetOptionalElement()),
GetArgumentsFromArrayInit(list.GetOptionalNextListNode().asARRINIT())));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateNew(EXPRCALL pExpr)
{
EXPRLIST list = pExpr.asCALL().GetOptionalArguments().asLIST();
var constructor = GetConstructorInfoFromExpr(list.GetOptionalElement().asMETHODINFO());
var arguments = GetArgumentsFromArrayInit(list.GetOptionalNextListNode().asARRINIT());
return new ExpressionEXPR(Expression.New(constructor, arguments));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateConstantType(EXPRCALL pExpr)
{
EXPRLIST list = pExpr.GetOptionalArguments().asLIST();
return new ExpressionEXPR(
Expression.Constant(
GetObject(list.GetOptionalElement()),
list.GetOptionalNextListNode().asTYPEOF().SourceType.type.AssociatedSystemType));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateAssignment(EXPRCALL pExpr)
{
EXPRLIST list = pExpr.GetOptionalArguments().asLIST();
return new ExpressionEXPR(Expression.Assign(
GetExpression(list.GetOptionalElement()),
GetExpression(list.GetOptionalNextListNode())));
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateBinaryOperator(EXPRCALL pExpr)
{
Expression arg1 = GetExpression(pExpr.GetOptionalArguments().asLIST().GetOptionalElement());
Expression arg2 = GetExpression(pExpr.GetOptionalArguments().asLIST().GetOptionalNextListNode());
switch (pExpr.PredefinedMethod)
{
case PREDEFMETH.PM_EXPRESSION_ADD:
return new ExpressionEXPR(Expression.Add(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_AND:
return new ExpressionEXPR(Expression.And(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_DIVIDE:
return new ExpressionEXPR(Expression.Divide(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_EQUAL:
return new ExpressionEXPR(Expression.Equal(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
return new ExpressionEXPR(Expression.ExclusiveOr(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
return new ExpressionEXPR(Expression.GreaterThan(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
return new ExpressionEXPR(Expression.GreaterThanOrEqual(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
return new ExpressionEXPR(Expression.LeftShift(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
return new ExpressionEXPR(Expression.LessThan(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
return new ExpressionEXPR(Expression.LessThanOrEqual(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_MODULO:
return new ExpressionEXPR(Expression.Modulo(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
return new ExpressionEXPR(Expression.Multiply(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
return new ExpressionEXPR(Expression.NotEqual(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_OR:
return new ExpressionEXPR(Expression.Or(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
return new ExpressionEXPR(Expression.RightShift(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
return new ExpressionEXPR(Expression.Subtract(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_ORELSE:
return new ExpressionEXPR(Expression.OrElse(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_ANDALSO:
return new ExpressionEXPR(Expression.AndAlso(arg1, arg2));
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
return new ExpressionEXPR(Expression.AddChecked(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
return new ExpressionEXPR(Expression.MultiplyChecked(arg1, arg2));
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
return new ExpressionEXPR(Expression.SubtractChecked(arg1, arg2));
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateBinaryOperator");
throw Error.InternalCompilerError();
}
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateUserDefinedBinaryOperator(EXPRCALL pExpr)
{
EXPRLIST list = pExpr.GetOptionalArguments().asLIST();
Expression arg1 = GetExpression(list.GetOptionalElement());
Expression arg2 = GetExpression(list.GetOptionalNextListNode().asLIST().GetOptionalElement());
list = list.GetOptionalNextListNode().asLIST();
MethodInfo methodInfo;
bool bIsLifted = false;
if (list.GetOptionalNextListNode().isLIST())
{
EXPRCONSTANT isLifted = list.GetOptionalNextListNode().asLIST().GetOptionalElement().asCONSTANT();
bIsLifted = isLifted.getVal().iVal == 1;
methodInfo = GetMethodInfoFromExpr(list.GetOptionalNextListNode().asLIST().GetOptionalNextListNode().asMETHODINFO());
}
else
{
methodInfo = GetMethodInfoFromExpr(list.GetOptionalNextListNode().asMETHODINFO());
}
switch (pExpr.PredefinedMethod)
{
case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
return new ExpressionEXPR(Expression.Add(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
return new ExpressionEXPR(Expression.And(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
return new ExpressionEXPR(Expression.Divide(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
return new ExpressionEXPR(Expression.Equal(arg1, arg2, bIsLifted, methodInfo));
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
return new ExpressionEXPR(Expression.ExclusiveOr(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
return new ExpressionEXPR(Expression.GreaterThan(arg1, arg2, bIsLifted, methodInfo));
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
return new ExpressionEXPR(Expression.GreaterThanOrEqual(arg1, arg2, bIsLifted, methodInfo));
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
return new ExpressionEXPR(Expression.LeftShift(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
return new ExpressionEXPR(Expression.LessThan(arg1, arg2, bIsLifted, methodInfo));
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
return new ExpressionEXPR(Expression.LessThanOrEqual(arg1, arg2, bIsLifted, methodInfo));
case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
return new ExpressionEXPR(Expression.Modulo(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
return new ExpressionEXPR(Expression.Multiply(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
return new ExpressionEXPR(Expression.NotEqual(arg1, arg2, bIsLifted, methodInfo));
case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
return new ExpressionEXPR(Expression.Or(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
return new ExpressionEXPR(Expression.RightShift(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
return new ExpressionEXPR(Expression.Subtract(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
return new ExpressionEXPR(Expression.OrElse(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
return new ExpressionEXPR(Expression.AndAlso(arg1, arg2, methodInfo));
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
return new ExpressionEXPR(Expression.AddChecked(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
return new ExpressionEXPR(Expression.MultiplyChecked(arg1, arg2, methodInfo));
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
return new ExpressionEXPR(Expression.SubtractChecked(arg1, arg2, methodInfo));
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedBinaryOperator");
throw Error.InternalCompilerError();
}
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateUnaryOperator(EXPRCALL pExpr)
{
PREDEFMETH pm = pExpr.PredefinedMethod;
Expression arg = GetExpression(pExpr.GetOptionalArguments());
switch (pm)
{
case PREDEFMETH.PM_EXPRESSION_NOT:
return new ExpressionEXPR(Expression.Not(arg));
case PREDEFMETH.PM_EXPRESSION_NEGATE:
return new ExpressionEXPR(Expression.Negate(arg));
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
return new ExpressionEXPR(Expression.NegateChecked(arg));
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateUnaryOperator");
throw Error.InternalCompilerError();
}
}
/////////////////////////////////////////////////////////////////////////////////
private ExpressionEXPR GenerateUserDefinedUnaryOperator(EXPRCALL pExpr)
{
PREDEFMETH pm = pExpr.PredefinedMethod;
EXPRLIST list = pExpr.GetOptionalArguments().asLIST();
Expression arg = GetExpression(list.GetOptionalElement());
MethodInfo methodInfo = GetMethodInfoFromExpr(list.GetOptionalNextListNode().asMETHODINFO());
switch (pm)
{
case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
return new ExpressionEXPR(Expression.Not(arg, methodInfo));
case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
return new ExpressionEXPR(Expression.Negate(arg, methodInfo));
case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
return new ExpressionEXPR(Expression.UnaryPlus(arg, methodInfo));
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
return new ExpressionEXPR(Expression.NegateChecked(arg, methodInfo));
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedUnaryOperator");
throw Error.InternalCompilerError();
}
}
#endregion
#region Helpers
/////////////////////////////////////////////////////////////////////////////////
private Expression GetExpression(EXPR pExpr)
{
if (pExpr.isWRAP())
{
return _DictionaryOfParameters[pExpr.asWRAP().GetOptionalExpression().asCALL()];
}
else if (pExpr.isCONSTANT())
{
Debug.Assert(pExpr.type.IsNullType());
return null;
}
else
{
// We can have a convert node or a call of a user defined conversion.
Debug.Assert(pExpr.isCALL());
EXPRCALL call = pExpr.asCALL();
PREDEFMETH pm = call.PredefinedMethod;
Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT ||
pm == PREDEFMETH.PM_EXPRESSION_CALL ||
pm == PREDEFMETH.PM_EXPRESSION_PROPERTY ||
pm == PREDEFMETH.PM_EXPRESSION_FIELD ||
pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX ||
pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2 ||
pm == PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE ||
pm == PREDEFMETH.PM_EXPRESSION_NEW ||
// Binary operators.
pm == PREDEFMETH.PM_EXPRESSION_ASSIGN ||
pm == PREDEFMETH.PM_EXPRESSION_ADD ||
pm == PREDEFMETH.PM_EXPRESSION_AND ||
pm == PREDEFMETH.PM_EXPRESSION_DIVIDE ||
pm == PREDEFMETH.PM_EXPRESSION_EQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_MODULO ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY ||
pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_OR ||
pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT ||
pm == PREDEFMETH.PM_EXPRESSION_ORELSE ||
pm == PREDEFMETH.PM_EXPRESSION_ANDALSO ||
pm == PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED ||
// Checked binary
pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED ||
// Unary operators.
pm == PREDEFMETH.PM_EXPRESSION_NOT ||
pm == PREDEFMETH.PM_EXPRESSION_NEGATE ||
pm == PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED ||
// Checked unary
pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED
);
switch (pm)
{
case PREDEFMETH.PM_EXPRESSION_CALL:
return GenerateCall(call).Expression;
case PREDEFMETH.PM_EXPRESSION_CONVERT:
case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED:
return GenerateConvert(call).Expression;
case PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT:
{
EXPRLIST list = call.GetOptionalArguments().asLIST();
return Expression.NewArrayInit(
list.GetOptionalElement().asTYPEOF().SourceType.type.AssociatedSystemType,
GetArgumentsFromArrayInit(list.GetOptionalNextListNode().asARRINIT()));
}
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX:
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2:
return GenerateArrayIndex(call).Expression;
case PREDEFMETH.PM_EXPRESSION_NEW:
return GenerateNew(call).Expression;
case PREDEFMETH.PM_EXPRESSION_PROPERTY:
return GenerateProperty(call).Expression;
case PREDEFMETH.PM_EXPRESSION_FIELD:
return GenerateField(call).Expression;
case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE:
return GenerateConstantType(call).Expression;
case PREDEFMETH.PM_EXPRESSION_ASSIGN:
return GenerateAssignment(call).Expression;
case PREDEFMETH.PM_EXPRESSION_ADD:
case PREDEFMETH.PM_EXPRESSION_AND:
case PREDEFMETH.PM_EXPRESSION_DIVIDE:
case PREDEFMETH.PM_EXPRESSION_EQUAL:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_MODULO:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
case PREDEFMETH.PM_EXPRESSION_OR:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
case PREDEFMETH.PM_EXPRESSION_ORELSE:
case PREDEFMETH.PM_EXPRESSION_ANDALSO:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
return GenerateBinaryOperator(call).Expression;
case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
return GenerateUserDefinedBinaryOperator(call).Expression;
case PREDEFMETH.PM_EXPRESSION_NOT:
case PREDEFMETH.PM_EXPRESSION_NEGATE:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
return GenerateUnaryOperator(call).Expression;
case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
return GenerateUserDefinedUnaryOperator(call).Expression;
default:
Debug.Assert(false, "Invalid Predefined Method in GetExpression");
throw Error.InternalCompilerError();
}
}
}
/////////////////////////////////////////////////////////////////////////////////
private object GetObject(EXPR pExpr)
{
if (pExpr.isCAST())
{
return GetObject(pExpr.asCAST().GetArgument());
}
else if (pExpr.isTYPEOF())
{
return pExpr.asTYPEOF().SourceType.type.AssociatedSystemType;
}
else if (pExpr.isMETHODINFO())
{
return GetMethodInfoFromExpr(pExpr.asMETHODINFO());
}
else if (pExpr.isCONSTANT())
{
CONSTVAL val = pExpr.asCONSTANT().Val;
CType underlyingType = pExpr.type;
object objval;
if (pExpr.type.IsNullType())
{
return null;
}
if (pExpr.type.isEnumType())
{
underlyingType = underlyingType.getAggregate().GetUnderlyingType();
}
switch (underlyingType.AssociatedSystemType.GetTypeCode())
{
case TypeCode.Boolean:
objval = val.boolVal;
break;
case TypeCode.SByte:
objval = val.sbyteVal;
break;
case TypeCode.Byte:
objval = val.byteVal;
break;
case TypeCode.Int16:
objval = val.shortVal;
break;
case TypeCode.UInt16:
objval = val.ushortVal;
break;
case TypeCode.Int32:
objval = val.iVal;
break;
case TypeCode.UInt32:
objval = val.uiVal;
break;
case TypeCode.Int64:
objval = val.longVal;
break;
case TypeCode.UInt64:
objval = val.ulongVal;
break;
case TypeCode.Single:
objval = val.floatVal;
break;
case TypeCode.Double:
objval = val.doubleVal;
break;
case TypeCode.Decimal:
objval = val.decVal;
break;
case TypeCode.Char:
objval = val.cVal;
break;
case TypeCode.String:
objval = val.strVal;
break;
default:
objval = val.objectVal;
break;
}
if (pExpr.type.isEnumType())
{
objval = Enum.ToObject(pExpr.type.AssociatedSystemType, objval);
}
return objval;
}
else if (pExpr.isZEROINIT())
{
if (pExpr.asZEROINIT().OptionalArgument != null)
{
return GetObject(pExpr.asZEROINIT().OptionalArgument);
}
return System.Activator.CreateInstance(pExpr.type.AssociatedSystemType);
}
Debug.Assert(false, "Invalid EXPR in GetObject");
throw Error.InternalCompilerError();
}
/////////////////////////////////////////////////////////////////////////////////
private Expression[] GetArgumentsFromArrayInit(EXPRARRINIT arrinit)
{
List<Expression> expressions = new List<Expression>();
if (arrinit != null)
{
EXPR list = arrinit.GetOptionalArguments();
EXPR p = list;
while (list != null)
{
if (list.isLIST())
{
p = list.asLIST().GetOptionalElement();
list = list.asLIST().GetOptionalNextListNode();
}
else
{
p = list;
list = null;
}
expressions.Add(GetExpression(p));
}
Debug.Assert(expressions.Count == arrinit.dimSizes[0]);
}
return expressions.ToArray();
}
/////////////////////////////////////////////////////////////////////////////////
private MethodInfo GetMethodInfoFromExpr(EXPRMETHODINFO methinfo)
{
// To do this, we need to construct a type array of the parameter types,
// get the parent constructed type, and get the method from it.
AggregateType aggType = methinfo.Method.Ats;
MethodSymbol methSym = methinfo.Method.Meth();
TypeArray genericParams = _typeManager.SubstTypeArray(methSym.Params, aggType, methSym.typeVars);
CType genericReturn = _typeManager.SubstType(methSym.RetType, aggType, methSym.typeVars);
Type type = aggType.AssociatedSystemType;
MethodInfo methodInfo = methSym.AssociatedMemberInfo as MethodInfo;
// This is to ensure that for embedded nopia types, we have the
// appropriate local type from the member itself; this is possible
// because nopia types are not generic or nested.
if (!type.GetTypeInfo().IsGenericType && !type.IsNested)
{
type = methodInfo.DeclaringType;
}
// We need to find the associated methodinfo on the instantiated type.
foreach (MethodInfo m in type.GetRuntimeMethods())
{
#if UNSUPPORTEDAPI
if ((m.MetadataToken != methodInfo.MetadataToken) || (m.Module != methodInfo.Module))
#else
if (!m.HasSameMetadataDefinitionAs(methodInfo))
#endif
{
continue;
}
Debug.Assert((m.Name == methodInfo.Name) &&
(m.GetParameters().Length == genericParams.size) &&
(TypesAreEqual(m.ReturnType, genericReturn.AssociatedSystemType)));
bool bMatch = true;
ParameterInfo[] parameters = m.GetParameters();
for (int i = 0; i < genericParams.size; i++)
{
if (!TypesAreEqual(parameters[i].ParameterType, genericParams.Item(i).AssociatedSystemType))
{
bMatch = false;
break;
}
}
if (bMatch)
{
if (m.IsGenericMethod)
{
int size = methinfo.Method.TypeArgs != null ? methinfo.Method.TypeArgs.size : 0;
Type[] typeArgs = new Type[size];
if (size > 0)
{
for (int i = 0; i < methinfo.Method.TypeArgs.size; i++)
{
typeArgs[i] = methinfo.Method.TypeArgs[i].AssociatedSystemType;
}
}
return m.MakeGenericMethod(typeArgs);
}
return m;
}
}
Debug.Assert(false, "Could not find matching method");
throw Error.InternalCompilerError();
}
/////////////////////////////////////////////////////////////////////////////////
private ConstructorInfo GetConstructorInfoFromExpr(EXPRMETHODINFO methinfo)
{
// To do this, we need to construct a type array of the parameter types,
// get the parent constructed type, and get the method from it.
AggregateType aggType = methinfo.Method.Ats;
MethodSymbol methSym = methinfo.Method.Meth();
TypeArray genericInstanceParams = _typeManager.SubstTypeArray(methSym.Params, aggType);
Type type = aggType.AssociatedSystemType;
ConstructorInfo ctorInfo = (ConstructorInfo)methSym.AssociatedMemberInfo;
// This is to ensure that for embedded nopia types, we have the
// appropriate local type from the member itself; this is possible
// because nopia types are not generic or nested.
if (!type.GetTypeInfo().IsGenericType && !type.IsNested)
{
type = ctorInfo.DeclaringType;
}
foreach (ConstructorInfo c in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
{
#if UNSUPPORTEDAPI
if ((c.MetadataToken != ctorInfo.MetadataToken) || (c.Module != ctorInfo.Module))
#else
if (!c.HasSameMetadataDefinitionAs(ctorInfo))
#endif
{
continue;
}
Debug.Assert(c.GetParameters() == null || c.GetParameters().Length == genericInstanceParams.size);
bool bMatch = true;
ParameterInfo[] parameters = c.GetParameters();
for (int i = 0; i < genericInstanceParams.size; i++)
{
if (!TypesAreEqual(parameters[i].ParameterType, genericInstanceParams.Item(i).AssociatedSystemType))
{
bMatch = false;
break;
}
}
if (bMatch)
{
return c;
}
}
Debug.Assert(false, "Could not find matching constructor");
throw Error.InternalCompilerError();
}
/////////////////////////////////////////////////////////////////////////////////
private PropertyInfo GetPropertyInfoFromExpr(EXPRPropertyInfo propinfo)
{
// To do this, we need to construct a type array of the parameter types,
// get the parent constructed type, and get the property from it.
AggregateType aggType = propinfo.Property.Ats;
PropertySymbol propSym = propinfo.Property.Prop();
TypeArray genericInstanceParams = _typeManager.SubstTypeArray(propSym.Params, aggType, null);
CType genericInstanceReturn = _typeManager.SubstType(propSym.RetType, aggType, null);
Type type = aggType.AssociatedSystemType;
PropertyInfo propertyInfo = propSym.AssociatedPropertyInfo;
// This is to ensure that for embedded nopia types, we have the
// appropriate local type from the member itself; this is possible
// because nopia types are not generic or nested.
if (!type.GetTypeInfo().IsGenericType && !type.IsNested)
{
type = propertyInfo.DeclaringType;
}
foreach (PropertyInfo p in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
{
#if UNSUPPORTEDAPI
if ((p.MetadataToken != propertyInfo.MetadataToken) || (p.Module != propertyInfo.Module))
#else
if (!p.HasSameMetadataDefinitionAs(propertyInfo))
{
#endif
continue;
}
Debug.Assert((p.Name == propertyInfo.Name) &&
(p.GetIndexParameters() == null || p.GetIndexParameters().Length == genericInstanceParams.size));
bool bMatch = true;
ParameterInfo[] parameters = p.GetSetMethod(true) != null ?
p.GetSetMethod(true).GetParameters() : p.GetGetMethod(true).GetParameters();
for (int i = 0; i < genericInstanceParams.size; i++)
{
if (!TypesAreEqual(parameters[i].ParameterType, genericInstanceParams.Item(i).AssociatedSystemType))
{
bMatch = false;
break;
}
}
if (bMatch)
{
return p;
}
}
Debug.Assert(false, "Could not find matching property");
throw Error.InternalCompilerError();
}
/////////////////////////////////////////////////////////////////////////////////
private bool TypesAreEqual(Type t1, Type t2)
{
if (t1 == t2)
{
return true;
}
return t1.IsEquivalentTo(t2);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels
{
using System;
using System.Diagnostics.Contracts;
using System.Threading;
using DotNetty.Buffers;
using DotNetty.Transport.Channels.Sockets;
/// <summary>
/// Shared configuration for SocketAsyncChannel. Provides access to pre-configured resources like ByteBuf allocator and
/// IO buffer pools
/// </summary>
public class DefaultChannelConfiguration : IChannelConfiguration
{
static readonly TimeSpan DefaultConnectTimeout = TimeSpan.FromSeconds(30);
volatile IByteBufferAllocator allocator = ByteBufferUtil.DefaultAllocator;
volatile IRecvByteBufAllocator recvByteBufAllocator = FixedRecvByteBufAllocator.Default;
volatile IMessageSizeEstimator messageSizeEstimator = DefaultMessageSizeEstimator.Default;
volatile int autoRead = 1;
volatile int writeSpinCount = 16;
volatile int writeBufferHighWaterMark = 64 * 1024;
volatile int writeBufferLowWaterMark = 32 * 1024;
long connectTimeout = DefaultConnectTimeout.Ticks;
protected readonly IChannel Channel;
public DefaultChannelConfiguration(IChannel channel)
: this(channel, new AdaptiveRecvByteBufAllocator())
{
}
public DefaultChannelConfiguration(IChannel channel, IRecvByteBufAllocator allocator)
{
Contract.Requires(channel != null);
this.Channel = channel;
var maxMessagesAllocator = allocator as IMaxMessagesRecvByteBufAllocator;
if (maxMessagesAllocator != null)
{
maxMessagesAllocator.MaxMessagesPerRead = channel.Metadata.DefaultMaxMessagesPerRead;
}
else if (allocator == null)
{
throw new ArgumentNullException(nameof(allocator));
}
this.RecvByteBufAllocator = allocator;
}
public virtual T GetOption<T>(ChannelOption<T> option)
{
Contract.Requires(option != null);
if (ChannelOption.ConnectTimeout.Equals(option))
{
return (T)(object)this.ConnectTimeout; // no boxing will happen, compiler optimizes away such casts
}
if (ChannelOption.WriteSpinCount.Equals(option))
{
return (T)(object)this.WriteSpinCount;
}
if (ChannelOption.Allocator.Equals(option))
{
return (T)this.Allocator;
}
if (ChannelOption.RcvbufAllocator.Equals(option))
{
return (T)this.RecvByteBufAllocator;
}
if (ChannelOption.AutoRead.Equals(option))
{
return (T)(object)this.AutoRead;
}
if (ChannelOption.WriteBufferHighWaterMark.Equals(option))
{
return (T)(object)this.WriteBufferHighWaterMark;
}
if (ChannelOption.WriteBufferLowWaterMark.Equals(option))
{
return (T)(object)this.WriteBufferLowWaterMark;
}
if (ChannelOption.MessageSizeEstimator.Equals(option))
{
return (T)this.MessageSizeEstimator;
}
return default(T);
}
public bool SetOption(ChannelOption option, object value) => option.Set(this, value);
public virtual bool SetOption<T>(ChannelOption<T> option, T value)
{
this.Validate(option, value);
if (ChannelOption.ConnectTimeout.Equals(option))
{
this.ConnectTimeout = (TimeSpan)(object)value;
}
else if (ChannelOption.WriteSpinCount.Equals(option))
{
this.WriteSpinCount = (int)(object)value;
}
else if (ChannelOption.Allocator.Equals(option))
{
this.Allocator = (IByteBufferAllocator)value;
}
else if (ChannelOption.RcvbufAllocator.Equals(option))
{
this.RecvByteBufAllocator = (IRecvByteBufAllocator)value;
}
else if (ChannelOption.AutoRead.Equals(option))
{
this.AutoRead = (bool)(object)value;
}
else if (ChannelOption.WriteBufferHighWaterMark.Equals(option))
{
this.writeBufferHighWaterMark = (int)(object)value;
}
else if (ChannelOption.WriteBufferLowWaterMark.Equals(option))
{
this.WriteBufferLowWaterMark = (int)(object)value;
}
else if (ChannelOption.MessageSizeEstimator.Equals(option))
{
this.MessageSizeEstimator = (IMessageSizeEstimator)value;
}
else
{
return false;
}
return true;
}
protected virtual void Validate<T>(ChannelOption<T> option, T value)
{
Contract.Requires(option != null);
option.Validate(value);
}
public TimeSpan ConnectTimeout
{
get { return new TimeSpan(Volatile.Read(ref this.connectTimeout)); }
set
{
Contract.Requires(value >= TimeSpan.Zero);
Volatile.Write(ref this.connectTimeout, value.Ticks);
}
}
public IByteBufferAllocator Allocator
{
get { return this.allocator; }
set
{
Contract.Requires(value != null);
this.allocator = value;
}
}
public IRecvByteBufAllocator RecvByteBufAllocator
{
get { return this.recvByteBufAllocator; }
set
{
Contract.Requires(value != null);
this.recvByteBufAllocator = value;
}
}
public IMessageSizeEstimator MessageSizeEstimator
{
get { return this.messageSizeEstimator; }
set
{
Contract.Requires(value != null);
this.messageSizeEstimator = value;
}
}
public bool AutoRead
{
get { return this.autoRead == 1; }
set
{
#pragma warning disable 420 // atomic exchange is ok
bool oldAutoRead = Interlocked.Exchange(ref this.autoRead, value ? 1 : 0) == 1;
#pragma warning restore 420
if (value && !oldAutoRead)
{
this.Channel.Read();
}
else if (!value && oldAutoRead)
{
this.AutoReadCleared();
}
}
}
protected virtual void AutoReadCleared()
{
}
public int WriteBufferHighWaterMark
{
get { return this.writeBufferHighWaterMark; }
set
{
Contract.Requires(value >= 0);
Contract.Requires(value >= this.writeBufferLowWaterMark);
this.writeBufferHighWaterMark = value;
}
}
public int WriteBufferLowWaterMark
{
get { return this.writeBufferLowWaterMark; }
set
{
Contract.Requires(value >= 0);
Contract.Requires(value <= this.writeBufferHighWaterMark);
this.writeBufferLowWaterMark = value;
}
}
public int WriteSpinCount
{
get { return this.writeSpinCount; }
set
{
Contract.Requires(value >= 1);
this.writeSpinCount = value;
}
}
}
}
| |
using System.Linq;
using System.Text.RegularExpressions;
using FluentMigrator.Runner.Helpers;
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Builders.Execute;
using FluentMigrator.Info;
using FluentMigrator.Runner.Generators;
using FluentMigrator.Runner.Generators.Oracle;
namespace FluentMigrator.Runner.Processors.Oracle
{
public class OracleProcessor : GenericProcessorBase
{
public override string DatabaseType
{
get { return "Oracle"; }
}
public OracleProcessor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory)
: base(connection, factory, generator, announcer, options)
{
}
public IQuoter Quoter
{
get { return ((OracleGenerator)this.Generator).Quoter; }
}
public override bool SchemaExists(string schemaName)
{
if (schemaName == null)
throw new ArgumentNullException("schemaName");
if (schemaName.Length == 0)
return false;
return Exists("SELECT 1 FROM ALL_USERS WHERE USERNAME = '{0}'", schemaName.ToUpper());
}
public override bool TableExists(string schemaName, string tableName)
{
if (tableName == null)
throw new ArgumentNullException("tableName");
if (tableName.Length == 0)
return false;
if (string.IsNullOrEmpty(schemaName))
return Exists("SELECT 1 FROM USER_TABLES WHERE upper(TABLE_NAME) = '{0}'", FormatHelper.FormatSqlEscape(tableName.ToUpper()));
return Exists("SELECT 1 FROM ALL_TABLES WHERE upper(OWNER) = '{0}' AND upper(TABLE_NAME) = '{1}'", schemaName.ToUpper(), FormatHelper.FormatSqlEscape(tableName.ToUpper()));
}
public override bool ColumnExists(string schemaName, string tableName, string columnName)
{
if (tableName == null)
throw new ArgumentNullException("tableName");
if (columnName == null)
throw new ArgumentNullException("columnName");
if (columnName.Length == 0 || tableName.Length == 0)
return false;
if (string.IsNullOrEmpty(schemaName))
return Exists("SELECT 1 FROM USER_TAB_COLUMNS WHERE upper(TABLE_NAME) = '{0}' AND upper(COLUMN_NAME) = '{1}'",
FormatHelper.FormatSqlEscape(tableName.ToUpper()),
FormatHelper.FormatSqlEscape(columnName.ToUpper()));
return Exists("SELECT 1 FROM ALL_TAB_COLUMNS WHERE upper(OWNER) = '{0}' AND upper(TABLE_NAME) = '{1}' AND upper(COLUMN_NAME) = '{2}'",
schemaName.ToUpper(), FormatHelper.FormatSqlEscape(tableName.ToUpper()), FormatHelper.FormatSqlEscape(columnName.ToUpper()));
}
public override bool ConstraintExists(string schemaName, string tableName, string constraintName)
{
if (tableName == null)
throw new ArgumentNullException("tableName");
if (constraintName == null)
throw new ArgumentNullException("constraintName");
//In Oracle DB constraint name is unique within the schema, so the table name is not used in the query
if (constraintName.Length == 0)
return false;
if (String.IsNullOrEmpty(schemaName))
return Exists("SELECT 1 FROM USER_CONSTRAINTS WHERE upper(CONSTRAINT_NAME) = '{0}'", FormatHelper.FormatSqlEscape(constraintName.ToUpper()));
return Exists("SELECT 1 FROM ALL_CONSTRAINTS WHERE upper(OWNER) = '{0}' AND upper(CONSTRAINT_NAME) = '{1}'", schemaName.ToUpper(),
FormatHelper.FormatSqlEscape(constraintName.ToUpper()));
}
public override bool IndexExists(string schemaName, string tableName, string indexName)
{
if (tableName == null)
throw new ArgumentNullException("tableName");
if (indexName == null)
throw new ArgumentNullException("indexName");
//In Oracle DB index name is unique within the schema, so the table name is not used in the query
if (indexName.Length == 0)
return false;
if (String.IsNullOrEmpty(schemaName))
return Exists("SELECT 1 FROM USER_INDEXES WHERE upper(INDEX_NAME) = '{0}'", FormatHelper.FormatSqlEscape(indexName.ToUpper()));
return Exists("SELECT 1 FROM ALL_INDEXES WHERE upper(OWNER) = '{0}' AND upper(INDEX_NAME) = '{1}'", schemaName.ToUpper(), FormatHelper.FormatSqlEscape(indexName.ToUpper()));
}
public override bool SequenceExists(string schemaName, string sequenceName)
{
return false;
}
public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue)
{
return false;
}
public override IEnumerable<TableInfo> GetTableInfos(string schemaName)
{
throw new NotImplementedException();
}
public override IEnumerable<ColumnInfo> GetColumnInfos(string schemaName, string tableName)
{
throw new NotImplementedException();
}
public override void Execute(string template, params object[] args)
{
Process(string.Format(template, args));
}
public override bool Exists(string template, params object[] args)
{
if (template == null)
throw new ArgumentNullException("template");
EnsureConnectionIsOpen();
Announcer.Sql(String.Format(template, args));
using (var command = Factory.CreateCommand(String.Format(template, args), Connection))
using (var reader = command.ExecuteReader())
{
return reader.Read();
}
}
public override DataSet ReadTableData(string schemaName, string tableName)
{
if (tableName == null)
throw new ArgumentNullException("tableName");
if (String.IsNullOrEmpty(schemaName))
return Read("SELECT * FROM {0}", Quoter.QuoteTableName(tableName));
return Read("SELECT * FROM {0}.{1}", Quoter.QuoteSchemaName(schemaName), Quoter.QuoteTableName(tableName));
}
public override DataSet Read(string template, params object[] args)
{
if (template == null)
throw new ArgumentNullException("template");
EnsureConnectionIsOpen();
var result = new DataSet();
using (var command = Factory.CreateCommand(String.Format(template, args), Connection))
{
var adapter = Factory.CreateDataAdapter(command);
adapter.Fill(result);
return result;
}
}
public override void Process(PerformDBOperationExpression expression)
{
EnsureConnectionIsOpen();
if (expression.Operation != null)
expression.Operation(Connection, null);
}
protected override void Process(string sql)
{
Announcer.Sql(sql);
if (Options.PreviewOnly || string.IsNullOrEmpty(sql))
return;
EnsureConnectionIsOpen();
var batches = Regex.Split(sql, @"^\s*;\s*$", RegexOptions.Multiline)
.Select(x => x.Trim())
.Where(x => !string.IsNullOrEmpty(x));
foreach (var batch in batches)
{
using (var command = Factory.CreateCommand(batch, Connection))
command.ExecuteNonQuery();
}
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using SharpDX.DXGI;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// A DepthStencilBuffer front end to <see cref="SharpDX.Direct3D11.Texture2D"/>.
/// </summary>
/// <remarks>
/// This class instantiates a <see cref="Texture2D"/> with the binding flags <see cref="BindFlags.DepthStencil"/>.
/// </remarks>
public class DepthStencilBuffer : Texture2DBase
{
internal readonly DXGI.Format DefaultViewFormat;
private TextureView[] depthStencilViews;
private TextureView[] readOnlyViews;
/// <summary>
/// Gets the <see cref="Graphics.DepthFormat"/> of this depth stencil buffer.
/// </summary>
public readonly DepthFormat DepthFormat;
/// <summary>
/// Gets a boolean value indicating if this buffer is supporting stencil.
/// </summary>
public readonly bool HasStencil;
/// <summary>
/// Gets a boolean value indicating if this buffer is supporting read-only view.
/// </summary>
public readonly bool HasReadOnlyView;
/// <summary>
/// Gets the selector for a <see cref="DepthStencilView"/>
/// </summary>
public readonly DepthStencilViewSelector DepthStencilView;
/// <summary>
/// Gets a a read-only <see cref="DepthStencilView"/>.
/// </summary>
/// <remarks>
/// This value can be null if not supported by hardware (minimum features level is 11.0)
/// </remarks>
public DepthStencilView ReadOnlyView
{
get
{
return readOnlyViews != null ? readOnlyViews[0] : null;
}
}
internal DepthStencilBuffer(Direct3D11.Device device, Texture2DDescription description2D, DepthFormat depthFormat)
: base(device, description2D)
{
DepthFormat = depthFormat;
DefaultViewFormat = ComputeViewFormat(DepthFormat, out HasStencil);
Initialize(Resource);
HasReadOnlyView = InitializeViewsDelayed();
DepthStencilView = new DepthStencilViewSelector(this);
}
internal DepthStencilBuffer(Direct3D11.Device device, Direct3D11.Texture2D texture, DepthFormat depthFormat)
: base(device, texture)
{
DepthFormat = depthFormat;
DefaultViewFormat = ComputeViewFormat(DepthFormat, out HasStencil);
Initialize(Resource);
HasReadOnlyView = InitializeViewsDelayed();
DepthStencilView = new DepthStencilViewSelector(this);
}
/// <summary>
///
/// </summary>
protected override void InitializeViews()
{
// Override this, because we need the DepthFormat setup in order to initialize this class
// This is caused by a bad design of the constructors/initialize sequence.
// TODO: Fix this problem
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected bool InitializeViewsDelayed()
{
bool hasReadOnlyView = false;
// Perform default initialization
base.InitializeViews();
if ((Description.BindFlags & BindFlags.DepthStencil) == 0)
return hasReadOnlyView;
int viewCount = GetViewCount();
depthStencilViews = new TextureView[viewCount];
GetDepthStencilView(ViewType.Full, 0, 0, false);
// ReadOnly for feature level Direct3D11
if (((Direct3D11.Device)GraphicsDevice).FeatureLevel >= FeatureLevel.Level_11_0)
{
hasReadOnlyView = true;
readOnlyViews = new TextureView[viewCount];
GetDepthStencilView(ViewType.Full, 0, 0, true);
}
return hasReadOnlyView;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override Format GetDefaultViewFormat()
{
return DefaultViewFormat;
}
/// <summary>
/// DepthStencilView casting operator.
/// </summary>
/// <param name="buffer">Source for the.</param>
public static implicit operator DepthStencilView(DepthStencilBuffer buffer)
{
return buffer == null ? null : buffer.depthStencilViews != null ? buffer.depthStencilViews[0] : null;
}
internal override TextureView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipIndex)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets a specific <see cref="DepthStencilView" /> from this texture.
/// </summary>
/// <param name="viewType">Type of the view slice.</param>
/// <param name="arrayOrDepthSlice">The texture array slice index.</param>
/// <param name="mipIndex">The mip map slice index.</param>
/// <param name="readOnlyView">Indicates if the view is read-only.</param>
/// <returns>A <see cref="DepthStencilView" /></returns>
internal virtual TextureView GetDepthStencilView(ViewType viewType, int arrayOrDepthSlice, int mipIndex, bool readOnlyView)
{
if ((this.Description.BindFlags & BindFlags.DepthStencil) == 0)
return null;
if (viewType == ViewType.MipBand)
throw new NotSupportedException("ViewSlice.MipBand is not supported for depth stencils");
if (readOnlyView && !HasReadOnlyView)
return null;
var views = readOnlyView ? readOnlyViews : depthStencilViews;
int arrayCount;
int mipCount;
GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount);
var dsvIndex = GetViewIndex(viewType, arrayOrDepthSlice, mipIndex);
lock (views)
{
var dsv = views[dsvIndex];
// Creates the shader resource view
if (dsv == null)
{
// Create the depth stencil view
var dsvDescription = new DepthStencilViewDescription() { Format = (Format)DepthFormat };
if (this.Description.ArraySize > 1)
{
dsvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampledArray : DepthStencilViewDimension.Texture2DArray;
if (this.Description.SampleDescription.Count > 1)
{
dsvDescription.Texture2DMSArray.ArraySize = arrayCount;
dsvDescription.Texture2DMSArray.FirstArraySlice = arrayOrDepthSlice;
}
else
{
dsvDescription.Texture2DArray.ArraySize = arrayCount;
dsvDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice;
dsvDescription.Texture2DArray.MipSlice = mipIndex;
}
}
else
{
dsvDescription.Dimension = this.Description.SampleDescription.Count > 1 ? DepthStencilViewDimension.Texture2DMultisampled : DepthStencilViewDimension.Texture2D;
if (this.Description.SampleDescription.Count <= 1)
dsvDescription.Texture2D.MipSlice = mipIndex;
}
if (readOnlyView)
{
dsvDescription.Flags = DepthStencilViewFlags.ReadOnlyDepth;
if (HasStencil)
dsvDescription.Flags |= DepthStencilViewFlags.ReadOnlyStencil;
}
dsv = new TextureView(this, new DepthStencilView(GraphicsDevice, Resource, dsvDescription));
views[dsvIndex] = ToDispose(dsv);
}
return dsv;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override Texture Clone()
{
return new DepthStencilBuffer(GraphicsDevice, this.Description, DepthFormat);
}
private static DXGI.Format ComputeViewFormat(DepthFormat format, out bool hasStencil)
{
DXGI.Format viewFormat;
hasStencil = false;
// Determine TypeLess Format and ShaderResourceView Format
switch (format)
{
case DepthFormat.Depth16:
viewFormat = SharpDX.DXGI.Format.R16_Float;
break;
case DepthFormat.Depth32:
viewFormat = SharpDX.DXGI.Format.R32_Float;
break;
case DepthFormat.Depth24Stencil8:
viewFormat = SharpDX.DXGI.Format.R24_UNorm_X8_Typeless;
hasStencil = true;
break;
case DepthFormat.Depth32Stencil8X24:
viewFormat = SharpDX.DXGI.Format.R32_Float_X8X24_Typeless;
hasStencil = true;
break;
default:
viewFormat = DXGI.Format.Unknown;
break;
}
return viewFormat;
}
private static DepthFormat ComputeViewFormat(DXGI.Format format)
{
switch (format)
{
case SharpDX.DXGI.Format.D16_UNorm:
case DXGI.Format.R16_Float:
case DXGI.Format.R16_Typeless:
return DepthFormat.Depth16;
case SharpDX.DXGI.Format.D32_Float:
case DXGI.Format.R32_Float:
case DXGI.Format.R32_Typeless:
return DepthFormat.Depth32;
case SharpDX.DXGI.Format.D24_UNorm_S8_UInt:
case SharpDX.DXGI.Format.R24_UNorm_X8_Typeless:
return DepthFormat.Depth24Stencil8;
case SharpDX.DXGI.Format.D32_Float_S8X24_UInt:
case SharpDX.DXGI.Format.R32_Float_X8X24_Typeless:
return DepthFormat.Depth32Stencil8X24;
}
throw new InvalidOperationException(string.Format("Unsupported DXGI.FORMAT [{0}] for depth buffer", format));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Security.Cryptography.Asn1
{
internal sealed partial class AsnWriter
{
/// <summary>
/// Write a Bit String value with a tag UNIVERSAL 3.
/// </summary>
/// <param name="bitString">The value to write.</param>
/// <param name="unusedBitCount">
/// The number of trailing bits which are not semantic.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="unusedBitCount"/> is not in the range [0,7]
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="bitString"/> has length 0 and <paramref name="unusedBitCount"/> is not 0 --OR--
/// <paramref name="bitString"/> is not empty and any of the bits identified by
/// <paramref name="unusedBitCount"/> is set
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteBitString(ReadOnlySpan<byte> bitString, int unusedBitCount = 0)
{
WriteBitStringCore(Asn1Tag.PrimitiveBitString, bitString, unusedBitCount);
}
/// <summary>
/// Write a Bit String value with a specified tag.
/// </summary>
/// <param name="tag">The tag to write.</param>
/// <param name="bitString">The value to write.</param>
/// <param name="unusedBitCount">
/// The number of trailing bits which are not semantic.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagClass"/> is
/// <see cref="TagClass.Universal"/>, but
/// <paramref name="tag"/>.<see cref="Asn1Tag.TagValue"/> is not correct for
/// the method
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="unusedBitCount"/> is not in the range [0,7]
/// </exception>
/// <exception cref="CryptographicException">
/// <paramref name="bitString"/> has length 0 and <paramref name="unusedBitCount"/> is not 0 --OR--
/// <paramref name="bitString"/> is not empty and any of the bits identified by
/// <paramref name="unusedBitCount"/> is set
/// </exception>
/// <exception cref="ObjectDisposedException">The writer has been Disposed.</exception>
public void WriteBitString(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount = 0)
{
CheckUniversalTag(tag, UniversalTagNumber.BitString);
// Primitive or constructed, doesn't matter.
WriteBitStringCore(tag, bitString, unusedBitCount);
}
// T-REC-X.690-201508 sec 8.6
private void WriteBitStringCore(Asn1Tag tag, ReadOnlySpan<byte> bitString, int unusedBitCount)
{
// T-REC-X.690-201508 sec 8.6.2.2
if (unusedBitCount < 0 || unusedBitCount > 7)
{
throw new ArgumentOutOfRangeException(
nameof(unusedBitCount),
unusedBitCount,
SR.Cryptography_Asn_UnusedBitCountRange);
}
CheckDisposed();
// T-REC-X.690-201508 sec 8.6.2.3
if (bitString.Length == 0 && unusedBitCount != 0)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
// If 3 bits are "unused" then build a mask for them to check for 0.
// 1 << 3 => 0b0000_1000
// subtract 1 => 0b000_0111
int mask = (1 << unusedBitCount) - 1;
byte lastByte = bitString.IsEmpty ? (byte)0 : bitString[bitString.Length - 1];
if ((lastByte & mask) != 0)
{
// T-REC-X.690-201508 sec 11.2
//
// This could be ignored for BER, but since DER is more common and
// it likely suggests a program error on the caller, leave it enabled for
// BER for now.
// TODO: Probably warrants a distinct message.
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
if (RuleSet == AsnEncodingRules.CER)
{
// T-REC-X.690-201508 sec 9.2
//
// If it's not within a primitive segment, use the constructed encoding.
// (>= instead of > because of the unused bit count byte)
if (bitString.Length >= AsnReader.MaxCERSegmentSize)
{
WriteConstructedCerBitString(tag, bitString, unusedBitCount);
return;
}
}
// Clear the constructed flag, if present.
WriteTag(tag.AsPrimitive());
// The unused bits byte requires +1.
WriteLength(bitString.Length + 1);
_buffer[_offset] = (byte)unusedBitCount;
_offset++;
bitString.CopyTo(_buffer.AsSpan(_offset));
_offset += bitString.Length;
}
// T-REC-X.690-201508 sec 9.2, 8.6
private void WriteConstructedCerBitString(Asn1Tag tag, ReadOnlySpan<byte> payload, int unusedBitCount)
{
const int MaxCERSegmentSize = AsnReader.MaxCERSegmentSize;
// Every segment has an "unused bit count" byte.
const int MaxCERContentSize = MaxCERSegmentSize - 1;
Debug.Assert(payload.Length > MaxCERContentSize);
WriteTag(tag.AsConstructed());
// T-REC-X.690-201508 sec 9.1
// Constructed CER uses the indefinite form.
WriteLength(-1);
int fullSegments = Math.DivRem(payload.Length, MaxCERContentSize, out int lastContentSize);
// The tag size is 1 byte.
// The length will always be encoded as 82 03 E8 (3 bytes)
// And 1000 content octets (by T-REC-X.690-201508 sec 9.2)
const int FullSegmentEncodedSize = 1004;
Debug.Assert(
FullSegmentEncodedSize == 1 + 1 + MaxCERSegmentSize + GetEncodedLengthSubsequentByteCount(MaxCERSegmentSize));
int remainingEncodedSize;
if (lastContentSize == 0)
{
remainingEncodedSize = 0;
}
else
{
// One byte of tag, minimum one byte of length, and one byte of unused bit count.
remainingEncodedSize = 3 + lastContentSize + GetEncodedLengthSubsequentByteCount(lastContentSize);
}
// Reduce the number of copies by pre-calculating the size.
// +2 for End-Of-Contents
int expectedSize = fullSegments * FullSegmentEncodedSize + remainingEncodedSize + 2;
EnsureWriteCapacity(expectedSize);
byte[] ensureNoExtraCopy = _buffer;
int savedOffset = _offset;
ReadOnlySpan<byte> remainingData = payload;
Span<byte> dest;
Asn1Tag primitiveBitString = Asn1Tag.PrimitiveBitString;
while (remainingData.Length > MaxCERContentSize)
{
// T-REC-X.690-201508 sec 8.6.4.1
WriteTag(primitiveBitString);
WriteLength(MaxCERSegmentSize);
// 0 unused bits in this segment.
_buffer[_offset] = 0;
_offset++;
dest = _buffer.AsSpan(_offset);
remainingData.Slice(0, MaxCERContentSize).CopyTo(dest);
remainingData = remainingData.Slice(MaxCERContentSize);
_offset += MaxCERContentSize;
}
WriteTag(primitiveBitString);
WriteLength(remainingData.Length + 1);
_buffer[_offset] = (byte)unusedBitCount;
_offset++;
dest = _buffer.AsSpan(_offset);
remainingData.CopyTo(dest);
_offset += remainingData.Length;
WriteEndOfContents();
Debug.Assert(_offset - savedOffset == expectedSize, $"expected size was {expectedSize}, actual was {_offset - savedOffset}");
Debug.Assert(_buffer == ensureNoExtraCopy, $"_buffer was replaced during {nameof(WriteConstructedCerBitString)}");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Xunit;
namespace System.Tests
{
public static class LazyTests
{
[Fact]
public static void Ctor()
{
var lazyString = new Lazy<string>();
VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false);
var lazyObject = new Lazy<int>();
VerifyLazy(lazyObject, 0, hasValue: true, isValueCreated: false);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void Ctor_Bool(bool isThreadSafe)
{
var lazyString = new Lazy<string>(isThreadSafe);
VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactory()
{
var lazyString = new Lazy<string>(() => "foo");
VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false);
var lazyInt = new Lazy<int>(() => 1);
VerifyLazy(lazyInt, 1, hasValue: true, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactory_NullValueFactory_ThrowsArguentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null)); // Value factory is null
}
[Fact]
public static void Ctor_LazyThreadSafetyMode()
{
var lazyString = new Lazy<string>(LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyString, "", hasValue: false, isValueCreated: false);
}
[Fact]
public static void Ctor_LazyThreadSafetyMode_InvalidMode_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void Ctor_ValueFactor_Bool(bool isThreadSafe)
{
var lazyString = new Lazy<string>(() => "foo", isThreadSafe);
VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactory_Bool_NullValueFactory_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, false)); // Value factory is null
}
[Fact]
public static void Ctor_ValueFactor_LazyThreadSafetyMode()
{
var lazyString = new Lazy<string>(() => "foo", LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyString, "foo", hasValue: true, isValueCreated: false);
var lazyInt = new Lazy<int>(() => 1, LazyThreadSafetyMode.PublicationOnly);
VerifyLazy(lazyInt, 1, hasValue: true, isValueCreated: false);
}
[Fact]
public static void Ctor_ValueFactor_LazyThreadSafetyMode_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("valueFactory", () => new Lazy<object>(null, LazyThreadSafetyMode.PublicationOnly)); // Value factory is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foo", LazyThreadSafetyMode.None - 1)); // Invalid thread saftety mode
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => new Lazy<string>(() => "foof", LazyThreadSafetyMode.ExecutionAndPublication + 1)); // Invalid thread saftety mode
}
[Fact]
public static void ToString_DoesntForceAllocation()
{
var lazy = new Lazy<object>(() => 1);
Assert.NotEqual("1", lazy.ToString());
Assert.False(lazy.IsValueCreated);
object tmp = lazy.Value;
Assert.Equal("1", lazy.ToString());
}
private static void Value_Invalid_Impl<T>(ref Lazy<T> x, Lazy<T> lazy)
{
x = lazy;
Assert.Throws<InvalidOperationException>(() => lazy.Value);
}
[Fact]
public static void Value_Invalid()
{
Lazy<int> x = null;
Func<int> f = () => x.Value;
Value_Invalid_Impl(ref x, new Lazy<int>(f));
Value_Invalid_Impl(ref x, new Lazy<int>(f, true));
Value_Invalid_Impl(ref x, new Lazy<int>(f, false));
Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.ExecutionAndPublication));
Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.None));
// When used with LazyThreadSafetyMode.PublicationOnly this causes a stack overflow
// Value_Invalid_Impl(ref x, new Lazy<int>(f, LazyThreadSafetyMode.PublicationOnly));
}
public class InitiallyExceptionThrowingCtor
{
public static int counter = 0;
public static int getValue()
{
if (++counter < 5)
throw new Exception();
else
return counter;
}
public int Value { get; }
public InitiallyExceptionThrowingCtor()
{
Value = getValue();
}
}
private static IEnumerable<Lazy<InitiallyExceptionThrowingCtor>> Ctor_ExceptionRecovery_MemberData()
{
yield return new Lazy<InitiallyExceptionThrowingCtor>();
yield return new Lazy<InitiallyExceptionThrowingCtor>(true);
yield return new Lazy<InitiallyExceptionThrowingCtor>(false);
yield return new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.ExecutionAndPublication);
yield return new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.None);
yield return new Lazy<InitiallyExceptionThrowingCtor>(LazyThreadSafetyMode.PublicationOnly);
}
//
// Do not use [Theory]. XUnit argument formatter can invoke the lazy.Value property underneath you and ruin the assumptions
// made by the test.
//
[Fact]
public static void Ctor_ExceptionRecovery()
{
foreach (Lazy<InitiallyExceptionThrowingCtor> lazy in Ctor_ExceptionRecovery_MemberData())
{
InitiallyExceptionThrowingCtor.counter = 0;
InitiallyExceptionThrowingCtor result = null;
for (int i = 0; i < 10; ++i)
{
try
{ result = lazy.Value; }
catch (Exception) { }
}
Assert.Equal(5, result.Value);
}
}
private static void Value_ExceptionRecovery_IntImpl(Lazy<int> lazy, ref int counter, int expected)
{
counter = 0;
int result = 0;
for (var i = 0; i < 10; ++i)
{
try { result = lazy.Value; } catch (Exception) { }
}
Assert.Equal(result, expected);
}
private static void Value_ExceptionRecovery_StringImpl(Lazy<string> lazy, ref int counter, string expected)
{
counter = 0;
var result = default(string);
for (var i = 0; i < 10; ++i)
{
try { result = lazy.Value; } catch (Exception) { }
}
Assert.Equal(expected, result);
}
[Fact]
public static void Value_ExceptionRecovery()
{
int counter = 0; // set in test function
var fint = new Func<int> (() => { if (++counter < 5) throw new Exception(); else return counter; });
var fobj = new Func<string>(() => { if (++counter < 5) throw new Exception(); else return counter.ToString(); });
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, true), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, false), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.None), ref counter, 0);
Value_ExceptionRecovery_IntImpl(new Lazy<int>(fint, LazyThreadSafetyMode.PublicationOnly), ref counter, 5);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, true), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, false), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.ExecutionAndPublication), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.None), ref counter, null);
Value_ExceptionRecovery_StringImpl(new Lazy<string>(fobj, LazyThreadSafetyMode.PublicationOnly), ref counter, 5.ToString());
}
class MyException
: Exception
{
public int Value { get; }
public MyException(int value)
{
Value = value;
}
}
public class ExceptionInCtor
{
public ExceptionInCtor() : this(99) { }
public ExceptionInCtor(int value)
{
throw new MyException(value);
}
}
public static IEnumerable<object[]> Value_Func_Exception_MemberData()
{
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, true) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, false) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Value_Func_Exception_MemberData))]
public static void Value_Func_Exception(Lazy<int> lazy)
{
Assert.Throws<MyException>(() => lazy.Value);
}
public static IEnumerable<object[]> Value_FuncCtor_Exception_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99)) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), true) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), false) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Value_FuncCtor_Exception_MemberData))]
public static void Value_FuncCtor_Exception(Lazy<ExceptionInCtor> lazy)
{
Assert.Throws<MyException>(() => lazy.Value);
}
public static IEnumerable<object[]> Value_TargetInvocationException_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>() };
yield return new object[] { new Lazy<ExceptionInCtor>(true) };
yield return new object[] { new Lazy<ExceptionInCtor>(false) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Value_TargetInvocationException_MemberData))]
public static void Value_TargetInvocationException(Lazy<ExceptionInCtor> lazy)
{
Assert.Throws<TargetInvocationException>(() => lazy.Value);
}
public static IEnumerable<object[]> Exceptions_Func_Idempotent_MemberData()
{
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, true) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, false) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.None) };
}
[Theory]
[MemberData(nameof(Exceptions_Func_Idempotent_MemberData))]
public static void Exceptions_Func_Idempotent(Lazy<int> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.Same(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
public static IEnumerable<object[]> Exceptions_Ctor_Idempotent_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99)) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), true) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), false) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.None) };
}
[Theory]
[MemberData(nameof(Exceptions_Ctor_Idempotent_MemberData))]
public static void Exceptions_Ctor_Idempotent(Lazy<ExceptionInCtor> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.Same(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
public static IEnumerable<object[]> Exceptions_Func_NotIdempotent_MemberData()
{
yield return new object[] { new Lazy<int>(() => { throw new MyException(99); }, LazyThreadSafetyMode.PublicationOnly) };
}
public static IEnumerable<object[]> Exceptions_Ctor_NotIdempotent_MemberData()
{
yield return new object[] { new Lazy<ExceptionInCtor>() };
yield return new object[] { new Lazy<ExceptionInCtor>(true) };
yield return new object[] { new Lazy<ExceptionInCtor>(false) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.ExecutionAndPublication) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.None) };
yield return new object[] { new Lazy<ExceptionInCtor>(LazyThreadSafetyMode.PublicationOnly) };
yield return new object[] { new Lazy<ExceptionInCtor>(() => new ExceptionInCtor(99), LazyThreadSafetyMode.PublicationOnly) };
}
[Theory]
[MemberData(nameof(Exceptions_Func_NotIdempotent_MemberData))]
public static void Exceptions_Func_NotIdempotent(Lazy<int> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.NotSame(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
[Theory]
[MemberData(nameof(Exceptions_Ctor_NotIdempotent_MemberData))]
public static void Exceptions_Ctor_NotIdempotent(Lazy<ExceptionInCtor> x)
{
var e = Assert.ThrowsAny<Exception>(() => x.Value);
Assert.NotSame(e, Assert.ThrowsAny<Exception>(() => x.Value));
}
[Theory]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
[InlineData(LazyThreadSafetyMode.None)]
public static void Value_ThrownException_DoesntCreateValue(LazyThreadSafetyMode mode)
{
var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, mode);
Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Assert.Same(exception1, exception2);
Assert.False(lazy.IsValueCreated);
}
[Fact]
public static void Value_ThrownException_DoesntCreateValue_PublicationOnly()
{
var lazy = new Lazy<string>(() => { throw new DivideByZeroException(); }, LazyThreadSafetyMode.PublicationOnly);
Exception exception1 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Exception exception2 = Assert.Throws<DivideByZeroException>(() => lazy.Value);
Assert.NotSame(exception1, exception2);
Assert.False(lazy.IsValueCreated);
}
[Fact]
public static void EnsureInitialized_SimpleRefTypes()
{
var hdcTemplate = new HasDefaultCtor();
string strTemplate = "foo";
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
Assert.NotNull(LazyInitializer.EnsureInitialized(ref a));
Assert.Same(a, LazyInitializer.EnsureInitialized(ref a));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b));
Assert.Same(b, LazyInitializer.EnsureInitialized(ref b));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, () => strTemplate));
Assert.Same(c, LazyInitializer.EnsureInitialized(ref c));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, () => strTemplate + "bar"));
Assert.Same(d, LazyInitializer.EnsureInitialized(ref d));
Assert.Equal(strTemplate, d);
}
[Fact]
public static void EnsureInitialized_SimpleRefTypes_Invalid()
{
// Func based initialization (nulls not permitted).
string e = null;
Assert.Throws<InvalidOperationException>(() => LazyInitializer.EnsureInitialized(ref e, () => null));
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc));
}
[Fact]
public static void EnsureInitialized_ComplexRefTypes()
{
string strTemplate = "foo";
var hdcTemplate = new HasDefaultCtor();
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
bool aInit = false;
object aLock = null;
Assert.NotNull(LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock));
Assert.NotNull(a);
Assert.True(aInit);
Assert.NotNull(aLock);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
bool bInit = true;
object bLock = null;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock));
Assert.Equal(hdcTemplate, b);
Assert.True(bInit);
Assert.Null(bLock);
// Func based initialization (uninitialized).
string c = null;
bool cInit = false;
object cLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => strTemplate));
Assert.Equal(strTemplate, c);
Assert.True(cInit);
Assert.NotNull(cLock);
// Func based initialization (already initialized).
string d = strTemplate;
bool dInit = true;
object dLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => strTemplate + "bar"));
Assert.Equal(strTemplate, d);
Assert.True(dInit);
Assert.Null(dLock);
// Func based initialization (nulls *ARE* permitted).
string e = null;
bool einit = false;
object elock = null;
int initCount = 0;
Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; }));
Assert.Null(e);
Assert.Equal(1, initCount);
Assert.True(einit);
Assert.NotNull(elock);
Assert.Null(LazyInitializer.EnsureInitialized(ref e, ref einit, ref elock, () => { initCount++; return null; }));
}
[Fact]
public static void EnsureInitialized_ComplexRefTypes_Invalid()
{
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
bool ndcInit = false;
object ndcLock = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized(ref ndc, ref ndcInit, ref ndcLock));
}
[Fact]
public static void LazyInitializerComplexValueTypes()
{
var empty = new LIX();
var template = new LIX(33);
// Activator.CreateInstance (uninitialized).
LIX a = default(LIX);
bool aInit = false;
object aLock = null;
LIX ensuredValA = LazyInitializer.EnsureInitialized(ref a, ref aInit, ref aLock);
Assert.Equal(empty, ensuredValA);
Assert.Equal(empty, a);
// Activator.CreateInstance (already initialized).
LIX b = template;
bool bInit = true;
object bLock = null;
LIX ensuredValB = LazyInitializer.EnsureInitialized(ref b, ref bInit, ref bLock);
Assert.Equal(template, ensuredValB);
Assert.Equal(template, b);
// Func based initialization (uninitialized).
LIX c = default(LIX);
bool cInit = false;
object cLock = null;
LIX ensuredValC = LazyInitializer.EnsureInitialized(ref c, ref cInit, ref cLock, () => template);
Assert.Equal(template, c);
Assert.Equal(template, ensuredValC);
// Func based initialization (already initialized).
LIX d = template;
bool dInit = true;
object dLock = null;
LIX template2 = new LIX(template.f * 2);
LIX ensuredValD = LazyInitializer.EnsureInitialized(ref d, ref dInit, ref dLock, () => template2);
Assert.Equal(template, ensuredValD);
Assert.Equal(template, d);
}
[Fact]
public static void Ctor_Value_ReferenceType()
{
var lazyString = new Lazy<string>("abc");
VerifyLazy(lazyString, "abc", hasValue: true, isValueCreated: true);
}
[Fact]
public static void Ctor_Value_ValueType()
{
var lazyObject = new Lazy<int>(123);
VerifyLazy(lazyObject, 123, hasValue: true, isValueCreated: true);
}
[Fact]
public static void EnsureInitialized_FuncInitializationWithoutTrackingBool_Uninitialized()
{
string template = "foo";
string target = null;
object syncLock = null;
Assert.Equal(template, LazyInitializer.EnsureInitialized(ref target, ref syncLock, () => template));
Assert.Equal(template, target);
Assert.NotNull(syncLock);
}
[Fact]
public static void EnsureInitialized_FuncInitializationWithoutTrackingBool_Initialized()
{
string template = "foo";
string target = template;
object syncLock = null;
Assert.Equal(template, LazyInitializer.EnsureInitialized(ref target, ref syncLock, () => template + "bar"));
Assert.Equal(template, target);
Assert.Null(syncLock);
}
[Fact]
public static void EnsureInitializer_FuncInitializationWithoutTrackingBool_Null()
{
string target = null;
object syncLock = null;
Assert.Throws<InvalidOperationException>(() => LazyInitializer.EnsureInitialized(ref target, ref syncLock, () => null));
}
private static void VerifyLazy<T>(Lazy<T> lazy, T expectedValue, bool hasValue, bool isValueCreated)
{
Assert.Equal(isValueCreated, lazy.IsValueCreated);
if (hasValue)
{
Assert.Equal(expectedValue, lazy.Value);
Assert.True(lazy.IsValueCreated);
}
else
{
Assert.Throws<MissingMemberException>(() => lazy.Value); // Value could not be created
Assert.False(lazy.IsValueCreated);
}
}
private class HasDefaultCtor { }
private class NoDefaultCtor
{
public NoDefaultCtor(int x) { }
}
private struct LIX
{
public int f;
public LIX(int f) { this.f = f; }
public override bool Equals(object other) => other is LIX && ((LIX)other).f == f;
public override int GetHashCode() => f.GetHashCode();
public override string ToString() => "LIX<" + f + ">";
}
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Remoting;
using System.Threading;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This cmdlet stops the asynchronously invoked remote operaitons.
/// </summary>
[Cmdlet(VerbsLifecycle.Stop, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet,
HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113413")]
[OutputType(typeof(Job))]
public class StopJobCommand : JobCmdletBase, IDisposable
{
#region Parameters
/// <summary>
/// Specifies the Jobs objects which need to be
/// removed
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = RemoveJobCommand.JobParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Job[] Job
{
get
{
return _jobs;
}
set
{
_jobs = value;
}
}
private Job[] _jobs;
/// <summary>
/// Pass the Job object through the pipeline.
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get
{
return _passThru;
}
set
{
_passThru = value;
}
}
private bool _passThru;
/// <summary>
///
/// </summary>
public override String[] Command
{
get
{
return null;
}
}
#endregion Parameters
#region Overrides
/// <summary>
/// Stop the Job.
/// </summary>
protected override void ProcessRecord()
{
//List of jobs to stop
List<Job> jobsToStop = null;
switch (ParameterSetName)
{
case NameParameterSet:
{
jobsToStop = FindJobsMatchingByName(true, false, true, false);
}
break;
case InstanceIdParameterSet:
{
jobsToStop = FindJobsMatchingByInstanceId(true, false, true, false);
}
break;
case SessionIdParameterSet:
{
jobsToStop = FindJobsMatchingBySessionId(true, false, true, false);
}
break;
case StateParameterSet:
{
jobsToStop = FindJobsMatchingByState(false);
}
break;
case FilterParameterSet:
{
jobsToStop = FindJobsMatchingByFilter(false);
}
break;
default:
{
jobsToStop = CopyJobsToList(_jobs, false, false);
}
break;
}
_allJobsToStop.AddRange(jobsToStop);
foreach (Job job in jobsToStop)
{
if (this.Stopping) return;
if (job.IsFinishedState(job.JobStateInfo.State))
{
continue;
}
string targetString =
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget,
job.Command, job.Id);
if (ShouldProcess(targetString, VerbsLifecycle.Stop))
{
Job2 job2 = job as Job2;
// if it is a Job2, then async is supported
// stop the job asynchornously
if (job2 != null)
{
_cleanUpActions.Add(job2, HandleStopJobCompleted);
job2.StopJobCompleted += HandleStopJobCompleted;
lock (_syncObject)
{
if (!job2.IsFinishedState(job2.JobStateInfo.State) &&
!_pendingJobs.Contains(job2.InstanceId))
{
_pendingJobs.Add(job2.InstanceId);
}
}
job2.StopJobAsync();
}
else
{
job.StopJob();
var parentJob = job as ContainerParentJob;
if (parentJob != null && parentJob.ExecutionError.Count > 0)
{
foreach (
var e in
parentJob.ExecutionError.Where(
e => e.FullyQualifiedErrorId == "ContainerParentJobStopError"))
{
WriteError(e);
}
}
}
}
}
}
/// <summary>
/// Wait for all the stop jobs to be completed
/// </summary>
protected override void EndProcessing()
{
bool haveToWait = false;
lock (_syncObject)
{
_needToCheckForWaitingJobs = true;
if (_pendingJobs.Count > 0)
haveToWait = true;
}
if (haveToWait)
_waitForJobs.WaitOne();
foreach (var e in _errorsToWrite) WriteError(e);
if (_passThru)
{
foreach (var job in _allJobsToStop) WriteObject(job);
}
}
/// <summary>
///
/// </summary>
protected override void StopProcessing()
{
_waitForJobs.Set();
}
#endregion Overrides
#region Private Methods
private void HandleStopJobCompleted(object sender, AsyncCompletedEventArgs eventArgs)
{
Job job = sender as Job;
if (eventArgs.Error != null)
{
_errorsToWrite.Add(new ErrorRecord(eventArgs.Error, "StopJobError", ErrorCategory.ReadError, job));
}
var parentJob = job as ContainerParentJob;
if (parentJob != null && parentJob.ExecutionError.Count > 0)
{
foreach (
var e in
parentJob.ExecutionError.Where(
e => e.FullyQualifiedErrorId == "ContainerParentJobStopAsyncError"))
{
_errorsToWrite.Add(e);
}
}
bool releaseWait = false;
lock (_syncObject)
{
if (_pendingJobs.Contains(job.InstanceId))
{
_pendingJobs.Remove(job.InstanceId);
}
if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0)
releaseWait = true;
}
// end processing has been called
// set waithandle if this is the last one
if (releaseWait)
_waitForJobs.Set();
}
#endregion Private Methods
#region Private Members
private readonly HashSet<Guid> _pendingJobs = new HashSet<Guid>();
private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false);
private readonly Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>> _cleanUpActions =
new Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>>();
private readonly List<Job> _allJobsToStop = new List<Job>();
private readonly List<ErrorRecord> _errorsToWrite = new List<ErrorRecord>();
private readonly object _syncObject = new object();
private bool _needToCheckForWaitingJobs;
#endregion Private Members
#region Dispose
/// <summary>
///
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
///
/// </summary>
/// <param name="disposing"></param>
protected void Dispose(bool disposing)
{
if (!disposing) return;
foreach (var pair in _cleanUpActions)
{
pair.Key.StopJobCompleted -= pair.Value;
}
_waitForJobs.Dispose();
}
#endregion Dispose
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cognito-identity-2014-06-30.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.CognitoIdentity;
using Amazon.CognitoIdentity.Model;
using Amazon.CognitoIdentity.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class CognitoIdentityMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("cognito-identity-2014-06-30.normal.json", "cognito-identity.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void CreateIdentityPoolMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateIdentityPoolRequest>();
var marshaller = new CreateIdentityPoolRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateIdentityPoolRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateIdentityPool").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateIdentityPoolResponseUnmarshaller.Instance.Unmarshall(context)
as CreateIdentityPoolResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void DeleteIdentitiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteIdentitiesRequest>();
var marshaller = new DeleteIdentitiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteIdentitiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteIdentities").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeleteIdentitiesResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteIdentitiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void DeleteIdentityPoolMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteIdentityPoolRequest>();
var marshaller = new DeleteIdentityPoolRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteIdentityPoolRequest>(request,jsonRequest);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void DescribeIdentityMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeIdentityRequest>();
var marshaller = new DescribeIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeIdentityRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeIdentity").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeIdentityResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void DescribeIdentityPoolMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeIdentityPoolRequest>();
var marshaller = new DescribeIdentityPoolRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeIdentityPoolRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeIdentityPool").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeIdentityPoolResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeIdentityPoolResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void GetCredentialsForIdentityMarshallTest()
{
var request = InstantiateClassGenerator.Execute<GetCredentialsForIdentityRequest>();
var marshaller = new GetCredentialsForIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<GetCredentialsForIdentityRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetCredentialsForIdentity").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = GetCredentialsForIdentityResponseUnmarshaller.Instance.Unmarshall(context)
as GetCredentialsForIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void GetIdMarshallTest()
{
var request = InstantiateClassGenerator.Execute<GetIdRequest>();
var marshaller = new GetIdRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<GetIdRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetId").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = GetIdResponseUnmarshaller.Instance.Unmarshall(context)
as GetIdResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void GetIdentityPoolRolesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<GetIdentityPoolRolesRequest>();
var marshaller = new GetIdentityPoolRolesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<GetIdentityPoolRolesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetIdentityPoolRoles").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = GetIdentityPoolRolesResponseUnmarshaller.Instance.Unmarshall(context)
as GetIdentityPoolRolesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void GetOpenIdTokenMarshallTest()
{
var request = InstantiateClassGenerator.Execute<GetOpenIdTokenRequest>();
var marshaller = new GetOpenIdTokenRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<GetOpenIdTokenRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetOpenIdToken").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = GetOpenIdTokenResponseUnmarshaller.Instance.Unmarshall(context)
as GetOpenIdTokenResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void GetOpenIdTokenForDeveloperIdentityMarshallTest()
{
var request = InstantiateClassGenerator.Execute<GetOpenIdTokenForDeveloperIdentityRequest>();
var marshaller = new GetOpenIdTokenForDeveloperIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<GetOpenIdTokenForDeveloperIdentityRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetOpenIdTokenForDeveloperIdentity").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = GetOpenIdTokenForDeveloperIdentityResponseUnmarshaller.Instance.Unmarshall(context)
as GetOpenIdTokenForDeveloperIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void ListIdentitiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListIdentitiesRequest>();
var marshaller = new ListIdentitiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListIdentitiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListIdentities").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListIdentitiesResponseUnmarshaller.Instance.Unmarshall(context)
as ListIdentitiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void ListIdentityPoolsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListIdentityPoolsRequest>();
var marshaller = new ListIdentityPoolsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListIdentityPoolsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListIdentityPools").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListIdentityPoolsResponseUnmarshaller.Instance.Unmarshall(context)
as ListIdentityPoolsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void LookupDeveloperIdentityMarshallTest()
{
var request = InstantiateClassGenerator.Execute<LookupDeveloperIdentityRequest>();
var marshaller = new LookupDeveloperIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<LookupDeveloperIdentityRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("LookupDeveloperIdentity").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = LookupDeveloperIdentityResponseUnmarshaller.Instance.Unmarshall(context)
as LookupDeveloperIdentityResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void MergeDeveloperIdentitiesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<MergeDeveloperIdentitiesRequest>();
var marshaller = new MergeDeveloperIdentitiesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<MergeDeveloperIdentitiesRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("MergeDeveloperIdentities").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = MergeDeveloperIdentitiesResponseUnmarshaller.Instance.Unmarshall(context)
as MergeDeveloperIdentitiesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void SetIdentityPoolRolesMarshallTest()
{
var request = InstantiateClassGenerator.Execute<SetIdentityPoolRolesRequest>();
var marshaller = new SetIdentityPoolRolesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<SetIdentityPoolRolesRequest>(request,jsonRequest);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void UnlinkDeveloperIdentityMarshallTest()
{
var request = InstantiateClassGenerator.Execute<UnlinkDeveloperIdentityRequest>();
var marshaller = new UnlinkDeveloperIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<UnlinkDeveloperIdentityRequest>(request,jsonRequest);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void UnlinkIdentityMarshallTest()
{
var request = InstantiateClassGenerator.Execute<UnlinkIdentityRequest>();
var marshaller = new UnlinkIdentityRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<UnlinkIdentityRequest>(request,jsonRequest);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("CognitoIdentity")]
public void UpdateIdentityPoolMarshallTest()
{
var request = InstantiateClassGenerator.Execute<UpdateIdentityPoolRequest>();
var marshaller = new UpdateIdentityPoolRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<UpdateIdentityPoolRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateIdentityPool").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = UpdateIdentityPoolResponseUnmarshaller.Instance.Unmarshall(context)
as UpdateIdentityPoolResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
namespace Gu.Units
{
using System;
internal class StringMap<TItem>
{
private static readonly CachedItem[] Empty = new CachedItem[0];
private readonly object gate = new object();
private CachedItem[] cache = Empty;
internal bool TryGetBySubString(string text, int pos, out TItem result)
{
return this.TryGetBySubString(text, pos, out string _, out result);
}
internal bool TryGetBySubString(string text, int pos, out string key, out TItem result)
{
if (text == null)
{
key = null;
result = default(TItem);
return false;
}
var tempCache = this.cache;
var index = BinaryFindSubstring(this.cache, text, pos);
if (index < 0)
{
key = null;
result = default(TItem);
return false;
}
var match = tempCache[index];
for (var i = index + 1; i < tempCache.Length; i++)
{
// searching linearly for longest match after finding one
var temp = tempCache[i];
if (Compare(temp.Key, text, pos) <= 0)
{
match = temp;
}
else
{
key = match.Key;
result = match.Value;
return true;
}
}
key = match.Key;
result = match.Value;
return true;
}
internal bool TryGet(string key, out TItem match)
{
if (key == null)
{
match = default(TItem);
return false;
}
var tempCache = this.cache;
var index = BinaryFind(this.cache, key);
if (index < 0)
{
match = default(TItem);
return false;
}
match = tempCache[index].Value;
return true;
}
internal CachedItem Add(string key, TItem item)
{
Ensure.NotNull(key, $"{nameof(item)}.{key}");
//// this was five times faster than ReaderWriterLockSlim in benchmarks.
lock (this.gate)
{
var i = BinaryFind(this.cache, key);
if (i >= 0)
{
var cachedItem = this.cache[i];
if (cachedItem.Key == key)
{
if (Equals(cachedItem.Value, item))
{
return cachedItem;
}
throw new InvalidOperationException("Cannot add same key with different values.\r\n" +
$"The key is {key} and the values are {{{item}, {cachedItem.Value}}}");
}
}
var updated = new CachedItem[this.cache.Length + 1];
Array.Copy(this.cache, 0, updated, 0, this.cache.Length);
var newItem = new CachedItem(key, item);
updated[this.cache.Length] = newItem;
Array.Sort(updated);
this.cache = updated;
return newItem;
}
}
private static int BinaryFindSubstring(CachedItem[] cache, string key, int pos)
{
var lo = 0;
var hi = cache.Length - 1;
while (lo <= hi)
{
var i = (lo + hi) / 2;
var cached = cache[i];
var c = Compare(cached.Key, key, pos);
if (c == 0)
{
return i;
}
if (c < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static int BinaryFind(CachedItem[] cache, string key)
{
var lo = 0;
var hi = cache.Length - 1;
while (lo <= hi)
{
var i = (lo + hi) / 2;
var cached = cache[i];
var c = Compare(cached.Key, key);
if (c == 0)
{
return i;
}
if (c < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static int Compare(string cached, string key, int pos)
{
for (var i = 0; i < cached.Length; i++)
{
var j = i + pos;
if (key.Length == j)
{
return 1;
}
var compare = Invariant(cached[i]) - Invariant(key[j]);
if (compare != 0)
{
return compare;
}
}
return 0;
}
private static char Invariant(char c)
{
switch (c)
{
case '\u00B5':
// use lowercase greek mu instead of micro.
// http://www.fileformat.info/info/unicode/char/00b5/index.htm
// http://www.fileformat.info/info/unicode/char/03BC/index.htm
return '\u03BC';
case '\u2126':
// use lowercase greek mu instead of micro.
// http://www.fileformat.info/info/unicode/char/2126/index.htm
// http://www.fileformat.info/info/unicode/char/03a9/index.htm
return '\u03A9';
default:
return c;
}
}
private static int Compare(string cached, string key)
{
for (var i = 0; i < cached.Length; i++)
{
if (key.Length == i)
{
return 1;
}
var compare = cached[i] - key[i];
if (compare != 0)
{
return compare;
}
}
return cached.Length - key.Length;
}
internal struct CachedItem : IComparable<CachedItem>
{
internal readonly string Key;
internal readonly TItem Value;
public CachedItem(string key, TItem value)
{
this.Key = key;
this.Value = value;
}
public int CompareTo(CachedItem other)
{
return Compare(this.Key, other.Key);
}
public override string ToString() => this.Key;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class GroupJoinTests
{
// Class which is passed as an argument for EqualityComparer
public class AnagramEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return getCanonicalString(x) == getCanonicalString(y);
}
public int GetHashCode(string obj)
{
return getCanonicalString(obj).GetHashCode();
}
private string getCanonicalString(string word)
{
char[] wordChars = word.ToCharArray();
Array.Sort<char>(wordChars);
return new string(wordChars);
}
}
public struct CustomerRec
{
public string name;
public int? custID;
}
public struct OrderRec
{
public int? orderID;
public int? custID;
public int? total;
}
public struct AnagramRec
{
public string name;
public int? orderID;
public int? total;
}
public struct JoinRec
{
public string name;
public int?[] orderID;
public int?[] total;
}
public class Helper
{
public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<OrderRec> orIE)
{
int count = 0;
JoinRec jr = new JoinRec();
jr.name = cr.name;
jr.orderID = new int?[orIE.Count()];
jr.total = new int?[orIE.Count()];
foreach (OrderRec or in orIE)
{
jr.orderID[count] = or.orderID;
jr.total[count] = or.total;
count++;
}
return jr;
}
public static JoinRec createJoinRec(CustomerRec cr, IEnumerable<AnagramRec> arIE)
{
int count = 0;
JoinRec jr = new JoinRec();
jr.name = cr.name;
jr.orderID = new int?[arIE.Count()];
jr.total = new int?[arIE.Count()];
foreach (AnagramRec ar in arIE)
{
jr.orderID[count] = ar.orderID;
jr.total[count] = ar.total;
count++;
}
return jr;
}
// The following verification function will be used when the PLINQ team runs these tests
// This is a non-order preserving verification function
#if PLINQ
public static int DataEqual(IEnumerable<JoinRec> ele1, IEnumerable<JoinRec> ele2)
{
if ((ele1 == null) && (ele2 == null)) return 0;
if (ele1.Count() != ele2.Count()) return 1;
List<JoinRec> elt = new List<JoinRec>(ele1);
foreach (JoinRec e2 in ele2)
{
bool contains = false;
for (int i = 0; i < elt.Count; i++)
{
JoinRec e1 = elt[i];
if (e1.name == e2.name && e1.orderID.Count() == e2.orderID.Count()&& e1.total.Count() == e2.total.Count())
{
bool eq = true;
for (int j = 0; j < e1.orderID.Count(); j++)
{
if (e1.orderID[j] != e2.orderID[j])
{
eq = false;
break;
}
}
for (int j = 0; j < e1.total.Count(); j++)
{
if (e1.total[j] != e2.total[j])
{
eq = false;
break;
}
}
if (!eq) continue;
elt.RemoveAt(i);
contains = true;
break;
}
}
if (!contains) return 1;
}
return 0;
}
#else
// The following is an order preserving verification function
public static int DataEqual(IEnumerable<JoinRec> ele1, IEnumerable<JoinRec> ele2)
{
if ((ele1 == null) && (ele2 == null)) return 0;
if (ele1.Count() != ele2.Count()) return 1;
using (IEnumerator<JoinRec> e1 = ele1.GetEnumerator())
using (IEnumerator<JoinRec> e2 = ele2.GetEnumerator())
{
while (e1.MoveNext())
{
e2.MoveNext();
JoinRec rec1 = (JoinRec)e1.Current;
JoinRec rec2 = (JoinRec)e2.Current;
if (rec1.name != rec2.name) return 1;
if (rec1.orderID.Count() != rec2.orderID.Count()) return 1;
if (rec1.total.Count() != rec2.total.Count()) return 1;
int num = rec1.orderID.Count();
for (int i = 0; i < num; i++)
if (rec1.orderID[i] != rec2.orderID[i]) return 1;
num = rec1.total.Count();
for (int i = 0; i < num; i++)
if (rec1.total[i] != rec2.total[i]) return 1;
}
}
return 0;
}
#endif
}
public class GroupJoin1
{
// outer is empty and inner is non-empty
public static int Test1()
{
CustomerRec[] outer = new CustomerRec[] { };
OrderRec[] inner = new OrderRec[]{ new OrderRec{orderID=45321, custID=98022, total=50},
new OrderRec{orderID=97865, custID=32103, total=25}
};
JoinRec[] expected = new JoinRec[] { };
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test1();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin10
{
// Overload-2: Test when IEqualityComparer is not-null
public static int Test10()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
AnagramRec[] inner = new AnagramRec[]{ new AnagramRec{name = "Robert", orderID=93483, total = 19},
new AnagramRec{name = "miT", orderID=93489, total = 45}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{93489}, total=new int?[]{45}},
new JoinRec{name="Bob", orderID=new int?[]{}, total=new int?[]{}},
new JoinRec{name="Robert", orderID=new int?[]{93483}, total=new int?[]{19}}
};
Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.name, (o) => o.name, resultSelector, new AnagramEqualityComparer());
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test10();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin11a
{
// Overload-2: Test when outer is null
public static int Test11a()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
AnagramRec[] inner = new AnagramRec[]{ new AnagramRec{name = "Robert", orderID=93483, total = 19},
new AnagramRec{name = "miT", orderID=93489, total = 45}
};
Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec> resultSelector = Helper.createJoinRec;
try
{
outer = null;
var actual = outer.GroupJoin(inner, (e) => e.name, (o) => o.name, resultSelector, new AnagramEqualityComparer());
return 1;
}
catch (ArgumentNullException ane)
{
if (!ane.CompareParamName("outer")) return 1;
return 0;
}
}
public static int Main()
{
return Test11a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin11b
{
// Overload-2: Test when inner is null
public static int Test11b()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
AnagramRec[] inner = new AnagramRec[]{ new AnagramRec{name = "Robert", orderID=93483, total = 19},
new AnagramRec{name = "miT", orderID=93489, total = 45}
};
Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec> resultSelector = Helper.createJoinRec;
try
{
inner = null;
var actual = outer.GroupJoin(inner, (e) => e.name, (o) => o.name, resultSelector, new AnagramEqualityComparer());
return 1;
}
catch (ArgumentNullException ane)
{
if (!ane.CompareParamName("inner")) return 1;
return 0;
}
}
public static int Main()
{
return Test11b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin11c
{
// Overload-2: Test when outerKeySelector is null
public static int Test11c()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
AnagramRec[] inner = new AnagramRec[]{ new AnagramRec{name = "Robert", orderID=93483, total = 19},
new AnagramRec{name = "miT", orderID=93489, total = 45}
};
Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec> resultSelector = Helper.createJoinRec;
try
{
var actual = outer.GroupJoin(inner, null, (o) => o.name, resultSelector, new AnagramEqualityComparer());
return 1;
}
catch (ArgumentNullException ane)
{
if (!ane.CompareParamName("outerKeySelector")) return 1;
return 0;
}
}
public static int Main()
{
return Test11c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin11d
{
// Overload-2: Test when innerKeySelector is null
public static int Test11d()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
AnagramRec[] inner = new AnagramRec[]{ new AnagramRec{name = "Robert", orderID=93483, total = 19},
new AnagramRec{name = "miT", orderID=93489, total = 45}
};
Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec> resultSelector = Helper.createJoinRec;
try
{
var actual = outer.GroupJoin(inner, (e) => e.name, null, resultSelector, new AnagramEqualityComparer());
return 1;
}
catch (ArgumentNullException ane)
{
if (!ane.CompareParamName("innerKeySelector")) return 1;
return 0;
}
}
public static int Main()
{
return Test11d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin11e
{
// Overload-2: Test when resultSelector is null
public static int Test11e()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
AnagramRec[] inner = new AnagramRec[]{ new AnagramRec{name = "Robert", orderID=93483, total = 19},
new AnagramRec{name = "miT", orderID=93489, total = 45}
};
Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec> resultSelector = Helper.createJoinRec;
try
{
resultSelector = null;
var actual = outer.GroupJoin(inner, (e) => e.name, (o) => o.name, resultSelector, new AnagramEqualityComparer());
return 1;
}
catch (ArgumentNullException ane)
{
if (!ane.CompareParamName("resultSelector")) return 1;
return 0;
}
}
public static int Main()
{
return Test11e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin12
{
// DDB:171937
public static int Test12()
{
string[] outer = new string[] { null };
string[] inner = new string[] { null };
string[] expected = new string[] { null };
Func<string, IEnumerable<string>, string> resultSelector = (string x, IEnumerable<string> y) => x;
var actual = outer.GroupJoin(inner, (e) => e, (o) => o, resultSelector, EqualityComparer<string>.Default);
return Verification.Allequal(expected, actual);
}
public static int Main()
{
return Test12();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin2
{
// outer is non-empty and inner is empty
public static int Test2()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=43434},
new CustomerRec{name="Bob", custID=34093}
};
OrderRec[] inner = new OrderRec[] { };
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{}, total=new int?[]{}},
new JoinRec{name="Bob", orderID=new int?[]{}, total=new int?[]{}}
};
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test2();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin3
{
// outer and inner has only one element and the key matches
public static int Test3()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=43434}
};
OrderRec[] inner = new OrderRec[]{ new OrderRec{orderID=97865, custID=43434, total=25}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{97865}, total=new int?[]{25}}
};
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test3();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin4
{
// outer and inner has only one element and the keys do not match
public static int Test4()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=43434}
};
OrderRec[] inner = new OrderRec[]{ new OrderRec{orderID=97865, custID=49434, total=25}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{}, total=new int?[]{}}
};
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test4();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin5
{
// innerKeySelector, outerKeySelector returns null
// Also tests outerKeySelector matches more than one innerKeySelector
public static int Test5()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=null},
new CustomerRec{name="Bob", custID=null}
};
OrderRec[] inner = new OrderRec[]{ new OrderRec{orderID=97865, custID=null, total=25},
new OrderRec{orderID=34390, custID=null, total=19}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{}, total=new int?[]{}},
new JoinRec{name="Bob", orderID=new int?[]{}, total=new int?[]{}}
};
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test5();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin6
{
// innerKeySelector produces same key for more than one element
// and is matched by one of the outerKeySelector.
public static int Test6()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865}
};
OrderRec[] inner = new OrderRec[]{ new OrderRec{orderID=97865, custID=1234, total=25},
new OrderRec{orderID=34390, custID=1234, total=19},
new OrderRec{orderID=34390, custID=9865, total=19}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{97865, 34390}, total=new int?[]{25, 19}},
new JoinRec{name="Bob", orderID=new int?[]{34390}, total=new int?[]{19}}
};
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test6();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin7
{
// outerKeySelector produces same key for more than one element
// and is matched by one of the innerKeySelector.
public static int Test7()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9865}
};
OrderRec[] inner = new OrderRec[]{ new OrderRec{orderID=97865, custID=1234, total=25},
new OrderRec{orderID=34390, custID=9865, total=19}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{97865}, total=new int?[]{25}},
new JoinRec{name="Bob", orderID=new int?[]{34390}, total=new int?[]{19}},
new JoinRec{name="Robert", orderID=new int?[]{34390}, total=new int?[]{19}}
};
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test7();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin8
{
// No match between innerKeySelector and outerKeySelector
public static int Test8()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
OrderRec[] inner = new OrderRec[]{ new OrderRec{orderID=97865, custID=2334, total=25},
new OrderRec{orderID=34390, custID=9065, total=19}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{}, total=new int?[]{}},
new JoinRec{name="Bob", orderID=new int?[]{}, total=new int?[]{}},
new JoinRec{name="Robert", orderID=new int?[]{}, total=new int?[]{}}
};
Func<CustomerRec, IEnumerable<OrderRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.custID, (o) => o.custID, resultSelector);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test8();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class GroupJoin9
{
// Overload-2: Test when IEqualityComparer is null
public static int Test9()
{
CustomerRec[] outer = new CustomerRec[]{ new CustomerRec{name="Tim", custID=1234},
new CustomerRec{name="Bob", custID=9865},
new CustomerRec{name="Robert", custID=9895}
};
AnagramRec[] inner = new AnagramRec[]{ new AnagramRec{name = "Robert", orderID=93483, total = 19},
new AnagramRec{name = "miT", orderID=93489, total = 45}
};
JoinRec[] expected = new JoinRec[]{ new JoinRec{name="Tim", orderID=new int?[]{}, total=new int?[]{}},
new JoinRec{name="Bob", orderID=new int?[]{}, total=new int?[]{}},
new JoinRec{name="Robert", orderID=new int?[]{93483}, total=new int?[]{19}}
};
Func<CustomerRec, IEnumerable<AnagramRec>, JoinRec> resultSelector = Helper.createJoinRec;
var actual = outer.GroupJoin(inner, (e) => e.name, (o) => o.name, resultSelector, null);
return Helper.DataEqual(expected, actual);
}
public static int Main()
{
return Test9();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientHandler_ServerCertificates_Test
{
[Fact]
public async Task NoCallback_ValidCertificate_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { HttpTestServers.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
HttpTestServers.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:HttpTestServers.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagates()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer)));
}
}
[Theory]
[InlineData(HttpTestServers.ExpiredCertRemoteServer)]
[InlineData(HttpTestServers.SelfSignedCertRemoteServer)]
[InlineData(HttpTestServers.WrongHostNameCertRemoteServer)]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[Fact]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.RevokedCertRemoteServer));
}
}
[ActiveIssue(7812, PlatformID.Windows)]
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[InlineData(HttpTestServers.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors)]
[InlineData(HttpTestServers.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors)]
[InlineData(HttpTestServers.WrongHostNameCertRemoteServer, SslPolicyErrors.RemoteCertificateNameMismatch)]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
Assert.Equal(expectedErrors, errors);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_AutomaticClientCerts_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Automatic }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_ManualClientCerts_ThrowsPlatformNotSupportedException()
{
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(new X509Certificate2());
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
private static bool BackendSupportsCustomCertificateHandling =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
(CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
[DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")]
private static extern string CurlSslVersionDescription();
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Spart;
using Spart.Actions;
using Spart.Parsers;
using Spart.Scanners;
using Debugger = Spart.Debug.Debugger;
namespace SIL.WritingSystems.Migration
{
public class IcuRulesParser
{
private XmlWriter _writer;
private Debugger _debugger;
private bool _useDebugger;
// You will notice that the xml tags used don't always match my parser/rule variable name.
// Collation in ldml is based off of icu and is pretty
// much a straight conversion of icu operators into xml tags. Unfortunately, ICU refers to some constructs
// with one name (which I used for my variable names), but ldml uses a different name for the actual
// xml tag.
// http://unicode.org/reports/tr35/#Collation_Elements - LDML collation element spec
// http://icu-project.org/userguide/Collate_Customization.html - ICU collation spec
// http://www.unicode.org/reports/tr10/ - UCA (Unicode Collation Algorithm) spec
public IcuRulesParser() : this(false) {}
public IcuRulesParser(bool useDebugger)
{
_useDebugger = useDebugger;
}
public void WriteIcuRules(XmlWriter writer, string icuRules)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (icuRules == null)
{
throw new ArgumentNullException("icuRules");
}
_writer = writer;
DefineParsingRules();
AssignSemanticActions();
InitializeDataObjects();
StringScanner sc = new StringScanner(icuRules);
try
{
ParserMatch match = _icuRules.Parse(sc);
if (!match.Success || !sc.AtEnd)
{
throw new ApplicationException("Invalid ICU rules.");
}
}
catch (ApplicationException e)
{
throw new ApplicationException("Invalid ICU rules: " + e.Message, e);
}
catch (ParserErrorException e)
{
throw new ApplicationException("Invalid ICU rules: " + e.Message, e);
}
finally
{
ClearDataObjects();
_writer = null;
}
}
public bool ValidateIcuRules(string icuRules, out string message)
{
// I was going to run with no semantic actions and therefore no dom needed,
// but some actions can throw (OnOptionVariableTop for one),
// so we need to run the actions as well for full validation.
_writer = null;
DefineParsingRules();
AssignSemanticActions();
InitializeDataObjects();
StringScanner sc = new StringScanner(icuRules);
ParserMatch match;
try
{
match = _icuRules.Parse(sc);
}
catch (ParserErrorException e)
{
string errString = sc.InputString.Split(new char[] {'\n'})[e.ParserError.Line - 1];
int startingPos = Math.Max((int) e.ParserError.Column - 2, 0);
errString = errString.Substring(startingPos, Math.Min(10, errString.Length - startingPos));
message = String.Format("{0}: '{1}'", e.ParserError.ErrorText, errString);
return false;
}
catch (Exception e)
{
message = e.Message;
return false;
}
finally
{
ClearDataObjects();
}
if (!match.Success || !sc.AtEnd)
{
message = "Invalid ICU rules.";
return false;
}
message = string.Empty;
return true;
}
private Parser _someWhiteSpace;
private Parser _optionalWhiteSpace;
private Parser _escapeSequence;
private Parser _singleQuoteLiteral;
private Parser _quotedStringCharacter;
private Parser _quotedString;
private Parser _normalCharacter;
private Parser _dataCharacter;
private Spart.Parsers.NonTerminal.Rule _dataString;
private Parser _firstOrLast;
private Parser _primarySecondaryTertiary;
private Parser _indirectOption;
private Spart.Parsers.NonTerminal.Rule _indirectPosition;
private Parser _top;
private Spart.Parsers.NonTerminal.Rule _simpleElement;
private Spart.Parsers.NonTerminal.Rule _expansion;
private Spart.Parsers.NonTerminal.Rule _prefix;
private Parser _extendedElement;
private Parser _beforeOption;
private Parser _beforeSpecifier;
private Parser _differenceOperator;
private Spart.Parsers.NonTerminal.Rule _simpleDifference;
private Spart.Parsers.NonTerminal.Rule _extendedDifference;
private Parser _difference;
private Spart.Parsers.NonTerminal.Rule _reset;
private Spart.Parsers.NonTerminal.Rule _oneRule;
private Parser _optionAlternate;
private Parser _optionBackwards;
private Parser _optionNormalization;
private Parser _optionOnOff;
private Parser _optionCaseLevel;
private Parser _optionCaseFirst;
private Parser _optionStrength;
private Parser _optionHiraganaQ;
private Parser _optionNumeric;
private Parser _optionVariableTop;
private Parser _optionSuppressContractions;
private Parser _optionOptimize;
private Parser _characterSet;
private Spart.Parsers.NonTerminal.Rule _option;
private Spart.Parsers.NonTerminal.Rule _icuRules;
private void DefineParsingRules()
{
// someWhiteSpace ::= WS+
// optionalWhiteSpace ::= WS*
_someWhiteSpace = Ops.OneOrMore(Prims.WhiteSpace);
_optionalWhiteSpace = Ops.ZeroOrMore(Prims.WhiteSpace);
// Valid escaping formats (from http://www.icu-project.org/userguide/Collate_Customization.html )
//
// Most of the characters can be used as parts of rules.
// However, whitespace characters will be skipped over,
// and all ASCII characters that are not digits or letters
// are considered to be part of syntax. In order to use
// these characters in rules, they need to be escaped.
// Escaping can be done in several ways:
// * Single characters can be escaped using backslash \ (U+005C).
// * Strings can be escaped by putting them between single quotes 'like this'.
// * Single quote can be quoted using two single quotes ''.
// because Unicode escape sequences are allowed in LDML we need to handle those also,
// escapeSequence ::= '\' U[A-F0-9]{8} | u[A-F0-9]{4} | anyChar
_escapeSequence = Ops.Choice(new Parser[] {
Ops.Sequence('\\', Ops.Sequence('U', Prims.HexDigit, Prims.HexDigit, Prims.HexDigit,
Prims.HexDigit, Prims.HexDigit, Prims.HexDigit, Prims.HexDigit,
Prims.HexDigit)),
Ops.Sequence('\\', Ops.Sequence('u', Prims.HexDigit, Prims.HexDigit, Prims.HexDigit,
Prims.HexDigit)),
Ops.Sequence('\\', Ops.Expect("icu0002", "Invalid escape sequence.", Prims.AnyChar))
});
// singleQuoteLiteral ::= "''"
// quotedStringCharacter ::= AllChars - "'"
// quotedString ::= "'" (singleQuoteLiteral | quotedStringCharacter)+ "'"
_singleQuoteLiteral = Prims.Str("''");
_quotedStringCharacter = Prims.AnyChar - '\'';
_quotedString = Ops.Sequence('\'', Ops.OneOrMore(_singleQuoteLiteral | _quotedStringCharacter),
Ops.Expect("icu0003", "Quoted string without matching end-quote.", '\''));
// Any alphanumeric ASCII character and all characters above the ASCII range are valid data characters
// normalCharacter ::= [A-Za-z0-9] | [U+0080-U+1FFFFF]
// dataCharacter ::= normalCharacter | singleQuoteLiteral | escapeSequence
// dataString ::= (dataCharacter | quotedString) (WS? (dataCharacter | quotedString))*
_normalCharacter = Prims.LetterOrDigit | Prims.Range('\u0080', char.MaxValue);
_dataCharacter = _normalCharacter | _singleQuoteLiteral | _escapeSequence;
_dataString = new Spart.Parsers.NonTerminal.Rule(Ops.List(_dataCharacter | _quotedString, _optionalWhiteSpace));
// firstOrLast ::= 'first' | 'last'
// primarySecondaryTertiary ::= 'primary' | 'secondary' | 'tertiary'
// indirectOption ::= (primarySecondaryTertiary WS 'ignorable') | 'variable' | 'regular' | 'implicit' | 'trailing'
// indirectPosition ::= '[' WS? firstOrLast WS indirectOption WS? ']'
// According to the LDML spec, "implicit" should not be allowed in a reset element, but we're not going to check that
_firstOrLast = Ops.Choice("first", "last");
_primarySecondaryTertiary = Ops.Choice("primary", "secondary", "tertiary");
_indirectOption = Ops.Choice(Ops.Sequence(_primarySecondaryTertiary, _someWhiteSpace, "ignorable"),
"variable", "regular", "implicit", "trailing");
_indirectPosition = new Spart.Parsers.NonTerminal.Rule(Ops.Sequence('[', _optionalWhiteSpace,
Ops.Expect("icu0004", "Invalid indirect position specifier: unknown option",
Ops.Sequence(_firstOrLast, _someWhiteSpace, _indirectOption)), _optionalWhiteSpace,
Ops.Expect("icu0005", "Indirect position specifier missing closing ']'", ']')));
// top ::= '[' WS? 'top' WS? ']'
// [top] is a deprecated element in ICU and should be replaced by indirect positioning.
_top = Ops.Sequence('[', _optionalWhiteSpace, "top", _optionalWhiteSpace, ']');
// simpleElement ::= indirectPosition | dataString
_simpleElement = new Spart.Parsers.NonTerminal.Rule("simpleElement", _indirectPosition | _dataString);
// expansion ::= WS? '/' WS? simpleElement
_expansion = new Spart.Parsers.NonTerminal.Rule("extend", Ops.Sequence(_optionalWhiteSpace, '/', _optionalWhiteSpace,
Ops.Expect("icu0007", "Invalid expansion: Data missing after '/'", _simpleElement)));
// prefix ::= simpleElement WS? '|' WS?
_prefix = new Spart.Parsers.NonTerminal.Rule("context", Ops.Sequence(_simpleElement, _optionalWhiteSpace, '|', _optionalWhiteSpace));
// extendedElement ::= (prefix simpleElement expansion?) | (prefix? simpleElement expansion)
_extendedElement = Ops.Sequence(_prefix, _simpleElement, !_expansion) |
Ops.Sequence(!_prefix, _simpleElement, _expansion);
// beforeOption ::= '1' | '2' | '3'
// beforeSpecifier ::= '[' WS? 'before' WS beforeOption WS? ']'
_beforeOption = Ops.Choice('1', '2', '3');
_beforeSpecifier = Ops.Sequence('[', _optionalWhiteSpace, "before", _someWhiteSpace,
Ops.Expect("icu0010", "Invalid 'before' specifier: Invalid or missing option", _beforeOption), _optionalWhiteSpace,
Ops.Expect("icu0011", "Invalid 'before' specifier: Missing closing ']'", ']'));
// The difference operator initially caused some problems with parsing. The spart library doesn't
// handle situations where the first choice is the beginning of the second choice.
// Ex: differenceOperator = "<" | "<<" | "<<<" | "=" DOES NOT WORK!
// That will fail to parse bothe the << and <<< operators because it always thinks it should match <.
// However, differenceOperator = "<<<" | "<<" | "<" | "=" will work because it tries to match <<< first.
// I'm using this strange production with the option '<' characters because it also works and doesn't
// depend on order. It is less likely for someone to change it and unknowingly mess it up.
// differenceOperator ::= ('<' '<'? '<'?) | '='
_differenceOperator = Ops.Sequence('<', !Prims.Ch('<'), !Prims.Ch('<')) | Prims.Ch('=');
// simpleDifference ::= differenceOperator WS? simpleElement
// extendedDifference ::= differenceOperator WS? extendedElement
// difference ::= simpleDifference | extendedDifference
// NOTE: Due to the implementation of the parser, extendedDifference MUST COME BEFORE simpleDifference in the difference definition
_simpleDifference = new Spart.Parsers.NonTerminal.Rule("simpleDifference", Ops.Sequence(_differenceOperator,
_optionalWhiteSpace, _simpleElement));
_extendedDifference = new Spart.Parsers.NonTerminal.Rule("x", Ops.Sequence(_differenceOperator,
_optionalWhiteSpace, _extendedElement));
_difference = _extendedDifference | _simpleDifference;
// reset ::= '&' WS? ((beforeSpecifier? WS? simpleElement) | top)
_reset = new Spart.Parsers.NonTerminal.Rule("reset", Ops.Sequence('&', _optionalWhiteSpace,
_top | Ops.Sequence(!_beforeSpecifier, _optionalWhiteSpace, _simpleElement)));
// This option is a weird one, as it can come at any place in a rule and sets the preceding
// dataString as the variable top option in the settings element. So, it has to look at the
// data for the preceding element to know its own value, but leaves the preceding and any
// succeeding elements as if the variable top option wasn't there. Go figure.
// Also, it's really probably only valid following a simpleDifference or reset with a dataString
// and not an indirect position, but checking for all that in the grammar would be very convoluted, so
// we'll do it in the semantic action and throw. Yuck.
// optionVariableTop ::= '<' WS? '[' WS? 'variable' WS? 'top' WS? ']'
_optionVariableTop = Ops.Sequence('<', _optionalWhiteSpace, '[', _optionalWhiteSpace, "variable",
_optionalWhiteSpace, "top", _optionalWhiteSpace, ']');
// oneRule ::= reset (WS? (optionVariableTop | difference))*
_oneRule = new Spart.Parsers.NonTerminal.Rule("oneRule", Ops.Sequence(_reset, Ops.ZeroOrMore(Ops.Sequence(_optionalWhiteSpace,
_optionVariableTop | _difference))));
// Option notes:
// * The 'strength' option is specified in ICU as having valid values 1-4 and 'I'. In the LDML spec, it
// seems to indicate that valid values in ICU are 1-5, so I am accepting both and treating 'I' and '5'
// as the same. I'm also accepting 'I' and 'i', although my approach is, in general, to be case-sensitive.
// * The 'numeric' option is not mentioned on the ICU website, but it is implied as being acceptable ICU
// in the LDML spec, so I am supporting it here.
// * There are LDML options 'match-boundaries' and 'match-style' that are not in ICU, so they are not listed here.
// * The UCA spec seems to indicate that there is a 'locale' option which is not mentioned in either the
// LDML or ICU specs, so I am not supporting it here. It could be referring to the 'base' element that
// is an optional part of the 'collation' element in LDML.
// optionOnOff ::= 'on' | 'off'
// optionAlternate ::= 'alternate' WS ('non-ignorable' | 'shifted')
// optionBackwards ::= 'backwards' WS ('1' | '2')
// optionNormalization ::= 'normalization' WS optionOnOff
// optionCaseLevel ::= 'caseLevel' WS optionOnOff
// optionCaseFirst ::= 'caseFirst' WS ('off' | 'upper' | 'lower')
// optionStrength ::= 'strength' WS ('1' | '2' | '3' | '4' | 'I' | 'i' | '5')
// optionHiraganaQ ::= 'hiraganaQ' WS optionOnOff
// optionNumeric ::= 'numeric' WS optionOnOff
// characterSet ::= '[' (AnyChar - ']')* ']'
// optionSuppressContractions ::= 'suppress' WS 'contractions' WS characterSet
// optionOptimize ::= 'optimize' WS characterSet
// option ::= '[' WS? (optionAlternate | optionBackwards | optionNormalization | optionCaseLevel
// | optionCaseFirst | optionStrength | optionHiraganaQ | optionNumeric
// | optionSuppressContractions | optionOptimize) WS? ']'
_optionOnOff = Ops.Choice("on", "off");
_optionAlternate = Ops.Sequence("alternate", _someWhiteSpace, Ops.Choice("non-ignorable", "shifted"));
_optionBackwards = Ops.Sequence("backwards", _someWhiteSpace, Ops.Choice('1', '2'));
_optionNormalization = Ops.Sequence("normalization", _someWhiteSpace, _optionOnOff);
_optionCaseLevel = Ops.Sequence("caseLevel", _someWhiteSpace, _optionOnOff);
_optionCaseFirst = Ops.Sequence("caseFirst", _someWhiteSpace, Ops.Choice("off", "upper", "lower"));
_optionStrength = Ops.Sequence("strength", _someWhiteSpace, Ops.Choice('1', '2', '3', '4', 'I', 'i', '5'));
_optionHiraganaQ = Ops.Sequence("hiraganaQ", _someWhiteSpace, _optionOnOff);
_optionNumeric = Ops.Sequence("numeric", _someWhiteSpace, _optionOnOff);
_characterSet = Ops.Sequence('[', Ops.ZeroOrMore(Prims.AnyChar - ']'), ']');
_optionSuppressContractions = Ops.Sequence("suppress", _someWhiteSpace, "contractions", _someWhiteSpace,
_characterSet);
_optionOptimize = Ops.Sequence("optimize", _someWhiteSpace, _characterSet);
_option = new Spart.Parsers.NonTerminal.Rule("option", Ops.Sequence('[', _optionalWhiteSpace, _optionAlternate |
_optionBackwards | _optionNormalization | _optionCaseLevel | _optionCaseFirst |
_optionStrength | _optionHiraganaQ | _optionNumeric | _optionSuppressContractions |
_optionOptimize, _optionalWhiteSpace, ']'));
// I don't know if ICU requires all options first (it's unclear), but I am. :)
// icuRules ::= WS? (option WS?)* (oneRule WS?)* EOF
_icuRules = new Spart.Parsers.NonTerminal.Rule("icuRules", Ops.Sequence(_optionalWhiteSpace,
Ops.ZeroOrMore(Ops.Sequence(_option, _optionalWhiteSpace)),
Ops.ZeroOrMore(Ops.Sequence(_oneRule, _optionalWhiteSpace)), Ops.Expect("icu0015", "Invalid ICU rules.", Prims.End)));
if (_useDebugger)
{
_debugger = new Spart.Debug.Debugger(Console.Out);
_debugger += _option;
_debugger += _oneRule;
_debugger += _reset;
_debugger += _simpleElement;
_debugger += _simpleDifference;
_debugger += _extendedDifference;
_debugger += _dataString;
}
}
private void AssignSemanticActions()
{
_escapeSequence.Act += OnEscapeSequence;
_singleQuoteLiteral.Act += OnSingleQuoteLiteral;
_quotedStringCharacter.Act += OnDataCharacter;
_normalCharacter.Act += OnDataCharacter;
_dataString.Act += OnDataString;
_firstOrLast.Act += OnIndirectPiece;
_indirectOption.Act += OnIndirectPiece;
_indirectPosition.Act += OnIndirectPosition;
_top.Act += OnTop;
_expansion.Act += OnElementWithData;
_prefix.Act += OnElementWithData;
_differenceOperator.Act += OnDifferenceOperator;
_simpleDifference.Act += OnSimpleDifference;
_extendedDifference.Act += OnExtendedDifference;
_beforeOption.Act += OnBeforeOption;
_reset.Act += OnReset;
_optionAlternate.Act += OnOptionNormal;
_optionBackwards.Act += OnOptionBackwards;
_optionNormalization.Act += OnOptionNormal;
_optionCaseLevel.Act += OnOptionNormal;
_optionCaseFirst.Act += OnOptionNormal;
_optionStrength.Act += OnOptionStrength;
_optionHiraganaQ.Act += OnOptionHiraganaQ;
_optionNumeric.Act += OnOptionNormal;
_optionVariableTop.Act += OnOptionVariableTop;
_characterSet.Act += OnCharacterSet;
_optionSuppressContractions.Act += OnOptionSuppressContractions;
_optionOptimize.Act += OnOptionOptimize;
_icuRules.Act += OnIcuRules;
}
private class IcuDataObject : IComparable<IcuDataObject>
{
private XmlNodeType _nodeType;
private string _name;
private string _value;
private List<IcuDataObject> _children;
private IcuDataObject(XmlNodeType nodeType, string name, string value)
{
_nodeType = nodeType;
_name = name;
_value = value;
if (_nodeType == XmlNodeType.Element)
{
_children = new List<IcuDataObject>();
}
}
public static IcuDataObject CreateAttribute(string name, string value)
{
return new IcuDataObject(XmlNodeType.Attribute, name, value);
}
public static IcuDataObject CreateAttribute(string name)
{
return new IcuDataObject(XmlNodeType.Attribute, name, string.Empty);
}
public static IcuDataObject CreateElement(string name)
{
return new IcuDataObject(XmlNodeType.Element, name, null);
}
public static IcuDataObject CreateText(string text)
{
return new IcuDataObject(XmlNodeType.Text, null, text);
}
public string Name
{
get { return _name; }
}
public string Value
{
set { _value = value; }
}
public string InnerText
{
get
{
if (_nodeType == XmlNodeType.Attribute || _nodeType == XmlNodeType.Text)
{
return _value;
}
StringBuilder sb = new StringBuilder();
foreach (IcuDataObject child in _children)
{
if (child._nodeType == XmlNodeType.Attribute)
{
continue;
}
sb.Append(child.InnerText);
}
return sb.ToString();
}
}
// adds node at end of children
public void AppendChild(IcuDataObject ido)
{
Debug.Assert(_nodeType == XmlNodeType.Element);
Debug.Assert(ido != null);
_children.Add(ido);
}
// inserts child node in correct sort order
public void InsertChild(IcuDataObject ido)
{
Debug.Assert(_nodeType == XmlNodeType.Element);
Debug.Assert(ido != null);
int i;
for (i=0; i < _children.Count; ++i)
{
if (ido.CompareTo(_children[i]) < 0)
{
break;
}
}
_children.Insert(i, ido);
}
public void Write(XmlWriter writer)
{
switch (_nodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(_name);
foreach (IcuDataObject ido in _children)
{
ido.Write(writer);
}
writer.WriteEndElement();
break;
case XmlNodeType.Attribute:
writer.WriteAttributeString(_name, _value);
break;
case XmlNodeType.Text:
LdmlDataMapper.WriteLdmlText(writer, _value);
break;
default:
Debug.Assert(false, "Unhandled Icu Data Object type");
break;
}
}
#region IComparable<IcuDataObject> Members
public int CompareTo(IcuDataObject other)
{
var _nodeTypeStrength = new Dictionary<XmlNodeType, int>
{{XmlNodeType.Attribute, 1}, {XmlNodeType.Element, 2}, {XmlNodeType.Text, 3}};
int result = _nodeTypeStrength[_nodeType].CompareTo(_nodeTypeStrength[other._nodeType]);
if (result != 0)
{
return result;
}
switch (_nodeType)
{
case XmlNodeType.Attribute:
return LdmlNodeComparer.CompareAttributeNames(_name, other._name);
case XmlNodeType.Element:
return LdmlNodeComparer.CompareElementNames(_name, other._name);
}
return 0;
}
#endregion
}
private StringBuilder _currentDataString;
private Stack<IcuDataObject> _currentDataObjects;
private List<IcuDataObject> _currentNodes;
private Stack<string> _currentOperators;
private StringBuilder _currentIndirectPosition;
private Queue<IcuDataObject> _attributesForReset;
private List<IcuDataObject> _optionElements;
private string _currentCharacterSet;
private void InitializeDataObjects()
{
_currentDataString = new StringBuilder();
_currentDataObjects = new Stack<IcuDataObject>();
_currentNodes = new List<IcuDataObject>();
_currentOperators = new Stack<string>();
_currentIndirectPosition = new StringBuilder();
_attributesForReset = new Queue<IcuDataObject>();
_optionElements = new List<IcuDataObject>();
_currentCharacterSet = null;
}
private void ClearDataObjects()
{
_currentDataString = null;
_currentDataObjects = null;
_currentNodes = null;
_currentOperators = null;
_currentIndirectPosition = null;
_attributesForReset = null;
_optionElements = null;
_currentCharacterSet = null;
}
private void AddXmlNodeWithData(string name)
{
IcuDataObject ido = IcuDataObject.CreateElement(name);
ido.AppendChild(_currentDataObjects.Pop());
_currentNodes.Add(ido);
}
private void OnReset(object sender, ActionEventArgs args)
{
IcuDataObject ido = IcuDataObject.CreateElement(((Spart.Parsers.NonTerminal.Rule)sender).ID);
foreach (IcuDataObject attr in _attributesForReset)
{
ido.AppendChild(attr);
}
ido.AppendChild(_currentDataObjects.Pop());
_currentNodes.Add(ido);
_attributesForReset = new Queue<IcuDataObject>();
}
private void OnSimpleDifference(object sender, ActionEventArgs args)
{
AddXmlNodeWithData(_currentOperators.Pop());
}
// The extended element is the trickiest one becuase the operator gets nested in an extended tag, and
// can be preceded by another element as well. Here's a simple rule:
// &a < b => <reset>a</reset><p>b</p>
// And the extended one for comparison:
// &a < b | c / d => <reset>a</reset><x><context>b</context><p>c</p><extend>d</extend></x>
// The operator tag is inserted inside the "x" tag, and comes after the "context" tag (represented by '|')
private void OnExtendedDifference(object sender, ActionEventArgs args)
{
// There should always at least be 2 nodes by this point - reset and either prefix or expansion
Debug.Assert(_currentNodes.Count >= 2);
IcuDataObject differenceNode = IcuDataObject.CreateElement("x");
IcuDataObject dataNode = IcuDataObject.CreateElement(_currentOperators.Pop());
dataNode.AppendChild(_currentDataObjects.Pop());
IcuDataObject prefixNode = _currentNodes[_currentNodes.Count - 2];
IcuDataObject expansionNode = _currentNodes[_currentNodes.Count - 1];
int deleteCount = 0;
if (expansionNode.Name != "extend")
{
prefixNode = expansionNode;
expansionNode = null;
}
if (prefixNode.Name == "context")
{
differenceNode.AppendChild(prefixNode);
deleteCount++;
}
differenceNode.AppendChild(dataNode);
if (expansionNode != null)
{
differenceNode.AppendChild(expansionNode);
deleteCount++;
}
_currentNodes.RemoveRange(_currentNodes.Count - deleteCount, deleteCount);
_currentNodes.Add(differenceNode);
}
private void OnElementWithData(object sender, ActionEventArgs args)
{
Debug.Assert(sender is Spart.Parsers.NonTerminal.Rule);
AddXmlNodeWithData(((Spart.Parsers.NonTerminal.Rule)sender).ID);
}
private void OnDifferenceOperator(object sender, ActionEventArgs args)
{
switch (args.Value)
{
case "<":
_currentOperators.Push("p");
break;
case "<<":
_currentOperators.Push("s");
break;
case "<<<":
_currentOperators.Push("t");
break;
case "=":
_currentOperators.Push("i");
break;
default:
Debug.Assert(false, "Unhandled operator");
break;
}
}
private void AddAttributeForReset(string name, string value)
{
IcuDataObject attr = IcuDataObject.CreateAttribute(name, value);
_attributesForReset.Enqueue(attr);
}
private void OnEscapeSequence(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value[0] == '\\');
if(args.Value.Length == 2)
{
_currentDataString.Append((char) args.Value[1]); //drop the backslash and just insert the escaped character
}
else if (args.Value.Length == 6 || args.Value.Length == 10)//put unicode escapes into text unmolested
{
_currentDataString.Append((string) args.Value);
}
}
private void OnSingleQuoteLiteral(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value == "''");
_currentDataString.Append("\'");
}
private void OnDataCharacter(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value.Length == 1);
_currentDataString.Append((string) args.Value);
}
private void OnDataString(object sender, ActionEventArgs args)
{
_currentDataObjects.Push(IcuDataObject.CreateText(_currentDataString.ToString()));
_currentDataString = new StringBuilder();
}
private void OnIndirectPiece(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value.Length > 0);
if (_currentIndirectPosition.Length > 0)
{
_currentIndirectPosition.Append('_');
}
// due to slight differences between ICU and LDML, regular becomes non_ignorable
_currentIndirectPosition.Append((string) args.Value.Replace("regular", "non_ignorable").Replace(' ', '_'));
}
private void OnIndirectPosition(object sender, ActionEventArgs args)
{
_currentDataObjects.Push(IcuDataObject.CreateElement(_currentIndirectPosition.ToString()));
_currentIndirectPosition = new StringBuilder();
}
private void OnBeforeOption(object sender, ActionEventArgs args)
{
Debug.Assert(args.Value.Length == 1);
Dictionary<string, string> optionMap = new Dictionary<string, string>(3);
optionMap["1"] = "primary";
optionMap["2"] = "secondary";
optionMap["3"] = "tertiary";
Debug.Assert(optionMap.ContainsKey(args.Value));
AddAttributeForReset("before", optionMap[args.Value]);
}
private void OnTop(object sender, ActionEventArgs args)
{
// [top] is deprecated in ICU and not directly allowed in LDML
// [top] is probably best rendered the same as [last regular]
_currentDataObjects.Push(IcuDataObject.CreateElement("last_non_ignorable"));
}
private void OnOptionNormal(object sender, ActionEventArgs args)
{
Regex regex = new Regex("(\\S+)\\s+(\\S+)");
Match match = regex.Match(args.Value);
Debug.Assert(match.Success);
IcuDataObject attr = IcuDataObject.CreateAttribute(match.Groups[1].Value, match.Groups[2].Value);
AddSettingsAttribute(attr);
}
private void OnOptionBackwards(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("backwards");
switch (args.Value[args.Value.Length - 1])
{
case '1':
attr.Value = "off";
break;
case '2':
attr.Value = "on";
break;
default:
Debug.Assert(false, "Unhandled backwards option.");
break;
}
AddSettingsAttribute(attr);
}
private void OnOptionStrength(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("strength");
switch (args.Value[args.Value.Length - 1])
{
case '1':
attr.Value = "primary";
break;
case '2':
attr.Value = "secondary";
break;
case '3':
attr.Value = "tertiary";
break;
case '4':
attr.Value = "quaternary";
break;
case '5':
case 'I':
case 'i':
attr.Value = "identical";
break;
default:
Debug.Assert(false, "Unhandled strength option.");
break;
}
AddSettingsAttribute(attr);
}
private void OnOptionHiraganaQ(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("hiraganaQuaternary");
attr.Value = args.Value.EndsWith("on") ? "on" : "off";
AddSettingsAttribute(attr);
}
private void OnOptionVariableTop(object sender, ActionEventArgs args)
{
IcuDataObject attr = IcuDataObject.CreateAttribute("variableTop");
IcuDataObject previousNode = _currentNodes[_currentNodes.Count - 1];
if (previousNode.Name == "x")
{
throw new ApplicationException("[variable top] cannot follow an extended node (prefix, expasion, or both).");
}
if (previousNode.InnerText.Length == 0)
{
throw new ApplicationException("[variable top] cannot follow an indirect position");
}
string unescapedValue = previousNode.InnerText;
string escapedValue = string.Empty;
for (int i=0; i < unescapedValue.Length; i++)
{
escapedValue += String.Format("u{0:X}", Char.ConvertToUtf32(unescapedValue, i));
// if we had a surogate, that means that two "char"s were encoding one code point,
// so skip the next "char" as it was already handled in this iteration
if (Char.IsSurrogate(unescapedValue, i))
{
i++;
}
}
attr.Value = escapedValue;
AddSettingsAttribute(attr);
}
private void OnCharacterSet(object sender, ActionEventArgs args)
{
Debug.Assert(_currentCharacterSet == null);
_currentCharacterSet = args.Value;
}
private void OnOptionSuppressContractions(object sender, ActionEventArgs args)
{
Debug.Assert(_currentCharacterSet != null);
var element = IcuDataObject.CreateElement("suppress_contractions");
element.AppendChild(IcuDataObject.CreateText(_currentCharacterSet));
_optionElements.Add(element);
_currentCharacterSet = null;
}
private void OnOptionOptimize(object sender, ActionEventArgs args)
{
Debug.Assert(_currentCharacterSet != null);
var element = IcuDataObject.CreateElement("optimize");
element.AppendChild(IcuDataObject.CreateText(_currentCharacterSet));
_optionElements.Add(element);
_currentCharacterSet = null;
}
// Use this to optimize successive difference elements into one element
private void OptimizeNodes()
{
// we can optimize primary, secondary, tertiary, and identity elements
List<string> optimizableElementNames = new List<string>(new string[] { "p", "s", "t", "i" });
List<IcuDataObject> currentOptimizableNodeGroup = null;
List<IcuDataObject> optimizedNodeList = new List<IcuDataObject>();
// first, build a list of lists of nodes we can optimize
foreach (IcuDataObject node in _currentNodes)
{
// Current node can be part of an optimized group if it is an allowed element
// AND it only contains one unicode code point.
bool nodeOptimizable = (optimizableElementNames.Contains(node.Name) &&
(node.InnerText.Length == 1 ||
(node.InnerText.Length == 2 && Char.IsSurrogatePair(node.InnerText, 0))));
// If we have a group of optimizable nodes, but we can't add the current node to that group
if (currentOptimizableNodeGroup != null && (!nodeOptimizable || currentOptimizableNodeGroup[0].Name != node.Name))
{
// optimize the current list and add it, then reset the list
optimizedNodeList.Add(CreateOptimizedNode(currentOptimizableNodeGroup));
currentOptimizableNodeGroup = null;
}
if (!nodeOptimizable)
{
optimizedNodeList.Add(node);
continue;
}
// start a new optimizable group if we're not in one already
if (currentOptimizableNodeGroup == null)
{
currentOptimizableNodeGroup = new List<IcuDataObject>();
}
currentOptimizableNodeGroup.Add(node);
}
// add the last group, if any
if (currentOptimizableNodeGroup != null)
{
optimizedNodeList.Add(CreateOptimizedNode(currentOptimizableNodeGroup));
}
_currentNodes = optimizedNodeList;
}
private IcuDataObject CreateOptimizedNode(List<IcuDataObject> nodeGroup)
{
Debug.Assert(nodeGroup != null);
Debug.Assert(nodeGroup.Count > 0);
// one node is already optimized
if (nodeGroup.Count == 1)
{
return nodeGroup[0];
}
// luckily the optimized names are the same as the unoptimized with 'c' appended
// so <p> becomes <pc>, <s> to <sc>, et al.
IcuDataObject optimizedNode = IcuDataObject.CreateElement(nodeGroup[0].Name + "c");
foreach (IcuDataObject node in nodeGroup)
{
optimizedNode.AppendChild(IcuDataObject.CreateText(node.InnerText));
}
return optimizedNode;
}
private void PreserveNonIcuSettings()
{
//XmlNode oldSettings = _parentNode.SelectSingleNode("settings", _nameSpaceManager);
//if (oldSettings == null)
//{
// return;
//}
//List<string> icuSettings = new List<string>(new string[] {"strength", "alternate", "backwards",
// "normalization", "caseLevel", "caseFirst", "hiraganaQuaternary", "numeric", "variableTop"});
//foreach (XmlAttribute attr in oldSettings.Attributes)
//{
// if (!icuSettings.Contains(attr.Name))
// {
// _optionAttributes.Add(attr.CloneNode(true));
// }
//}
}
private void AddSettingsAttribute(IcuDataObject attr)
{
IcuDataObject settings = null;
foreach (var option in _optionElements)
{
if (option.Name == "settings")
{
settings = option;
break;
}
}
if (settings == null)
{
settings = IcuDataObject.CreateElement("settings");
_optionElements.Insert(0, settings);
}
settings.InsertChild(attr);
}
private void OnIcuRules(object sender, ActionEventArgs args)
{
OptimizeNodes();
if (_writer == null)
{
// we are in validate only mode
return;
}
PreserveNonIcuSettings();
// add any the option elements, if needed.
if (_optionElements.Count > 0)
{
_optionElements.Sort();
_optionElements.ForEach(e => e.Write(_writer));
}
if (_currentNodes.Count == 0)
{
return;
}
_writer.WriteStartElement("rules");
_currentNodes.ForEach(n => n.Write(_writer));
_writer.WriteEndElement();
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Umbraco.Core
{
/// <summary>
/// A set of helper methods for dealing with expressions
/// </summary>
/// <remarks></remarks>
internal static class ExpressionHelper
{
private static readonly ConcurrentDictionary<LambdaExpressionCacheKey, PropertyInfo> PropertyInfoCache = new ConcurrentDictionary<LambdaExpressionCacheKey, PropertyInfo>();
/// <summary>
/// Gets a <see cref="PropertyInfo"/> object from an expression.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="source">The source.</param>
/// <param name="propertyLambda">The property lambda.</param>
/// <returns></returns>
/// <remarks></remarks>
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(this TSource source, Expression<Func<TSource, TProperty>> propertyLambda)
{
return GetPropertyInfo(propertyLambda);
}
/// <summary>
/// Gets a <see cref="PropertyInfo"/> object from an expression.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="propertyLambda">The property lambda.</param>
/// <returns></returns>
/// <remarks></remarks>
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
{
return PropertyInfoCache.GetOrAdd(
new LambdaExpressionCacheKey(propertyLambda),
x =>
{
var type = typeof(TSource);
var member = propertyLambda.Body as MemberExpression;
if (member == null)
{
if (propertyLambda.Body.GetType().Name == "UnaryExpression")
{
// The expression might be for some boxing, e.g. representing a value type like HiveId as an object
// in which case the expression will be Convert(x.MyProperty)
var unary = propertyLambda.Body as UnaryExpression;
if (unary != null)
{
var boxedMember = unary.Operand as MemberExpression;
if (boxedMember == null)
throw new ArgumentException("The type of property could not be infered, try specifying the type parameters explicitly. This can happen if you have tried to access PropertyInfo where the property's return type is a value type, but the expression is trying to convert it to an object");
else member = boxedMember;
}
}
else throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.", propertyLambda));
}
var propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda,
type));
return propInfo;
});
}
public static MemberInfo FindProperty(LambdaExpression lambdaExpression)
{
Expression expressionToCheck = lambdaExpression;
bool done = false;
while (!done)
{
switch (expressionToCheck.NodeType)
{
case ExpressionType.Convert:
expressionToCheck = ((UnaryExpression)expressionToCheck).Operand;
break;
case ExpressionType.Lambda:
expressionToCheck = ((LambdaExpression)expressionToCheck).Body;
break;
case ExpressionType.MemberAccess:
var memberExpression = ((MemberExpression)expressionToCheck);
if (memberExpression.Expression.NodeType != ExpressionType.Parameter &&
memberExpression.Expression.NodeType != ExpressionType.Convert)
{
throw new ArgumentException(string.Format("Expression '{0}' must resolve to top-level member and not any child object's properties. Use a custom resolver on the child type or the AfterMap option instead.", lambdaExpression), "lambdaExpression");
}
MemberInfo member = memberExpression.Member;
return member;
default:
done = true;
break;
}
}
throw new Exception("Configuration for members is only supported for top-level individual members on a type.");
}
public static IDictionary<string, object> GetMethodParams<T1, T2>(Expression<Func<T1, T2>> fromExpression)
{
if (fromExpression == null) return null;
var body = fromExpression.Body as MethodCallExpression;
if (body == null)
return new Dictionary<string, object>();
var rVal = new Dictionary<string, object>();
var parameters = body.Method.GetParameters().Select(x => x.Name).ToArray();
var i = 0;
foreach (var argument in body.Arguments)
{
var lambda = Expression.Lambda(argument, fromExpression.Parameters);
var d = lambda.Compile();
var value = d.DynamicInvoke(new object[1]);
rVal.Add(parameters[i], value);
i++;
}
return rVal;
}
/// <summary>
/// Gets a <see cref="MethodInfo"/> from an <see cref="Expression{Action{T}}"/> provided it refers to a method call.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fromExpression">From expression.</param>
/// <returns>The <see cref="MethodInfo"/> or null if <paramref name="fromExpression"/> is null or cannot be converted to <see cref="MethodCallExpression"/>.</returns>
/// <remarks></remarks>
public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> fromExpression)
{
if (fromExpression == null) return null;
var body = fromExpression.Body as MethodCallExpression;
return body != null ? body.Method : null;
}
/// <summary>
/// Gets the method info.
/// </summary>
/// <typeparam name="TReturn">The return type of the method.</typeparam>
/// <param name="fromExpression">From expression.</param>
/// <returns></returns>
public static MethodInfo GetMethodInfo<TReturn>(Expression<Func<TReturn>> fromExpression)
{
if (fromExpression == null) return null;
var body = fromExpression.Body as MethodCallExpression;
return body != null ? body.Method : null;
}
/// <summary>
/// Gets the method info.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <typeparam name="T2">The type of the 2.</typeparam>
/// <param name="fromExpression">From expression.</param>
/// <returns></returns>
public static MethodInfo GetMethodInfo<T1, T2>(Expression<Func<T1, T2>> fromExpression)
{
if (fromExpression == null) return null;
MethodCallExpression me;
switch (fromExpression.Body.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
var ue = fromExpression.Body as UnaryExpression;
me = ((ue != null) ? ue.Operand : null) as MethodCallExpression;
break;
default:
me = fromExpression.Body as MethodCallExpression;
break;
}
return me != null ? me.Method : null;
}
/// <summary>
/// Gets a <see cref="MethodInfo"/> from an <see cref="Expression"/> provided it refers to a method call.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> or null if <paramref name="expression"/> cannot be converted to <see cref="MethodCallExpression"/>.</returns>
/// <remarks></remarks>
public static MethodInfo GetMethod(Expression expression)
{
if (expression == null) return null;
return IsMethod(expression) ? (((MethodCallExpression)expression).Method) : null;
}
/// <summary>
/// Gets a <see cref="MemberInfo"/> from an <see cref="Expression{Func{T, TReturn}}"/> provided it refers to member access.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TReturn">The type of the return.</typeparam>
/// <param name="fromExpression">From expression.</param>
/// <returns>The <see cref="MemberInfo"/> or null if <paramref name="fromExpression"/> cannot be converted to <see cref="MemberExpression"/>.</returns>
/// <remarks></remarks>
public static MemberInfo GetMemberInfo<T, TReturn>(Expression<Func<T, TReturn>> fromExpression)
{
if (fromExpression == null) return null;
var body = fromExpression.Body as MemberExpression;
return body != null ? body.Member : null;
}
/// <summary>
/// Determines whether the MethodInfo is the same based on signature, not based on the equality operator or HashCode.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>
/// <c>true</c> if [is method signature equal to] [the specified left]; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// This is useful for comparing Expression methods that may contain different generic types
/// </remarks>
public static bool IsMethodSignatureEqualTo(this MethodInfo left, MethodInfo right)
{
if (left.Equals(right))
return true;
if (left.DeclaringType != right.DeclaringType)
return false;
if (left.Name != right.Name)
return false;
var leftParams = left.GetParameters();
var rightParams = right.GetParameters();
if (leftParams.Length != rightParams.Length)
return false;
for (int i = 0; i < leftParams.Length; i++)
{
//if they are delegate parameters, then assume they match as they could be anything
if (typeof(Delegate).IsAssignableFrom(leftParams[i].ParameterType) && typeof(Delegate).IsAssignableFrom(rightParams[i].ParameterType))
continue;
//if they are not delegates, then compare the types
if (leftParams[i].ParameterType != rightParams[i].ParameterType)
return false;
}
if (left.ReturnType != right.ReturnType)
return false;
return true;
}
/// <summary>
/// Gets a <see cref="MemberInfo"/> from an <see cref="Expression"/> provided it refers to member access.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns></returns>
/// <remarks></remarks>
public static MemberInfo GetMember(Expression expression)
{
if (expression == null) return null;
return IsMember(expression) ? (((MemberExpression)expression).Member) : null;
}
/// <summary>
/// Gets a <see cref="MethodInfo"/> from a <see cref="Delegate"/>
/// </summary>
/// <param name="fromMethodGroup">From method group.</param>
/// <returns></returns>
/// <remarks></remarks>
public static MethodInfo GetStaticMethodInfo(Delegate fromMethodGroup)
{
if (fromMethodGroup == null) throw new ArgumentNullException("fromMethodGroup");
return fromMethodGroup.Method;
}
///// <summary>
///// Formats an unhandled item for representing the expression as a string.
///// </summary>
///// <typeparam name="T"></typeparam>
///// <param name="unhandledItem">The unhandled item.</param>
///// <returns></returns>
///// <remarks></remarks>
//public static string FormatUnhandledItem<T>(T unhandledItem) where T : class
//{
// if (unhandledItem == null) throw new ArgumentNullException("unhandledItem");
// var itemAsExpression = unhandledItem as Expression;
// return itemAsExpression != null
// ? FormattingExpressionTreeVisitor.Format(itemAsExpression)
// : unhandledItem.ToString();
//}
/// <summary>
/// Determines whether the specified expression is a method.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns><c>true</c> if the specified expression is method; otherwise, <c>false</c>.</returns>
/// <remarks></remarks>
public static bool IsMethod(Expression expression)
{
return expression != null && typeof(MethodCallExpression).IsAssignableFrom(expression.GetType());
}
/// <summary>
/// Determines whether the specified expression is a member.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns><c>true</c> if the specified expression is member; otherwise, <c>false</c>.</returns>
/// <remarks></remarks>
public static bool IsMember(Expression expression)
{
return expression != null && typeof(MemberExpression).IsAssignableFrom(expression.GetType());
}
/// <summary>
/// Determines whether the specified expression is a constant.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns><c>true</c> if the specified expression is constant; otherwise, <c>false</c>.</returns>
/// <remarks></remarks>
public static bool IsConstant(Expression expression)
{
return expression != null && typeof(ConstantExpression).IsAssignableFrom(expression.GetType());
}
/// <summary>
/// Gets the first value from the supplied arguments of an expression, for those arguments that can be cast to <see cref="ConstantExpression"/>.
/// </summary>
/// <param name="arguments">The arguments.</param>
/// <returns></returns>
/// <remarks></remarks>
public static object GetFirstValueFromArguments(IEnumerable<Expression> arguments)
{
if (arguments == null) return false;
return
arguments.Where(x => typeof(ConstantExpression).IsAssignableFrom(x.GetType())).Cast
<ConstantExpression>().Select(x => x.Value).DefaultIfEmpty(null).FirstOrDefault();
}
}
}
| |
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using GuruComponents.Netrix.ComInterop;
using GuruComponents.Netrix.UserInterface.TypeConverters;
using GuruComponents.Netrix.UserInterface.TypeEditors;
using DisplayNameAttribute=GuruComponents.Netrix.UserInterface.TypeEditors.DisplayNameAttribute;
using TE=GuruComponents.Netrix.UserInterface.TypeEditors;
namespace GuruComponents.Netrix.WebEditing.Elements
{
/// <summary>
/// The FRAMESET element is a frame container for dividing a window into rectangular subspaces called frames.
/// </summary>
/// <remarks>
/// In a Frameset document, the outermost FRAMESET element takes the place of BODY and immediately follows the HEAD.
/// <para>The FRAMESET element contains one or more FRAMESET or FRAME elements, along with an optional NOFRAMES element to provide alternate content for browsers that do not support frames or have frames disabled. A meaningful NOFRAMES element should always be provided and should at the very least contain links to the main frame or frames.</para>
/// </remarks>
public sealed class FrameSetElement : StyledElement
{
[Category("Element Layout")]
[DefaultValueAttribute(typeof(Color), "")]
[DescriptionAttribute("")]
[TypeConverterAttribute(typeof(UITypeConverterColor))]
[EditorAttribute(
typeof(UITypeEditorColor),
typeof(UITypeEditor))]
[DisplayNameAttribute()]
public new Color BorderColor
{
get
{
return base.GetColorAttribute("bordercolor");
}
set
{
base.SetColorAttribute("bordercolor", value);
}
}
[CategoryAttribute("Element Layout")]
[DefaultValueAttribute(true)]
[TypeConverter(typeof(UITypeConverterDropList))]
[DescriptionAttribute("")]
[DisplayName()]
public bool frameBorder
{
set
{
this.SetAttribute ("frameBorder", (value) ? 1 : 0);
return;
}
get
{
return this.GetIntegerAttribute ("frameBorder", 1) == 1;
}
}
/// <summary>
/// The ROWS attribute defines the dimensions of each frame in the set.
/// </summary>
/// <remarks>
/// The attribute takes a comma-separated list of lengths, specified in pixels, as a percentage,
/// or as a relative length. A relative length is expressed as i* where i is an integer.
/// For example, a frameset defined with ROWS="3*,*" (* is equivalent to 1*) will have its
/// first row allotted three times the height of the second row.
/// </remarks>
[CategoryAttribute("Element Layout")]
[DefaultValueAttribute("")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
public string Rows
{
set
{
this.SetStringAttribute ("rows", value, "*,*");
return;
}
get
{
return this.GetStringAttribute ("rows", "*,*");
}
}
/// <summary>
/// The COLS attribute defines the dimensions of each frame in the set.
/// </summary>
/// <remarks>
/// The attribute takes a comma-separated list of lengths, specified in pixels, as a percentage,
/// or as a relative length. A relative length is expressed as i* where i is an integer.
/// For example, a frameset defined with COLS="3*,*" (* is equivalent to 1*) will have its
/// first column allotted three times the height of the second column.
/// </remarks>
[CategoryAttribute("Element Layout")]
[DefaultValueAttribute("")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
public string Cols
{
set
{
this.SetStringAttribute ("cols", value, "*,*");
return;
}
get
{
return this.GetStringAttribute ("cols", "*.*");
}
}
[CategoryAttribute("Element Layout")]
[DefaultValueAttribute(0)]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorInt),
typeof(UITypeEditor))]
[DisplayName()]
public int Border
{
get
{
return this.GetIntegerAttribute ("border", 0);
}
set
{
this.SetIntegerAttribute ("border", value, 0);
return;
}
}
[CategoryAttribute("JavaScript Events")]
[DefaultValueAttribute("")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
[ScriptingVisible()] public string ScriptOnLoad
{
set
{
this.SetStringAttribute ("onLoad", value);
return;
}
get
{
return this.GetStringAttribute ("onLoad");
}
}
[CategoryAttribute("JavaScript Events")]
[DefaultValueAttribute("")]
[DescriptionAttribute("")]
[EditorAttribute(
typeof(UITypeEditorString),
typeof(UITypeEditor))]
[DisplayName()]
[ScriptingVisible()] public string ScriptOnUnLoad
{
set
{
this.SetStringAttribute ("unLoad", value);
return;
}
get
{
return this.GetStringAttribute ("unLoad");
}
}
/// <summary>
/// Creates the specified element.
/// </summary>
/// <remarks>
/// The element is being created and attached to the current document, but nevertheless not visible,
/// until it's being placed anywhere within the DOM. To attach an element it's possible to either
/// use the <see cref="ElementDom"/> property of any other already placed element and refer to this
/// DOM or use the body element (<see cref="HtmlEditor.GetBodyElement"/>) and add the element there. Also, in
/// case of user interactive solutions, it's possible to add an element near the current caret
/// position, using <see cref="HtmlEditor.CreateElementAtCaret(string)"/> method.
/// <para>
/// Note: Invisible elements do neither appear in the DOM nor do they get saved.
/// </para>
/// </remarks>
/// <param name="editor">The editor this element belongs to.</param>
public FrameSetElement(IHtmlEditor editor)
: base("frameset", editor)
{
}
internal FrameSetElement (Interop.IHTMLElement peer, IHtmlEditor editor) : base (peer, editor)
{
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InventoryTransferModule")]
public class InventoryTransferModule : ISharedRegionModule
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = true;
/// <summary>
private List<Scene> m_Scenelist = new List<Scene>();
private IMessageTransferModule m_TransferModule;
#region Region Module interface
public string Name
{
get { return "InventoryModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenelist.Add(scene);
// scene.RegisterModuleInterface<IInventoryTransferModule>(this);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
}
public void Close()
{
}
public void Initialise(IConfigSource config)
{
if (config.Configs["Messaging"] != null)
{
// Allow disabling this module in config
//
if (config.Configs["Messaging"].GetString(
"InventoryTransferModule", "InventoryTransferModule") !=
"InventoryTransferModule")
{
m_Enabled = false;
return;
}
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
if (m_TransferModule == null)
{
m_TransferModule = m_Scenelist[0].RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
m_log.Error("[INVENTORY TRANSFER]: No Message transfer module found, transfers will be local only");
m_Enabled = false;
// m_Scenelist.Clear();
// scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
}
}
}
public void RemoveRegion(Scene scene)
{
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
m_Scenelist.Remove(scene);
}
#endregion Region Module interface
private Scene FindClientScene(UUID agentId)
{
lock (m_Scenelist)
{
foreach (Scene scene in m_Scenelist)
{
ScenePresence presence = scene.GetScenePresence(agentId);
if (presence != null)
return scene;
}
}
return null;
}
/// <summary>
///
/// </summary>
/// <param name="im"></param>
private void OnGridInstantMessage(GridInstantMessage im)
{
// Check if it's a type of message that we should handle
if (!((im.dialog == (byte)InstantMessageDialog.InventoryOffered)
|| (im.dialog == (byte)InstantMessageDialog.InventoryAccepted)
|| (im.dialog == (byte)InstantMessageDialog.InventoryDeclined)
|| (im.dialog == (byte)InstantMessageDialog.TaskInventoryDeclined)))
return;
m_log.DebugFormat(
"[INVENTORY TRANSFER]: {0} IM type received from grid. From={1} ({2}), To={3}",
(InstantMessageDialog)im.dialog, im.fromAgentID, im.fromAgentName, im.toAgentID);
// Check if this is ours to handle
//
Scene scene = FindClientScene(new UUID(im.toAgentID));
if (scene == null)
return;
// Find agent to deliver to
//
ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID));
if (user != null)
{
user.ControllingClient.SendInstantMessage(im);
if (im.dialog == (byte)InstantMessageDialog.InventoryOffered)
{
AssetType assetType = (AssetType)im.binaryBucket[0];
UUID inventoryID = new UUID(im.binaryBucket, 1);
IInventoryService invService = scene.InventoryService;
InventoryNodeBase node = null;
if (AssetType.Folder == assetType)
{
InventoryFolderBase folder = new InventoryFolderBase(inventoryID, new UUID(im.toAgentID));
node = invService.GetFolder(folder);
}
else
{
InventoryItemBase item = new InventoryItemBase(inventoryID, new UUID(im.toAgentID));
node = invService.GetItem(item);
}
if (node != null)
user.ControllingClient.SendBulkUpdateInventory(node);
}
}
}
private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
// m_log.DebugFormat(
// "[INVENTORY TRANSFER]: {0} IM type received from client {1}. From={2} ({3}), To={4}",
// (InstantMessageDialog)im.dialog, client.Name,
// im.fromAgentID, im.fromAgentName, im.toAgentID);
Scene scene = FindClientScene(client.AgentId);
if (scene == null) // Something seriously wrong here.
return;
if (im.dialog == (byte)InstantMessageDialog.InventoryOffered)
{
//m_log.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0]));
if (im.binaryBucket.Length < 17) // Invalid
return;
UUID receipientID = new UUID(im.toAgentID);
ScenePresence user = scene.GetScenePresence(receipientID);
UUID copyID;
// First byte is the asset type
AssetType assetType = (AssetType)im.binaryBucket[0];
if (AssetType.Folder == assetType)
{
UUID folderID = new UUID(im.binaryBucket, 1);
m_log.DebugFormat(
"[INVENTORY TRANSFER]: Inserting original folder {0} into agent {1}'s inventory",
folderID, new UUID(im.toAgentID));
InventoryFolderBase folderCopy
= scene.GiveInventoryFolder(receipientID, client.AgentId, folderID, UUID.Zero);
if (folderCopy == null)
{
client.SendAgentAlertMessage("Can't find folder to give. Nothing given.", false);
return;
}
// The outgoing binary bucket should contain only the byte which signals an asset folder is
// being copied and the following bytes for the copied folder's UUID
copyID = folderCopy.ID;
byte[] copyIDBytes = copyID.GetBytes();
im.binaryBucket = new byte[1 + copyIDBytes.Length];
im.binaryBucket[0] = (byte)AssetType.Folder;
Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length);
if (user != null)
user.ControllingClient.SendBulkUpdateInventory(folderCopy);
// HACK!!
// Insert the ID of the copied folder into the IM so that we know which item to move to trash if it
// is rejected.
// XXX: This is probably a misuse of the session ID slot.
im.imSessionID = copyID.Guid;
}
else
{
// First byte of the array is probably the item type
// Next 16 bytes are the UUID
UUID itemID = new UUID(im.binaryBucket, 1);
m_log.DebugFormat("[INVENTORY TRANSFER]: (giving) Inserting item {0} " +
"into agent {1}'s inventory",
itemID, new UUID(im.toAgentID));
InventoryItemBase itemCopy = scene.GiveInventoryItem(
new UUID(im.toAgentID),
client.AgentId, itemID);
if (itemCopy == null)
{
client.SendAgentAlertMessage("Can't find item to give. Nothing given.", false);
return;
}
copyID = itemCopy.ID;
Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16);
if (user != null)
user.ControllingClient.SendBulkUpdateInventory(itemCopy);
// HACK!!
// Insert the ID of the copied item into the IM so that we know which item to move to trash if it
// is rejected.
// XXX: This is probably a misuse of the session ID slot.
im.imSessionID = copyID.Guid;
}
// Send the IM to the recipient. The item is already
// in their inventory, so it will not be lost if
// they are offline.
//
if (user != null)
{
user.ControllingClient.SendInstantMessage(im);
return;
}
else
{
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success)
{
if (!success)
client.SendAlertMessage("User not online. Inventory has been saved");
});
}
}
else if (im.dialog == (byte)InstantMessageDialog.InventoryAccepted)
{
ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID));
if (user != null) // Local
{
user.ControllingClient.SendInstantMessage(im);
}
else
{
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success)
{
// justincc - FIXME: Comment out for now. This code was added in commit db91044 Mon Aug 22 2011
// and is apparently supposed to fix bulk inventory updates after accepting items. But
// instead it appears to cause two copies of an accepted folder for the receiving user in
// at least some cases. Folder/item update is already done when the offer is made (see code above)
// // Send BulkUpdateInventory
// IInventoryService invService = scene.InventoryService;
// UUID inventoryEntityID = new UUID(im.imSessionID); // The inventory item /folder, back from it's trip
//
// InventoryFolderBase folder = new InventoryFolderBase(inventoryEntityID, client.AgentId);
// folder = invService.GetFolder(folder);
//
// ScenePresence fromUser = scene.GetScenePresence(new UUID(im.fromAgentID));
//
// // If the user has left the scene by the time the message comes back then we can't send
// // them the update.
// if (fromUser != null)
// fromUser.ControllingClient.SendBulkUpdateInventory(folder);
});
}
}
// XXX: This code was placed here to try and accomodate RLV which moves given folders named #RLV/~<name>
// to the requested folder, which in this case is #RLV. However, it is the viewer that appears to be
// response from renaming the #RLV/~example folder to ~example. For some reason this is not yet
// happening, possibly because we are not sending the correct inventory update messages with the correct
// transaction IDs
else if (im.dialog == (byte)InstantMessageDialog.TaskInventoryAccepted)
{
UUID destinationFolderID = UUID.Zero;
if (im.binaryBucket != null && im.binaryBucket.Length >= 16)
{
destinationFolderID = new UUID(im.binaryBucket, 0);
}
if (destinationFolderID != UUID.Zero)
{
InventoryFolderBase destinationFolder = new InventoryFolderBase(destinationFolderID, client.AgentId);
if (destinationFolder == null)
{
m_log.WarnFormat(
"[INVENTORY TRANSFER]: TaskInventoryAccepted message from {0} in {1} specified folder {2} which does not exist",
client.Name, scene.Name, destinationFolderID);
return;
}
IInventoryService invService = scene.InventoryService;
UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip
InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId);
item = invService.GetItem(item);
InventoryFolderBase folder = null;
UUID? previousParentFolderID = null;
if (item != null) // It's an item
{
previousParentFolderID = item.Folder;
item.Folder = destinationFolderID;
invService.DeleteItems(item.Owner, new List<UUID>() { item.ID });
scene.AddInventoryItem(client, item);
}
else
{
folder = new InventoryFolderBase(inventoryID, client.AgentId);
folder = invService.GetFolder(folder);
if (folder != null) // It's a folder
{
previousParentFolderID = folder.ParentID;
folder.ParentID = destinationFolderID;
invService.MoveFolder(folder);
}
}
// Tell client about updates to original parent and new parent (this should probably be factored with existing move item/folder code).
if (previousParentFolderID != null)
{
InventoryFolderBase previousParentFolder
= new InventoryFolderBase((UUID)previousParentFolderID, client.AgentId);
previousParentFolder = invService.GetFolder(previousParentFolder);
scene.SendInventoryUpdate(client, previousParentFolder, true, true);
scene.SendInventoryUpdate(client, destinationFolder, true, true);
}
}
}
else if (
im.dialog == (byte)InstantMessageDialog.InventoryDeclined
|| im.dialog == (byte)InstantMessageDialog.TaskInventoryDeclined)
{
// Here, the recipient is local and we can assume that the
// inventory is loaded. Courtesy of the above bulk update,
// It will have been pushed to the client, too
//
IInventoryService invService = scene.InventoryService;
InventoryFolderBase trashFolder =
invService.GetFolderForType(client.AgentId, AssetType.TrashFolder);
UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip
InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId);
item = invService.GetItem(item);
InventoryFolderBase folder = null;
UUID? previousParentFolderID = null;
if (item != null && trashFolder != null)
{
previousParentFolderID = item.Folder;
item.Folder = trashFolder.ID;
// Diva comment: can't we just update this item???
List<UUID> uuids = new List<UUID>();
uuids.Add(item.ID);
invService.DeleteItems(item.Owner, uuids);
scene.AddInventoryItem(client, item);
}
else
{
folder = new InventoryFolderBase(inventoryID, client.AgentId);
folder = invService.GetFolder(folder);
if (folder != null & trashFolder != null)
{
previousParentFolderID = folder.ParentID;
folder.ParentID = trashFolder.ID;
invService.MoveFolder(folder);
}
}
if ((null == item && null == folder) | null == trashFolder)
{
string reason = String.Empty;
if (trashFolder == null)
reason += " Trash folder not found.";
if (item == null)
reason += " Item not found.";
if (folder == null)
reason += " Folder not found.";
client.SendAgentAlertMessage("Unable to delete " +
"received inventory" + reason, false);
}
// Tell client about updates to original parent and new parent (this should probably be factored with existing move item/folder code).
else if (previousParentFolderID != null)
{
InventoryFolderBase previousParentFolder
= new InventoryFolderBase((UUID)previousParentFolderID, client.AgentId);
previousParentFolder = invService.GetFolder(previousParentFolder);
scene.SendInventoryUpdate(client, previousParentFolder, true, true);
scene.SendInventoryUpdate(client, trashFolder, true, true);
}
if (im.dialog == (byte)InstantMessageDialog.InventoryDeclined)
{
ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID));
if (user != null) // Local
{
user.ControllingClient.SendInstantMessage(im);
}
else
{
if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success) { });
}
}
}
}
private void OnNewClient(IClientAPI client)
{
// Inventory giving is conducted via instant message
client.OnInstantMessage += OnInstantMessage;
}
}
}
| |
//
// Copyright (c) 2004-2021 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.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Text;
#if !NETSTANDARD1_3 && !NETSTANDARD1_5
using System.Transactions;
#endif
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
#if !NETSTANDARD
using System.Configuration;
using ConfigurationManager = System.Configuration.ConfigurationManager;
#endif
/// <summary>
/// Writes log messages to the database using an ADO.NET provider.
/// </summary>
/// <remarks>
/// - NETSTANDARD cannot load connectionstrings from .config
/// </remarks>
/// <seealso href="https://github.com/nlog/nlog/wiki/Database-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <para>
/// The configuration is dependent on the database type, because
/// there are different methods of specifying connection string, SQL
/// command and command parameters.
/// </para>
/// <para>MS SQL Server using System.Data.SqlClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" />
/// <para>Oracle using System.Data.OracleClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" />
/// <para>Oracle using System.Data.OleDBClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" />
/// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para>
/// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" />
/// </example>
[Target("Database")]
[Target("DB")]
public class DatabaseTarget : Target, IInstallable
{
private IDbConnection _activeConnection;
private string _activeConnectionString;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseTarget" /> class.
/// </summary>
public DatabaseTarget()
{
InstallDdlCommands = new List<DatabaseCommandInfo>();
UninstallDdlCommands = new List<DatabaseCommandInfo>();
DBProvider = "sqlserver";
DBHost = ".";
#if !NETSTANDARD
ConnectionStringsSettings = ConfigurationManager.ConnectionStrings;
#endif
CommandType = CommandType.Text;
}
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseTarget" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
public DatabaseTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets the name of the database provider.
/// </summary>
/// <remarks>
/// <para>
/// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are:
/// </para>
/// <ul>
/// <li><c>System.Data.SqlClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li>
/// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="https://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li>
/// <li><c>System.Data.OracleClient</c> - <see href="https://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li>
/// <li><c>Oracle.DataAccess.Client</c> - <see href="https://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li>
/// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li>
/// <li><c>Npgsql</c> - <see href="https://www.npgsql.org/">Npgsql driver for PostgreSQL</see></li>
/// <li><c>MySql.Data.MySqlClient</c> - <see href="https://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li>
/// </ul>
/// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para>
/// <para>
/// Alternatively the parameter value can be be a fully qualified name of the provider
/// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens:
/// </para>
/// <ul>
/// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li>
/// <li><c>oledb</c> - OLEDB Data Provider</li>
/// <li><c>odbc</c> - ODBC Data Provider</li>
/// </ul>
/// </remarks>
/// <docgen category='Connection Options' order='10' />
[RequiredParameter]
[DefaultValue("sqlserver")]
public string DBProvider { get; set; }
#if !NETSTANDARD
/// <summary>
/// Gets or sets the name of the connection string (as specified in <see href="https://msdn.microsoft.com/en-us/library/bf7sd233.aspx"><connectionStrings> configuration section</see>.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public string ConnectionStringName { get; set; }
#endif
/// <summary>
/// Gets or sets the connection string. When provided, it overrides the values
/// specified in DBHost, DBUserName, DBPassword, DBDatabase.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout ConnectionString { get; set; }
/// <summary>
/// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used.
/// </summary>
/// <docgen category='Installation Options' order='10' />
public Layout InstallConnectionString { get; set; }
/// <summary>
/// Gets the installation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "install-command")]
public IList<DatabaseCommandInfo> InstallDdlCommands { get; private set; }
/// <summary>
/// Gets the uninstallation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")]
public IList<DatabaseCommandInfo> UninstallDdlCommands { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to keep the
/// database connection open between the log events.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(false)]
public bool KeepConnection { get; set; }
/// <summary>
/// Gets or sets the database host name. If the ConnectionString is not provided
/// this value will be used to construct the "Server=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBHost { get; set; }
/// <summary>
/// Gets or sets the database user name. If the ConnectionString is not provided
/// this value will be used to construct the "User ID=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBUserName { get; set; }
/// <summary>
/// Gets or sets the database password. If the ConnectionString is not provided
/// this value will be used to construct the "Password=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBPassword
{
get => _dbPassword;
set
{
_dbPassword = value;
if (value is SimpleLayout simpleLayout && simpleLayout.IsFixedText)
_dbPasswordFixed = EscapeValueForConnectionString(simpleLayout.OriginalText);
else
_dbPasswordFixed = null;
}
}
private Layout _dbPassword;
private string _dbPasswordFixed;
/// <summary>
/// Gets or sets the database name. If the ConnectionString is not provided
/// this value will be used to construct the "Database=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBDatabase { get; set; }
/// <summary>
/// Gets or sets the text of the SQL command to be run on each log level.
/// </summary>
/// <remarks>
/// Typically this is a SQL INSERT statement or a stored procedure call.
/// It should use the database-specific parameters (marked as <c>@parameter</c>
/// for SQL server or <c>:parameter</c> for Oracle, other data providers
/// have their own notation) and not the layout renderers,
/// because the latter is prone to SQL injection attacks.
/// The layout renderers should be specified as <parameter /> elements instead.
/// </remarks>
/// <docgen category='SQL Statement' order='10' />
[RequiredParameter]
public Layout CommandText { get; set; }
/// <summary>
/// Gets or sets the type of the SQL command to be run on each log level.
/// </summary>
/// <remarks>
/// This specifies how the command text is interpreted, as "Text" (default) or as "StoredProcedure".
/// When using the value StoredProcedure, the commandText-property would
/// normally be the name of the stored procedure. TableDirect method is not supported in this context.
/// </remarks>
/// <docgen category='SQL Statement' order='11' />
[DefaultValue(CommandType.Text)]
public CommandType CommandType { get; set; }
/// <summary>
/// Gets the collection of parameters. Each item contains a mapping
/// between NLog layout and a database named or positional parameter.
/// </summary>
/// <docgen category='SQL Statement' order='14' />
[ArrayParameter(typeof(DatabaseParameterInfo), "parameter")]
public IList<DatabaseParameterInfo> Parameters { get; } = new List<DatabaseParameterInfo>();
/// <summary>
/// Gets the collection of properties. Each item contains a mapping
/// between NLog layout and a property on the DbConnection instance
/// </summary>
/// <docgen category='Connection Options' order='10' />
[ArrayParameter(typeof(DatabaseObjectPropertyInfo), "connectionproperty")]
public IList<DatabaseObjectPropertyInfo> ConnectionProperties { get; } = new List<DatabaseObjectPropertyInfo>();
/// <summary>
/// Gets the collection of properties. Each item contains a mapping
/// between NLog layout and a property on the DbCommand instance
/// </summary>
/// <docgen category='Connection Options' order='10' />
[ArrayParameter(typeof(DatabaseObjectPropertyInfo), "commandproperty")]
public IList<DatabaseObjectPropertyInfo> CommandProperties { get; } = new List<DatabaseObjectPropertyInfo>();
/// <summary>
/// Configures isolated transaction batch writing. If supported by the database, then it will improve insert performance.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
public System.Data.IsolationLevel? IsolationLevel { get; set; }
#if !NETSTANDARD
internal DbProviderFactory ProviderFactory { get; set; }
// this is so we can mock the connection string without creating sub-processes
internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; }
#endif
internal Type ConnectionType { get; private set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
RunInstallCommands(installationContext, InstallDdlCommands);
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
RunInstallCommands(installationContext, UninstallDdlCommands);
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
return null;
}
internal IDbConnection OpenConnection(string connectionString, LogEventInfo logEventInfo)
{
IDbConnection connection;
#if !NETSTANDARD
if (ProviderFactory != null)
{
connection = ProviderFactory.CreateConnection();
}
else
#endif
{
connection = (IDbConnection)Activator.CreateInstance(ConnectionType);
}
if (connection is null)
{
throw new NLogRuntimeException("Creation of connection failed");
}
connection.ConnectionString = connectionString;
if (ConnectionProperties?.Count > 0)
{
ApplyDatabaseObjectProperties(connection, ConnectionProperties, logEventInfo ?? LogEventInfo.CreateNullEvent());
}
connection.Open();
return connection;
}
private void ApplyDatabaseObjectProperties(object databaseObject, IList<DatabaseObjectPropertyInfo> objectProperties, LogEventInfo logEventInfo)
{
for (int i = 0; i < objectProperties.Count; ++i)
{
var propertyInfo = objectProperties[i];
try
{
var propertyValue = propertyInfo.RenderValue(logEventInfo);
if (!propertyInfo.SetPropertyValue(databaseObject, propertyValue))
{
InternalLogger.Warn("{0}: Failed to lookup property {1} on {2}", this, propertyInfo.Name, databaseObject.GetType());
}
}
catch (Exception ex)
{
InternalLogger.Error(ex, "{0}: Failed to assign value for property {1} on {2}", this, propertyInfo.Name, databaseObject.GetType());
if (LogManager.ThrowExceptions)
throw;
}
}
}
/// <inheritdoc/>
protected override void InitializeTarget()
{
base.InitializeTarget();
bool foundProvider = false;
string providerName = string.Empty;
#if !NETSTANDARD
if (!string.IsNullOrEmpty(ConnectionStringName))
{
// read connection string and provider factory from the configuration file
var cs = ConnectionStringsSettings[ConnectionStringName];
if (cs is null)
{
throw new NLogConfigurationException($"Connection string '{ConnectionStringName}' is not declared in <connectionStrings /> section.");
}
if (!string.IsNullOrEmpty(cs.ConnectionString?.Trim()))
{
ConnectionString = SimpleLayout.Escape(cs.ConnectionString.Trim());
}
providerName = cs.ProviderName?.Trim() ?? string.Empty;
}
#endif
if (ConnectionString != null)
{
providerName = InitConnectionString(providerName);
}
#if !NETSTANDARD
if (string.IsNullOrEmpty(providerName))
{
providerName = GetProviderNameFromDbProviderFactories(providerName);
}
if (!string.IsNullOrEmpty(providerName))
{
foundProvider = InitProviderFactory(providerName);
}
#endif
if (!foundProvider)
{
try
{
SetConnectionType();
if (ConnectionType is null)
{
InternalLogger.Warn("{0}: No ConnectionType created from DBProvider={1}", this, DBProvider);
}
}
catch (Exception ex)
{
InternalLogger.Error(ex, "{0}: Failed to create ConnectionType from DBProvider={1}", this, DBProvider);
throw;
}
}
}
private string InitConnectionString(string providerName)
{
try
{
var connectionString = BuildConnectionString(LogEventInfo.CreateNullEvent());
var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = connectionString };
if (dbConnectionStringBuilder.TryGetValue("provider connection string", out var connectionStringValue))
{
// Special Entity Framework Connection String
if (dbConnectionStringBuilder.TryGetValue("provider", out var providerValue))
{
// Provider was overriden by ConnectionString
providerName = providerValue.ToString()?.Trim() ?? string.Empty;
}
// ConnectionString was overriden by ConnectionString :)
ConnectionString = SimpleLayout.Escape(connectionStringValue.ToString());
}
}
catch (Exception ex)
{
#if !NETSTANDARD
if (!string.IsNullOrEmpty(ConnectionStringName))
InternalLogger.Warn(ex, "{0}: DbConnectionStringBuilder failed to parse '{1}' ConnectionString", this, ConnectionStringName);
else
#endif
InternalLogger.Warn(ex, "{0}: DbConnectionStringBuilder failed to parse ConnectionString", this);
}
return providerName;
}
#if !NETSTANDARD
private bool InitProviderFactory(string providerName)
{
bool foundProvider;
try
{
ProviderFactory = DbProviderFactories.GetFactory(providerName);
foundProvider = true;
}
catch (Exception ex)
{
InternalLogger.Error(ex, "{0}: DbProviderFactories failed to get factory from ProviderName={1}", this, providerName);
throw;
}
return foundProvider;
}
private string GetProviderNameFromDbProviderFactories(string providerName)
{
string dbProvider = DBProvider?.Trim() ?? string.Empty;
if (!string.IsNullOrEmpty(dbProvider))
{
foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
{
var invariantname = (string)row["InvariantName"];
if (string.Equals(invariantname, dbProvider, StringComparison.OrdinalIgnoreCase))
{
providerName = invariantname;
break;
}
}
}
return providerName;
}
#endif
/// <summary>
/// Set the <see cref="ConnectionType"/> to use it for opening connections to the database.
/// </summary>
private void SetConnectionType()
{
switch (DBProvider.ToUpperInvariant())
{
case "SQLSERVER":
case "MSSQL":
case "MICROSOFT":
case "MSDE":
#if NETSTANDARD
{
try
{
var assembly = Assembly.Load(new AssemblyName("Microsoft.Data.SqlClient"));
ConnectionType = assembly.GetType("Microsoft.Data.SqlClient.SqlConnection", true, true);
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "{0}: Failed to load assembly 'Microsoft.Data.SqlClient'. Falling back to 'System.Data.SqlClient'.", this);
var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient"));
ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true);
}
break;
}
case "SYSTEM.DATA.SQLCLIENT":
{
var assembly = Assembly.Load(new AssemblyName("System.Data.SqlClient"));
ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true);
break;
}
#else
case "SYSTEM.DATA.SQLCLIENT":
{
var assembly = typeof(IDbConnection).GetAssembly();
ConnectionType = assembly.GetType("System.Data.SqlClient.SqlConnection", true, true);
break;
}
#endif
case "MICROSOFT.DATA.SQLCLIENT":
{
var assembly = Assembly.Load(new AssemblyName("Microsoft.Data.SqlClient"));
ConnectionType = assembly.GetType("Microsoft.Data.SqlClient.SqlConnection", true, true);
break;
}
#if !NETSTANDARD
case "OLEDB":
{
var assembly = typeof(IDbConnection).GetAssembly();
ConnectionType = assembly.GetType("System.Data.OleDb.OleDbConnection", true, true);
break;
}
#endif
case "ODBC":
case "SYSTEM.DATA.ODBC":
{
#if NETSTANDARD
var assembly = Assembly.Load(new AssemblyName("System.Data.Odbc"));
#else
var assembly = typeof(IDbConnection).GetAssembly();
#endif
ConnectionType = assembly.GetType("System.Data.Odbc.OdbcConnection", true, true);
break;
}
default:
ConnectionType = Type.GetType(DBProvider, true, true);
break;
}
}
/// <inheritdoc/>
protected override void CloseTarget()
{
base.CloseTarget();
InternalLogger.Trace("{0}: Close connection because of CloseTarget", this);
CloseConnection();
}
/// <summary>
/// Writes the specified logging event to the database. It creates
/// a new database command, prepares parameters for it by calculating
/// layouts and executes the command.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
try
{
WriteLogEventSuppressTransactionScope(logEvent, BuildConnectionString(logEvent));
}
finally
{
if (!KeepConnection)
{
InternalLogger.Trace("{0}: Close connection (KeepConnection = false).", this);
CloseConnection();
}
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
var buckets = GroupInBuckets(logEvents);
if (buckets.Count == 1)
{
var firstBucket = System.Linq.Enumerable.First(buckets);
WriteLogEventsToDatabase(firstBucket.Value, firstBucket.Key);
}
else
{
foreach (var bucket in buckets)
WriteLogEventsToDatabase(bucket.Value, bucket.Key);
}
}
private ICollection<KeyValuePair<string, IList<AsyncLogEventInfo>>> GroupInBuckets(IList<AsyncLogEventInfo> logEvents)
{
if (logEvents.Count == 0)
{
#if !NET35 && !NET45
return Array.Empty<KeyValuePair<string, IList<AsyncLogEventInfo>>>();
#else
return new KeyValuePair<string, IList<AsyncLogEventInfo>>[0];
#endif
}
string firstConnectionString = BuildConnectionString(logEvents[0].LogEvent);
IDictionary<string, IList<AsyncLogEventInfo>> dictionary = null;
for (int i = 1; i < logEvents.Count; ++i)
{
var connectionString = BuildConnectionString(logEvents[i].LogEvent);
if (dictionary is null)
{
if (connectionString == firstConnectionString)
continue;
var firstBucket = new List<AsyncLogEventInfo>(i);
for (int j = 0; j < i; ++j)
firstBucket.Add(logEvents[j]);
dictionary = new Dictionary<string, IList<AsyncLogEventInfo>>(StringComparer.Ordinal) { { firstConnectionString, firstBucket } };
}
if (!dictionary.TryGetValue(connectionString, out var bucket))
bucket = dictionary[connectionString] = new List<AsyncLogEventInfo>();
bucket.Add(logEvents[i]);
}
return (ICollection<KeyValuePair<string, IList<AsyncLogEventInfo>>>)dictionary ?? new KeyValuePair<string, IList<AsyncLogEventInfo>>[] { new KeyValuePair<string, IList<AsyncLogEventInfo>>(firstConnectionString, logEvents) };
}
private void WriteLogEventsToDatabase(IList<AsyncLogEventInfo> logEvents, string connectionString)
{
try
{
if (IsolationLevel.HasValue && logEvents.Count > 1)
{
WriteLogEventsWithTransactionScope(logEvents, connectionString);
}
else
{
WriteLogEventsSuppressTransactionScope(logEvents, connectionString);
}
}
finally
{
if (!KeepConnection)
{
InternalLogger.Trace("{0}: Close connection because of KeepConnection=false", this);
CloseConnection();
}
}
}
private void WriteLogEventsSuppressTransactionScope(IList<AsyncLogEventInfo> logEvents, string connectionString)
{
for (int i = 0; i < logEvents.Count; i++)
{
try
{
WriteLogEventSuppressTransactionScope(logEvents[i].LogEvent, connectionString);
logEvents[i].Continuation(null);
}
catch (Exception exception)
{
if (LogManager.ThrowExceptions)
throw;
logEvents[i].Continuation(exception);
}
}
}
private void WriteLogEventsWithTransactionScope(IList<AsyncLogEventInfo> logEvents, string connectionString)
{
try
{
//Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction.
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
EnsureConnectionOpen(connectionString, logEvents.Count > 0 ? logEvents[0].LogEvent : null);
var dbTransaction = _activeConnection.BeginTransaction(IsolationLevel.Value);
try
{
for (int i = 0; i < logEvents.Count; ++i)
{
ExecuteDbCommandWithParameters(logEvents[i].LogEvent, _activeConnection, dbTransaction);
}
dbTransaction?.Commit();
for (int i = 0; i < logEvents.Count; i++)
{
logEvents[i].Continuation(null);
}
dbTransaction?.Dispose(); // Can throw error on dispose, so no using
transactionScope.Complete(); //not really needed as there is no transaction at all.
}
catch
{
try
{
if (dbTransaction?.Connection != null)
{
dbTransaction?.Rollback();
}
dbTransaction?.Dispose();
}
catch (Exception exception)
{
InternalLogger.Error(exception, "{0}: Error during rollback of batch writing {1} logevents to database.", this, logEvents.Count);
if (LogManager.ThrowExceptions)
throw;
}
throw;
}
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "{0}: Error when batch writing {1} logevents to database.", this, logEvents.Count);
if (LogManager.ThrowExceptions)
throw;
InternalLogger.Trace("{0}: Close connection because of error", this);
CloseConnection();
for (int i = 0; i < logEvents.Count; i++)
{
logEvents[i].Continuation(exception);
}
}
}
private void WriteLogEventSuppressTransactionScope(LogEventInfo logEvent, string connectionString)
{
try
{
//Always suppress transaction so that the caller does not rollback logging if they are rolling back their transaction.
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
EnsureConnectionOpen(connectionString, logEvent);
ExecuteDbCommandWithParameters(logEvent, _activeConnection, null);
transactionScope.Complete(); //not really needed as there is no transaction at all.
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "{0}: Error when writing to database.", this);
if (LogManager.ThrowExceptions)
throw;
InternalLogger.Trace("{0}: Close connection because of error", this);
CloseConnection();
throw;
}
}
/// <summary>
/// Write logEvent to database
/// </summary>
private void ExecuteDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, IDbTransaction dbTransaction)
{
using (IDbCommand command = CreateDbCommand(logEvent, dbConnection))
{
if (dbTransaction != null)
command.Transaction = dbTransaction;
int result = command.ExecuteNonQuery();
InternalLogger.Trace("{0}: Finished execution, result = {1}", this, result);
}
}
internal IDbCommand CreateDbCommand(LogEventInfo logEvent, IDbConnection dbConnection)
{
var commandText = RenderLogEvent(CommandText, logEvent);
InternalLogger.Trace("{0}: Executing {1}: {2}", this, CommandType, commandText);
return CreateDbCommandWithParameters(logEvent, dbConnection, CommandType, commandText, Parameters);
}
private IDbCommand CreateDbCommandWithParameters(LogEventInfo logEvent, IDbConnection dbConnection, CommandType commandType, string dbCommandText, IList<DatabaseParameterInfo> databaseParameterInfos)
{
var dbCommand = dbConnection.CreateCommand();
dbCommand.CommandType = commandType;
if (CommandProperties?.Count > 0)
{
ApplyDatabaseObjectProperties(dbCommand, CommandProperties, logEvent);
}
dbCommand.CommandText = dbCommandText;
for (int i = 0; i < databaseParameterInfos.Count; ++i)
{
var parameterInfo = databaseParameterInfos[i];
var dbParameter = CreateDatabaseParameter(dbCommand, parameterInfo);
var dbParameterValue = GetDatabaseParameterValue(logEvent, parameterInfo);
dbParameter.Value = dbParameterValue;
dbCommand.Parameters.Add(dbParameter);
InternalLogger.Trace(" DatabaseTarget: Parameter: '{0}' = '{1}' ({2})", dbParameter.ParameterName, dbParameter.Value, dbParameter.DbType);
}
return dbCommand;
}
/// <summary>
/// Build the connectionstring from the properties.
/// </summary>
/// <remarks>
/// Using <see cref="ConnectionString"/> at first, and falls back to the properties <see cref="DBHost"/>,
/// <see cref="DBUserName"/>, <see cref="DBPassword"/> and <see cref="DBDatabase"/>
/// </remarks>
/// <param name="logEvent">Event to render the layout inside the properties.</param>
/// <returns></returns>
protected string BuildConnectionString(LogEventInfo logEvent)
{
if (ConnectionString != null)
{
return RenderLogEvent(ConnectionString, logEvent);
}
var sb = new StringBuilder();
sb.Append("Server=");
sb.Append(RenderLogEvent(DBHost, logEvent));
sb.Append(";");
var dbUserName = RenderLogEvent(DBUserName, logEvent);
if (string.IsNullOrEmpty(dbUserName))
{
sb.Append("Trusted_Connection=SSPI;");
}
else
{
sb.Append("User id=");
sb.Append(dbUserName);
sb.Append(";Password=");
var password = _dbPasswordFixed ?? EscapeValueForConnectionString(_dbPassword.Render(logEvent));
sb.Append(password);
sb.Append(";");
}
var dbDatabase = RenderLogEvent(DBDatabase, logEvent);
if (!string.IsNullOrEmpty(dbDatabase))
{
sb.Append("Database=");
sb.Append(dbDatabase);
}
return sb.ToString();
}
/// <summary>
/// Escape quotes and semicolons.
/// See https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms722656(v=vs.85)#setting-values-that-use-reserved-characters
/// </summary>
private static string EscapeValueForConnectionString(string value)
{
if (string.IsNullOrEmpty(value))
return value;
const char singleQuote = '\'';
if (value.IndexOf(singleQuote) == 0 && (value.LastIndexOf(singleQuote) == value.Length - 1))
{
// already escaped
return value;
}
const char doubleQuote = '\"';
if (value.IndexOf(doubleQuote) == 0 && (value.LastIndexOf(doubleQuote) == value.Length - 1))
{
// already escaped
return value;
}
var containsSingle = value.IndexOf(singleQuote) >= 0;
var containsDouble = value.IndexOf(doubleQuote) >= 0;
if (containsSingle || containsDouble || value.IndexOf(';') >= 0)
{
if (!containsSingle)
{
return singleQuote + value + singleQuote;
}
if (!containsDouble)
{
return doubleQuote + value + doubleQuote;
}
// both single and double
var escapedValue = value.Replace("\"", "\"\"");
return doubleQuote + escapedValue + doubleQuote;
}
return value;
}
private void EnsureConnectionOpen(string connectionString, LogEventInfo logEventInfo)
{
if (_activeConnection != null && _activeConnectionString != connectionString)
{
InternalLogger.Trace("{0}: Close connection because of opening new.", this);
CloseConnection();
}
if (_activeConnection != null)
{
return;
}
InternalLogger.Trace("{0}: Open connection.", this);
_activeConnection = OpenConnection(connectionString, logEventInfo);
_activeConnectionString = connectionString;
}
private void CloseConnection()
{
try
{
var activeConnection = _activeConnection;
if (activeConnection != null)
{
activeConnection.Close();
activeConnection.Dispose();
}
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "{0}: Error while closing connection.", this);
}
finally
{
_activeConnectionString = null;
_activeConnection = null;
}
}
private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands)
{
// create log event that will be used to render all layouts
LogEventInfo logEvent = installationContext.CreateLogEvent();
try
{
foreach (var commandInfo in commands)
{
var connectionString = GetConnectionStringFromCommand(commandInfo, logEvent);
// Set ConnectionType if it has not been initialized already
if (ConnectionType is null)
{
SetConnectionType();
}
EnsureConnectionOpen(connectionString, logEvent);
string commandText = RenderLogEvent(commandInfo.Text, logEvent);
installationContext.Trace("DatabaseTarget(Name={0}) - Executing {1} '{2}'", Name, commandInfo.CommandType, commandText);
using (IDbCommand command = CreateDbCommandWithParameters(logEvent, _activeConnection, commandInfo.CommandType, commandText, commandInfo.Parameters))
{
try
{
command.ExecuteNonQuery();
}
catch (Exception exception)
{
if (LogManager.ThrowExceptions)
throw;
if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures)
{
installationContext.Warning(exception.Message);
}
else
{
installationContext.Error(exception.Message);
throw;
}
}
}
}
}
finally
{
InternalLogger.Trace("{0}: Close connection after install.", this);
CloseConnection();
}
}
private string GetConnectionStringFromCommand(DatabaseCommandInfo commandInfo, LogEventInfo logEvent)
{
string connectionString;
if (commandInfo.ConnectionString != null)
{
// if there is connection string specified on the command info, use it
connectionString = RenderLogEvent(commandInfo.ConnectionString, logEvent);
}
else if (InstallConnectionString != null)
{
// next, try InstallConnectionString
connectionString = RenderLogEvent(InstallConnectionString, logEvent);
}
else
{
// if it's not defined, fall back to regular connection string
connectionString = BuildConnectionString(logEvent);
}
return connectionString;
}
/// <summary>
/// Create database parameter
/// </summary>
/// <param name="command">Current command.</param>
/// <param name="parameterInfo">Parameter configuration info.</param>
protected virtual IDbDataParameter CreateDatabaseParameter(IDbCommand command, DatabaseParameterInfo parameterInfo)
{
IDbDataParameter dbParameter = command.CreateParameter();
dbParameter.Direction = ParameterDirection.Input;
if (parameterInfo.Name != null)
{
dbParameter.ParameterName = parameterInfo.Name;
}
if (parameterInfo.Size != 0)
{
dbParameter.Size = parameterInfo.Size;
}
if (parameterInfo.Precision != 0)
{
dbParameter.Precision = parameterInfo.Precision;
}
if (parameterInfo.Scale != 0)
{
dbParameter.Scale = parameterInfo.Scale;
}
try
{
if (!parameterInfo.SetDbType(dbParameter))
{
InternalLogger.Warn(" DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType);
}
}
catch (Exception ex)
{
InternalLogger.Error(ex, " DatabaseTarget: Parameter: '{0}' - Failed to assign DbType={1}", parameterInfo.Name, parameterInfo.DbType);
if (LogManager.ThrowExceptions)
throw;
}
return dbParameter;
}
/// <summary>
/// Extract parameter value from the logevent
/// </summary>
/// <param name="logEvent">Current logevent.</param>
/// <param name="parameterInfo">Parameter configuration info.</param>
protected internal virtual object GetDatabaseParameterValue(LogEventInfo logEvent, DatabaseParameterInfo parameterInfo)
{
var value = parameterInfo.RenderValue(logEvent);
if (parameterInfo.AllowDbNull && string.Empty.Equals(value))
return DBNull.Value;
else
return value;
}
#if NETSTANDARD1_3 || NETSTANDARD1_5
/// <summary>
/// Fake transaction
///
/// Transactions aren't in .NET Core: https://github.com/dotnet/corefx/issues/2949
/// </summary>
private sealed class TransactionScope : IDisposable
{
private readonly TransactionScopeOption _suppress;
public TransactionScope(TransactionScopeOption suppress)
{
_suppress = suppress;
}
public void Complete()
{
// Fake scope for compatibility, so nothing to do
}
public void Dispose()
{
// Fake scope for compatibility, so nothing to do
}
}
/// <summary>
/// Fake option
/// </summary>
private enum TransactionScopeOption
{
Required,
RequiresNew,
Suppress,
}
#endif
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.Services.Authenticate.SharePointWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.CodeTools
{
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TextManager.Interop;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.OLE.Interop;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
// The main package class
#region Attributes
[Microsoft.VisualStudio.Shell.DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0")
, Microsoft.VisualStudio.Shell.ProvideLoadKey("Standard", "1.0", "Microsoft.VisualStudio.CodeTools.TaskManager", "Microsoft", 1)
, Microsoft.VisualStudio.Shell.ProvideMenuResource(1000, 1)
, Guid("DA85543E-97EC-4478-90EC-45CBCB4FA5C1")
, ComVisible(true)]
#endregion
internal sealed class TaskManagerPackage : Microsoft.VisualStudio.Shell.Package
, IVsSolutionEvents, IVsUpdateSolutionEvents2
, ITaskManagerFactory, IOleCommandTarget
{
#region ITaskManagerFactory
public ITaskManager CreateTaskManager(string providerName)
{
return new TaskManager(providerName);
}
private IList<TaskManager> sharedTaskManagers;
public ITaskManager QuerySharedTaskManager(string providerName, bool createIfAbsent)
{
foreach (TaskManager taskManager in sharedTaskManagers)
{
string name;
taskManager.GetProviderName(out name);
if (name == providerName)
{
Interlocked.Increment(ref taskManager.sharedCount);
return taskManager;
}
}
if (createIfAbsent)
{
TaskManager taskManager = new TaskManager(providerName);
Interlocked.Increment(ref taskManager.sharedCount);
sharedTaskManagers.Add(taskManager);
return taskManager;
}
else
return null;
}
public void ReleaseSharedTaskManager(ITaskManager itaskManager)
{
if (itaskManager == null) return;
if (!(itaskManager is TaskManager)) return;
TaskManager taskManager = (TaskManager)itaskManager;
if (sharedTaskManagers.Contains(taskManager))
{
Interlocked.Decrement(ref taskManager.sharedCount);
if (taskManager.sharedCount == 0)
{
taskManager.Release();
sharedTaskManagers.Remove(taskManager);
}
}
}
public ITaskManager GetToolTaskManager(string toolName)
{
return tools.GetTaskManager(toolName);
}
#endregion
#region Private fields
private Tools tools;
private RootMenu taskListMenu;
#endregion
#region Construction
private IVsSolution solution;
private uint solutionEventsCookie;
private IVsSolutionBuildManager buildManager;
private uint buildManagerCookie;
private bool allTasksCleanedDuringThisSolutionUpdate;
protected override void Initialize()
{
Common.Trace("Package intialize");
base.Initialize();
Common.Trace("Task manager.Initialize()");
// Initialize common functionality
Common.Initialize(this);
taskListMenu = new RootMenu();
// Initialize fields
tools = new Tools();
sharedTaskManagers = new List<TaskManager>();
// Attach to solution events
solution = GetService(typeof(SVsSolution)) as IVsSolution;
if (solution == null) Common.Log("Could not get solution");
solution.AdviseSolutionEvents(this as IVsSolutionEvents, out solutionEventsCookie);
// Attach to build events
buildManager = GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager;
if (buildManager == null) Common.Log("Could not get build manager");
buildManager.AdviseUpdateSolutionEvents(this, out buildManagerCookie);
// Add a TaskManagerFactory service
ITaskManagerFactory factory = this as ITaskManagerFactory;
(this as System.ComponentModel.Design.IServiceContainer).AddService(typeof(ITaskManagerFactory), factory, true);
// Set PID for msbuild tasks
Environment.SetEnvironmentVariable("VSPID", System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
}
protected override void Dispose(bool disposing)
{
Common.Trace("Package release start");
if (disposing)
{
if (tools != null)
{
tools.Release();
tools = null;
}
if (sharedTaskManagers != null)
{
sharedTaskManagers.Clear();
sharedTaskManagers = null;
}
if (buildManager != null)
{
buildManager.UnadviseUpdateSolutionEvents(buildManagerCookie);
buildManager = null;
}
if (solution != null)
{
solution.UnadviseSolutionEvents(solutionEventsCookie);
solution = null;
}
if (taskListMenu != null)
{
taskListMenu.Release();
taskListMenu = null;
}
Common.Release();
GC.SuppressFinalize(this);
}
base.Dispose(disposing);
Common.Trace("Package release done");
}
#endregion
#region IVsSolutionEvents Members
// We watch solution events to automatically set the host objects
// for newly loaded/opened projects
int IVsSolutionEvents.OnAfterCloseSolution(object pUnkReserved)
{
return 0;
}
int IVsSolutionEvents.OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy)
{
var start = DateTime.Now;
tools.ProjectSetHostObjects(pRealHierarchy);
Debug.WriteLine("OnAfterLoadProject: {0}", ElapsedSince(start));
return 0;
}
int IVsSolutionEvents.OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded)
{
var start = DateTime.Now;
tools.ProjectSetHostObjects(pHierarchy);
Debug.WriteLine("OnAfterOpenProject: {0}", ElapsedSince(start));
/*
object objClsids;
int hr = pHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, out objClsids);
ErrorHandler.ThrowOnFailure(hr);
string clsids = objClsids as String;
clsids = clsids + ";{35A69422-A11A-4ce8-8962-061DFABB02EB}";
hr = pHierarchy.SetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_CfgPropertyPagesCLSIDList, clsids);
ErrorHandler.ThrowOnFailure(hr);
*/
return 0;
}
int IVsSolutionEvents.OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
{
var start = DateTime.Now;
tools.RefreshTasks();
Debug.WriteLine("OnAfterOpenSolution: {0}", ElapsedSince(start));
return 0;
}
int IVsSolutionEvents.OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved)
{
if (allTasksCleanedDuringThisSolutionUpdate) return 0;
var start = DateTime.Now;
tools.ClearTasksOnHierarchy(pHierarchy);
Debug.WriteLine("OnBeforeCloseProject: {0}", ElapsedSince(start));
return 0;
}
int IVsSolutionEvents.OnBeforeCloseSolution(object pUnkReserved)
{
allTasksCleanedDuringThisSolutionUpdate = true;
var start = DateTime.Now;
tools.ClearTasks();
tools.SolutionRelease();
Debug.WriteLine("OnBeforeCloseSolution: {0}", ElapsedSince(start));
return 0;
}
int IVsSolutionEvents.OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy)
{
return 0;
}
int IVsSolutionEvents.OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel)
{
return 0;
}
int IVsSolutionEvents.OnQueryCloseSolution(object pUnkReserved, ref int pfCancel)
{
return 0;
}
int IVsSolutionEvents.OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel)
{
return 0;
}
#endregion
#region IVsUpdateSolutionEvents Members
// We watch build to automatically clear and refresh the tool lists
public int OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy)
{
if (allTasksCleanedDuringThisSolutionUpdate) { return 0; }
allTasksCleanedDuringThisSolutionUpdate = true;
var start = DateTime.Now;
tools.ClearTasks(); // amortize configuration changings for entire solution
tools.SolutionBuildCancelAsync();
Debug.WriteLine("OnActiveProjectCfgChange: {0}", ElapsedSince(start));
return 0;
}
public int UpdateSolution_Begin(ref int pfCancelUpdate)
{
pfCancelUpdate = 0;
allTasksCleanedDuringThisSolutionUpdate = false;
var start = DateTime.Now;
tools.SolutionBuildStart();
Debug.WriteLine("UpdateSolution_Begin: {0}", ElapsedSince(start));
return 0;
}
private string ElapsedSince(DateTime start)
{
var now = DateTime.Now;
return (now - start).Milliseconds.ToString() + "ms";
}
public int UpdateSolution_Cancel()
{
var start = DateTime.Now;
tools.SolutionBuildCancel();
Debug.WriteLine("UpdateSolution_Cancel: {0}", ElapsedSince(start));
return 0;
}
public int UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand)
{
var start = DateTime.Now;
tools.SolutionBuildEnd(fSucceeded > 0 && fCancelCommand == 0);
tools.RefreshTasks();
Debug.WriteLine("UpdateSolution_Done: {0}", ElapsedSince(start));
return 0;
}
public int UpdateSolution_StartUpdate(ref int pfCancelUpdate)
{
return 0;
}
#endregion
#region IOleCommandTarget Members
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (taskListMenu != null)
{
var start = DateTime.Now;
try
{
return taskListMenu.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
finally
{
Debug.WriteLine("Exec: {0}", ElapsedSince(start));
}
}
else
return OLECMDERR.OLECMDERR_E_NOTSUPPORTED;
}
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText)
{
if (taskListMenu != null)
{
var start = DateTime.Now;
try
{
return taskListMenu.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
finally
{
Debug.WriteLine("QueryStatus: {0}", ElapsedSince(start));
}
}
else
return OLECMDERR.OLECMDERR_E_UNKNOWNGROUP;
}
#endregion
public int UpdateProjectCfg_Begin(IVsHierarchy pHierProj, IVsCfg pCfgProj, IVsCfg pCfgSln, uint dwAction, ref int pfCancel)
{
if (allTasksCleanedDuringThisSolutionUpdate) return 0;
var start = DateTime.Now;
bool cleanAll = false;
VSSOLNBUILDUPDATEFLAGS flags = (VSSOLNBUILDUPDATEFLAGS)dwAction;
if ((flags & VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_FORCE_UPDATE) != 0)
{
cleanAll = true;
}
if (cleanAll)
{
allTasksCleanedDuringThisSolutionUpdate = true;
tools.ClearTasks();
}
else
{
tools.ClearTasksOnHierarchy(pHierProj);
}
Debug.WriteLine("UpdateProjectCfg_Begin: {0}", ElapsedSince(start));
return 0;
}
public int UpdateProjectCfg_Done(IVsHierarchy pHierProj, IVsCfg pCfgProj, IVsCfg pCfgSln, uint dwAction, int fSuccess, int fCancel)
{
return 0;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations for operating on Azure SQL Server
/// disaster recovery configurations. Contains operations to: Create,
/// Retrieve, Update, Failover, and Delete.
/// </summary>
internal partial class ServerDisasterRecoveryConfigurationOperations : IServiceOperations<SqlManagementClient>, IServerDisasterRecoveryConfigurationOperations
{
/// <summary>
/// Initializes a new instance of the
/// ServerDisasterRecoveryConfigurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ServerDisasterRecoveryConfigurationOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Begins creating a new or updating an existing Azure SQL Server
/// disaster recovery configuration. To determine the status of the
/// operation call
/// GetServerDisasterRecoveryConfigurationOperationStatus.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='serverDisasterRecoveryConfigurationName'>
/// Required. The name of the Azure SQL Server disaster recovery
/// configuration to be operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// disaster recovery configuration.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql server disaster recovery
/// configuration operation.
/// </returns>
public async Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (serverDisasterRecoveryConfigurationName == null)
{
throw new ArgumentNullException("serverDisasterRecoveryConfigurationName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/disasterRecoveryConfiguration/";
url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue = new JObject();
requestDoc = serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.AutoFailover != null)
{
propertiesValue["autoFailover"] = parameters.Properties.AutoFailover;
}
if (parameters.Properties.FailoverPolicy != null)
{
propertiesValue["failoverPolicy"] = parameters.Properties.FailoverPolicy;
}
if (parameters.Properties.PartnerLogicalServerName != null)
{
propertiesValue["partnerLogicalServerName"] = parameters.Properties.PartnerLogicalServerName;
}
if (parameters.Properties.PartnerServerId != null)
{
propertiesValue["partnerServerId"] = parameters.Properties.PartnerServerId;
}
if (parameters.Properties.Role != null)
{
propertiesValue["role"] = parameters.Properties.Role;
}
if (parameters.Properties.Type != null)
{
propertiesValue["type"] = parameters.Properties.Type;
}
if (parameters.Location != null)
{
serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue["location"] = parameters.Location;
}
if (parameters.Tags != null)
{
JObject tagsDictionary = new JObject();
foreach (KeyValuePair<string, string> pair in parameters.Tags)
{
string tagsKey = pair.Key;
string tagsValue = pair.Value;
tagsDictionary[tagsKey] = tagsValue;
}
serverDisasterRecoveryConfigurationCreateOrUpdateParametersValue["tags"] = tagsDictionary;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerDisasterRecoveryConfigurationCreateOrUpdateResponse result = null;
// Deserialize Response
result = new ServerDisasterRecoveryConfigurationCreateOrUpdateResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("Location"))
{
result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault();
}
if (httpResponse.Headers.Contains("Retry-After"))
{
result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture);
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Creates a new or updates an existing Azure SQL Server disaster
/// recovery configuration.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Database Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='serverDisasterRecoveryConfigurationName'>
/// Required. The name of the Azure SQL Server disaster recovery
/// configuration to be operated on (Updated or created).
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for creating or updating a Server
/// disaster recovery configuration.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql server disaster recovery
/// configuration operation.
/// </returns>
public async Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, ServerDisasterRecoveryConfigurationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
SqlManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ServerDisasterRecoveryConfigurationCreateOrUpdateResponse response = await client.ServerDisasterRecoveryConfigurations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, serverDisasterRecoveryConfigurationName, parameters, cancellationToken).ConfigureAwait(false);
if (response.Status == OperationStatus.Succeeded)
{
return response;
}
cancellationToken.ThrowIfCancellationRequested();
ServerDisasterRecoveryConfigurationCreateOrUpdateResponse result = await client.ServerDisasterRecoveryConfigurations.GetServerDisasterRecoveryConfigurationOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
int delayInSeconds = response.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 30;
}
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == OperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.ServerDisasterRecoveryConfigurations.GetServerDisasterRecoveryConfigurationOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false);
delayInSeconds = result.RetryAfter;
if (delayInSeconds == 0)
{
delayInSeconds = 15;
}
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Deletes the Azure SQL server disaster recovery configuration with
/// the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='serverDisasterRecoveryConfigurationName'>
/// Required. The name of the Azure SQL server disaster recovery
/// configuration to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (serverDisasterRecoveryConfigurationName == null)
{
throw new ArgumentNullException("serverDisasterRecoveryConfigurationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/disasterRecoveryConfiguration/";
url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Begins failover for the Azure SQL server disaster recovery
/// configuration with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='serverDisasterRecoveryConfigurationName'>
/// Required. The name of the Azure SQL server disaster recovery
/// configuration to start failover.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> FailoverAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (serverDisasterRecoveryConfigurationName == null)
{
throw new ArgumentNullException("serverDisasterRecoveryConfigurationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName);
TracingAdapter.Enter(invocationId, this, "FailoverAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/disasterRecoveryConfiguration/";
url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName);
url = url + "/failover";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Begins failover for the Azure SQL server disaster recovery
/// configuration with the given name.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='serverDisasterRecoveryConfigurationName'>
/// Required. The name of the Azure SQL server disaster recovery
/// configuration to start failover.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> FailoverAllowDataLossAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (serverDisasterRecoveryConfigurationName == null)
{
throw new ArgumentNullException("serverDisasterRecoveryConfigurationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName);
TracingAdapter.Enter(invocationId, this, "FailoverAllowDataLossAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/disasterRecoveryConfiguration/";
url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName);
url = url + "/forceFailoverAllowDataLoss";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about an Azure SQL Server disaster recovery
/// configurations.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='serverDisasterRecoveryConfigurationName'>
/// Required. The name of the Azure SQL server disaster recovery
/// configuration to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get server disaster recovery
/// configuration request.
/// </returns>
public async Task<ServerDisasterRecoveryConfigurationGetResponse> GetAsync(string resourceGroupName, string serverName, string serverDisasterRecoveryConfigurationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (serverDisasterRecoveryConfigurationName == null)
{
throw new ArgumentNullException("serverDisasterRecoveryConfigurationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("serverDisasterRecoveryConfigurationName", serverDisasterRecoveryConfigurationName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/disasterRecoveryConfiguration/";
url = url + Uri.EscapeDataString(serverDisasterRecoveryConfigurationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerDisasterRecoveryConfigurationGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerDisasterRecoveryConfigurationGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ServerDisasterRecoveryConfiguration serverDisasterRecoveryConfigurationInstance = new ServerDisasterRecoveryConfiguration();
result.ServerDisasterRecoveryConfiguration = serverDisasterRecoveryConfigurationInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerDisasterRecoveryConfigurationProperties propertiesInstance = new ServerDisasterRecoveryConfigurationProperties();
serverDisasterRecoveryConfigurationInstance.Properties = propertiesInstance;
JToken autoFailoverValue = propertiesValue["autoFailover"];
if (autoFailoverValue != null && autoFailoverValue.Type != JTokenType.Null)
{
string autoFailoverInstance = ((string)autoFailoverValue);
propertiesInstance.AutoFailover = autoFailoverInstance;
}
JToken failoverPolicyValue = propertiesValue["failoverPolicy"];
if (failoverPolicyValue != null && failoverPolicyValue.Type != JTokenType.Null)
{
string failoverPolicyInstance = ((string)failoverPolicyValue);
propertiesInstance.FailoverPolicy = failoverPolicyInstance;
}
JToken partnerLogicalServerNameValue = propertiesValue["partnerLogicalServerName"];
if (partnerLogicalServerNameValue != null && partnerLogicalServerNameValue.Type != JTokenType.Null)
{
string partnerLogicalServerNameInstance = ((string)partnerLogicalServerNameValue);
propertiesInstance.PartnerLogicalServerName = partnerLogicalServerNameInstance;
}
JToken partnerServerIdValue = propertiesValue["partnerServerId"];
if (partnerServerIdValue != null && partnerServerIdValue.Type != JTokenType.Null)
{
string partnerServerIdInstance = ((string)partnerServerIdValue);
propertiesInstance.PartnerServerId = partnerServerIdInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken typeValue = propertiesValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
propertiesInstance.Type = typeInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverDisasterRecoveryConfigurationInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverDisasterRecoveryConfigurationInstance.Name = nameInstance;
}
JToken typeValue2 = responseDoc["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
serverDisasterRecoveryConfigurationInstance.Type = typeInstance2;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverDisasterRecoveryConfigurationInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverDisasterRecoveryConfigurationInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets the status of an Azure Sql Server disaster recovery
/// configuration create or update operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for long running Azure Sql server disaster recovery
/// configuration operation.
/// </returns>
public async Task<ServerDisasterRecoveryConfigurationCreateOrUpdateResponse> GetServerDisasterRecoveryConfigurationOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
TracingAdapter.Enter(invocationId, this, "GetServerDisasterRecoveryConfigurationOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + operationStatusLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerDisasterRecoveryConfigurationCreateOrUpdateResponse result = null;
// Deserialize Response
result = new ServerDisasterRecoveryConfigurationCreateOrUpdateResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Created)
{
result.Status = OperationStatus.Succeeded;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Returns information about Azure SQL Server disaster recovery
/// configurations.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the Azure SQL
/// Server belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Server.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a List Azure Sql Server disaster
/// recovery configuration request.
/// </returns>
public async Task<ServerDisasterRecoveryConfigurationListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/disasterRecoveryConfiguration";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServerDisasterRecoveryConfigurationListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerDisasterRecoveryConfigurationListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ServerDisasterRecoveryConfiguration serverDisasterRecoveryConfigurationInstance = new ServerDisasterRecoveryConfiguration();
result.ServerDisasterRecoveryConfigurations.Add(serverDisasterRecoveryConfigurationInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerDisasterRecoveryConfigurationProperties propertiesInstance = new ServerDisasterRecoveryConfigurationProperties();
serverDisasterRecoveryConfigurationInstance.Properties = propertiesInstance;
JToken autoFailoverValue = propertiesValue["autoFailover"];
if (autoFailoverValue != null && autoFailoverValue.Type != JTokenType.Null)
{
string autoFailoverInstance = ((string)autoFailoverValue);
propertiesInstance.AutoFailover = autoFailoverInstance;
}
JToken failoverPolicyValue = propertiesValue["failoverPolicy"];
if (failoverPolicyValue != null && failoverPolicyValue.Type != JTokenType.Null)
{
string failoverPolicyInstance = ((string)failoverPolicyValue);
propertiesInstance.FailoverPolicy = failoverPolicyInstance;
}
JToken partnerLogicalServerNameValue = propertiesValue["partnerLogicalServerName"];
if (partnerLogicalServerNameValue != null && partnerLogicalServerNameValue.Type != JTokenType.Null)
{
string partnerLogicalServerNameInstance = ((string)partnerLogicalServerNameValue);
propertiesInstance.PartnerLogicalServerName = partnerLogicalServerNameInstance;
}
JToken partnerServerIdValue = propertiesValue["partnerServerId"];
if (partnerServerIdValue != null && partnerServerIdValue.Type != JTokenType.Null)
{
string partnerServerIdInstance = ((string)partnerServerIdValue);
propertiesInstance.PartnerServerId = partnerServerIdInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
JToken typeValue = propertiesValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
propertiesInstance.Type = typeInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
serverDisasterRecoveryConfigurationInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
serverDisasterRecoveryConfigurationInstance.Name = nameInstance;
}
JToken typeValue2 = valueValue["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
serverDisasterRecoveryConfigurationInstance.Type = typeInstance2;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
serverDisasterRecoveryConfigurationInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
serverDisasterRecoveryConfigurationInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// Implementation of CallContext ... currently leverages off
// the LocalDataStore facility.
namespace System.Runtime.Remoting.Messaging{
using System.Threading;
using System.Runtime.Remoting;
using System.Security.Principal;
using System.Collections;
using System.Runtime.Serialization;
using System.Security.Permissions;
// This class exposes the API for the users of call context. All methods
// in CallContext are static and operate upon the call context in the Thread.
// NOTE: CallContext is a specialized form of something that behaves like
// TLS for method calls. However, since the call objects may get serialized
// and deserialized along the path, it is tough to guarantee identity
// preservation.
// The LogicalCallContext class has all the actual functionality. We have
// to use this scheme because Remoting message sinks etc do need to have
// the distinction between the call context on the physical thread and
// the call context that the remoting message actually carries. In most cases
// they will operate on the message's call context and hence the latter
// exposes the same set of methods as instance methods.
// Only statics does not need to marked with the serializable attribute
[System.Security.SecurityCritical] // auto-generated_required
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class CallContext
{
private CallContext()
{
}
#if MONO
internal static object SetCurrentCallContext (LogicalCallContext ctx)
{
return null;
}
#endif
// Sets the given logical call context object on the thread.
// Returns the previous one.
internal static LogicalCallContext SetLogicalCallContext(
LogicalCallContext callCtx)
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
LogicalCallContext prev = ec.LogicalCallContext;
ec.LogicalCallContext = callCtx;
return prev;
}
/*=========================================================================
** Frees a named data slot.
=========================================================================*/
[System.Security.SecurityCritical] // auto-generated
public static void FreeNamedDataSlot(String name)
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
ec.LogicalCallContext.FreeNamedDataSlot(name);
ec.IllogicalCallContext.FreeNamedDataSlot(name);
}
/*=========================================================================
** Get data on the logical call context
=========================================================================*/
[System.Security.SecurityCritical] // auto-generated
public static Object LogicalGetData(String name)
{
return Thread.CurrentThread.GetExecutionContextReader().LogicalCallContext.GetData(name);
}
/*=========================================================================
** Get data on the illogical call context
=========================================================================*/
private static Object IllogicalGetData(String name)
{
return Thread.CurrentThread.GetExecutionContextReader().IllogicalCallContext.GetData(name);
}
internal static IPrincipal Principal
{
[System.Security.SecurityCritical] // auto-generated
get
{
return Thread.CurrentThread.GetExecutionContextReader().LogicalCallContext.Principal;
}
[System.Security.SecurityCritical] // auto-generated
set
{
Thread.CurrentThread.
GetMutableExecutionContext().LogicalCallContext.Principal = value;
}
}
public static Object HostContext
{
[System.Security.SecurityCritical] // auto-generated
get
{
ExecutionContext.Reader ec = Thread.CurrentThread.GetExecutionContextReader();
Object hC = ec.IllogicalCallContext.HostContext;
if (hC == null)
hC = ec.LogicalCallContext.HostContext;
return hC;
}
[System.Security.SecurityCritical] // auto-generated_required
set
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
if (value is ILogicalThreadAffinative)
{
ec.IllogicalCallContext.HostContext = null;
ec.LogicalCallContext.HostContext = value;
}
else
{
ec.IllogicalCallContext.HostContext = value;
ec.LogicalCallContext.HostContext = null;
}
}
}
// <STRIP>For callContexts we intend to expose only name, value dictionary
// type of behavior for now. We will re-consider if we need to expose
// the other functions above for Beta-2.</STRIP>
[System.Security.SecurityCritical] // auto-generated
public static Object GetData(String name)
{
Object o = LogicalGetData(name);
if (o == null)
{
return IllogicalGetData(name);
}
else
{
return o;
}
}
[System.Security.SecurityCritical] // auto-generated
public static void SetData(String name, Object data)
{
if (data is ILogicalThreadAffinative)
{
LogicalSetData(name, data);
}
else
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
ec.LogicalCallContext.FreeNamedDataSlot(name);
ec.IllogicalCallContext.SetData(name, data);
}
}
[System.Security.SecurityCritical] // auto-generated
public static void LogicalSetData(String name, Object data)
{
ExecutionContext ec = Thread.CurrentThread.GetMutableExecutionContext();
ec.IllogicalCallContext.FreeNamedDataSlot(name);
ec.LogicalCallContext.SetData(name, data);
}
[System.Security.SecurityCritical] // auto-generated
public static Header[] GetHeaders()
{
// Header is mutable, so we need to get these from a mutable ExecutionContext
LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
return lcc.InternalGetHeaders();
} // GetHeaders
[System.Security.SecurityCritical] // auto-generated
public static void SetHeaders(Header[] headers)
{
LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
lcc.InternalSetHeaders(headers);
} // SetHeaders
} // class CallContext
[System.Runtime.InteropServices.ComVisible(true)]
public interface ILogicalThreadAffinative
{
}
internal class IllogicalCallContext
{
private Hashtable m_Datastore;
private Object m_HostContext;
internal struct Reader
{
IllogicalCallContext m_ctx;
public Reader(IllogicalCallContext ctx) { m_ctx = ctx; }
public bool IsNull { get { return m_ctx == null; } }
[System.Security.SecurityCritical]
public Object GetData(String name) { return IsNull ? null : m_ctx.GetData(name); }
public Object HostContext { get { return IsNull ? null : m_ctx.HostContext; } }
}
private Hashtable Datastore
{
get
{
if (null == m_Datastore)
{
// The local store has not yet been created for this thread.
m_Datastore = new Hashtable();
}
return m_Datastore;
}
}
internal Object HostContext
{
get
{
return m_HostContext;
}
set
{
m_HostContext = value;
}
}
internal bool HasUserData
{
get { return ((m_Datastore != null) && (m_Datastore.Count > 0));}
}
/*=========================================================================
** Frees a named data slot.
=========================================================================*/
public void FreeNamedDataSlot(String name)
{
Datastore.Remove(name);
}
public Object GetData(String name)
{
return Datastore[name];
}
public void SetData(String name, Object data)
{
Datastore[name] = data;
}
public IllogicalCallContext CreateCopy()
{
IllogicalCallContext ilcc = new IllogicalCallContext();
ilcc.HostContext = this.HostContext;
if (HasUserData)
{
IDictionaryEnumerator de = this.m_Datastore.GetEnumerator();
while (de.MoveNext())
{
ilcc.Datastore[(String)de.Key] = de.Value;
}
}
return ilcc;
}
}
// This class handles the actual call context functionality. It leverages on the
// implementation of local data store ... except that the local store manager is
// not static. That is to say, allocating a slot in one call context has no effect
// on another call contexts. Different call contexts are entirely unrelated.
[System.Security.SecurityCritical] // auto-generated_required
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class LogicalCallContext : ISerializable, ICloneable
{
// Private static data
private static Type s_callContextType = typeof(LogicalCallContext);
private const string s_CorrelationMgrSlotName = "System.Diagnostics.Trace.CorrelationManagerSlot";
/*=========================================================================
** Data accessed from managed code that needs to be defined in
** LogicalCallContextObject to maintain alignment between the two classes.
** DON'T CHANGE THESE UNLESS YOU MODIFY LogicalContextObject in vm\object.h
=========================================================================*/
// Private member data
private Hashtable m_Datastore;
private CallContextRemotingData m_RemotingData = null;
private CallContextSecurityData m_SecurityData = null;
private Object m_HostContext = null;
private bool m_IsCorrelationMgr = false;
// _sendHeaders is for Headers that should be sent out on the next call.
// _recvHeaders are for Headers that came from a response.
private Header[] _sendHeaders = null;
private Header[] _recvHeaders = null;
internal LogicalCallContext()
{
}
internal struct Reader
{
LogicalCallContext m_ctx;
public Reader(LogicalCallContext ctx) { m_ctx = ctx; }
public bool IsNull { get { return m_ctx == null; } }
public bool HasInfo { get { return IsNull ? false : m_ctx.HasInfo; } }
public LogicalCallContext Clone() { return (LogicalCallContext)m_ctx.Clone(); }
public IPrincipal Principal { get { return IsNull ? null : m_ctx.Principal; } }
[System.Security.SecurityCritical]
public Object GetData(String name) { return IsNull ? null : m_ctx.GetData(name); }
public Object HostContext { get { return IsNull ? null : m_ctx.HostContext; } }
}
[System.Security.SecurityCritical] // auto-generated
internal LogicalCallContext(SerializationInfo info, StreamingContext context)
{
SerializationInfoEnumerator e = info.GetEnumerator();
while (e.MoveNext())
{
if (e.Name.Equals("__RemotingData"))
{
m_RemotingData = (CallContextRemotingData) e.Value;
}
else if (e.Name.Equals("__SecurityData"))
{
if (context.State == StreamingContextStates.CrossAppDomain)
{
m_SecurityData = (CallContextSecurityData) e.Value;
}
else
{
BCLDebug.Assert(false, "Security data should only be serialized in cross appdomain case.");
}
}
else if (e.Name.Equals("__HostContext"))
{
m_HostContext = e.Value;
}
else if (e.Name.Equals("__CorrelationMgrSlotPresent"))
{
m_IsCorrelationMgr = (bool)e.Value;
}
else
{
Datastore[e.Name] = e.Value;
}
}
}
[System.Security.SecurityCritical] // auto-generated_required
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
info.SetType(s_callContextType);
if (m_RemotingData != null)
{
info.AddValue("__RemotingData", m_RemotingData);
}
if (m_SecurityData != null)
{
if (context.State == StreamingContextStates.CrossAppDomain)
{
info.AddValue("__SecurityData", m_SecurityData);
}
}
if (m_HostContext != null)
{
info.AddValue("__HostContext", m_HostContext);
}
if (m_IsCorrelationMgr)
{
info.AddValue("__CorrelationMgrSlotPresent", m_IsCorrelationMgr);
}
if (HasUserData)
{
IDictionaryEnumerator de = m_Datastore.GetEnumerator();
while (de.MoveNext())
{
info.AddValue((String)de.Key, de.Value);
}
}
}
// ICloneable::Clone
// Used to create a deep copy of the call context when an async
// call starts.
// <
[System.Security.SecuritySafeCritical] // overrides public transparent member
public Object Clone()
{
LogicalCallContext lc = new LogicalCallContext();
if (m_RemotingData != null)
lc.m_RemotingData = (CallContextRemotingData)m_RemotingData.Clone();
if (m_SecurityData != null)
lc.m_SecurityData = (CallContextSecurityData)m_SecurityData.Clone();
if (m_HostContext != null)
lc.m_HostContext = m_HostContext;
lc.m_IsCorrelationMgr = m_IsCorrelationMgr;
if (HasUserData)
{
IDictionaryEnumerator de = m_Datastore.GetEnumerator();
if (!m_IsCorrelationMgr)
{
while (de.MoveNext())
{
lc.Datastore[(String)de.Key] = de.Value;
}
}
else
{
while (de.MoveNext())
{
String key = (String)de.Key;
// Deep clone "System.Diagnostics.Trace.CorrelationManagerSlot"
if (key.Equals(s_CorrelationMgrSlotName))
{
lc.Datastore[key] = ((ICloneable)de.Value).Clone();
}
else
lc.Datastore[key] = de.Value;
}
}
}
return lc;
}
// Used to do a (limited) merge the call context from a returning async call
[System.Security.SecurityCritical] // auto-generated
internal void Merge(LogicalCallContext lc)
{
// we ignore the RemotingData & SecurityData
// and only merge the user sections of the two call contexts
// the idea being that if the original call had any
// identity/remoting callID that should remain unchanged
// If we have a non-null callContext and it is not the same
// as the one on the current thread (can happen in x-context async)
// and there is any userData in the callContext, do the merge
if ((lc != null) && (this != lc) && lc.HasUserData)
{
IDictionaryEnumerator de = lc.Datastore.GetEnumerator();
while (de.MoveNext())
{
Datastore[(String)de.Key] = de.Value;
}
}
}
public bool HasInfo
{
[System.Security.SecurityCritical] // auto-generated
get
{
bool fInfo = false;
// Set the flag to true if there is either remoting data, or
// security data or user data
if(
(m_RemotingData != null && m_RemotingData.HasInfo) ||
(m_SecurityData != null && m_SecurityData.HasInfo) ||
(m_HostContext != null) ||
HasUserData
)
{
fInfo = true;
}
return fInfo;
}
}
private bool HasUserData
{
get { return ((m_Datastore != null) && (m_Datastore.Count > 0));}
}
internal CallContextRemotingData RemotingData
{
get
{
if (m_RemotingData == null)
m_RemotingData = new CallContextRemotingData();
return m_RemotingData;
}
}
internal CallContextSecurityData SecurityData
{
get
{
if (m_SecurityData == null)
m_SecurityData = new CallContextSecurityData();
return m_SecurityData;
}
}
internal Object HostContext
{
get
{
return m_HostContext;
}
set
{
m_HostContext = value;
}
}
private Hashtable Datastore
{
get
{
if (null == m_Datastore)
{
// The local store has not yet been created for this thread.
m_Datastore = new Hashtable();
}
return m_Datastore;
}
}
// This is used for quick access to the current principal when going
// between appdomains.
internal IPrincipal Principal
{
get
{
// This MUST not fault in the security data object if it doesn't exist.
if (m_SecurityData != null)
return m_SecurityData.Principal;
return null;
} // get
[System.Security.SecurityCritical] // auto-generated
set
{
SecurityData.Principal = value;
} // set
} // Principal
/*=========================================================================
** Frees a named data slot.
=========================================================================*/
[System.Security.SecurityCritical] // auto-generated
public void FreeNamedDataSlot(String name)
{
Datastore.Remove(name);
}
[System.Security.SecurityCritical] // auto-generated
public Object GetData(String name)
{
return Datastore[name];
}
[System.Security.SecurityCritical] // auto-generated
public void SetData(String name, Object data)
{
Datastore[name] = data;
if (name.Equals(s_CorrelationMgrSlotName))
m_IsCorrelationMgr = true;
}
private Header[] InternalGetOutgoingHeaders()
{
Header[] outgoingHeaders = _sendHeaders;
_sendHeaders = null;
// A new remote call is being made, so we null out the
// current received headers so these can't be confused
// with a response from the next call.
_recvHeaders = null;
return outgoingHeaders;
} // InternalGetOutgoingHeaders
internal void InternalSetHeaders(Header[] headers)
{
_sendHeaders = headers;
_recvHeaders = null;
} // InternalSetHeaders
internal Header[] InternalGetHeaders()
{
// If _sendHeaders is currently set, we always want to return them.
if (_sendHeaders != null)
return _sendHeaders;
// Either _recvHeaders is non-null and those are the ones we want to
// return, or there are no currently set headers, so we'll return
// null.
return _recvHeaders;
} // InternalGetHeaders
// Nulls out the principal if its not serializable.
// Since principals do flow for x-appdomain cases
// we need to handle this behaviour both during invoke
// and response
[System.Security.SecurityCritical] // auto-generated
internal IPrincipal RemovePrincipalIfNotSerializable()
{
IPrincipal currentPrincipal = this.Principal;
// If the principal is not serializable, we need to
// null it out.
if (currentPrincipal != null)
{
if (!currentPrincipal.GetType().IsSerializable)
this.Principal = null;
}
return currentPrincipal;
}
#if FEATURE_REMOTING
// Takes outgoing headers and inserts them
[System.Security.SecurityCritical] // auto-generated
internal void PropagateOutgoingHeadersToMessage(IMessage msg)
{
Header[] headers = InternalGetOutgoingHeaders();
if (headers != null)
{
BCLDebug.Assert(msg != null, "Why is the message null?");
IDictionary properties = msg.Properties;
BCLDebug.Assert(properties != null, "Why are the properties null?");
foreach (Header header in headers)
{
// add header to the message dictionary
if (header != null)
{
// The header key is composed from its name and namespace.
String name = GetPropertyKeyForHeader(header);
properties[name] = header;
}
}
}
} // PropagateOutgoingHeadersToMessage
#endif
// Retrieve key to use for header.
internal static String GetPropertyKeyForHeader(Header header)
{
if (header == null)
return null;
if (header.HeaderNamespace != null)
return header.Name + ", " + header.HeaderNamespace;
else
return header.Name;
} // GetPropertyKeyForHeader
#if FEATURE_REMOTING
// Take headers out of message and stores them in call context
[System.Security.SecurityCritical] // auto-generated
internal void PropagateIncomingHeadersToCallContext(IMessage msg)
{
BCLDebug.Assert(msg != null, "Why is the message null?");
// If it's an internal message, we can quickly tell if there are any
// headers.
IInternalMessage iim = msg as IInternalMessage;
if (iim != null)
{
if (!iim.HasProperties())
{
// If there are no properties just return immediately.
return;
}
}
IDictionary properties = msg.Properties;
BCLDebug.Assert(properties != null, "Why are the properties null?");
IDictionaryEnumerator e = (IDictionaryEnumerator) properties.GetEnumerator();
// cycle through the properties to get a count of the headers
int count = 0;
while (e.MoveNext())
{
String key = (String)e.Key;
if (!key.StartsWith("__", StringComparison.Ordinal))
{
// We don't want to have to check for special values, so we
// blanketly state that header names can't start with
// double underscore.
if (e.Value is Header)
count++;
}
}
// If there are headers, create array and set it to the received header property
Header[] headers = null;
if (count > 0)
{
headers = new Header[count];
count = 0;
e.Reset();
while (e.MoveNext())
{
String key = (String)e.Key;
if (!key.StartsWith("__", StringComparison.Ordinal))
{
Header header = e.Value as Header;
if (header != null)
headers[count++] = header;
}
}
}
_recvHeaders = headers;
_sendHeaders = null;
} // PropagateIncomingHeadersToCallContext
#endif // FEATURE_REMOTING
} // class LogicalCallContext
[Serializable]
internal class CallContextSecurityData : ICloneable
{
// This is used for the special getter/setter for security related
// info in the callContext.
IPrincipal _principal;
// <
internal IPrincipal Principal
{
get {return _principal;}
set {_principal = value;}
}
// Checks if there is any useful data to be serialized
internal bool HasInfo
{
get
{
return (null != _principal);
}
}
public Object Clone()
{
CallContextSecurityData sd = new CallContextSecurityData();
sd._principal = _principal;
return sd;
}
}
[Serializable]
internal class CallContextRemotingData : ICloneable
{
// This is used for the special getter/setter for remoting related
// info in the callContext.
String _logicalCallID;
internal String LogicalCallID
{
get {return _logicalCallID;}
set {_logicalCallID = value;}
}
// Checks if there is any useful data to be serialized
internal bool HasInfo
{
get
{
// Keep this updated if we add more stuff to remotingData!
return (_logicalCallID!=null);
}
}
public Object Clone()
{
CallContextRemotingData rd = new CallContextRemotingData();
rd.LogicalCallID = LogicalCallID;
return rd;
}
}
}
| |
/*
* 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>
/// CartFinalizeOrderRequestOptions
/// </summary>
[DataContract]
public partial class CartFinalizeOrderRequestOptions : IEquatable<CartFinalizeOrderRequestOptions>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CartFinalizeOrderRequestOptions" /> class.
/// </summary>
/// <param name="autoApprovePurchaseOrder">Automatically approve the purchase order.</param>
/// <param name="channelPartnerCode">Channel partner code to associate this order with.</param>
/// <param name="channelPartnerOid">Channel partner oid to associate this order with.</param>
/// <param name="channelPartnerOrderId">Channel partner order id for reference.</param>
/// <param name="considerRecurring">Consider this order a recurring order for the purposes of payment gateway recurring flag.</param>
/// <param name="creditCardAuthorizationAmount">If the order was authorized outside of UltraCart, this is the amount of the authorization.</param>
/// <param name="creditCardAuthorizationDate">If the order was authorized outside of UltraCart, this is the date/time of the authorization.</param>
/// <param name="creditCardAuthorizationReferenceNumber">If the order was authorized outside of UltraCart, this is the authorization reference number.</param>
/// <param name="noRealtimePaymentProcessing">Prevents normal real-time processing of the payment and sends the order to Accounts Receivable.</param>
/// <param name="setupNextCart">True if the system should create another cart automatically if the current cart was logged into a profile.</param>
/// <param name="skipPaymentProcessing">Skip payment processing and move the order on to shipping (or completed if no shipping required).</param>
/// <param name="storeCompleted">True the order in the completed stage.</param>
/// <param name="storeIfPaymentDeclines">Store the order in accounts receivable if the payment declines.</param>
public CartFinalizeOrderRequestOptions(bool? autoApprovePurchaseOrder = default(bool?), string channelPartnerCode = default(string), int? channelPartnerOid = default(int?), string channelPartnerOrderId = default(string), bool? considerRecurring = default(bool?), decimal? creditCardAuthorizationAmount = default(decimal?), string creditCardAuthorizationDate = default(string), string creditCardAuthorizationReferenceNumber = default(string), bool? noRealtimePaymentProcessing = default(bool?), bool? setupNextCart = default(bool?), bool? skipPaymentProcessing = default(bool?), bool? storeCompleted = default(bool?), bool? storeIfPaymentDeclines = default(bool?))
{
this.AutoApprovePurchaseOrder = autoApprovePurchaseOrder;
this.ChannelPartnerCode = channelPartnerCode;
this.ChannelPartnerOid = channelPartnerOid;
this.ChannelPartnerOrderId = channelPartnerOrderId;
this.ConsiderRecurring = considerRecurring;
this.CreditCardAuthorizationAmount = creditCardAuthorizationAmount;
this.CreditCardAuthorizationDate = creditCardAuthorizationDate;
this.CreditCardAuthorizationReferenceNumber = creditCardAuthorizationReferenceNumber;
this.NoRealtimePaymentProcessing = noRealtimePaymentProcessing;
this.SetupNextCart = setupNextCart;
this.SkipPaymentProcessing = skipPaymentProcessing;
this.StoreCompleted = storeCompleted;
this.StoreIfPaymentDeclines = storeIfPaymentDeclines;
}
/// <summary>
/// Automatically approve the purchase order
/// </summary>
/// <value>Automatically approve the purchase order</value>
[DataMember(Name="auto_approve_purchase_order", EmitDefaultValue=false)]
public bool? AutoApprovePurchaseOrder { get; set; }
/// <summary>
/// Channel partner code to associate this order with
/// </summary>
/// <value>Channel partner code to associate this order with</value>
[DataMember(Name="channel_partner_code", EmitDefaultValue=false)]
public string ChannelPartnerCode { get; set; }
/// <summary>
/// Channel partner oid to associate this order with
/// </summary>
/// <value>Channel partner oid to associate this order with</value>
[DataMember(Name="channel_partner_oid", EmitDefaultValue=false)]
public int? ChannelPartnerOid { get; set; }
/// <summary>
/// Channel partner order id for reference
/// </summary>
/// <value>Channel partner order id for reference</value>
[DataMember(Name="channel_partner_order_id", EmitDefaultValue=false)]
public string ChannelPartnerOrderId { get; set; }
/// <summary>
/// Consider this order a recurring order for the purposes of payment gateway recurring flag
/// </summary>
/// <value>Consider this order a recurring order for the purposes of payment gateway recurring flag</value>
[DataMember(Name="consider_recurring", EmitDefaultValue=false)]
public bool? ConsiderRecurring { get; set; }
/// <summary>
/// If the order was authorized outside of UltraCart, this is the amount of the authorization
/// </summary>
/// <value>If the order was authorized outside of UltraCart, this is the amount of the authorization</value>
[DataMember(Name="credit_card_authorization_amount", EmitDefaultValue=false)]
public decimal? CreditCardAuthorizationAmount { get; set; }
/// <summary>
/// If the order was authorized outside of UltraCart, this is the date/time of the authorization
/// </summary>
/// <value>If the order was authorized outside of UltraCart, this is the date/time of the authorization</value>
[DataMember(Name="credit_card_authorization_date", EmitDefaultValue=false)]
public string CreditCardAuthorizationDate { get; set; }
/// <summary>
/// If the order was authorized outside of UltraCart, this is the authorization reference number
/// </summary>
/// <value>If the order was authorized outside of UltraCart, this is the authorization reference number</value>
[DataMember(Name="credit_card_authorization_reference_number", EmitDefaultValue=false)]
public string CreditCardAuthorizationReferenceNumber { get; set; }
/// <summary>
/// Prevents normal real-time processing of the payment and sends the order to Accounts Receivable
/// </summary>
/// <value>Prevents normal real-time processing of the payment and sends the order to Accounts Receivable</value>
[DataMember(Name="no_realtime_payment_processing", EmitDefaultValue=false)]
public bool? NoRealtimePaymentProcessing { get; set; }
/// <summary>
/// True if the system should create another cart automatically if the current cart was logged into a profile
/// </summary>
/// <value>True if the system should create another cart automatically if the current cart was logged into a profile</value>
[DataMember(Name="setup_next_cart", EmitDefaultValue=false)]
public bool? SetupNextCart { get; set; }
/// <summary>
/// Skip payment processing and move the order on to shipping (or completed if no shipping required)
/// </summary>
/// <value>Skip payment processing and move the order on to shipping (or completed if no shipping required)</value>
[DataMember(Name="skip_payment_processing", EmitDefaultValue=false)]
public bool? SkipPaymentProcessing { get; set; }
/// <summary>
/// True the order in the completed stage
/// </summary>
/// <value>True the order in the completed stage</value>
[DataMember(Name="store_completed", EmitDefaultValue=false)]
public bool? StoreCompleted { get; set; }
/// <summary>
/// Store the order in accounts receivable if the payment declines
/// </summary>
/// <value>Store the order in accounts receivable if the payment declines</value>
[DataMember(Name="store_if_payment_declines", EmitDefaultValue=false)]
public bool? StoreIfPaymentDeclines { 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 CartFinalizeOrderRequestOptions {\n");
sb.Append(" AutoApprovePurchaseOrder: ").Append(AutoApprovePurchaseOrder).Append("\n");
sb.Append(" ChannelPartnerCode: ").Append(ChannelPartnerCode).Append("\n");
sb.Append(" ChannelPartnerOid: ").Append(ChannelPartnerOid).Append("\n");
sb.Append(" ChannelPartnerOrderId: ").Append(ChannelPartnerOrderId).Append("\n");
sb.Append(" ConsiderRecurring: ").Append(ConsiderRecurring).Append("\n");
sb.Append(" CreditCardAuthorizationAmount: ").Append(CreditCardAuthorizationAmount).Append("\n");
sb.Append(" CreditCardAuthorizationDate: ").Append(CreditCardAuthorizationDate).Append("\n");
sb.Append(" CreditCardAuthorizationReferenceNumber: ").Append(CreditCardAuthorizationReferenceNumber).Append("\n");
sb.Append(" NoRealtimePaymentProcessing: ").Append(NoRealtimePaymentProcessing).Append("\n");
sb.Append(" SetupNextCart: ").Append(SetupNextCart).Append("\n");
sb.Append(" SkipPaymentProcessing: ").Append(SkipPaymentProcessing).Append("\n");
sb.Append(" StoreCompleted: ").Append(StoreCompleted).Append("\n");
sb.Append(" StoreIfPaymentDeclines: ").Append(StoreIfPaymentDeclines).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 CartFinalizeOrderRequestOptions);
}
/// <summary>
/// Returns true if CartFinalizeOrderRequestOptions instances are equal
/// </summary>
/// <param name="input">Instance of CartFinalizeOrderRequestOptions to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CartFinalizeOrderRequestOptions input)
{
if (input == null)
return false;
return
(
this.AutoApprovePurchaseOrder == input.AutoApprovePurchaseOrder ||
(this.AutoApprovePurchaseOrder != null &&
this.AutoApprovePurchaseOrder.Equals(input.AutoApprovePurchaseOrder))
) &&
(
this.ChannelPartnerCode == input.ChannelPartnerCode ||
(this.ChannelPartnerCode != null &&
this.ChannelPartnerCode.Equals(input.ChannelPartnerCode))
) &&
(
this.ChannelPartnerOid == input.ChannelPartnerOid ||
(this.ChannelPartnerOid != null &&
this.ChannelPartnerOid.Equals(input.ChannelPartnerOid))
) &&
(
this.ChannelPartnerOrderId == input.ChannelPartnerOrderId ||
(this.ChannelPartnerOrderId != null &&
this.ChannelPartnerOrderId.Equals(input.ChannelPartnerOrderId))
) &&
(
this.ConsiderRecurring == input.ConsiderRecurring ||
(this.ConsiderRecurring != null &&
this.ConsiderRecurring.Equals(input.ConsiderRecurring))
) &&
(
this.CreditCardAuthorizationAmount == input.CreditCardAuthorizationAmount ||
(this.CreditCardAuthorizationAmount != null &&
this.CreditCardAuthorizationAmount.Equals(input.CreditCardAuthorizationAmount))
) &&
(
this.CreditCardAuthorizationDate == input.CreditCardAuthorizationDate ||
(this.CreditCardAuthorizationDate != null &&
this.CreditCardAuthorizationDate.Equals(input.CreditCardAuthorizationDate))
) &&
(
this.CreditCardAuthorizationReferenceNumber == input.CreditCardAuthorizationReferenceNumber ||
(this.CreditCardAuthorizationReferenceNumber != null &&
this.CreditCardAuthorizationReferenceNumber.Equals(input.CreditCardAuthorizationReferenceNumber))
) &&
(
this.NoRealtimePaymentProcessing == input.NoRealtimePaymentProcessing ||
(this.NoRealtimePaymentProcessing != null &&
this.NoRealtimePaymentProcessing.Equals(input.NoRealtimePaymentProcessing))
) &&
(
this.SetupNextCart == input.SetupNextCart ||
(this.SetupNextCart != null &&
this.SetupNextCart.Equals(input.SetupNextCart))
) &&
(
this.SkipPaymentProcessing == input.SkipPaymentProcessing ||
(this.SkipPaymentProcessing != null &&
this.SkipPaymentProcessing.Equals(input.SkipPaymentProcessing))
) &&
(
this.StoreCompleted == input.StoreCompleted ||
(this.StoreCompleted != null &&
this.StoreCompleted.Equals(input.StoreCompleted))
) &&
(
this.StoreIfPaymentDeclines == input.StoreIfPaymentDeclines ||
(this.StoreIfPaymentDeclines != null &&
this.StoreIfPaymentDeclines.Equals(input.StoreIfPaymentDeclines))
);
}
/// <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.AutoApprovePurchaseOrder != null)
hashCode = hashCode * 59 + this.AutoApprovePurchaseOrder.GetHashCode();
if (this.ChannelPartnerCode != null)
hashCode = hashCode * 59 + this.ChannelPartnerCode.GetHashCode();
if (this.ChannelPartnerOid != null)
hashCode = hashCode * 59 + this.ChannelPartnerOid.GetHashCode();
if (this.ChannelPartnerOrderId != null)
hashCode = hashCode * 59 + this.ChannelPartnerOrderId.GetHashCode();
if (this.ConsiderRecurring != null)
hashCode = hashCode * 59 + this.ConsiderRecurring.GetHashCode();
if (this.CreditCardAuthorizationAmount != null)
hashCode = hashCode * 59 + this.CreditCardAuthorizationAmount.GetHashCode();
if (this.CreditCardAuthorizationDate != null)
hashCode = hashCode * 59 + this.CreditCardAuthorizationDate.GetHashCode();
if (this.CreditCardAuthorizationReferenceNumber != null)
hashCode = hashCode * 59 + this.CreditCardAuthorizationReferenceNumber.GetHashCode();
if (this.NoRealtimePaymentProcessing != null)
hashCode = hashCode * 59 + this.NoRealtimePaymentProcessing.GetHashCode();
if (this.SetupNextCart != null)
hashCode = hashCode * 59 + this.SetupNextCart.GetHashCode();
if (this.SkipPaymentProcessing != null)
hashCode = hashCode * 59 + this.SkipPaymentProcessing.GetHashCode();
if (this.StoreCompleted != null)
hashCode = hashCode * 59 + this.StoreCompleted.GetHashCode();
if (this.StoreIfPaymentDeclines != null)
hashCode = hashCode * 59 + this.StoreIfPaymentDeclines.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)
{
// CreditCardAuthorizationReferenceNumber (string) maxLength
if(this.CreditCardAuthorizationReferenceNumber != null && this.CreditCardAuthorizationReferenceNumber.Length > 60)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CreditCardAuthorizationReferenceNumber, length must be less than 60.", new [] { "CreditCardAuthorizationReferenceNumber" });
}
yield break;
}
}
}
| |
// $ANTLR 2.7.6 (20061021): "iCal.g" -> "iCalLexer.cs"$
using System.Text;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using DDay.iCal.Serialization;
using DDay.iCal.Serialization.iCalendar;
namespace DDay.iCal
{
// Generate header specific to lexer CSharp file
using System;
using Stream = System.IO.Stream;
using TextReader = System.IO.TextReader;
using Hashtable = System.Collections.Hashtable;
using Comparer = System.Collections.Comparer;
using TokenStreamException = antlr.TokenStreamException;
using TokenStreamIOException = antlr.TokenStreamIOException;
using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException;
using CharStreamException = antlr.CharStreamException;
using CharStreamIOException = antlr.CharStreamIOException;
using ANTLRException = antlr.ANTLRException;
using CharScanner = antlr.CharScanner;
using InputBuffer = antlr.InputBuffer;
using ByteBuffer = antlr.ByteBuffer;
using CharBuffer = antlr.CharBuffer;
using Token = antlr.Token;
using IToken = antlr.IToken;
using CommonToken = antlr.CommonToken;
using SemanticException = antlr.SemanticException;
using RecognitionException = antlr.RecognitionException;
using NoViableAltForCharException = antlr.NoViableAltForCharException;
using MismatchedCharException = antlr.MismatchedCharException;
using TokenStream = antlr.TokenStream;
using LexerSharedInputState = antlr.LexerSharedInputState;
using BitSet = antlr.collections.impl.BitSet;
public class iCalLexer : antlr.CharScanner , TokenStream
{
public const int EOF = 1;
public const int NULL_TREE_LOOKAHEAD = 3;
public const int CRLF = 4;
public const int BEGIN = 5;
public const int COLON = 6;
public const int VCALENDAR = 7;
public const int END = 8;
public const int IANA_TOKEN = 9;
public const int X_NAME = 10;
public const int SEMICOLON = 11;
public const int EQUAL = 12;
public const int COMMA = 13;
public const int DQUOTE = 14;
public const int CTL = 15;
public const int BACKSLASH = 16;
public const int NUMBER = 17;
public const int DOT = 18;
public const int CR = 19;
public const int LF = 20;
public const int ALPHA = 21;
public const int DIGIT = 22;
public const int DASH = 23;
public const int UNDERSCORE = 24;
public const int UNICODE = 25;
public const int SPECIAL = 26;
public const int SPACE = 27;
public const int HTAB = 28;
public const int SLASH = 29;
public const int ESCAPED_CHAR = 30;
public const int LINEFOLDER = 31;
public iCalLexer(Stream ins) : this(new ByteBuffer(ins))
{
}
public iCalLexer(TextReader r) : this(new CharBuffer(r))
{
}
public iCalLexer(InputBuffer ib) : this(new LexerSharedInputState(ib))
{
}
public iCalLexer(LexerSharedInputState state) : base(state)
{
initialize();
}
private void initialize()
{
caseSensitiveLiterals = true;
setCaseSensitive(true);
// literals = new Hashtable(100, (float) 0.4, null, Comparer.Default);
literals = new Hashtable ();
}
override public IToken nextToken() //throws TokenStreamException
{
#pragma warning disable 0219
IToken theRetToken = null;
#pragma warning restore 0219
tryAgain:
for (;;)
{
#pragma warning disable 0219
IToken _token = null;
#pragma warning restore 0219
int _ttype = Token.INVALID_TYPE;
resetText();
try // for char stream error handling
{
try // for lexical error handling
{
switch ( cached_LA1 )
{
case '\n':
{
mLF(true);
theRetToken = returnToken_;
break;
}
case ' ':
{
mSPACE(true);
theRetToken = returnToken_;
break;
}
case '\t':
{
mHTAB(true);
theRetToken = returnToken_;
break;
}
case ':':
{
mCOLON(true);
theRetToken = returnToken_;
break;
}
case ';':
{
mSEMICOLON(true);
theRetToken = returnToken_;
break;
}
case ',':
{
mCOMMA(true);
theRetToken = returnToken_;
break;
}
case '.':
{
mDOT(true);
theRetToken = returnToken_;
break;
}
case '=':
{
mEQUAL(true);
theRetToken = returnToken_;
break;
}
case '/':
{
mSLASH(true);
theRetToken = returnToken_;
break;
}
case '"':
{
mDQUOTE(true);
theRetToken = returnToken_;
break;
}
default:
if ((cached_LA1=='\r') && (cached_LA2=='\n') && (LA(3)=='\t'||LA(3)==' '))
{
mLINEFOLDER(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='\r') && (cached_LA2=='\n') && (true)) {
mCRLF(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='\\') && (tokenSet_0_.member(cached_LA2))) {
mESCAPED_CHAR(true);
theRetToken = returnToken_;
}
else if ((cached_LA1=='\\') && (true)) {
mBACKSLASH(true);
theRetToken = returnToken_;
}
else if ((tokenSet_1_.member(cached_LA1)) && (true)) {
mCTL(true);
theRetToken = returnToken_;
}
else if ((tokenSet_2_.member(cached_LA1))) {
mIANA_TOKEN(true);
theRetToken = returnToken_;
}
else
{
if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); }
else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());}
}
break; }
if ( null==returnToken_ ) goto tryAgain; // found SKIP token
_ttype = returnToken_.Type;
_ttype = testLiteralsTable(_ttype);
returnToken_.Type = _ttype;
return returnToken_;
}
catch (RecognitionException e) {
throw new TokenStreamRecognitionException(e);
}
}
catch (CharStreamException cse) {
if ( cse is CharStreamIOException ) {
throw new TokenStreamIOException(((CharStreamIOException)cse).io);
}
else {
throw new TokenStreamException(cse.Message);
}
}
}
}
protected void mCR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = CR;
match('\u000d');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLF(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LF;
match('\u000a');
_ttype = Token.SKIP;
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mALPHA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ALPHA;
switch ( cached_LA1 )
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
{
matchRange('\u0041','\u005a');
break;
}
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z':
{
matchRange('\u0061','\u007a');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mDIGIT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DIGIT;
matchRange('\u0030','\u0039');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mDASH(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DASH;
match('\u002d');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mUNDERSCORE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = UNDERSCORE;
match('\u005F');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mUNICODE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = UNICODE;
matchRange('\u0100','\uFFFE');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
protected void mSPECIAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SPECIAL;
switch ( cached_LA1 )
{
case '!':
{
match('\u0021');
break;
}
case '#': case '$': case '%': case '&':
case '\'': case '(': case ')': case '*':
case '+':
{
matchRange('\u0023','\u002b');
break;
}
case '<':
{
match('\u003c');
break;
}
case '>': case '?': case '@':
{
matchRange('\u003e','\u0040');
break;
}
case '[':
{
match('\u005b');
break;
}
case ']': case '^':
{
matchRange('\u005d','\u005e');
break;
}
case '`':
{
match('\u0060');
break;
}
case '{': case '|': case '}': case '~':
{
matchRange('\u007b','\u007e');
break;
}
default:
if (((cached_LA1 >= '\u0080' && cached_LA1 <= '\u00ff')))
{
matchRange('\u0080','\u00ff');
}
else
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
break; }
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSPACE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SPACE;
match('\u0020');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mHTAB(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = HTAB;
match('\u0009');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = COLON;
match('\u003a');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSEMICOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SEMICOLON;
match('\u003b');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = COMMA;
match('\u002c');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DOT;
match('\u002e');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mEQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = EQUAL;
match('\u003d');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mBACKSLASH(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = BACKSLASH;
match('\u005c');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mSLASH(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = SLASH;
match('\u002f');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mDQUOTE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = DQUOTE;
match('\u0022');
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCRLF(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = CRLF;
mCR(false);
mLF(false);
newline();
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mCTL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = CTL;
switch ( cached_LA1 )
{
case '\u0000': case '\u0001': case '\u0002': case '\u0003':
case '\u0004': case '\u0005': case '\u0006': case '\u0007':
case '\u0008':
{
matchRange('\u0000','\u0008');
break;
}
case '\u000b': case '\u000c': case '\r': case '\u000e':
case '\u000f': case '\u0010': case '\u0011': case '\u0012':
case '\u0013': case '\u0014': case '\u0015': case '\u0016':
case '\u0017': case '\u0018': case '\u0019': case '\u001a':
case '\u001b': case '\u001c': case '\u001d': case '\u001e':
case '\u001f':
{
matchRange('\u000b','\u001F');
break;
}
case '\u007f':
{
match('\u007F');
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mESCAPED_CHAR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = ESCAPED_CHAR;
mBACKSLASH(false);
{
switch ( cached_LA1 )
{
case '\\':
{
mBACKSLASH(false);
break;
}
case '"':
{
mDQUOTE(false);
break;
}
case ';':
{
mSEMICOLON(false);
break;
}
case ',':
{
mCOMMA(false);
break;
}
case 'N':
{
match("N");
break;
}
case 'n':
{
match("n");
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mIANA_TOKEN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = IANA_TOKEN;
{ // ( ... )+
int _cnt82=0;
for (;;)
{
switch ( cached_LA1 )
{
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'K': case 'L':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z': case 'a': case 'b':
case 'c': case 'd': case 'e': case 'f':
case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r':
case 's': case 't': case 'u': case 'v':
case 'w': case 'x': case 'y': case 'z':
{
mALPHA(false);
break;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9':
{
mDIGIT(false);
break;
}
case '-':
{
mDASH(false);
break;
}
case '_':
{
mUNDERSCORE(false);
break;
}
default:
if ((tokenSet_3_.member(cached_LA1)))
{
mSPECIAL(false);
}
else if (((cached_LA1 >= '\u0100' && cached_LA1 <= '\ufffe'))) {
mUNICODE(false);
}
else
{
if (_cnt82 >= 1) { goto _loop82_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; }
}
break; }
_cnt82++;
}
_loop82_breakloop: ;
} // ( ... )+
string s = text.ToString(_begin, text.Length-_begin);
int val;
if (int.TryParse(s, out val))
_ttype = NUMBER;
else
{
switch(s.ToUpper())
{
case "BEGIN": _ttype = BEGIN; break;
case "END": _ttype = END; break;
case "VCALENDAR": _ttype = VCALENDAR; break;
default:
if (s.Length > 2 && s.Substring(0,2).Equals("X-"))
_ttype = X_NAME;
break;
}
}
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
public void mLINEFOLDER(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException
{
int _ttype; IToken _token=null; int _begin=text.Length;
_ttype = LINEFOLDER;
mCRLF(false);
{
switch ( cached_LA1 )
{
case ' ':
{
mSPACE(false);
break;
}
case '\t':
{
mHTAB(false);
break;
}
default:
{
throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());
}
}
}
_ttype = Token.SKIP;
if (_createToken && (null == _token) && (_ttype != Token.SKIP))
{
_token = makeToken(_ttype);
_token.setText(text.ToString(_begin, text.Length-_begin));
}
returnToken_ = _token;
}
private static long[] mk_tokenSet_0_()
{
long[] data = new long[1025];
data[0]=576478361669337088L;
data[1]=70369012629504L;
for (int i = 2; i<=1024; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_());
private static long[] mk_tokenSet_1_()
{
long[] data = new long[1025];
data[0]=4294965759L;
data[1]=-9223372036854775808L;
for (int i = 2; i<=1024; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_());
private static long[] mk_tokenSet_2_()
{
long[] data = new long[2560];
data[0]=-3170762861857210368L;
data[1]=9223372036586340351L;
for (int i = 2; i<=1022; i++) { data[i]=-1L; }
data[1023]=9223372036854775807L;
for (int i = 1024; i<=2559; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_());
private static long[] mk_tokenSet_3_()
{
long[] data = new long[1025];
data[0]=-3458746947404300288L;
data[1]=8646911290591150081L;
for (int i = 2; i<=3; i++) { data[i]=-1L; }
for (int i = 4; i<=1024; i++) { data[i]=0L; }
return data;
}
public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_());
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PCSComUtils.Common;
using PCSComUtils.Framework.ReportFrame.BO;
using PCSComUtils.Framework.ReportFrame.DS;
using PCSComUtils.PCSExc;
using PCSUtils.Log;
using PCSUtils.Utils;
namespace PCSUtils.Framework.ReportFrame
{
/// <summary>
/// Summary description for ReportList.
/// </summary>
public class ReportList : Form
{
private ListBox lstReportList;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private const string THIS = "PCSUtils.Framework.ReportFrame.ReportList";
// ID of master report
private string strMasterID = string.Empty;
// search by report code or report name
private string strSearchBy = string.Empty;
private sys_ReportVO mvoReport;
private ArrayList arrReports = new ArrayList();
/// <summary>
/// Return selected report
/// </summary>
public sys_ReportVO SelectedReport
{
get { return this.mvoReport; }
}
//**************************************************************************
/// <Description>
/// Defaut constructor with parameter
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 06-Jan-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public ReportList(string pstrMasterID, string pstrSearchBy)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
strMasterID = pstrMasterID;
strSearchBy = pstrSearchBy;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ReportList));
this.lstReportList = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// lstReportList
//
this.lstReportList.AccessibleDescription = resources.GetString("lstReportList.AccessibleDescription");
this.lstReportList.AccessibleName = resources.GetString("lstReportList.AccessibleName");
this.lstReportList.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("lstReportList.Anchor")));
this.lstReportList.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("lstReportList.BackgroundImage")));
this.lstReportList.ColumnWidth = ((int)(resources.GetObject("lstReportList.ColumnWidth")));
this.lstReportList.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("lstReportList.Dock")));
this.lstReportList.Enabled = ((bool)(resources.GetObject("lstReportList.Enabled")));
this.lstReportList.Font = ((System.Drawing.Font)(resources.GetObject("lstReportList.Font")));
this.lstReportList.HorizontalExtent = ((int)(resources.GetObject("lstReportList.HorizontalExtent")));
this.lstReportList.HorizontalScrollbar = ((bool)(resources.GetObject("lstReportList.HorizontalScrollbar")));
this.lstReportList.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("lstReportList.ImeMode")));
this.lstReportList.IntegralHeight = ((bool)(resources.GetObject("lstReportList.IntegralHeight")));
this.lstReportList.ItemHeight = ((int)(resources.GetObject("lstReportList.ItemHeight")));
this.lstReportList.Location = ((System.Drawing.Point)(resources.GetObject("lstReportList.Location")));
this.lstReportList.Name = "lstReportList";
this.lstReportList.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("lstReportList.RightToLeft")));
this.lstReportList.ScrollAlwaysVisible = ((bool)(resources.GetObject("lstReportList.ScrollAlwaysVisible")));
this.lstReportList.Size = ((System.Drawing.Size)(resources.GetObject("lstReportList.Size")));
this.lstReportList.TabIndex = ((int)(resources.GetObject("lstReportList.TabIndex")));
this.lstReportList.Visible = ((bool)(resources.GetObject("lstReportList.Visible")));
this.lstReportList.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ReportList_KeyDown);
this.lstReportList.DoubleClick += new System.EventHandler(this.lstReportList_DoubleClick);
//
// ReportList
//
this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
this.AccessibleName = resources.GetString("$this.AccessibleName");
this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize")));
this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin")));
this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize")));
this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize")));
this.Controls.Add(this.lstReportList);
this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font")));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.KeyPreview = true;
this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location")));
this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize")));
this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize")));
this.Name = "ReportList";
this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft")));
this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition")));
this.Text = resources.GetString("$this.Text");
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ReportList_KeyDown);
this.Load += new System.EventHandler(this.ReportList_Load);
this.ResumeLayout(false);
}
#endregion
//**************************************************************************
/// <Description>
/// When load the form, get all data from sys_Report table and fill to list
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 06-Jan-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
private void ReportList_Load(object sender, EventArgs e)
{
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.WaitCursor;
#endregion Code Inserted Automatically
const string METHOD_NAME = THIS + ".ReportList_Load()";
try
{
ReportManagementBO boReportManagement = new ReportManagementBO();
arrReports = boReportManagement.GetAllReports();
if (arrReports.Count > 0)
{
sys_ReportVO voReport;
for (int i = 0; i < arrReports.Count; i++)
{
voReport = (sys_ReportVO) arrReports[i];
// add to list
if (!voReport.ReportID.Equals(this.strMasterID))
{
if (this.strSearchBy.Equals(sys_ReportTable.REPORTID_FLD))
{
lstReportList.Items.Add(voReport.ReportID);
}
else
{
lstReportList.Items.Add(voReport.ReportName);
}
}
}
this.lstReportList.Focus();
this.lstReportList.Select();
}
}
catch (PCSException ex)
{
// displays the error message.
PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
// displays the error message.
PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error);
// log message.
try
{
Logger.LogMessage(ex, METHOD_NAME, Level.ERROR);
}
catch
{
PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error);
}
}
// Code Inserted Automatically
#region Code Inserted Automatically
this.Cursor = Cursors.Default;
#endregion Code Inserted Automatically
}
private void ReportList_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
if (e.KeyCode == Keys.Enter)
{
// return selected report for drill down form
if (lstReportList.SelectedItem != null)
{
for (int i = 0; i < arrReports.Count; i++)
{
try
{
this.mvoReport = (sys_ReportVO) arrReports[i];
}
catch // catch InvalidCastException
{
PCSMessageBox.Show(ErrorCode.MESSAGE_DATA_CAST);
}
// search by report id
if (strSearchBy.Equals(sys_ReportTable.REPORTID_FLD))
{
if (mvoReport.ReportID.Equals(lstReportList.SelectedItem.ToString()))
{
break;
}
}
// search by report name
else
{
if (mvoReport.ReportName.Equals(lstReportList.SelectedItem.ToString()))
{
break;
}
}
}
// close the form
this.Close();
}
}
}
private void lstReportList_DoubleClick(object sender, System.EventArgs e)
{
this.ReportList_KeyDown(this, new KeyEventArgs(Keys.Enter));
}
}
}
| |
// 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 XorInt32()
{
var test = new SimpleBinaryOpTest__XorInt32();
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__XorInt32
{
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__XorInt32()
{
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__XorInt32()
{
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.Xor(
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.Xor(
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.Xor(
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.Xor), 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.Xor), 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.Xor), 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.Xor(
_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.Xor(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.Xor(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.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorInt32();
var result = Avx2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Xor(_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.Xor)}<Int32>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Collections;
using System;
namespace ReactNative.Animated
{
class SpringAnimationDriver : AnimationDriver
{
/// <summary>
/// Maximum amount of time to simulate per physics iteration in seconds (4 frames at 60 FPS).
/// </summary>
private const double MaxDeltaTimeSec = 0.064;
/// <summary>
/// Fixed timestep to use in the physics solver in seconds.
/// </summary>
private const double SolverTimestepSec = 0.001;
private long _lastTime;
private bool _springStarted;
// configuration
private double _springStiffness;
private double _springDamping;
private double _springMass;
private double _initialVelocity;
private bool _overshootClampingEnabled;
// all physics simulation objects are reused in each processing pass
private PhysicsState _currentState = new PhysicsState();
private double _startValue;
private double _endValue;
// thresholds for determining when the spring is at rest
private double _restSpeedThreshold;
private double _displacementFromRestThreshold;
private double _timeAccumulator = 0;
// for controlling loop
private int _iterations;
private int _currentLoop = 0;
private double _originalValue;
public SpringAnimationDriver(int id, ValueAnimatedNode animatedValue, ICallback endCallback, JObject config)
: base(id, animatedValue, endCallback)
{
_springStiffness = config.Value<double>("stiffness");
_springDamping = config.Value<double>("damping");
_springMass = config.Value<double>("mass");
_initialVelocity = config.Value<double>("initialVelocity");
_currentState.Velocity = _initialVelocity;
_endValue = config.Value<double>("toValue");
_restSpeedThreshold = config.Value<double>("restSpeedThreshold");
_displacementFromRestThreshold = config.Value<double>("restDisplacementThreshold");
_overshootClampingEnabled = config.Value<bool>("overshootClamping");
_iterations = config.ContainsKey("iterations") ? config.Value<int>("iterations") : 1;
HasFinished = _iterations == 0;
}
public override void RunAnimationStep(TimeSpan renderingTime)
{
var frameTimeMillis = renderingTime.Ticks / 10000;
if (!_springStarted)
{
if (_currentLoop == 0)
{
_originalValue = AnimatedValue.RawValue;
_currentLoop = 1;
}
_startValue = _currentState.Position = AnimatedValue.RawValue;
_lastTime = frameTimeMillis;
_timeAccumulator = 0.0;
_springStarted = true;
}
Advance((frameTimeMillis - _lastTime) / 1000.0);
_lastTime = frameTimeMillis;
AnimatedValue.RawValue = _currentState.Position;
if (IsAtRest())
{
if (_iterations == -1 || _currentLoop < _iterations)
{
// looping animation, return to start
_springStarted = false;
AnimatedValue.RawValue = _originalValue;
_currentLoop++;
}
else
{
// animation has completed
HasFinished = IsAtRest();
}
}
}
/// <summary>
/// Gets the displacement from rest for a given physics state.
/// </summary>
/// <param name="state">The state to measure from.</param>
/// <returns>The distance displaced by.</returns>
private double GetDisplacementDistanceForState(PhysicsState state)
{
return Math.Abs(_endValue - state.Position);
}
/// <summary>
/// Check if current state is at rest.
/// </summary>
/// <returns>
/// <code>true</code> if the spring is at rest, otherwise <code>false</code>.
/// </returns>
private bool IsAtRest()
{
return Math.Abs(_currentState.Velocity) <= _restSpeedThreshold &&
(GetDisplacementDistanceForState(_currentState) <= _displacementFromRestThreshold ||
_springStiffness == 0);
}
/// <summary>
/// Check if the spring is overshooting beyond its target.
/// </summary>
/// <returns>
/// <code>true</code> if the spring is overshooting its target,
/// otherwise <code>false</code>.
/// </returns>
private bool IsOvershooting()
{
return _springStiffness > 0 &&
((_startValue < _endValue && _currentState.Position > _endValue) ||
(_startValue > _endValue && _currentState.Position < _endValue));
}
private void Advance(double realDeltaTime)
{
if (IsAtRest())
{
return;
}
// clamp the amount of realDeltaTime to avoid stuttering in the UI.
// We should be able to catch up in a subsequent advance if necessary.
var adjustedDeltaTime = realDeltaTime;
if (realDeltaTime > MaxDeltaTimeSec)
{
adjustedDeltaTime = MaxDeltaTimeSec;
}
_timeAccumulator += adjustedDeltaTime;
var c = _springDamping;
var m = _springMass;
var k = _springStiffness;
var v0 = -_initialVelocity;
var zeta = c / (2 * Math.Sqrt(k * m));
var omega0 = Math.Sqrt(k / m);
var omega1 = omega0 * Math.Sqrt(1.0 - (zeta * zeta));
var x0 = _endValue - _startValue;
double velocity;
double position;
var t = _timeAccumulator;
if (zeta < 1)
{
// Under damped
double envelope = Math.Exp(-zeta * omega0 * t);
position =
_endValue -
envelope *
((v0 + zeta * omega0 * x0) / omega1 * Math.Sin(omega1 * t) +
x0 * Math.Cos(omega1 * t));
// This looks crazy -- it's actually just the derivative of the
// oscillation function
velocity =
zeta *
omega0 *
envelope *
(Math.Sin(omega1 * t) * (v0 + zeta * omega0 * x0) / omega1 +
x0 * Math.Cos(omega1 * t)) -
envelope *
(Math.Cos(omega1 * t) * (v0 + zeta * omega0 * x0) -
omega1 * x0 * Math.Sin(omega1 * t));
}
else
{
// Critically damped spring
double envelope = Math.Exp(-omega0 * t);
position = _endValue - envelope * (x0 + (v0 + omega0 * x0) * t);
velocity =
envelope * (v0 * (t * omega0 - 1) + t * x0 * (omega0 * omega0));
}
_currentState.Position = position;
_currentState.Velocity = velocity;
// End the spring immediately if it is overshooting and overshoot clamping is enabled.
// Also make sure that if the spring was considered within a resting threshold that it's now
// snapped to its end value.
if (IsAtRest() || (_overshootClampingEnabled && IsOvershooting()))
{
// Don't call setCurrentValue because that forces a call to onSpringUpdate
if (_springStiffness > 0)
{
_startValue = _endValue;
_currentState.Position = _endValue;
}
else
{
_endValue = _currentState.Position;
_startValue = _endValue;
}
_currentState.Velocity = 0;
}
}
struct PhysicsState
{
public double Position;
public double Velocity;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
using System.Text;
namespace System.IO
{
/// <summary>Contains internal path helpers that are shared between many projects.</summary>
internal static partial class PathInternal
{
// All paths in Win32 ultimately end up becoming a path to a File object in the Windows object manager. Passed in paths get mapped through
// DosDevice symbolic links in the object tree to actual File objects under \Devices. To illustrate, this is what happens with a typical
// path "Foo" passed as a filename to any Win32 API:
//
// 1. "Foo" is recognized as a relative path and is appended to the current directory (say, "C:\" in our example)
// 2. "C:\Foo" is prepended with the DosDevice namespace "\??\"
// 3. CreateFile tries to create an object handle to the requested file "\??\C:\Foo"
// 4. The Object Manager recognizes the DosDevices prefix and looks
// a. First in the current session DosDevices ("\Sessions\1\DosDevices\" for example, mapped network drives go here)
// b. If not found in the session, it looks in the Global DosDevices ("\GLOBAL??\")
// 5. "C:" is found in DosDevices (in our case "\GLOBAL??\C:", which is a symbolic link to "\Device\HarddiskVolume6")
// 6. The full path is now "\Device\HarddiskVolume6\Foo", "\Device\HarddiskVolume6" is a File object and parsing is handed off
// to the registered parsing method for Files
// 7. The registered open method for File objects is invoked to create the file handle which is then returned
//
// There are multiple ways to directly specify a DosDevices path. The final format of "\??\" is one way. It can also be specified
// as "\\.\" (the most commonly documented way) and "\\?\". If the question mark syntax is used the path will skip normalization
// (essentially GetFullPathName()) and path length checks.
// Windows Kernel-Mode Object Manager
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff565763.aspx
// https://channel9.msdn.com/Shows/Going+Deep/Windows-NT-Object-Manager
//
// Introduction to MS-DOS Device Names
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff548088.aspx
//
// Local and Global MS-DOS Device Names
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff554302.aspx
internal const char DirectorySeparatorChar = '\\';
internal const char AltDirectorySeparatorChar = '/';
internal const char VolumeSeparatorChar = ':';
internal const char PathSeparator = ';';
internal const string DirectorySeparatorCharAsString = "\\";
internal const string ExtendedPathPrefix = @"\\?\";
internal const string UncPathPrefix = @"\\";
internal const string UncExtendedPrefixToInsert = @"?\UNC\";
internal const string UncExtendedPathPrefix = @"\\?\UNC\";
internal const string DevicePathPrefix = @"\\.\";
internal const string ParentDirectoryPrefix = @"..\";
internal const int MaxShortPath = 260;
internal const int MaxShortDirectoryPath = 248;
// \\?\, \\.\, \??\
internal const int DevicePrefixLength = 4;
// \\
internal const int UncPrefixLength = 2;
// \\?\UNC\, \\.\UNC\
internal const int UncExtendedPrefixLength = 8;
/// <summary>
/// Returns true if the given character is a valid drive letter
/// </summary>
internal static bool IsValidDriveChar(char value)
{
return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z'));
}
internal static bool EndsWithPeriodOrSpace(string path)
{
if (string.IsNullOrEmpty(path))
return false;
char c = path[path.Length - 1];
return c == ' ' || c == '.';
}
/// <summary>
/// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative,
/// AND the path is more than 259 characters. (> MAX_PATH + null). This will also insert the extended
/// prefix if the path ends with a period or a space. Trailing periods and spaces are normally eaten
/// away from paths during normalization, but if we see such a path at this point it should be
/// normalized and has retained the final characters. (Typically from one of the *Info classes)
/// </summary>
internal static string EnsureExtendedPrefixIfNeeded(string path)
{
if (path != null && (path.Length >= MaxShortPath || EndsWithPeriodOrSpace(path)))
{
return EnsureExtendedPrefix(path);
}
else
{
return path;
}
}
/// <summary>
/// DO NOT USE- Use EnsureExtendedPrefixIfNeeded. This will be removed shortly.
/// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative,
/// AND the path is more than 259 characters. (> MAX_PATH + null)
/// </summary>
internal static string EnsureExtendedPrefixOverMaxPath(string path)
{
if (path != null && path.Length >= MaxShortPath)
{
return EnsureExtendedPrefix(path);
}
else
{
return path;
}
}
/// <summary>
/// Adds the extended path prefix (\\?\) if not relative or already a device path.
/// </summary>
internal static string EnsureExtendedPrefix(string path)
{
// Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which
// means adding to relative paths will prevent them from getting the appropriate current directory inserted.
// If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it
// as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly
// in the future we wouldn't want normalization to come back and break existing code.
// In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this
// shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a
// normalized base path.)
if (IsPartiallyQualified(path.AsSpan()) || IsDevice(path.AsSpan()))
return path;
// Given \\server\share in longpath becomes \\?\UNC\server\share
if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase))
return path.Insert(2, UncExtendedPrefixToInsert);
return ExtendedPathPrefix + path;
}
/// <summary>
/// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\")
/// </summary>
internal static bool IsDevice(ReadOnlySpan<char> path)
{
// If the path begins with any two separators is will be recognized and normalized and prepped with
// "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not.
return IsExtended(path)
||
(
path.Length >= DevicePrefixLength
&& IsDirectorySeparator(path[0])
&& IsDirectorySeparator(path[1])
&& (path[2] == '.' || path[2] == '?')
&& IsDirectorySeparator(path[3])
);
}
/// <summary>
/// Returns true if the path is a device UNC (\\?\UNC\, \\.\UNC\)
/// </summary>
internal static bool IsDeviceUNC(ReadOnlySpan<char> path)
{
return path.Length >= UncExtendedPrefixLength
&& IsDevice(path)
&& IsDirectorySeparator(path[7])
&& path[4] == 'U'
&& path[5] == 'N'
&& path[6] == 'C';
}
/// <summary>
/// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the
/// path matches exactly (cannot use alternate directory separators) Windows will skip normalization
/// and path length checks.
/// </summary>
internal static bool IsExtended(ReadOnlySpan<char> path)
{
// While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths.
// Skipping of normalization will *only* occur if back slashes ('\') are used.
return path.Length >= DevicePrefixLength
&& path[0] == '\\'
&& (path[1] == '\\' || path[1] == '?')
&& path[2] == '?'
&& path[3] == '\\';
}
/// <summary>
/// Check for known wildcard characters. '*' and '?' are the most common ones.
/// </summary>
internal static bool HasWildCardCharacters(ReadOnlySpan<char> path)
{
// Question mark is part of dos device syntax so we have to skip if we are
int startIndex = IsDevice(path) ? ExtendedPathPrefix.Length : 0;
// [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression
// https://msdn.microsoft.com/en-us/library/ff469270.aspx
for (int i = startIndex; i < path.Length; i++)
{
char c = path[i];
if (c <= '?') // fast path for common case - '?' is highest wildcard character
{
if (c == '\"' || c == '<' || c == '>' || c == '*' || c == '?')
return true;
}
}
return false;
}
/// <summary>
/// Gets the length of the root of the path (drive, share, etc.).
/// </summary>
internal static int GetRootLength(ReadOnlySpan<char> path)
{
int pathLength = path.Length;
int i = 0;
bool deviceSyntax = IsDevice(path);
bool deviceUnc = deviceSyntax && IsDeviceUNC(path);
if ((!deviceSyntax || deviceUnc) && pathLength > 0 && IsDirectorySeparator(path[0]))
{
// UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo")
if (deviceUnc || (pathLength > 1 && IsDirectorySeparator(path[1])))
{
// UNC (\\?\UNC\ or \\), scan past server\share
// Start past the prefix ("\\" or "\\?\UNC\")
i = deviceUnc ? UncExtendedPrefixLength : UncPrefixLength;
// Skip two separators at most
int n = 2;
while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0))
i++;
}
else
{
// Current drive rooted (e.g. "\foo")
i = 1;
}
}
else if (deviceSyntax)
{
// Device path (e.g. "\\?\.", "\\.\")
// Skip any characters following the prefix that aren't a separator
i = DevicePrefixLength;
while (i < pathLength && !IsDirectorySeparator(path[i]))
i++;
// If there is another separator take it, as long as we have had at least one
// non-separator after the prefix (e.g. don't take "\\?\\", but take "\\?\a\")
if (i < pathLength && i > DevicePrefixLength && IsDirectorySeparator(path[i]))
i++;
}
else if (pathLength >= 2
&& path[1] == VolumeSeparatorChar
&& IsValidDriveChar(path[0]))
{
// Valid drive specified path ("C:", "D:", etc.)
i = 2;
// If the colon is followed by a directory separator, move past it (e.g "C:\")
if (pathLength > 2 && IsDirectorySeparator(path[2]))
i++;
}
return i;
}
/// <summary>
/// Returns true if the path specified is relative to the current drive or working directory.
/// Returns false if the path is fixed to a specific drive or UNC path. This method does no
/// validation of the path (URIs will be returned as relative as a result).
/// </summary>
/// <remarks>
/// Handles paths that use the alternate directory separator. It is a frequent mistake to
/// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case.
/// "C:a" is drive relative- meaning that it will be resolved against the current directory
/// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
/// will not be used to modify the path).
/// </remarks>
internal static bool IsPartiallyQualified(ReadOnlySpan<char> path)
{
if (path.Length < 2)
{
// It isn't fixed, it must be relative. There is no way to specify a fixed
// path with one character (or less).
return true;
}
if (IsDirectorySeparator(path[0]))
{
// There is no valid way to specify a relative path with two initial slashes or
// \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\
return !(path[1] == '?' || IsDirectorySeparator(path[1]));
}
// The only way to specify a fixed path that doesn't begin with two slashes
// is the drive, colon, slash format- i.e. C:\
return !((path.Length >= 3)
&& (path[1] == VolumeSeparatorChar)
&& IsDirectorySeparator(path[2])
// To match old behavior we'll check the drive character for validity as the path is technically
// not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream.
&& IsValidDriveChar(path[0]));
}
/// <summary>
/// True if the given character is a directory separator.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsDirectorySeparator(char c)
{
return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar;
}
/// <summary>
/// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present.
/// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip).
///
/// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false.
/// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as
/// such can't be used here (and is overkill for our uses).
///
/// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments.
/// </summary>
/// <remarks>
/// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do
/// not need trimming of trailing whitespace here.
///
/// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization.
///
/// For legacy desktop behavior with ExpandShortPaths:
/// - It has no impact on GetPathRoot() so doesn't need consideration.
/// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share).
///
/// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was
/// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you
/// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by
/// this undocumented behavior.
///
/// We won't match this old behavior because:
///
/// 1. It was undocumented
/// 2. It was costly (extremely so if it actually contained '~')
/// 3. Doesn't play nice with string logic
/// 4. Isn't a cross-plat friendly concept/behavior
/// </remarks>
internal static string NormalizeDirectorySeparators(string path)
{
if (string.IsNullOrEmpty(path))
return path;
char current;
// Make a pass to see if we need to normalize so we can potentially skip allocating
bool normalized = true;
for (int i = 0; i < path.Length; i++)
{
current = path[i];
if (IsDirectorySeparator(current)
&& (current != DirectorySeparatorChar
// Check for sequential separators past the first position (we need to keep initial two for UNC/extended)
|| (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))))
{
normalized = false;
break;
}
}
if (normalized)
return path;
StringBuilder builder = new StringBuilder(path.Length);
int start = 0;
if (IsDirectorySeparator(path[start]))
{
start++;
builder.Append(DirectorySeparatorChar);
}
for (int i = start; i < path.Length; i++)
{
current = path[i];
// If we have a separator
if (IsDirectorySeparator(current))
{
// If the next is a separator, skip adding this
if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))
{
continue;
}
// Ensure it is the primary separator
current = DirectorySeparatorChar;
}
builder.Append(current);
}
return builder.ToString();
}
/// <summary>
/// Returns true if the path is effectively empty for the current OS.
/// For unix, this is empty or null. For Windows, this is empty, null, or
/// just spaces ((char)32).
/// </summary>
internal static bool IsEffectivelyEmpty(ReadOnlySpan<char> path)
{
if (path.IsEmpty)
return true;
foreach (char c in path)
{
if (c != ' ')
return false;
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.Net.Sockets
{
internal partial class SafeCloseSocket :
#if DEBUG
DebugSafeHandleMinusOneIsInvalid
#else
SafeHandleMinusOneIsInvalid
#endif
{
private int _receiveTimeout = -1;
private int _sendTimeout = -1;
private bool _nonBlocking;
private SocketAsyncContext _asyncContext;
public SocketAsyncContext AsyncContext
{
get
{
if (Volatile.Read(ref _asyncContext) == null)
{
Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null);
}
return _asyncContext;
}
}
public bool IsNonBlocking
{
get
{
return _nonBlocking;
}
set
{
_nonBlocking = value;
//
// If transitioning to non-blocking, we need to set the native socket to non-blocking mode.
// If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate
// blocking. This avoids problems with switching to native blocking while there are pending async
// operations.
//
if (value)
{
AsyncContext.SetNonBlocking();
}
}
}
public int ReceiveTimeout
{
get
{
return _receiveTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_receiveTimeout = value;;
}
}
public int SendTimeout
{
get
{
return _sendTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_sendTimeout = value;
}
}
public unsafe static SafeCloseSocket CreateSocket(int fileDescriptor)
{
return CreateSocket(InnerSafeCloseSocket.CreateSocket(fileDescriptor));
}
public unsafe static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out errorCode));
return errorCode;
}
public unsafe static SocketError Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize, out errorCode));
return errorCode;
}
private void InnerReleaseHandle()
{
if (_asyncContext != null)
{
_asyncContext.Close();
}
}
internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid
{
private unsafe SocketError InnerReleaseHandle()
{
int errorCode;
// If _blockable was set in BlockingRelease, it's safe to block here, which means
// we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which
// case we need to do some recovery.
if (_blockable)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") Following 'blockable' branch.");
}
errorCode = Interop.Sys.Close(handle);
if (errorCode == -1)
{
errorCode = (int)Interop.Sys.GetLastError();
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#1:" + errorCode.ToString());
}
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
// If it's not EWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != (int)Interop.Error.EWOULDBLOCK)
{
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket must be non-blocking with a linger timeout set.
// We have to set the socket to blocking.
errorCode = Interop.Sys.Fcntl.DangerousSetIsNonBlocking(handle, 0);
if (errorCode == 0)
{
// The socket successfully made blocking; retry the close().
errorCode = Interop.Sys.Close(handle);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close()#2:" + errorCode.ToString());
}
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket could not be made blocking; fall through to the regular abortive close.
}
// By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST).
var linger = new Interop.Sys.LingerOption {
OnOff = 1,
Seconds = 0
};
errorCode = (int)Interop.Sys.DangerousSetLingerOption((int)handle, &linger);
#if DEBUG
_closeSocketLinger = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") setsockopt():" + errorCode.ToString());
}
if (errorCode != 0 && errorCode != (int)Interop.Error.EINVAL && errorCode != (int)Interop.Error.ENOPROTOOPT)
{
// Too dangerous to try closesocket() - it might block!
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
errorCode = Interop.Sys.Close(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") close#3():" + (errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode).ToString());
}
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
public static InnerSafeCloseSocket CreateSocket(int fileDescriptor)
{
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)fileDescriptor);
return res;
}
public static unsafe InnerSafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SocketError errorCode)
{
int fd;
Interop.Error error = Interop.Sys.Socket(addressFamily, socketType, protocolType, &fd);
if (error == Interop.Error.SUCCESS)
{
Debug.Assert(fd != -1, "fd should not be -1");
errorCode = SocketError.Success;
// The socket was created successfully; enable IPV6_V6ONLY by default for AF_INET6 sockets.
if (addressFamily == AddressFamily.InterNetworkV6)
{
int on = 1;
error = Interop.Sys.DangerousSetSockOpt(fd, SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (byte*)&on, sizeof(int));
if (error != Interop.Error.SUCCESS)
{
Interop.Sys.Close((IntPtr)fd);
fd = -1;
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
}
}
else
{
Debug.Assert(fd == -1, $"Unexpected fd: {fd}");
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)fd);
return res;
}
public static unsafe InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressLen, out SocketError errorCode)
{
int acceptedFd;
if (!socketHandle.IsNonBlocking)
{
errorCode = socketHandle.AsyncContext.Accept(socketAddress, ref socketAddressLen, -1, out acceptedFd);
}
else
{
SocketPal.TryCompleteAccept(socketHandle, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode);
}
var res = new InnerSafeCloseSocket();
res.SetHandle((IntPtr)acceptedFd);
return res;
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using Zenject.ReflectionBaking.Mono.Cecil.Cil;
using Zenject.ReflectionBaking.Mono.Collections.Generic;
using Zenject.ReflectionBaking.Mono.CompilerServices.SymbolWriter;
namespace Zenject.ReflectionBaking.Mono.Cecil.Mdb {
#if !READ_ONLY
public class MdbWriterProvider : ISymbolWriterProvider {
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
return new MdbWriter (module.Mvid, fileName);
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
throw new NotImplementedException ();
}
}
public class MdbWriter : ISymbolWriter {
readonly Guid mvid;
readonly MonoSymbolWriter writer;
readonly Dictionary<string, SourceFile> source_files;
public MdbWriter (Guid mvid, string assembly)
{
this.mvid = mvid;
this.writer = new MonoSymbolWriter (assembly);
this.source_files = new Dictionary<string, SourceFile> ();
}
static Collection<Instruction> GetInstructions (MethodBody body)
{
var instructions = new Collection<Instruction> ();
foreach (var instruction in body.Instructions)
if (instruction.SequencePoint != null)
instructions.Add (instruction);
return instructions;
}
SourceFile GetSourceFile (Document document)
{
var url = document.Url;
SourceFile source_file;
if (source_files.TryGetValue (url, out source_file))
return source_file;
var entry = writer.DefineDocument (url);
var compile_unit = writer.DefineCompilationUnit (entry);
source_file = new SourceFile (compile_unit, entry);
source_files.Add (url, source_file);
return source_file;
}
void Populate (Collection<Instruction> instructions, int [] offsets,
int [] startRows, int [] endRows, int [] startCols, int [] endCols, out SourceFile file)
{
SourceFile source_file = null;
for (int i = 0; i < instructions.Count; i++) {
var instruction = instructions [i];
offsets [i] = instruction.Offset;
var sequence_point = instruction.SequencePoint;
if (source_file == null)
source_file = GetSourceFile (sequence_point.Document);
startRows [i] = sequence_point.StartLine;
endRows [i] = sequence_point.EndLine;
startCols [i] = sequence_point.StartColumn;
endCols [i] = sequence_point.EndColumn;
}
file = source_file;
}
public void Write (MethodBody body)
{
var method = new SourceMethod (body.Method);
var instructions = GetInstructions (body);
int count = instructions.Count;
if (count == 0)
return;
var offsets = new int [count];
var start_rows = new int [count];
var end_rows = new int [count];
var start_cols = new int [count];
var end_cols = new int [count];
SourceFile file;
Populate (instructions, offsets, start_rows, end_rows, start_cols, end_cols, out file);
var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
for (int i = 0; i < count; i++) {
builder.MarkSequencePoint (
offsets [i],
file.CompilationUnit.SourceFile,
start_rows [i],
end_rows [i],
start_cols [i],
end_cols [i],
false);
}
if (body.Scope != null && body.Scope.HasScopes)
WriteScope (body.Scope, true);
else
if (body.HasVariables)
AddVariables (body.Variables);
writer.CloseMethod ();
}
private void WriteScope (Scope scope, bool root)
{
if (scope.Start.Offset == scope.End.Offset) return;
writer.OpenScope (scope.Start.Offset);
if (scope.HasVariables)
{
foreach (var el in scope.Variables)
{
if (!String.IsNullOrEmpty (el.Name))
writer.DefineLocalVariable (el.Index, el.Name);
}
}
if (scope.HasScopes)
{
foreach (var el in scope.Scopes)
WriteScope (el, false);
}
writer.CloseScope (scope.End.Offset + scope.End.GetSize());
}
readonly static byte [] empty_header = new byte [0];
public bool GetDebugHeader (out ImageDebugDirectory directory, out byte [] header)
{
directory = new ImageDebugDirectory ();
header = empty_header;
return false;
}
void AddVariables (IList<VariableDefinition> variables)
{
for (int i = 0; i < variables.Count; i++) {
var variable = variables [i];
writer.DefineLocalVariable (i, variable.Name);
}
}
public void Write (MethodSymbols symbols)
{
var method = new SourceMethodSymbol (symbols);
var file = GetSourceFile (symbols.Instructions [0].SequencePoint.Document);
var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
var count = symbols.Instructions.Count;
for (int i = 0; i < count; i++) {
var instruction = symbols.Instructions [i];
var sequence_point = instruction.SequencePoint;
builder.MarkSequencePoint (
instruction.Offset,
GetSourceFile (sequence_point.Document).CompilationUnit.SourceFile,
sequence_point.StartLine,
sequence_point.EndLine,
sequence_point.StartColumn,
sequence_point.EndColumn,
false);
}
if (symbols.HasVariables)
AddVariables (symbols.Variables);
writer.CloseMethod ();
}
public void Dispose ()
{
writer.WriteSymbolFile (mvid);
}
class SourceFile : ISourceFile {
readonly CompileUnitEntry compilation_unit;
readonly SourceFileEntry entry;
public SourceFileEntry Entry {
get { return entry; }
}
public CompileUnitEntry CompilationUnit {
get { return compilation_unit; }
}
public SourceFile (CompileUnitEntry comp_unit, SourceFileEntry entry)
{
this.compilation_unit = comp_unit;
this.entry = entry;
}
}
class SourceMethodSymbol : IMethodDef {
readonly string name;
readonly int token;
public string Name {
get { return name;}
}
public int Token {
get { return token; }
}
public SourceMethodSymbol (MethodSymbols symbols)
{
name = symbols.MethodName;
token = symbols.MethodToken.ToInt32 ();
}
}
class SourceMethod : IMethodDef {
readonly MethodDefinition method;
public string Name {
get { return method.Name; }
}
public int Token {
get { return method.MetadataToken.ToInt32 (); }
}
public SourceMethod (MethodDefinition method)
{
this.method = method;
}
}
}
#endif
}
| |
using System;
using System.IO;
using System.Reflection;
namespace NMock2.Monitoring
{
public class Invocation : ISelfDescribing
{
public readonly object Receiver;
public readonly MethodInfo Method;
public readonly ParameterList Parameters;
private object result = null;
private Exception exception = null;
private bool isThrowing = false;
public Invocation(object receiver, MethodInfo method, object[] parameters)
{
Receiver = receiver;
Method = method;
Parameters = new ParameterList(method, parameters);
}
public object Result
{
get
{
return result;
}
set
{
CheckReturnType(value);
result = value;
exception = null;
isThrowing = false;
}
}
private void CheckReturnType(object value)
{
if (Method.ReturnType == typeof(void) && value != null)
{
throw new ArgumentException("cannot return a value from a void method", "Result");
}
if (Method.ReturnType != typeof(void) && Method.ReturnType.IsValueType && value == null)
{
#if NET20
if ( !( Method.ReturnType.IsGenericType && Method.ReturnType.GetGenericTypeDefinition() == typeof( Nullable<> ) ) )
{
throw new ArgumentException( "cannot return a null value type", "Result" );
}
#else
throw new ArgumentException("cannot return a null value type", "Result" );
#endif
}
if (value != null && !Method.ReturnType.IsInstanceOfType(value))
{
throw new ArgumentException("cannot return a value of type " + value.GetType()
+ " from a method returning " + Method.ReturnType,
"Result");
}
}
public Exception Exception
{
get
{
return exception;
}
set
{
if (value == null) throw new ArgumentNullException("Exception");
exception = value;
result = null;
isThrowing = true;
}
}
public bool IsThrowing
{
get { return isThrowing; }
}
public void InvokeOn(object otherReceiver)
{
try
{
Result = Method.Invoke(otherReceiver, Parameters.AsArray);
Parameters.MarkAllValuesAsSet();
}
catch(TargetInvocationException e)
{
Exception = e.InnerException;
}
}
public void DescribeTo(TextWriter writer)
{
writer.Write(Receiver.ToString());
if (MethodIsIndexerGetter())
{
DescribeAsIndexerGetter(writer);
}
else if (MethodIsIndexerSetter())
{
DescribeAsIndexerSetter(writer);
}
else if (MethodIsEventAdder())
{
DescribeAsEventAdder(writer);
}
else if (MethodIsEventRemover())
{
DescribeAsEventRemover(writer);
}
else if (MethodIsProperty())
{
DescribeAsProperty(writer);
}
else
{
DescribeNormalMethod(writer);
}
}
private bool MethodIsProperty()
{
return Method.IsSpecialName &&
((Method.Name.StartsWith("get_") && Parameters.Count == 0) ||
(Method.Name.StartsWith("set_") && Parameters.Count == 1));
}
private bool MethodIsIndexerGetter()
{
return Method.IsSpecialName
&& Method.Name == "get_Item"
&& Parameters.Count >= 1;
}
private bool MethodIsIndexerSetter()
{
return Method.IsSpecialName
&& Method.Name == "set_Item"
&& Parameters.Count >= 2;
}
private bool MethodIsEventAdder()
{
return Method.IsSpecialName
&& Method.Name.StartsWith("add_")
&& Parameters.Count == 1
&& typeof(Delegate).IsAssignableFrom(Method.GetParameters()[0].ParameterType);
}
private bool MethodIsEventRemover()
{
return Method.IsSpecialName
&& Method.Name.StartsWith("remove_")
&& Parameters.Count == 1
&& typeof(Delegate).IsAssignableFrom(Method.GetParameters()[0].ParameterType);
}
private void DescribeAsProperty(TextWriter writer)
{
writer.Write(".");
writer.Write(Method.Name.Substring(4));
if (Parameters.Count > 0)
{
writer.Write(" = ");
writer.Write(Parameters[0]);
}
}
private void DescribeAsIndexerGetter(TextWriter writer)
{
writer.Write("[");
WriteParameterList(writer, Parameters.Count);
writer.Write("]");
}
private void DescribeAsIndexerSetter(TextWriter writer)
{
writer.Write("[");
WriteParameterList(writer, Parameters.Count-1);
writer.Write("] = ");
writer.Write(Parameters[Parameters.Count-1]);
}
private void DescribeNormalMethod(TextWriter writer)
{
writer.Write(".");
writer.Write(Method.Name);
writer.Write("(");
WriteParameterList(writer, Parameters.Count);
writer.Write(")");
}
private void WriteParameterList(TextWriter writer, int count)
{
for (int i = 0; i < count; i++)
{
if (i > 0) writer.Write(", ");
if (Method.GetParameters()[i].IsOut)
{
writer.Write("out");
}
else
{
writer.Write(Parameters[i]);
}
}
}
private void DescribeAsEventAdder(TextWriter writer)
{
writer.Write(" += ");
writer.Write(Parameters[0]);
}
private void DescribeAsEventRemover(TextWriter writer)
{
writer.Write(" -= ");
writer.Write(Parameters[0]); }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace JugueteriaEntity.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Flame.Build;
using Flame.Compiler.Build;
using Flame.LLVM.Codegen;
using LLVMSharp;
using static LLVMSharp.LLVM;
namespace Flame.LLVM
{
/// <summary>
/// A type builder for LLVM assemblies.
/// </summary>
public sealed class LLVMType : ITypeBuilder
{
public LLVMType(LLVMNamespace Namespace, ITypeSignatureTemplate Template)
{
this.Namespace = Namespace;
this.templateInstance = new TypeSignatureInstance(Template, this);
this.attrMap = new AttributeMapBuilder();
this.declaredMethods = new List<LLVMMethod>();
this.declaredStaticCtors = new List<LLVMMethod>();
this.declaredInstanceFields = new List<LLVMField>();
this.declaredStaticFields = new List<LLVMField>();
this.declaredFields = new List<LLVMField>();
this.fieldCounter = 0;
this.declaredProperties = new List<LLVMProperty>();
this.RelativeVTable = new VTableSlots();
}
private AttributeMapBuilder attrMap;
private TypeSignatureInstance templateInstance;
private List<LLVMMethod> declaredMethods;
private List<LLVMMethod> declaredStaticCtors;
private List<LLVMField> declaredInstanceFields;
private int fieldCounter;
private List<LLVMField> declaredStaticFields;
private List<LLVMField> declaredFields;
private List<LLVMProperty> declaredProperties;
/// <summary>
/// Gets this type's vtable slots for methods that are declared in this type.
/// </summary>
/// <returns>The vtable slots.</returns>
public VTableSlots RelativeVTable { get; private set; }
/// <summary>
/// Gets this LLVM type's declaring namespace.
/// </summary>
/// <returns>The declaring namespace.</returns>
public LLVMNamespace Namespace { get; private set; }
/// <summary>
/// Gets the name of this type.
/// </summary>
/// <returns>This type's name.</returns>
public UnqualifiedName Name => templateInstance.Name;
/// <summary>
/// Gets this type's qualified name.
/// </summary>
/// <returns>The type's qualified name.</returns>
public QualifiedName FullName => Name.Qualify(Namespace.FullName);
/// <summary>
/// Gets this LLVM type's declaring namespace.
/// </summary>
/// <returns>The declaring namespace.</returns>
public INamespace DeclaringNamespace => Namespace;
/// <summary>
/// Gets the ancestry rules for this type.
/// </summary>
public IAncestryRules AncestryRules => DefinitionAncestryRules.Instance;
/// <summary>
/// Gets this type's attribute map.
/// </summary>
/// <returns>The attribute map.</returns>
public AttributeMap Attributes => new AttributeMap(attrMap);
/// <summary>
/// Gets the list of all instance fields defined by this type.
/// </summary>
public IReadOnlyList<LLVMField> InstanceFields => declaredInstanceFields;
/// <summary>
/// Gets the list of all static constructors defined by this type.
/// </summary>
public IReadOnlyList<LLVMMethod> StaticConstructors => declaredStaticCtors;
/// <summary>
/// Tests if this type is a value type that is stored as a single value.
/// The runtime representation of these types is not wrapped in a struct.
/// </summary>
/// <returns><c>true</c> if this is a single-value value type; otherwise, <c>false</c>.</returns>
public bool IsSingleValue => InstanceFields.Count == 1 && this.GetIsValueType();
/// <summary>
/// Checks if this type is a runtime-implemented delegate type. The data layout
/// of these types is provided by the runtime instead of user code.
/// </summary>
/// <returns>
/// <c>true</c> if this is a runtime-implemented delegate type; otherwise, <c>false</c>.
/// </returns>
public bool IsRuntimeImplementedDelegate =>
this.HasAttribute(PrimitiveAttributes.Instance.RuntimeImplementedAttribute.AttributeType)
&& this.HasAttribute(MethodType.DelegateAttributeType);
public IEnumerable<IMethod> Methods => declaredMethods;
public IEnumerable<IType> BaseTypes => templateInstance.BaseTypes.Value;
public IEnumerable<IProperty> Properties => declaredProperties;
public IEnumerable<IField> Fields => declaredFields;
public IEnumerable<IGenericParameter> GenericParameters => Enumerable.Empty<IGenericParameter>();
public IType Build()
{
return this;
}
public IFieldBuilder DeclareField(IFieldSignatureTemplate Template)
{
var fieldDef = new LLVMField(
this,
Template,
Template.IsStatic ? -1 : fieldCounter);
if (fieldDef.IsStatic)
{
declaredStaticFields.Add(fieldDef);
}
else
{
declaredInstanceFields.Add(fieldDef);
fieldCounter++;
}
declaredFields.Add(fieldDef);
return fieldDef;
}
public IMethodBuilder DeclareMethod(IMethodSignatureTemplate Template)
{
var methodDef = new LLVMMethod(this, Template);
declaredMethods.Add(methodDef);
if (methodDef.IsStatic && methodDef.IsConstructor)
{
declaredStaticCtors.Add(methodDef);
}
return methodDef;
}
public IPropertyBuilder DeclareProperty(IPropertySignatureTemplate Template)
{
var propDef = new LLVMProperty(this, Template);
declaredProperties.Add(propDef);
return propDef;
}
public IBoundObject GetDefaultValue()
{
return null;
}
public void Initialize()
{
this.attrMap.AddRange(templateInstance.Attributes.Value);
this.fieldCounter += this.GetIsValueType() ? 0 : 1;
}
/// <summary>
/// Defines the data layout of this type as an LLVM type.
/// </summary>
/// <param name="Module">The module to define the type in.</param>
/// <returns>An LLVM type ref for this type's data layout.</returns>
public LLVMTypeRef DefineLayout(LLVMModuleBuilder Module)
{
if (IsRuntimeImplementedDelegate)
{
return DelegateBlock.MethodTypeLayout;
}
if (this.GetIsEnum())
{
return Module.Declare(this.GetParent());
}
bool isStruct = this.GetIsValueType();
if (isStruct && IsSingleValue)
{
return Module.Declare(declaredInstanceFields[0].FieldType);
}
int offset = isStruct ? 0 : 1;
var elementTypes = new LLVMTypeRef[offset + declaredInstanceFields.Count];
if (!isStruct)
{
var baseType = this.GetParent();
if (baseType == null)
{
// Type is a root type. Embed a pointer to its vtable.
elementTypes[0] = Module.Declare(
PrimitiveTypes.UInt8.MakePointerType(
PointerKind.TransientPointer));
}
else
{
// Type is not a root type. Embed its base type.
elementTypes[0] = Module.DeclareDataLayout((LLVMType)baseType);
}
}
for (int i = 0; i < elementTypes.Length - offset; i++)
{
elementTypes[i + offset] = Module.Declare(
declaredInstanceFields[i].FieldType);
}
return StructType(elementTypes, false);
}
/// <summary>
/// The type of a vtable.
/// </summary>
/// <remarks>
/// A vtable consists of the following components:
/// 1. The type ID: a unique uint64 that is used for `is`, `as` and
/// dynamic casts.
///
/// 2. The type index: a unique uint64 that is used for interface
/// implementation lookups. The range of type indices is dense,
/// so a switch on type indices may be lowered more efficiently
/// than a switch on type IDs.
///
/// 3. A list of `virtual` and `abstract` method implementations.
/// </remarks>
public static readonly LLVMTypeRef VTableType = StructType(
new LLVMTypeRef[]
{
Int64Type(),
Int64Type(),
ArrayType(PointerType(Int8Type(), 0), 0)
},
false);
/// <summary>
/// Defines the vtable for this type.
/// </summary>
/// <param name="Module">The module to define the vtable in.</param>
/// <returns>An LLVM global for this type's vtable.</returns>
public VTableInstance DefineVTable(LLVMModuleBuilder Module)
{
var allEntries = new List<LLVMMethod>();
GetAllVTableEntries(allEntries);
return new VTableInstance(
DefineVTableGlobal(
Module,
this,
GetVTableEntryImpls(Module, allEntries)), allEntries);
}
/// <summary>
/// Defines the global variable that backs a vtable.
/// </summary>
/// <param name="Module">The module to declare the global in.</param>
/// <param name="Type">The type that owns the vtable.</param>
/// <param name="VTableEntryImpls">
/// The list of virtual function pointers in the vtable.
/// </param>
/// <returns>A vtable global variable.</returns>
public static LLVMValueRef DefineVTableGlobal(
LLVMModuleBuilder Module,
IType Type,
LLVMValueRef[] VTableEntryImpls)
{
var fields = new LLVMValueRef[3];
fields[0] = ConstInt(Int64Type(), Module.GetTypeId(Type), false);
fields[1] = ConstInt(Int64Type(), Module.GetTypeIndex(Type), false);
fields[2] = ConstArray(
PointerType(Int8Type(), 0),
VTableEntryImpls);
var vtableContents = ConstStruct(fields, false);
var vtable = Module.DeclareGlobal(
vtableContents.TypeOf(),
Type.FullName.ToString() + ".vtable");
vtable.SetGlobalConstant(true);
vtable.SetLinkage(LLVMLinkage.LLVMInternalLinkage);
vtable.SetInitializer(vtableContents);
return vtable;
}
private void GetAllVTableEntries(List<LLVMMethod> Results)
{
var parent = this.GetParent() as LLVMType;
if (parent != null)
{
parent.GetAllVTableEntries(Results);
}
Results.AddRange(RelativeVTable.Entries);
}
private LLVMValueRef[] GetVTableEntryImpls(
LLVMModuleBuilder Module,
List<LLVMMethod> AllEntries)
{
var allImpls = new LLVMValueRef[AllEntries.Count];
for (int i = 0; i < allImpls.Length; i++)
{
allImpls[i] = ConstBitCast(
Module.DeclareVirtual(AllEntries[i].GetImplementation(this) ?? AllEntries[i]),
PointerType(Int8Type(), 0));
}
return allImpls;
}
/// <summary>
/// Writes this type's definitions to the given module.
/// </summary>
/// <param name="Module">The module to populate.</param>
public void Emit(LLVMModuleBuilder Module)
{
foreach (var method in declaredMethods)
{
method.Emit(Module);
}
foreach (var property in declaredProperties)
{
property.Emit(Module);
}
}
public override string ToString()
{
return FullName.ToString();
}
}
/// <summary>
/// A data structure that manages a type's virtual function table slots.
/// </summary>
public sealed class VTableSlots
{
public VTableSlots()
{
this.slots = new Dictionary<LLVMMethod, int>();
this.contents = new List<LLVMMethod>();
}
private Dictionary<LLVMMethod, int> slots;
private List<LLVMMethod> contents;
/// <summary>
/// Gets the entries in this vtable.
/// </summary>
/// <returns>The vtable entries.</returns>
public IReadOnlyList<LLVMMethod> Entries => contents;
/// <summary>
/// Creates a relative vtable slot for the given method.
/// </summary>
/// <param name="Method">The method to create a vtable slot for.</param>
/// <returns>A vtable slot.</returns>
public int CreateRelativeSlot(LLVMMethod Method)
{
int slot = contents.Count;
contents.Add(Method);
slots.Add(Method, slot);
return slot;
}
/// <summary>
/// Gets the relative vtable slot for the given method.
/// </summary>
/// <param name="Method">The method to get a vtable slot for.</param>
/// <returns>A vtable slot.</returns>
public int GetRelativeSlot(LLVMMethod Method)
{
return slots[Method];
}
}
/// <summary>
/// Describes a vtable instance: a concrete vtable for a specific class.
/// </summary>
public sealed class VTableInstance
{
public VTableInstance(LLVMValueRef Pointer, IReadOnlyList<LLVMMethod> Entries)
{
this.Pointer = Pointer;
this.absSlots = new Dictionary<LLVMMethod, int>();
for (int i = 0; i < Entries.Count; i++)
{
this.absSlots[Entries[i]] = i;
}
}
/// <summary>
/// Gets a pointer to the vtable.
/// </summary>
/// <returns>A pointer to the vtable.</returns>
public LLVMValueRef Pointer { get; private set; }
private Dictionary<LLVMMethod, int> absSlots;
/// <summary>
/// Gets the absolute vtable slot for the given method.
/// </summary>
/// <param name="Method">The method to get the absolute vtable slot for.</param>
/// <returns>An absolute vtable slot.</returns>
public int GetAbsoluteSlot(LLVMMethod Method)
{
int slot;
if (!absSlots.TryGetValue(Method, out slot))
{
slot = GetAbsoluteSlot(Method.ParentMethod);
absSlots[Method] = slot;
}
return slot;
}
}
}
| |
// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: Chris Seeley
using Google.Api.Ads.Common.Lib;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Google.Api.Ads.Dfp.Lib {
/// <summary>
/// Lists all the services available through this library.
/// </summary>
public partial class DfpService : AdsService {
/// <summary>
/// All the services available in v201505.
/// </summary>
public class v201505 {
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ActivityGroupService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityGroupService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ActivityService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ActivityService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/AdExclusionRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdExclusionRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/AdRuleService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AdRuleService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/BaseRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature BaseRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ContactService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContactService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/AudienceSegmentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature AudienceSegmentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/CompanyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature CompanyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ContentService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ContentMetadataKeyHierarchyService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ContentMetadataKeyHierarchyService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/CreativeService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/CreativeSetService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeSetService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/CreativeTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/CreativeWrapperService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CreativeWrapperService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/CustomFieldService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomFieldService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/CustomTargetingService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature CustomTargetingService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ExchangeRateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ExchangeRateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ForecastService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ForecastService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/InventoryService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature InventoryService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/LabelService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LabelService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/LineItemTemplateService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemTemplateService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/LineItemService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/LineItemCreativeAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LineItemCreativeAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/LiveStreamEventService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature LiveStreamEventService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/NetworkService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature NetworkService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/OrderService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature OrderService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/PackageService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature PackageService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ProductPackageItemService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ProductPackageItemService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ProductPackageService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ProductPackageService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/PlacementService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PlacementService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/PremiumRateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PremiumRateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ProductService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ProductTemplateService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProductTemplateService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ProposalService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ProposalLineItemService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature ProposalLineItemService;
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/PublisherQueryLanguageService">
/// this page </a> for details.
/// </summary>
public static readonly ServiceSignature PublisherQueryLanguageService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/RateCardService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature RateCardService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ReconciliationOrderReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationOrderReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ReconciliationReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ReconciliationReportRowService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReconciliationReportRowService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/ReportService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature ReportService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/SharedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SharedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/SuggestedAdUnitService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature SuggestedAdUnitService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/TeamService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature TeamService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/UserService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/UserTeamAssociationService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature UserTeamAssociationService;
/// <summary>
/// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v201505/WorkflowRequestService">
/// this page</a> for details.
/// </summary>
public static readonly ServiceSignature WorkflowRequestService;
/// <summary>
/// Factory type for v201505 services.
/// </summary>
public static readonly Type factoryType = typeof(DfpServiceFactory);
/// <summary>
/// Static constructor to initialize the service constants.
/// </summary>
static v201505() {
ActivityGroupService = DfpService.MakeServiceSignature("v201505", "ActivityGroupService");
ActivityService = DfpService.MakeServiceSignature("v201505", "ActivityService");
AdExclusionRuleService = DfpService.MakeServiceSignature("v201505", "AdExclusionRuleService");
AdRuleService = DfpService.MakeServiceSignature("v201505", "AdRuleService");
BaseRateService = DfpService.MakeServiceSignature("v201505", "BaseRateService");
ContactService = DfpService.MakeServiceSignature("v201505", "ContactService");
AudienceSegmentService = DfpService.MakeServiceSignature("v201505",
"AudienceSegmentService");
CompanyService = DfpService.MakeServiceSignature("v201505", "CompanyService");
ContentService = DfpService.MakeServiceSignature("v201505", "ContentService");
ContentMetadataKeyHierarchyService = DfpService.MakeServiceSignature("v201505",
"ContentMetadataKeyHierarchyService");
CreativeService = DfpService.MakeServiceSignature("v201505", "CreativeService");
CreativeSetService = DfpService.MakeServiceSignature("v201505", "CreativeSetService");
CreativeTemplateService = DfpService.MakeServiceSignature("v201505",
"CreativeTemplateService");
CreativeWrapperService = DfpService.MakeServiceSignature("v201505",
"CreativeWrapperService");
CustomTargetingService = DfpService.MakeServiceSignature("v201505",
"CustomTargetingService");
CustomFieldService = DfpService.MakeServiceSignature("v201505",
"CustomFieldService");
ExchangeRateService = DfpService.MakeServiceSignature("v201505", "ExchangeRateService");
ForecastService = DfpService.MakeServiceSignature("v201505", "ForecastService");
InventoryService = DfpService.MakeServiceSignature("v201505", "InventoryService");
LabelService = DfpService.MakeServiceSignature("v201505", "LabelService");
LineItemTemplateService = DfpService.MakeServiceSignature("v201505",
"LineItemTemplateService");
LineItemService = DfpService.MakeServiceSignature("v201505", "LineItemService");
LineItemCreativeAssociationService =
DfpService.MakeServiceSignature("v201505", "LineItemCreativeAssociationService");
LiveStreamEventService = DfpService.MakeServiceSignature("v201505",
"LiveStreamEventService");
NetworkService = DfpService.MakeServiceSignature("v201505", "NetworkService");
OrderService = DfpService.MakeServiceSignature("v201505", "OrderService");
PackageService = DfpService.MakeServiceSignature("v201505", "PackageService");
ProductPackageService = DfpService.MakeServiceSignature("v201505", "ProductPackageService");
ProductPackageItemService = DfpService.MakeServiceSignature("v201505", "ProductPackageItemService");
PlacementService = DfpService.MakeServiceSignature("v201505", "PlacementService");
PremiumRateService = DfpService.MakeServiceSignature("v201505", "PremiumRateService");
ProductService = DfpService.MakeServiceSignature("v201505", "ProductService");
ProductTemplateService = DfpService.MakeServiceSignature("v201505",
"ProductTemplateService");
ProposalService = DfpService.MakeServiceSignature("v201505", "ProposalService");
ProposalLineItemService = DfpService.MakeServiceSignature("v201505",
"ProposalLineItemService");
PublisherQueryLanguageService = DfpService.MakeServiceSignature("v201505",
"PublisherQueryLanguageService");
RateCardService = DfpService.MakeServiceSignature("v201505", "RateCardService");
ReconciliationOrderReportService = DfpService.MakeServiceSignature("v201505",
"ReconciliationOrderReportService");
ReconciliationReportService = DfpService.MakeServiceSignature("v201505",
"ReconciliationReportService");
ReconciliationReportRowService = DfpService.MakeServiceSignature("v201505",
"ReconciliationReportRowService");
ReportService = DfpService.MakeServiceSignature("v201505", "ReportService");
SharedAdUnitService = DfpService.MakeServiceSignature("v201505",
"SharedAdUnitService");
SuggestedAdUnitService = DfpService.MakeServiceSignature("v201505",
"SuggestedAdUnitService");
TeamService = DfpService.MakeServiceSignature("v201505", "TeamService");
UserService = DfpService.MakeServiceSignature("v201505", "UserService");
UserTeamAssociationService = DfpService.MakeServiceSignature("v201505",
"UserTeamAssociationService");
WorkflowRequestService = DfpService.MakeServiceSignature("v201505",
"WorkflowRequestService");
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Physics;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers
{
/// <summary>
/// SurfaceMagnetism casts rays to Surfaces in the world align the object to the surface.
/// </summary>
public class SurfaceMagnetism : Solver
{
private const float MaxDot = 0.97f;
private enum RaycastDirectionEnum
{
CameraFacing,
ToObject,
ToLinkedPosition
}
private enum OrientModeEnum
{
None,
Vertical,
Full,
Blended
}
[SerializeField]
[Tooltip("LayerMask to apply Surface Magnetism to")]
private LayerMask[] magneticSurfaces = { UnityEngine.Physics.DefaultRaycastLayers };
[SerializeField]
[Tooltip("Max distance to check for surfaces")]
private float maxDistance = 3.0f;
[SerializeField]
[Tooltip("Closest distance to bring object")]
private float closeDistance = 0.5f;
[SerializeField]
[Tooltip("Offset from surface along surface normal")]
private float surfaceNormalOffset = 0.5f;
[SerializeField]
[Tooltip("Offset from surface along ray cast direction")]
private float surfaceRayOffset = 0;
[SerializeField]
[Tooltip("Surface raycast mode")]
private SceneQueryType raycastMode = SceneQueryType.SimpleRaycast;
[SerializeField]
[Tooltip("Number of rays per edge, should be odd. Total casts is n^2")]
private int boxRaysPerEdge = 3;
[SerializeField]
[Tooltip("If true, use orthographic casting for box lines instead of perspective")]
private bool orthographicBoxCast = false;
[SerializeField]
[Tooltip("Align to ray cast direction if box cast hits many normals facing in varying directions")]
private float maximumNormalVariance = 0.5f;
[SerializeField]
[Tooltip("Radius to use for sphere cast")]
private float sphereSize = 1.0f;
[SerializeField]
[Tooltip("When doing volume casts, use size override if non-zero instead of object's current scale")]
private float volumeCastSizeOverride = 0;
[SerializeField]
[Tooltip("When doing volume casts, use linked AltScale instead of object's current scale")]
private bool useLinkedAltScaleOverride = false;
[SerializeField]
[Tooltip("Raycast direction. Can cast from head in facing direction, or cast from head to object position")]
private RaycastDirectionEnum raycastDirection = RaycastDirectionEnum.ToLinkedPosition;
[SerializeField]
[Tooltip("Orientation mode. None = no orienting, Vertical = Face head, but always oriented up/down, Full = Aligned to surface normal completely")]
private OrientModeEnum orientationMode = OrientModeEnum.Vertical;
[SerializeField]
[Tooltip("Orientation Blend Value 0.0 = All head 1.0 = All surface")]
private float orientationBlend = 0.65f;
[SerializeField]
[Tooltip("If enabled, the debug lines will be drawn in the editor")]
private bool debugEnabled = false;
/// <summary>
/// Whether or not the object is currently magnetized to a surface.
/// </summary>
public bool OnSurface { get; private set; }
private BoxCollider boxCollider;
private Vector3 RaycastOrigin => SolverHandler.TransformTarget == null ? Vector3.zero : SolverHandler.TransformTarget.position;
/// <summary>
/// Which point should the ray cast toward? Not really the 'end' of the ray. The ray may be cast along
/// the head facing direction, from the eye to the object, or to the solver's linked position (working from
/// the previous solvers)
/// </summary>
private Vector3 RaycastEndPoint
{
get
{
Vector3 origin = RaycastOrigin;
Vector3 endPoint = Vector3.forward;
switch (raycastDirection)
{
case RaycastDirectionEnum.CameraFacing:
endPoint = SolverHandler.TransformTarget.position + SolverHandler.TransformTarget.forward;
break;
case RaycastDirectionEnum.ToObject:
endPoint = transform.position;
break;
case RaycastDirectionEnum.ToLinkedPosition:
endPoint = SolverHandler.GoalPosition;
break;
}
return endPoint;
}
}
/// <summary>
/// Calculate the raycast direction based on the two ray points
/// </summary>
private Vector3 RaycastDirection
{
get
{
Vector3 direction = Vector3.forward;
if (raycastDirection == RaycastDirectionEnum.CameraFacing)
{
if (SolverHandler.TransformTarget != null)
{
direction = SolverHandler.TransformTarget.forward;
}
}
else
{
direction = (RaycastEndPoint - RaycastOrigin).normalized;
}
return direction;
}
}
/// <summary>
/// A constant scale override may be specified for volumetric raycasts, otherwise uses the current value of the solver link's alt scale
/// </summary>
private float ScaleOverride => useLinkedAltScaleOverride ? SolverHandler.AltScale.Current.magnitude : volumeCastSizeOverride;
protected override void OnValidate()
{
base.OnValidate();
if (raycastMode == SceneQueryType.BoxRaycast)
{
boxCollider = gameObject.GetComponent<BoxCollider>();
if (boxCollider == null)
{
Debug.LogError($"Box raycast mode requires a BoxCollider, but none was found on {name}! Please add one.");
}
}
}
private void Start()
{
if (raycastMode == SceneQueryType.BoxRaycast && boxCollider == null)
{
boxCollider = gameObject.GetComponent<BoxCollider>();
if (boxCollider == null)
{
Debug.LogError($"Box raycast mode requires a BoxCollider, but none was found on {name}! Defaulting to Simple raycast mode.");
raycastMode = SceneQueryType.SimpleRaycast;
}
}
}
/// <summary>
/// Calculates how the object should orient to the surface. May be none to pass shared orientation through,
/// oriented to the surface but fully vertical, fully oriented to the surface normal, or a slerped blend
/// of the vertical orientation and the pass-through rotation.
/// </summary>
/// <param name="direction"></param>
/// <param name="surfaceNormal"></param>
/// <returns>Quaternion, the orientation to use for the object</returns>
private Quaternion CalculateMagnetismOrientation(Vector3 direction, Vector3 surfaceNormal)
{
// Calculate the surface rotation
Vector3 newDirection = -surfaceNormal;
if (IsNormalVertical(newDirection))
{
newDirection = direction;
}
newDirection.y = 0;
var surfaceRot = Quaternion.LookRotation(newDirection, Vector3.up);
switch (orientationMode)
{
case OrientModeEnum.None:
return SolverHandler.GoalRotation;
case OrientModeEnum.Vertical:
return surfaceRot;
case OrientModeEnum.Full:
return Quaternion.LookRotation(-surfaceNormal, Vector3.up);
case OrientModeEnum.Blended:
return Quaternion.Slerp(SolverHandler.GoalRotation, surfaceRot, orientationBlend);
default:
return Quaternion.identity;
}
}
/// <summary>
/// Checks if a normal is nearly vertical
/// </summary>
/// <param name="normal"></param>
/// <returns>Returns true, if normal is vertical.</returns>
private static bool IsNormalVertical(Vector3 normal) => 1f - Mathf.Abs(normal.y) < 0.01f;
public override void SolverUpdate()
{
// Pass-through by default
GoalPosition = WorkingPosition;
GoalRotation = WorkingRotation;
// Determine raycast params
var rayStep = new RayStep(RaycastOrigin, RaycastEndPoint);
// Skip if there isn't a valid direction
if (rayStep.Direction == Vector3.zero)
{
return;
}
switch (raycastMode)
{
case SceneQueryType.SimpleRaycast:
SimpleRaycastStepUpdate(rayStep);
break;
case SceneQueryType.BoxRaycast:
BoxRaycastStepUpdate(rayStep);
break;
case SceneQueryType.SphereCast:
SphereRaycastStepUpdate(rayStep);
break;
}
// Do frame to frame updates of transform, smoothly toward the goal, if desired
UpdateWorkingPositionToGoal();
UpdateWorkingRotationToGoal();
}
private void SimpleRaycastStepUpdate(RayStep rayStep)
{
bool isHit;
RaycastHit result;
// Do the cast!
isHit = MixedRealityRaycaster.RaycastSimplePhysicsStep(rayStep, maxDistance, magneticSurfaces, out result);
OnSurface = isHit;
// Enforce CloseDistance
Vector3 hitDelta = result.point - rayStep.Origin;
float length = hitDelta.magnitude;
if (length < closeDistance)
{
result.point = rayStep.Origin + rayStep.Direction * closeDistance;
}
// Apply results
if (isHit)
{
GoalPosition = result.point + surfaceNormalOffset * result.normal + surfaceRayOffset * rayStep.Direction;
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, result.normal);
}
}
private void SphereRaycastStepUpdate(RayStep rayStep)
{
bool isHit;
RaycastHit result;
float scaleOverride = ScaleOverride;
// Do the cast!
float size = scaleOverride > 0 ? scaleOverride : transform.lossyScale.x * sphereSize;
isHit = MixedRealityRaycaster.RaycastSpherePhysicsStep(rayStep, size, maxDistance, magneticSurfaces, out result);
OnSurface = isHit;
// Enforce CloseDistance
Vector3 hitDelta = result.point - rayStep.Origin;
float length = hitDelta.magnitude;
if (length < closeDistance)
{
result.point = rayStep.Origin + rayStep.Direction * closeDistance;
}
// Apply results
if (isHit)
{
GoalPosition = result.point + surfaceNormalOffset * result.normal + surfaceRayOffset * rayStep.Direction;
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, result.normal);
}
}
private void BoxRaycastStepUpdate(RayStep rayStep)
{
Vector3 scale = transform.lossyScale;
float scaleOverride = ScaleOverride;
if (scaleOverride > 0)
{
scale = scale.normalized * scaleOverride;
}
Quaternion orientation = orientationMode == OrientModeEnum.None ?
Quaternion.LookRotation(rayStep.Direction, Vector3.up) :
CalculateMagnetismOrientation(rayStep.Direction, Vector3.up);
Matrix4x4 targetMatrix = Matrix4x4.TRS(Vector3.zero, orientation, scale);
if (boxCollider == null)
{
boxCollider = GetComponent<BoxCollider>();
}
Debug.Assert(boxCollider != null, $"Missing a box collider for Surface Magnetism on {gameObject}");
Vector3 extents = boxCollider.size;
Vector3[] positions;
Vector3[] normals;
bool[] hits;
if (MixedRealityRaycaster.RaycastBoxPhysicsStep(rayStep, extents, transform.position, targetMatrix, maxDistance, magneticSurfaces, boxRaysPerEdge, orthographicBoxCast, out positions, out normals, out hits))
{
Plane plane;
float distance;
// Place an unconstrained plane down the ray. Don't use vertical constrain.
FindPlacementPlane(rayStep.Origin, rayStep.Direction, positions, normals, hits, boxCollider.size.x, maximumNormalVariance, false, orientationMode == OrientModeEnum.None, out plane, out distance);
// If placing on a horizontal surface, need to adjust the calculated distance by half the app height
float verticalCorrectionOffset = 0;
if (IsNormalVertical(plane.normal) && !Mathf.Approximately(rayStep.Direction.y, 0))
{
float boxSurfaceVerticalOffset = targetMatrix.MultiplyVector(new Vector3(0, extents.y * 0.5f, 0)).magnitude;
Vector3 correctionVector = boxSurfaceVerticalOffset * (rayStep.Direction / rayStep.Direction.y);
verticalCorrectionOffset = -correctionVector.magnitude;
}
float boxSurfaceOffset = targetMatrix.MultiplyVector(new Vector3(0, 0, extents.z * 0.5f)).magnitude;
// Apply boxSurfaceOffset to ray direction and not surface normal direction to reduce sliding
GoalPosition = rayStep.Origin + rayStep.Direction * Mathf.Max(closeDistance, distance + surfaceRayOffset + boxSurfaceOffset + verticalCorrectionOffset) + plane.normal * (0 * boxSurfaceOffset + surfaceNormalOffset);
GoalRotation = CalculateMagnetismOrientation(rayStep.Direction, plane.normal);
OnSurface = true;
}
else
{
OnSurface = false;
}
}
/// <summary>
/// Calculates a plane from all raycast hit locations upon which the object may align. Used in Box Raycast Mode.
/// </summary>
/// <param name="origin"></param>
/// <param name="direction"></param>
/// <param name="positions"></param>
/// <param name="normals"></param>
/// <param name="hits"></param>
/// <param name="assetWidth"></param>
/// <param name="maxNormalVariance"></param>
/// <param name="constrainVertical"></param>
/// <param name="useClosestDistance"></param>
/// <param name="plane"></param>
/// <param name="closestDistance"></param>
private void FindPlacementPlane(Vector3 origin, Vector3 direction, Vector3[] positions, Vector3[] normals, bool[] hits, float assetWidth, float maxNormalVariance, bool constrainVertical, bool useClosestDistance, out Plane plane, out float closestDistance)
{
int rayCount = positions.Length;
Vector3 originalDirection = direction;
if (constrainVertical)
{
direction.y = 0.0f;
direction = direction.normalized;
}
// Go through all the points and find the closest distance
closestDistance = float.PositiveInfinity;
int numHits = 0;
int closestPoint = -1;
float farthestDistance = 0f;
var averageNormal = Vector3.zero;
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex])
{
float distance = Vector3.Dot(direction, positions[hitIndex] - origin);
if (distance < closestDistance)
{
closestPoint = hitIndex;
closestDistance = distance;
}
if (distance > farthestDistance)
{
farthestDistance = distance;
}
averageNormal += normals[hitIndex];
++numHits;
}
}
averageNormal /= numHits;
// Calculate variance of all normals
float variance = 0;
for (int hitIndex = 0; hitIndex < rayCount; ++hitIndex)
{
if (hits[hitIndex])
{
variance += (normals[hitIndex] - averageNormal).magnitude;
}
}
variance /= numHits;
// If variance is too high, I really don't want to deal with this surface
// And if we don't even have enough rays, I'm not confident about this at all
if (variance > maxNormalVariance || numHits < rayCount * 0.25f)
{
plane = new Plane(-direction, positions[closestPoint]);
return;
}
// go through all the points and find the most orthogonal plane
var lowAngle = float.PositiveInfinity;
var highAngle = float.NegativeInfinity;
int lowIndex = -1;
int highIndex = -1;
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex] == false || hitIndex == closestPoint)
{
continue;
}
Vector3 difference = positions[hitIndex] - positions[closestPoint];
if (constrainVertical)
{
difference.y = 0.0f;
difference.Normalize();
if (difference == Vector3.zero)
{
continue;
}
}
difference.Normalize();
float angle = Vector3.Dot(direction, difference);
if (angle < lowAngle)
{
lowAngle = angle;
lowIndex = hitIndex;
}
}
if (!constrainVertical && lowIndex != -1)
{
for (int hitIndex = 0; hitIndex < rayCount; hitIndex++)
{
if (hits[hitIndex] == false || hitIndex == closestPoint || hitIndex == lowIndex)
{
continue;
}
float dot = Mathf.Abs(Vector3.Dot((positions[hitIndex] - positions[closestPoint]).normalized, (positions[lowIndex] - positions[closestPoint]).normalized));
if (dot > MaxDot)
{
continue;
}
float nextAngle = Mathf.Abs(Vector3.Dot(direction, Vector3.Cross(positions[lowIndex] - positions[closestPoint], positions[hitIndex] - positions[closestPoint]).normalized));
if (nextAngle > highAngle)
{
highAngle = nextAngle;
highIndex = hitIndex;
}
}
}
Vector3 placementNormal;
if (lowIndex != -1)
{
if (debugEnabled)
{
Debug.DrawLine(positions[closestPoint], positions[lowIndex], Color.red);
}
if (highIndex != -1)
{
if (debugEnabled)
{
Debug.DrawLine(positions[closestPoint], positions[highIndex], Color.green);
}
placementNormal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], positions[highIndex] - positions[closestPoint]).normalized;
}
else
{
Vector3 planeUp = Vector3.Cross(positions[lowIndex] - positions[closestPoint], direction);
placementNormal = Vector3.Cross(positions[lowIndex] - positions[closestPoint], constrainVertical ? Vector3.up : planeUp).normalized;
}
if (debugEnabled)
{
Debug.DrawLine(positions[closestPoint], positions[closestPoint] + placementNormal, Color.blue);
}
}
else
{
placementNormal = direction * -1.0f;
}
if (Vector3.Dot(placementNormal, direction) > 0.0f)
{
placementNormal *= -1.0f;
}
plane = new Plane(placementNormal, positions[closestPoint]);
if (debugEnabled)
{
Debug.DrawRay(positions[closestPoint], placementNormal, Color.cyan);
}
// Figure out how far the plane should be.
if (!useClosestDistance && closestPoint >= 0)
{
float centerPlaneDistance;
if (plane.Raycast(new Ray(origin, originalDirection), out centerPlaneDistance) || !centerPlaneDistance.Equals(0.0f))
{
// When the plane is nearly parallel to the user, we need to clamp the distance to where the raycasts hit.
closestDistance = Mathf.Clamp(centerPlaneDistance, closestDistance, farthestDistance + assetWidth * 0.5f);
}
else
{
Debug.LogError("FindPlacementPlane: Not expected to have the center point not intersect the plane.");
}
}
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B03_Continent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="B03_Continent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class B03_Continent_ReChild : BusinessBase<B03_Continent_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int continent_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "Continent Child Name");
/// <summary>
/// Gets or sets the Continent Child Name.
/// </summary>
/// <value>The Continent Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B03_Continent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B03_Continent_ReChild"/> object.</returns>
internal static B03_Continent_ReChild NewB03_Continent_ReChild()
{
return DataPortal.CreateChild<B03_Continent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="B03_Continent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B03_Continent_ReChild"/> object.</returns>
internal static B03_Continent_ReChild GetB03_Continent_ReChild(SafeDataReader dr)
{
B03_Continent_ReChild obj = new B03_Continent_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B03_Continent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B03_Continent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B03_Continent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B03_Continent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name"));
// parent properties
continent_ID2 = dr.GetInt32("Continent_ID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B03_Continent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B02_Continent parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IB03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Continent_ID,
Continent_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B03_Continent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B02_Continent parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IB03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Continent_ID,
Continent_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="B03_Continent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B02_Continent parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IB03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gcwcv = Google.Cloud.Workflows.Common.V1;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Workflows.Executions.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedExecutionsClientTest
{
[xunit::FactAttribute]
public void CreateExecutionRequestObject()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CreateExecutionRequest request = new CreateExecutionRequest
{
ParentAsWorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Execution = new Execution(),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CreateExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.CreateExecution(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateExecutionRequestObjectAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CreateExecutionRequest request = new CreateExecutionRequest
{
ParentAsWorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Execution = new Execution(),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CreateExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.CreateExecutionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.CreateExecutionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateExecution()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CreateExecutionRequest request = new CreateExecutionRequest
{
ParentAsWorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Execution = new Execution(),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CreateExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.CreateExecution(request.Parent, request.Execution);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateExecutionAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CreateExecutionRequest request = new CreateExecutionRequest
{
ParentAsWorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Execution = new Execution(),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CreateExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.CreateExecutionAsync(request.Parent, request.Execution, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.CreateExecutionAsync(request.Parent, request.Execution, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateExecutionResourceNames()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CreateExecutionRequest request = new CreateExecutionRequest
{
ParentAsWorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Execution = new Execution(),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CreateExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.CreateExecution(request.ParentAsWorkflowName, request.Execution);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateExecutionResourceNamesAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CreateExecutionRequest request = new CreateExecutionRequest
{
ParentAsWorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Execution = new Execution(),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CreateExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.CreateExecutionAsync(request.ParentAsWorkflowName, request.Execution, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.CreateExecutionAsync(request.ParentAsWorkflowName, request.Execution, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetExecutionRequestObject()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
GetExecutionRequest request = new GetExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
View = ExecutionView.Basic,
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.GetExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.GetExecution(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetExecutionRequestObjectAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
GetExecutionRequest request = new GetExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
View = ExecutionView.Basic,
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.GetExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.GetExecutionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.GetExecutionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetExecution()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
GetExecutionRequest request = new GetExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.GetExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.GetExecution(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetExecutionAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
GetExecutionRequest request = new GetExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.GetExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.GetExecutionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.GetExecutionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetExecutionResourceNames()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
GetExecutionRequest request = new GetExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.GetExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.GetExecution(request.ExecutionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetExecutionResourceNamesAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
GetExecutionRequest request = new GetExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.GetExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.GetExecutionAsync(request.ExecutionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.GetExecutionAsync(request.ExecutionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelExecutionRequestObject()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CancelExecutionRequest request = new CancelExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CancelExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.CancelExecution(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelExecutionRequestObjectAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CancelExecutionRequest request = new CancelExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CancelExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.CancelExecutionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.CancelExecutionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelExecution()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CancelExecutionRequest request = new CancelExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CancelExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.CancelExecution(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelExecutionAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CancelExecutionRequest request = new CancelExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CancelExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.CancelExecutionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.CancelExecutionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CancelExecutionResourceNames()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CancelExecutionRequest request = new CancelExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CancelExecution(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution response = client.CancelExecution(request.ExecutionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CancelExecutionResourceNamesAsync()
{
moq::Mock<Executions.ExecutionsClient> mockGrpcClient = new moq::Mock<Executions.ExecutionsClient>(moq::MockBehavior.Strict);
CancelExecutionRequest request = new CancelExecutionRequest
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
};
Execution expectedResponse = new Execution
{
ExecutionName = ExecutionName.FromProjectLocationWorkflowExecution("[PROJECT]", "[LOCATION]", "[WORKFLOW]", "[EXECUTION]"),
StartTime = new wkt::Timestamp(),
EndTime = new wkt::Timestamp(),
State = Execution.Types.State.Failed,
Argument = "argument60e0cd03",
Result = "result1784a8b4",
Error = new Execution.Types.Error(),
WorkflowRevisionId = "workflow_revision_id3b9c4f02",
CallLogLevel = Execution.Types.CallLogLevel.LogAllCalls,
};
mockGrpcClient.Setup(x => x.CancelExecutionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Execution>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ExecutionsClient client = new ExecutionsClientImpl(mockGrpcClient.Object, null);
Execution responseCallSettings = await client.CancelExecutionAsync(request.ExecutionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Execution responseCancellationToken = await client.CancelExecutionAsync(request.ExecutionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
/* ====================================================================
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 is1 distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Record.Chart
{
using System;
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.SS.Formula;
using NPOI.HSSF.Record.Chart;
using NUnit.Framework;
using NPOI.SS.Formula.PTG;
/**
* Tests the serialization and deserialization of the LinkedDataRecord
* class works correctly. Test data taken directly from a real
* Excel file.
*
* @author Glen Stampoultzis (glens at apache.org)
*/
[TestFixture]
public class TestLinkedDataRecord
{
/*
The records below are records that would appear in a simple bar chart
The first record links to the series title (linkType = 0). It's
reference type is1 1 which means that it links directly to data entered
into the forumula bar. There seems to be no reference to any data
however. The formulaOfLink field contains two 0 bytes. This probably
means that there is1 no particular heading Set.
============================================
OffSet 0xf9c (3996)
rectype = 0x1051, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 00 01 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1051, size =8
[AI]
.linkType = 0x00 (0 )
.referenceType = 0x01 (1 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@95fd19 )
[/AI]
The second record links to the series data (linkType=1). The
referenceType = 2 which means it's linked to the worksheet.
It links using a formula. The formula value is
0B 00 3B 00 00 00 00 1E 00 01 00 01 00.
0B 00 11 bytes length
3B (tArea3d) Rectangular area
00 00 index to REF entry in extern sheet
00 00 index to first row
1E 00 index to last row
01 00 index to first column and relative flags
01 00 index to last column and relative flags
============================================
OffSet 0xfa8 (4008)
rectype = 0x1051, recsize = 0x13
-BEGIN DUMP---------------------------------
00000000 01 02 00 00 00 00 0B 00 3B 00 00 00 00 1E 00 01 ........;.......
00000010 00 01 00 ...
-END DUMP-----------------------------------
recordid = 0x1051, size =19
[AI]
.linkType = 0x01 (1 )
.referenceType = 0x02 (2 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@11b9fb1 )
[/AI]
The third record links to the series categories (linkType=2). The
reference type of 2 means that it's linked to the worksheet.
It links using a formula. The formula value is
0B 00 3B 00 00 00 00 1E 00 01 00 01 00
0B 00 11 bytes in length
3B (tArea3d) Rectangular area
00 00 index to REF entry in extern sheet
00 00 index to first row
00 1F index to last row
00 00 index to first column and relative flags
00 00 index to last column and relative flags
============================================
OffSet 0xfbf (4031)
rectype = 0x1051, recsize = 0x13
-BEGIN DUMP---------------------------------
00000000 02 02 00 00 69 01 0B 00 3B 00 00 00 00 1F 00 00 ....i...;.......
00000010 00 00 00 ...
-END DUMP-----------------------------------
recordid = 0x1051, size =19
[AI]
.linkType = 0x02 (2 )
.referenceType = 0x02 (2 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0169 (361 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@913fe2 )
[/AI]
This third link type does not seem to be documented and does not appear to
contain any useful information anyway.
============================================
OffSet 0xfd6 (4054)
rectype = 0x1051, recsize = 0x8
-BEGIN DUMP---------------------------------
00000000 03 01 00 00 00 00 00 00 ........
-END DUMP-----------------------------------
recordid = 0x1051, size =8
[AI]
.linkType = 0x03 (3 )
.referenceType = 0x01 (1 )
.options = 0x0000 (0 )
.customNumberFormat = false
.indexNumberFmtRecord = 0x0000 (0 )
.formulaOfLink = (org.apache.poi.hssf.record.LinkedDataFormulaField@1f934ad )
[/AI]
*/
byte[] data = new byte[]{
(byte)0x01, // link type
(byte)0x02, // reference type
(byte)0x00,(byte)0x00, // options
(byte)0x00,(byte)0x00, // index number format record
(byte)0x0B,(byte)0x00, // 11 bytes length
(byte)0x3B, // formula of link
(byte)0x00,(byte)0x00, // index to ref entry in extern sheet
(byte)0x00,(byte)0x00, // index to first row
(byte)0x00,(byte)0x1F, // index to last row
(byte)0x00,(byte)0x00, // index to first column and relative flags
(byte)0x00,(byte)0x00, // index to last column and relative flags
};
public TestLinkedDataRecord()
{
}
[Test]
public void TestLoad()
{
LinkedDataRecord record = new LinkedDataRecord(TestcaseRecordInputStream.Create((short)0x1051, data));
Assert.AreEqual(LinkedDataRecord.LINK_TYPE_VALUES, record.LinkType);
Assert.AreEqual(LinkedDataRecord.REFERENCE_TYPE_WORKSHEET, record.ReferenceType);
Assert.AreEqual(0, record.Options);
Assert.AreEqual(false, record.IsCustomNumberFormat);
Assert.AreEqual(0, record.IndexNumberFmtRecord);
Area3DPtg ptgExpected = new Area3DPtg(0, 7936, 0, 0,false, false, false, false, 0);
Object ptgActual = record.FormulaOfLink[0];
Assert.AreEqual(ptgExpected.ToString(), ptgActual.ToString());
Assert.AreEqual(data.Length + 4, record.RecordSize);
}
[Test]
public void TestStore()
{
LinkedDataRecord record = new LinkedDataRecord();
record.LinkType=(LinkedDataRecord.LINK_TYPE_VALUES);
record.ReferenceType=(LinkedDataRecord.REFERENCE_TYPE_WORKSHEET);
record.Options=((short)0);
record.IsCustomNumberFormat=(false);
record.IndexNumberFmtRecord=((short)0);
Area3DPtg ptg = new Area3DPtg(0, 7936, 0, 0,
false, false, false, false, 0);
record.FormulaOfLink = (new Ptg[] { ptg, });
byte[] recordBytes = record.Serialize();
Assert.AreEqual(recordBytes.Length - 4, data.Length);
for (int i = 0; i < data.Length; i++)
Assert.AreEqual(data[i], recordBytes[i + 4], "At offset " + i);
}
}
}
| |
namespace Nancy.Tests.Unit.ViewEngines
{
using System;
using System.Dynamic;
using System.IO;
using System.Linq;
using FakeItEasy;
using Nancy.Conventions;
using Nancy.Diagnostics;
using Nancy.Tests.Fakes;
using Nancy.ViewEngines;
using Xunit;
public class DefaultViewFactoryFixture
{
private readonly IViewResolver resolver;
private readonly IRenderContextFactory renderContextFactory;
private readonly ViewLocationContext viewLocationContext;
private readonly ViewLocationConventions conventions;
private readonly IRootPathProvider rootPathProvider;
public DefaultViewFactoryFixture()
{
this.rootPathProvider = A.Fake<IRootPathProvider>();
A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns("The root path");
this.resolver = A.Fake<IViewResolver>();
this.renderContextFactory = A.Fake<IRenderContextFactory>();
this.conventions = new ViewLocationConventions(Enumerable.Empty<Func<string, object, ViewLocationContext, string>>());
this.viewLocationContext =
new ViewLocationContext
{
Context = new NancyContext
{
Trace = new DefaultRequestTrace
{
TraceLog = new DefaultTraceLog()
}
}
};
}
private DefaultViewFactory CreateFactory(params IViewEngine[] viewEngines)
{
if (viewEngines == null)
{
viewEngines = ArrayCache.Empty<IViewEngine>();
}
return new DefaultViewFactory(this.resolver, viewEngines, this.renderContextFactory, this.conventions, this.rootPathProvider);
}
[Fact]
public void Should_get_render_context_from_factory_when_rendering_view()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("view.html", new object(), this.viewLocationContext);
// Then
A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_render_view_with_context_created_by_factory()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var context = A.Fake<IRenderContext>();
A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).Returns(context);
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("view.html", new object(), this.viewLocationContext);
// Then
A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, A<object>.Ignored, context)).MustHaveHappened();
}
[Fact]
public void Should_not_build_render_context_more_than_once()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("view.html", new object(), this.viewLocationContext);
// Then
A.CallTo(() => this.renderContextFactory.GetRenderContext(A<ViewLocationContext>.Ignored)).MustHaveHappenedOnceOrLess();
}
[Fact]
public void Should_throw_argumentnullexception_when_rendering_view_and_viewlocationcontext_is_null()
{
// Given
var factory = this.CreateFactory(null);
// When
var exception = Record.Exception(() => factory.RenderView("viewName", new object(), null));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_throw_argumentexception_when_rendering_view_and_view_name_is_empty_and_model_is_null()
{
// Given
var factory = this.CreateFactory(null);
// When
var exception = Record.Exception(() => factory.RenderView(string.Empty, null, this.viewLocationContext));
// Then
exception.ShouldBeOfType<ArgumentException>();
}
[Fact]
public void Should_throw_argumentexception_when_rendering_view_and_both_viewname_and_model_is_null()
{
// Given
var factory = this.CreateFactory(null);
// When
var exception = Record.Exception(() => factory.RenderView(null, null, this.viewLocationContext));
// Then
exception.ShouldBeOfType<ArgumentException>();
}
[Fact]
public void Should_retrieve_view_from_view_locator_using_provided_view_name()
{
// Given
var factory = this.CreateFactory();
// When
Record.Exception(() => factory.RenderView("viewname.html", null, this.viewLocationContext));
// Then
A.CallTo(() => this.resolver.GetViewLocation("viewname.html", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_retrieve_view_from_view_locator_using_provided_model()
{
// Given
var factory = this.CreateFactory();
var model = new object();
// When
Record.Exception(() => factory.RenderView(null, model, this.viewLocationContext));
// Then
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, model, A<ViewLocationContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_retrieve_view_from_view_locator_using_provided_module_path()
{
// Given
var factory = this.CreateFactory();
var model = new object();
var viewContext =
new ViewLocationContext
{
Context = new NancyContext
{
Trace = new DefaultRequestTrace
{
TraceLog = new DefaultTraceLog()
}
},
ModulePath = "/bar"
};
// When
Record.Exception(() => factory.RenderView(null, model, viewContext));
// Then
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.That.Matches(x => x.ModulePath.Equals("/bar")))).MustHaveHappened();
}
[Fact]
public void Should_call_first_view_engine_that_supports_extension_with_view_location_results()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "html" });
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("foo", null, this.viewLocationContext);
// Then
A.CallTo(() => viewEngines[0].RenderView(location, null, A<IRenderContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_ignore_case_when_locating_view_engine_for_view_name_extension()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "HTML" });
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("foo", null, this.viewLocationContext);
// Then
A.CallTo(() => viewEngines[0].RenderView(location, null, A<IRenderContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_return_response_from_invoked_engine()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
Action<Stream> actionReturnedFromEngine = x => { };
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, A<IRenderContext>.Ignored)).Returns(actionReturnedFromEngine);
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var factory = this.CreateFactory(viewEngines);
// When
var response = factory.RenderView("foo", null, this.viewLocationContext);
// Then
response.Contents.ShouldBeSameAs(actionReturnedFromEngine);
}
[Fact]
public void Should_return_empty_action_when_view_engine_throws_exception()
{
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, A<IRenderContext>.Ignored)).Throws(new Exception());
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var stream = new MemoryStream();
var factory = this.CreateFactory(viewEngines);
// When
var response = factory.RenderView("foo", null, this.viewLocationContext);
response.Contents.Invoke(stream);
// Then
stream.Length.ShouldEqual(0L);
}
[Fact]
public void Should_invoke_view_engine_with_model()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, null, null)).Throws(new Exception());
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var model = new object();
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("foo", model, this.viewLocationContext);
// Then
A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, model, A<IRenderContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_covert_anonymoustype_model_to_expandoobject_before_invoking_view_engine()
{
// Given
var viewEngines = new[] {
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var model = new { Name = "" };
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("foo", model, this.viewLocationContext);
// Then
A.CallTo(() => viewEngines[0].RenderView(A<ViewLocationResult>.Ignored, A<object>.That.Matches(x => x.GetType().Equals(typeof(ExpandoObject))), A<IRenderContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_transfer_anonymoustype_model_members_to_expandoobject_members_before_invoking_view_engines()
{
// Given
var viewEngines = new[] {
new FakeViewEngine { Extensions = new[] { "html"}}
};
var location = new ViewLocationResult("location", "name", "html", GetEmptyContentReader());
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(location);
var model = new { Name = "Nancy" };
var factory = this.CreateFactory(viewEngines);
// When
factory.RenderView("foo", model, this.viewLocationContext);
// Then
((string)viewEngines[0].Model.Name).ShouldEqual("Nancy");
}
[Fact]
public void Should_use_the_name_of_the_model_type_as_view_name_when_only_model_is_specified()
{
// Given
var factory = this.CreateFactory();
// When
Record.Exception(() => factory.RenderView(null, new object(), this.viewLocationContext));
// Then
A.CallTo(() => this.resolver.GetViewLocation("Object", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_use_the_name_of_the_model_type_without_model_suffix_as_view_name_when_only_model_is_specified()
{
// Given
var factory = this.CreateFactory();
// When
Record.Exception(() => factory.RenderView(null, new ViewModel(), this.viewLocationContext));
// Then
A.CallTo(() => this.resolver.GetViewLocation("View", A<object>.Ignored, A<ViewLocationContext>.Ignored)).MustHaveHappened();
}
[Fact]
public void Should_throw_when_view_could_not_be_located()
{
var factory = this.CreateFactory();
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null);
var result = Record.Exception(() => factory.RenderView("foo", null, this.viewLocationContext));
result.ShouldBeOfType<ViewNotFoundException>();
}
[Fact]
public void Should_provide_view_name_and_available_extensions_in_not_found_exception()
{
var viewEngines = new[] {
A.Fake<IViewEngine>(),
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "sshtml" });
var factory = this.CreateFactory(viewEngines);
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null);
var result = Record.Exception(() => factory.RenderView("foo", null, this.viewLocationContext)) as ViewNotFoundException;
result.AvailableViewEngineExtensions.ShouldEqualSequence(new[] { "html", "sshtml" });
result.ViewName.ShouldEqual("foo");
}
[Fact]
public void Should_provide_list_of_inspected_view_locations_in_not_found_exception()
{
var viewEngines = new[] {
A.Fake<IViewEngine>(),
A.Fake<IViewEngine>(),
};
A.CallTo(() => viewEngines[0].Extensions).Returns(new[] { "html" });
A.CallTo(() => viewEngines[1].Extensions).Returns(new[] { "sshtml" });
var conventions = new Func<string, dynamic, ViewLocationContext, string>[] {(a,b,c) => "baz"};
var factory = new DefaultViewFactory(this.resolver, viewEngines, this.renderContextFactory, new ViewLocationConventions(conventions), this.rootPathProvider);
A.CallTo(() => this.resolver.GetViewLocation(A<string>.Ignored, A<object>.Ignored, A<ViewLocationContext>.Ignored)).Returns(null);
var result = (Record.Exception(() => factory.RenderView("foo", null, this.viewLocationContext))) as ViewNotFoundException;
result.AvailableViewEngineExtensions.ShouldEqualSequence(new[] { "html", "sshtml" });
result.ViewName.ShouldEqual("foo");
result.InspectedLocations.ShouldEqualSequence(new [] {"baz"});
}
private static Func<TextReader> GetEmptyContentReader()
{
return () => new StreamReader(new MemoryStream());
}
}
}
| |
using J2N.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using JCG = J2N.Collections.Generic;
namespace YAF.Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// A <see cref="CompositeReader"/> which reads multiple, parallel indexes. Each index added
/// must have the same number of documents, and exactly the same hierarchical subreader structure,
/// but typically each contains different fields. Deletions are taken from the first reader.
/// Each document contains the union of the fields of all
/// documents with the same document number. When searching, matches for a
/// query term are from the first index added that has the field.
///
/// <para/>This is useful, e.g., with collections that have large fields which
/// change rarely and small fields that change more frequently. The smaller
/// fields may be re-indexed in a new index and both indexes may be searched
/// together.
///
/// <para/><strong>Warning:</strong> It is up to you to make sure all indexes
/// are created and modified the same way. For example, if you add
/// documents to one index, you need to add the same documents in the
/// same order to the other indexes. <em>Failure to do so will result in
/// undefined behavior</em>.
/// A good strategy to create suitable indexes with <see cref="IndexWriter"/> is to use
/// <see cref="LogDocMergePolicy"/>, as this one does not reorder documents
/// during merging (like <see cref="TieredMergePolicy"/>) and triggers merges
/// by number of documents per segment. If you use different <see cref="MergePolicy"/>s
/// it might happen that the segment structure of your index is no longer predictable.
/// </summary>
public class ParallelCompositeReader : BaseCompositeReader<IndexReader>
{
private readonly bool closeSubReaders;
private readonly ISet<IndexReader> completeReaderSet = new JCG.HashSet<IndexReader>(IdentityEqualityComparer<IndexReader>.Default);
/// <summary>
/// Create a <see cref="ParallelCompositeReader"/> based on the provided
/// readers; auto-disposes the given <paramref name="readers"/> on <see cref="IndexReader.Dispose()"/>.
/// </summary>
public ParallelCompositeReader(params CompositeReader[] readers)
: this(true, readers)
{
}
/// <summary>
/// Create a <see cref="ParallelCompositeReader"/> based on the provided
/// <paramref name="readers"/>.
/// </summary>
public ParallelCompositeReader(bool closeSubReaders, params CompositeReader[] readers)
: this(closeSubReaders, readers, readers)
{
}
/// <summary>
/// Expert: create a <see cref="ParallelCompositeReader"/> based on the provided
/// <paramref name="readers"/> and <paramref name="storedFieldReaders"/>; when a document is
/// loaded, only <paramref name="storedFieldReaders"/> will be used.
/// </summary>
public ParallelCompositeReader(bool closeSubReaders, CompositeReader[] readers, CompositeReader[] storedFieldReaders)
: base(PrepareSubReaders(readers, storedFieldReaders))
{
this.closeSubReaders = closeSubReaders;
completeReaderSet.UnionWith(readers);
completeReaderSet.UnionWith(storedFieldReaders);
// update ref-counts (like MultiReader):
if (!closeSubReaders)
{
foreach (IndexReader reader in completeReaderSet)
{
reader.IncRef();
}
}
// finally add our own synthetic readers, so we close or decRef them, too (it does not matter what we do)
completeReaderSet.UnionWith(GetSequentialSubReaders());
}
private static IndexReader[] PrepareSubReaders(CompositeReader[] readers, CompositeReader[] storedFieldsReaders)
{
if (readers.Length == 0)
{
if (storedFieldsReaders.Length > 0)
{
throw new System.ArgumentException("There must be at least one main reader if storedFieldsReaders are used.");
}
return new IndexReader[0];
}
else
{
IList<IndexReader> firstSubReaders = readers[0].GetSequentialSubReaders();
// check compatibility:
int maxDoc = readers[0].MaxDoc, noSubs = firstSubReaders.Count;
int[] childMaxDoc = new int[noSubs];
bool[] childAtomic = new bool[noSubs];
for (int i = 0; i < noSubs; i++)
{
IndexReader r = firstSubReaders[i];
childMaxDoc[i] = r.MaxDoc;
childAtomic[i] = r is AtomicReader;
}
Validate(readers, maxDoc, childMaxDoc, childAtomic);
Validate(storedFieldsReaders, maxDoc, childMaxDoc, childAtomic);
// hierarchically build the same subreader structure as the first CompositeReader with Parallel*Readers:
IndexReader[] subReaders = new IndexReader[noSubs];
for (int i = 0; i < subReaders.Length; i++)
{
if (firstSubReaders[i] is AtomicReader)
{
AtomicReader[] atomicSubs = new AtomicReader[readers.Length];
for (int j = 0; j < readers.Length; j++)
{
atomicSubs[j] = (AtomicReader)readers[j].GetSequentialSubReaders()[i];
}
AtomicReader[] storedSubs = new AtomicReader[storedFieldsReaders.Length];
for (int j = 0; j < storedFieldsReaders.Length; j++)
{
storedSubs[j] = (AtomicReader)storedFieldsReaders[j].GetSequentialSubReaders()[i];
}
// We pass true for closeSubs and we prevent closing of subreaders in doClose():
// By this the synthetic throw-away readers used here are completely invisible to ref-counting
subReaders[i] = new ParallelAtomicReaderAnonymousInnerClassHelper(atomicSubs, storedSubs);
}
else
{
Debug.Assert(firstSubReaders[i] is CompositeReader);
CompositeReader[] compositeSubs = new CompositeReader[readers.Length];
for (int j = 0; j < readers.Length; j++)
{
compositeSubs[j] = (CompositeReader)readers[j].GetSequentialSubReaders()[i];
}
CompositeReader[] storedSubs = new CompositeReader[storedFieldsReaders.Length];
for (int j = 0; j < storedFieldsReaders.Length; j++)
{
storedSubs[j] = (CompositeReader)storedFieldsReaders[j].GetSequentialSubReaders()[i];
}
// We pass true for closeSubs and we prevent closing of subreaders in doClose():
// By this the synthetic throw-away readers used here are completely invisible to ref-counting
subReaders[i] = new ParallelCompositeReaderAnonymousInnerClassHelper(compositeSubs, storedSubs);
}
}
return subReaders;
}
}
private class ParallelAtomicReaderAnonymousInnerClassHelper : ParallelAtomicReader
{
public ParallelAtomicReaderAnonymousInnerClassHelper(Lucene.Net.Index.AtomicReader[] atomicSubs, Lucene.Net.Index.AtomicReader[] storedSubs)
: base(true, atomicSubs, storedSubs)
{
}
protected internal override void DoClose()
{
}
}
private class ParallelCompositeReaderAnonymousInnerClassHelper : ParallelCompositeReader
{
public ParallelCompositeReaderAnonymousInnerClassHelper(Lucene.Net.Index.CompositeReader[] compositeSubs, Lucene.Net.Index.CompositeReader[] storedSubs)
: base(true, compositeSubs, storedSubs)
{
}
protected internal override void DoClose()
{
}
}
private static void Validate(CompositeReader[] readers, int maxDoc, int[] childMaxDoc, bool[] childAtomic)
{
for (int i = 0; i < readers.Length; i++)
{
CompositeReader reader = readers[i];
IList<IndexReader> subs = reader.GetSequentialSubReaders();
if (reader.MaxDoc != maxDoc)
{
throw new System.ArgumentException("All readers must have same MaxDoc: " + maxDoc + "!=" + reader.MaxDoc);
}
int noSubs = subs.Count;
if (noSubs != childMaxDoc.Length)
{
throw new System.ArgumentException("All readers must have same number of subReaders");
}
for (int subIDX = 0; subIDX < noSubs; subIDX++)
{
IndexReader r = subs[subIDX];
if (r.MaxDoc != childMaxDoc[subIDX])
{
throw new System.ArgumentException("All readers must have same corresponding subReader maxDoc");
}
if (!(childAtomic[subIDX] ? (r is AtomicReader) : (r is CompositeReader)))
{
throw new System.ArgumentException("All readers must have same corresponding subReader types (atomic or composite)");
}
}
}
}
protected internal override void DoClose()
{
lock (this)
{
IOException ioe = null;
foreach (IndexReader reader in completeReaderSet)
{
try
{
if (closeSubReaders)
{
reader.Dispose();
}
else
{
reader.DecRef();
}
}
catch (IOException e)
{
if (ioe == null)
{
ioe = e;
}
}
}
// throw the first exception
if (ioe != null)
{
throw ioe;
}
}
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Encog.Engine.Network.Activation;
using Encog.MathUtil;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.ML.Data.Temporal;
using Encog.Util.Arrayutil;
namespace Encog.Util.NetworkUtil
{
/// <summary>
/// Use this helper class to build training inputs for neural networks (only memory based datasets).
/// Mostly this class is used in financial neural networks when receiving multiple inputs (indicators, prices, etc) and
/// having to put them in neural datasets.
///
/// </summary>
public static class TrainerHelper
{
/// <summary>
/// Makes the double [][] from single array.
/// this is a very important method used in financial markets when you have multiple inputs (Close price, 1 indicator, 1 ATR, 1 moving average for example) , and each is already formated in an array of doubles.
/// You just provide the number of inputs (4 here) , and it will create the resulting double [][]
/// </summary>
/// <param name="array">The array.</param>
/// <param name="numberofinputs">The numberofinputs.</param>
/// <returns></returns>
public static double [][] MakeDoubleJaggedInputFromArray(double [] array , int numberofinputs)
{
//we must be able to fit all our numbers in the same double array..no spill over.
if (array.Length % numberofinputs != 0)
return null;
int dimension = array.Length / numberofinputs;
int currentindex = 0;
double[][] result = EngineArray.AllocateDouble2D(dimension, numberofinputs);
//now we loop through the index.
int index = 0;
for (index = 0; index < result.Length; index++)
{
for (int j = 0; j < numberofinputs; j++)
{
result[index][j] = array[currentindex++];
}
}
return (result);
}
/// <summary>
/// Doubles the List of doubles into a jagged array.
/// This is exactly similar as the MakeDoubleJaggedInputFromArray just it takes a List of double as parameter.
/// It quite easier to Add doubles to a list than into a double [] Array (so this method is used more).
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <param name="lenght">The lenght.</param>
/// <returns></returns>
public static double[][] DoubleInputsToArraySimple(List<double> inputs, int lenght)
{
//we must be able to fit all our numbers in the same double array..no spill over.
if (inputs.Count % lenght != 0)
return null;
int dimension = inputs.Count / lenght;
double[][] result = EngineArray.AllocateDouble2D(dimension, lenght);
foreach (double doubles in inputs)
{
for (int index = 0; index < result.Length; index++)
{
for (int j = 0; j < lenght; j++)
{
result[index][j] = doubles;
}
}
}
return (result);
}
/// <summary>
/// Processes the specified double serie into an IMLDataset.
/// To use this method, you must provide a formated double array.
/// The number of points in the input window makes the input array , and the predict window will create the array used in ideal.
/// Example you have an array with 1, 2, 3 , 4 , 5.
/// You can use this method to make an IMLDataset 4 inputs and 1 ideal (5).
/// </summary>
/// <param name="data">The data.</param>
/// <param name="_inputWindow">The _input window.</param>
/// <param name="_predictWindow">The _predict window.</param>
/// <returns></returns>
public static IMLDataSet ProcessDoubleSerieIntoIMLDataset(double[] data, int _inputWindow, int _predictWindow)
{
var result = new BasicMLDataSet();
int totalWindowSize = _inputWindow + _predictWindow;
int stopPoint = data.Length - totalWindowSize;
for (int i = 0; i < stopPoint; i++)
{
var inputData = new BasicMLData(_inputWindow);
var idealData = new BasicMLData(_predictWindow);
int index = i;
// handle input window
for (int j = 0; j < _inputWindow; j++)
{
inputData[j] = data[index++];
}
// handle predict window
for (int j = 0; j < _predictWindow; j++)
{
idealData[j] = data[index++];
}
var pair = new BasicMLDataPair(inputData, idealData);
result.Add(pair);
}
return result;
}
/// <summary>
/// Processes the specified double serie into an IMLDataset.
/// To use this method, you must provide a formated double array with the input data and the ideal data in another double array.
/// The number of points in the input window makes the input array , and the predict window will create the array used in ideal.
/// This method will use ALL the data inputs and ideals you have provided.
/// </summary>
/// <param name="datainput">The datainput.</param>
/// <param name="ideals">The ideals.</param>
/// <param name="_inputWindow">The _input window.</param>
/// <param name="_predictWindow">The _predict window.</param>
/// <returns></returns>
public static IMLDataSet ProcessDoubleSerieIntoIMLDataset(List<double> datainput,List<double>ideals, int _inputWindow, int _predictWindow)
{
var result = new BasicMLDataSet();
//int count = 0;
////lets check if there is a modulo , if so we move forward in the List of doubles in inputs.This is just a check
////as the data of inputs should be able to fill without having .
//while (datainput.Count % _inputWindow !=0)
//{
// count++;
//}
var inputData = new BasicMLData(_inputWindow);
var idealData = new BasicMLData(_predictWindow);
foreach (double d in datainput)
{
// handle input window
for (int j = 0; j < _inputWindow; j++)
{
inputData[j] = d;
}
}
foreach (double ideal in ideals)
{
// handle predict window
for (int j = 0; j < _predictWindow; j++)
{
idealData[j] =ideal;
}
}
var pair = new BasicMLDataPair(inputData, idealData);
result.Add(pair);
return result;
}
static bool IsNoModulo(double first,int second)
{
return first % second == 0;
}
/// <summary>
/// Grabs every Predict point in a double serie.
/// This is useful if you have a double series and you need to grab every 5 points for examples and make an ourput serie (like in elmhan networks).
/// E.G , 1, 2, 1, 2,5 ...and you just need the 5..
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <param name="PredictSize">Size of the predict.</param>
/// <returns></returns>
public static List<double> CreateIdealFromSerie(List<double> inputs, int PredictSize)
{
//we need to copy into a new list only the doubles on each point of predict..
List<int> Indexes = new List<int>();
for (int i =0 ; i < inputs.Count;i++)
{
if (i % PredictSize == 0)
Indexes.Add(i);
}
List<double> Results = Indexes.Select(index => inputs[index]).ToList();
return Results;
}
/// <summary>
/// Generates the Temporal MLDataset with a given data array.
/// You must input the "predict" size (inputs) and the windowsize (outputs).
/// This is oftenly used with Ehlman networks.
/// The temporal dataset will be in RAW format (no normalization used..Most of the times it means you already have normalized your inputs /ouputs.
///
/// </summary>
/// <param name="inputserie">The inputserie.</param>
/// <param name="windowsize">The windowsize.</param>
/// <param name="predictsize">The predictsize.</param>
/// <returns>A temporalMLDataset</returns>
public static TemporalMLDataSet GenerateTrainingWithRawSerie(double[] inputserie, int windowsize, int predictsize)
{
TemporalMLDataSet result = new TemporalMLDataSet(windowsize, predictsize);
TemporalDataDescription desc = new TemporalDataDescription(
TemporalDataDescription.Type.Raw, true, true);
result.AddDescription(desc);
for (int index = 0; index < inputserie.Length - 1; index++)
{
TemporalPoint point = new TemporalPoint(1);
point.Sequence = index;
point.Data[0] = inputserie[index];
result.Points.Add(point);
}
result.Generate();
return result;
}
/// <summary>
/// Generates the training with delta change on serie.
/// </summary>
/// <param name="inputserie">The inputserie.</param>
/// <param name="windowsize">The windowsize.</param>
/// <param name="predictsize">The predictsize.</param>
/// <returns></returns>
public static TemporalMLDataSet GenerateTrainingWithDeltaChangeOnSerie(double[] inputserie, int windowsize, int predictsize)
{
TemporalMLDataSet result = new TemporalMLDataSet(windowsize, predictsize);
TemporalDataDescription desc = new TemporalDataDescription(
TemporalDataDescription.Type.DeltaChange, true, true);
result.AddDescription(desc);
for (int index = 0; index < inputserie.Length - 1; index++)
{
TemporalPoint point = new TemporalPoint(1);
point.Sequence = index;
point.Data[0] = inputserie[index];
result.Points.Add(point);
}
result.Generate();
return result;
}
/// <summary>
/// Generates a temporal data set with a given double serie or a any number of double series , making your inputs.
/// uses Type percent change.
/// </summary>
/// <param name="windowsize">The windowsize.</param>
/// <param name="predictsize">The predictsize.</param>
/// <param name="inputserie">The inputserie.</param>
/// <returns></returns>
public static TemporalMLDataSet GenerateTrainingWithPercentChangeOnSerie(int windowsize, int predictsize, params double[][] inputserie)
{
TemporalMLDataSet result = new TemporalMLDataSet(windowsize, predictsize);
TemporalDataDescription desc = new TemporalDataDescription(TemporalDataDescription.Type.PercentChange, true,
true);
result.AddDescription(desc);
foreach (double[] t in inputserie)
{
for (int j = 0; j < t.Length; j++)
{
TemporalPoint point = new TemporalPoint(1);
point.Sequence = j;
point.Data[0] = t[j];
result.Points.Add(point);
}
result.Generate();
return result;
}
return null;
}
/// <summary>
/// This method takes ARRAYS of arrays (parametrable arrays) and places them in double [][]
/// You can use this method if you have already formatted arrays and you want to create a double [][] ready for network.
/// Example you could use this method to input the XOR example:
/// A[0,0] B[0,1] C[1, 0] D[1,1] would format them directly in the double [][] in one method call.
/// This could also be used in unsupervised learning.
/// </summary>
/// <param name="Inputs">The inputs.</param>
/// <returns></returns>
public static double[][] NetworkbuilArrayByParams(params double[][] Inputs)
{
double[][] Resulting = new double[Inputs.Length][];
int i = Inputs.Length;
foreach (double[] doubles in Resulting)
{
for (int k = 0; k < Inputs.Length; k++)
Resulting[k] = doubles;
}
return Resulting;
}
/// <summary>
/// Prints the content of an array to the console.(Mostly used in debugging).
/// </summary>
/// <param name="num">The num.</param>
public static void PrinteJaggedArray(int[][] num)
{
foreach (int t1 in num.SelectMany(t => t))
{
Console.WriteLine(@"Values : {0}", t1);//displaying values of Jagged Array
}
}
/// <summary>
/// Processes a double array of data of input and a second array of data for ideals
/// you must input the input and output size.
/// this typically builds a supervised IMLDatapair, which you must add to a IMLDataset.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="ideal">The ideal.</param>
/// <param name="_inputWindow">The _input window.</param>
/// <param name="_predictWindow">The _predict window.</param>
/// <returns></returns>
public static IMLDataPair ProcessPairs(double[] data, double[] ideal, int _inputWindow, int _predictWindow)
{
var result = new BasicMLDataSet();
for (int i = 0; i < data.Length; i++)
{
var inputData = new BasicMLData(_inputWindow);
var idealData = new BasicMLData(_predictWindow);
int index = i;
// handle input window
for (int j = 0; j < _inputWindow; j++)
{
inputData[j] = data[index++];
}
index = 0;
// handle predict window
for (int j = 0; j < _predictWindow; j++)
{
idealData[j] = ideal[index++];
}
IMLDataPair pair = new BasicMLDataPair(inputData, idealData);
return pair;
}
return null;
}
/// <summary>
/// Takes 2 inputs arrays and makes a jagged array.
/// this just copies the second array after the first array in a double [][]
/// </summary>
/// <param name="firstArray">The first array.</param>
/// <param name="SecondArray">The second array.</param>
/// <returns></returns>
public static double[][] FromDualToJagged(double[] firstArray, double[] SecondArray)
{
return new[] { firstArray, SecondArray };
}
///// <summary>
///// Generates the Temporal Training based on an array of doubles.
///// You need to have 2 array of doubles [] for this method to work!
///// </summary>
///// <param name="inputsize">The inputsize.</param>
///// <param name="outputsize">The outputsize.</param>
///// <param name="Arraydouble">The arraydouble.</param>
///// <returns></returns>
//public static TemporalMLDataSet GenerateTraining(int inputsize, int outputsize, params double[][] Arraydouble)
//{
// if (Arraydouble.Length < 2)
// return null;
// if (Arraydouble.Length > 2)
// return null;
// TemporalMLDataSet result = new TemporalMLDataSet(inputsize, outputsize);
// TemporalDataDescription desc = new TemporalDataDescription(new ActivationTANH(), TemporalDataDescription.Type.PercentChange, true, true);
// result.AddDescription(desc);
// TemporalPoint point = new TemporalPoint(Arraydouble.Length);
// int currentindex;
// for (int w = 0; w < Arraydouble[0].Length; w++)
// {
// //We have filled in one dimension now lets put them in our temporal dataset.
// for (int year = 0; year < Arraydouble.Length - 1; year++)
// {
// //We have as many points as we passed the array of doubles.
// point = new TemporalPoint(Arraydouble.Length);
// //our first sequence (0).
// point.Sequence = w;
// //point 0 is double[0] array.
// point.Data[0] = Arraydouble[0][w];
// point.Data[1] = Arraydouble[1][w++];
// //we add the point..
// }
// result.Points.Add(point);
// }
// result.Generate();
// return result;
//}
/// <summary>
/// Calculates and returns the copied array.
/// This is used in live data , when you want have a full array of doubles but you want to cut from a starting position
/// and return only from that point to the end.
/// example you have 1000 doubles , but you want only the last 100.
/// input size is the input you must set to 100.
/// I use this method next to every day when calculating on an array of doubles which has just received a new price (A quote for example).
/// As the array of quotes as all the quotes since a few days, i just need the last 100 for example , so this method is used when not training but using the neural network.
/// </summary>
/// <param name="inputted">The inputted.</param>
/// <param name="inputsize">The input neuron size (window size).</param>
/// <returns></returns>
public static double[] ReturnArrayOnSize(double[] inputted, int inputsize)
{
//lets say we receive an array of 105 doubles ...input size is 100.(or window size)
//we need to just copy the last 100.
//so if inputted.Lenght > inputsize :
// start index = inputtedLenght - inputsize.
//if inputtedlenght is equal to input size , well our index will be 0..
//if inputted lenght is smaller than input...We return null.
double[] arr = new double[inputsize];
int howBig = 0;
if (inputted.Length >= inputsize)
{
howBig = inputted.Length - inputsize;
}
EngineArray.ArrayCopy(inputted, howBig, arr, 0, inputsize);
return arr;
}
/// <summary>
/// Quickly an IMLDataset from a double array using the TemporalWindow array.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="inputsize">The inputsize.</param>
/// <param name="outputsize">The outputsize.</param>
/// <returns></returns>
public static IMLDataSet QuickTrainingFromDoubleArray(double[] array, int inputsize, int outputsize)
{
TemporalWindowArray temp = new TemporalWindowArray(inputsize, outputsize);
temp.Analyze(array);
return temp.Process(array);
}
/// <summary>
/// Generates an array with as many double array inputs as wanted.
/// This is useful for neural networks when you have already formated your data arrays and need to create a double []
/// with all the inputs following each others.(Elman type format)
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <returns>
/// the double [] array with all inputs.
/// </returns>
public static double[] GenerateInputz(params double[][] inputs)
{
ArrayList al = new ArrayList();
foreach (double[] doublear in inputs)
{
al.Add((double[])doublear);
}
return (double[])al.ToArray(typeof(double));
}
/// <summary>
/// Prepare realtime inputs, and place them in an understandable one jagged input neuron array.
/// This method uses linq.
/// you can use this method if you have many inputs and need to format them as inputs with a specified "window"/input size.
/// You can add as many inputs as wanted to this input layer (parametrable inputs).
/// </summary>
/// <param name="inputsize">The inputsize.</param>
/// <param name="firstinputt">The firstinputt.</param>
/// <returns>a ready to use jagged array with all the inputs setup.</returns>
public static double[][] AddInputsViaLinq(int inputsize, params double[][] firstinputt)
{
ArrayList arlist = new ArrayList(4);
ArrayList FirstList = new ArrayList();
List<double> listused = new List<double>();
int lenghtofArrays = firstinputt[0].Length;
//There must be NO modulo...or the arrays would not be divisible by this input size.
if (lenghtofArrays % inputsize != 0)
return null;
//we add each input one , after the other in a list of doubles till we reach the input size
for (int i = 0; i < lenghtofArrays; i++)
{
foreach (double[] t in firstinputt.Where(t => listused.Count < inputsize*firstinputt.Length))
{
listused.Add(t[i]);
if (listused.Count != inputsize*firstinputt.Length) continue;
FirstList.Add(listused.ToArray());
listused.Clear();
}
}
return (double[][])FirstList.ToArray(typeof(double[]));
}
/// <summary>
/// Prepare realtime inputs, and place them in an understandable one jagged input neuron array.
/// you can use this method if you have many inputs and need to format them as inputs with a specified "window"/input size.
/// You can add as many inputs as wanted to this input layer (parametrable inputs).
/// </summary>
/// <param name="inputsize">The inputsize.</param>
/// <param name="firstinputt">The firstinputt.</param>
/// <returns>a ready to use jagged array with all the inputs setup.</returns>
public static double[][] AddInputs(int inputsize, params double[][] firstinputt)
{
ArrayList arlist = new ArrayList(4);
ArrayList FirstList = new ArrayList();
List<double> listused = new List<double>();
int lenghtofArrays = firstinputt[0].Length;
//There must be NO modulo...or the arrays would not be divisile by this input size.
if (lenghtofArrays % inputsize != 0)
return null;
//we add each input one , after the other in a list of doubles till we reach the input size
for (int i = 0; i < lenghtofArrays; i++)
{
for (int k = 0; k < firstinputt.Length; k++)
{
if (listused.Count < inputsize * firstinputt.Length)
{
listused.Add(firstinputt[k][i]);
if (listused.Count == inputsize * firstinputt.Length)
{
FirstList.Add(listused.ToArray());
listused.Clear();
}
}
}
}
return (double[][])FirstList.ToArray(typeof(double[]));
}
/// <summary>
/// Makes a data set with parametrable inputs and one output double array.
/// you can provide as many inputs as needed and the timelapse size (input size).
/// for more information on this method read the AddInputs Method.
/// </summary>
/// <param name="outputs">The outputs.</param>
/// <param name="inputsize">The inputsize.</param>
/// <param name="firstinputt">The firstinputt.</param>
/// <returns></returns>
public static IMLDataSet MakeDataSet(double[] outputs, int inputsize, params double[][] firstinputt)
{
IMLDataSet set = new BasicMLDataSet();
ArrayList outputsar = new ArrayList();
ArrayList FirstList = new ArrayList();
List<double> listused = new List<double>();
int lenghtofArrays = firstinputt[0].Length;
//There must be NO modulo...or the arrays would not be divisible by this input size.
if (lenghtofArrays % inputsize != 0)
return null;
//we add each input one , after the other in a list of doubles till we reach the input size
for (int i = 0; i < lenghtofArrays; i++)
{
for (int k = 0; k < firstinputt.Length; k++)
{
if (listused.Count < inputsize * firstinputt.Length)
{
listused.Add(firstinputt[k][i]);
if (listused.Count == inputsize * firstinputt.Length)
{
FirstList.Add(listused.ToArray());
listused.Clear();
}
}
}
}
foreach (double d in outputs)
{
listused.Add(d);
outputsar.Add(listused.ToArray());
listused.Clear();
}
set = new BasicMLDataSet((double[][])FirstList.ToArray(typeof(double[])), (double[][])outputsar.ToArray(typeof(double[])));
return set;
}
public static double[] MakeInputs(int number)
{
Random rdn = new Random();
Encog.MathUtil.Randomize.RangeRandomizer encogRnd = new Encog.MathUtil.Randomize.RangeRandomizer(-1, 1);
double[] x = new double[number];
for (int i = 0; i < number; i++)
{
x[i] = encogRnd.Randomize((rdn.NextDouble()));
}
return x;
}
/// <summary>
/// Makes a random dataset with the number of IMLDatapairs.
/// Quite useful to test networks (benchmarks).
/// </summary>
/// <param name="inputs">The inputs.</param>
/// <param name="predictWindow">The predict window.</param>
/// <param name="numberofPairs">The numberof pairs.</param>
/// <returns></returns>
public static BasicMLDataSet MakeRandomIMLDataset(int inputs, int predictWindow, int numberofPairs)
{
BasicMLDataSet SuperSet = new BasicMLDataSet();
for (int i = 0; i < numberofPairs;i++ )
{
double[] firstinput = MakeInputs(inputs);
double[] secondideal = MakeInputs(inputs);
IMLDataPair pair = ProcessPairs(firstinput, secondideal, inputs, predictWindow);
SuperSet.Add(pair);
}
return SuperSet;
}
/// <summary>
/// This is the most used method in finance.
/// You send directly your double arrays and get an IMLData set ready for network training.
/// You must place your ideal data as the last double data array.
/// IF you have 1 data of closing prices, 1 moving average, 1 data series of interest rates , and the data you want to predict
/// This method will look the lenght of the first Data input to calculate how many points to take from each array.
/// this is the method you will use to make your Dataset.
/// </summary>
/// <param name="number">The number.</param>
/// <param name="inputs">The inputs.</param>
/// <returns></returns>
public static IMLDataSet MakeSetFromInputsSources(int predwindow, params double[][] inputs)
{
ArrayList list = new ArrayList(inputs.Length);
IMLDataSet set = new BasicMLDataSet();
//we know now how many items we have in each data series (all series should be of equal lenght).
int dimension = inputs[0].Length;
//we will take predictwindow of each serie and make new series.
List<double> InputList = new List<double>();
int index = 0;
int currentArrayObserved = 0;
//foreach (double[] doubles in inputs)
//{
// for (int k = 0; k < dimension; k++)
// {
// //We will take predict window number from each of our array and add them up.
// for (int i = 0; i < predwindow; i++)
// {
// InputList.Add(doubles[index]);
// }
// }
// index++;
//}
foreach (double[] doublear in inputs)
{
list.Add((double[])doublear);
}
// return (double[][])list.ToArray(typeof(double[]));
return set;
}
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
[TestFixture]
public class RsaTest
: SimpleTest
{
static BigInteger mod = new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16);
static BigInteger pubExp = new BigInteger("11", 16);
static BigInteger privExp = new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16);
static BigInteger p = new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16);
static BigInteger q = new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16);
static BigInteger pExp = new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16);
static BigInteger qExp = new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16);
static BigInteger crtCoef = new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16);
static string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
//
// to check that we handling byte extension by big number correctly.
//
static string edgeInput = "ff6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
static byte[] oversizedSig = Hex.Decode("01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] dudBlock = Hex.Decode("000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] truncatedDataBlock = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff004e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] incorrectPadding = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e");
static byte[] missingDataBlock = Hex.Decode("0001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
public override string Name
{
get { return "RSA"; }
}
private void doTestStrictPkcs1Length(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
IAsymmetricBlockCipher eng = new RsaEngine();
eng.Init(true, privParameters);
byte[] data = null;
try
{
data = eng.ProcessBlock(oversizedSig, 0, oversizedSig.Length);
}
catch (Exception e)
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
eng = new Pkcs1Encoding(eng);
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
Fail("oversized signature block not recognised");
}
catch (InvalidCipherTextException e)
{
if (!e.Message.Equals("block incorrect size"))
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
}
// Create the encoding with StrictLengthEnabled=false (done thru environment in Java version)
Pkcs1Encoding.StrictLengthEnabled = false;
eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (InvalidCipherTextException e)
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
Pkcs1Encoding.StrictLengthEnabled = true;
}
private void doTestTruncatedPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, truncatedDataBlock, "block truncated");
}
private void doTestDudPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, dudBlock, "unknown block type");
}
private void doTestWrongPaddingPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, incorrectPadding, "block padding incorrect");
}
private void doTestMissingDataPkcs1Block(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
checkForPkcs1Exception(pubParameters, privParameters, missingDataBlock, "no data in block");
}
private void checkForPkcs1Exception(RsaKeyParameters pubParameters, RsaKeyParameters privParameters, byte[] inputData, string expectedMessage)
{
IAsymmetricBlockCipher eng = new RsaEngine();
eng.Init(true, privParameters);
byte[] data = null;
try
{
data = eng.ProcessBlock(inputData, 0, inputData.Length);
}
catch (Exception e)
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
eng = new Pkcs1Encoding(eng);
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
Fail("missing data block not recognised");
}
catch (InvalidCipherTextException e)
{
if (!e.Message.Equals(expectedMessage))
{
Fail("RSA: failed - exception " + e.ToString(), e);
}
}
}
private void doTestOaep(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
{
//
// OAEP - public encrypt, private decrypt
//
IAsymmetricBlockCipher eng = new OaepEncoding(new RsaEngine());
byte[] data = Hex.Decode(input);
eng.Init(true, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed OAEP Test");
}
}
// TODO Move this when other JCE tests are ported from Java
/**
* signature with a "forged signature" (sig block not at end of plain text)
*/
private void doTestBadSig()//PrivateKey priv, PublicKey pub)
{
// Signature sig = Signature.getInstance("SHA1WithRSAEncryption", "BC");
ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");
// KeyPairGenerator fact;
// KeyPair keyPair;
// byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
// fact = KeyPairGenerator.getInstance("RSA", "BC");
RsaKeyPairGenerator fact = new RsaKeyPairGenerator();
// fact.initialize(768, new SecureRandom());
RsaKeyGenerationParameters factParams = new RsaKeyGenerationParameters(
// BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);
BigInteger.ValueOf(3), new SecureRandom(), 768, 25);
fact.Init(factParams);
// keyPair = fact.generateKeyPair();
//
// PrivateKey signingKey = keyPair.getPrivate();
// PublicKey verifyKey = keyPair.getPublic();
AsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();
AsymmetricKeyParameter priv = keyPair.Private;
AsymmetricKeyParameter pub = keyPair.Public;
// testBadSig(signingKey, verifyKey);
// MessageDigest sha1 = MessageDigest.getInstance("SHA1", "BC");
IDigest sha1 = DigestUtilities.GetDigest("SHA1");
// Cipher signer = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
// IBufferedCipher signer = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());
// signer.init(Cipher.ENCRYPT_MODE, priv);
signer.Init(true, priv);
// byte[] block = new byte[signer.getBlockSize()];
// byte[] block = new byte[signer.GetBlockSize()];
byte[] block = new byte[signer.GetInputBlockSize()];
// sha1.update((byte)0);
sha1.Update(0);
// byte[] sigHeader = Hex.decode("3021300906052b0e03021a05000414");
byte[] sigHeader = Hex.Decode("3021300906052b0e03021a05000414");
// System.arraycopy(sigHeader, 0, block, 0, sigHeader.length);
Array.Copy(sigHeader, 0, block, 0, sigHeader.Length);
// sha1.digest(block, sigHeader.length, sha1.getDigestLength());
sha1.DoFinal(block, sigHeader.Length);
// System.arraycopy(sigHeader, 0, block,
// sigHeader.length + sha1.getDigestLength(), sigHeader.length);
Array.Copy(sigHeader, 0, block,
sigHeader.Length + sha1.GetDigestSize(), sigHeader.Length);
// byte[] sigBytes = signer.doFinal(block);
byte[] sigBytes = signer.ProcessBlock(block, 0, block.Length);
// Signature verifier = Signature.getInstance("SHA1WithRSA", "BC");
ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA");
// verifier.initVerify(pub);
verifier.Init(false, pub);
// verifier.update((byte)0);
verifier.Update(0);
// if (verifier.verify(sig))
if (verifier.VerifySignature(sigBytes))
{
// fail("bad signature passed");
Fail("bad signature passed");
}
}
private void testZeroBlock(ICipherParameters encParameters, ICipherParameters decParameters)
{
IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(true, encParameters);
if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
{
Fail("PKCS1 output block size incorrect");
}
byte[] zero = new byte[0];
byte[] data = null;
try
{
data = eng.ProcessBlock(zero, 0, zero.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
eng.Init(false, decParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString(), e);
}
if (!Arrays.AreEqual(zero, data))
{
Fail("failed PKCS1 zero Test");
}
}
public override void PerformTest()
{
RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp);
RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);
byte[] data = Hex.Decode(edgeInput);
//
// RAW
//
IAsymmetricBlockCipher eng = new RsaEngine();
eng.Init(true, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("RSA: failed - exception " + e.ToString());
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
if (!edgeInput.Equals(Hex.ToHexString(data)))
{
Fail("failed RAW edge Test");
}
data = Hex.Decode(input);
eng.Init(true, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed RAW Test");
}
//
// PKCS1 - public encrypt, private decrypt
//
eng = new Pkcs1Encoding(eng);
eng.Init(true, pubParameters);
if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
{
Fail("PKCS1 output block size incorrect");
}
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
eng.Init(false, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed PKCS1 public/private Test");
}
//
// PKCS1 - private encrypt, public decrypt
//
eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher());
eng.Init(true, privParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
eng.Init(false, pubParameters);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed PKCS1 private/public Test");
}
testZeroBlock(pubParameters, privParameters);
testZeroBlock(privParameters, pubParameters);
//
// key generation test
//
RsaKeyPairGenerator pGen = new RsaKeyPairGenerator();
RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);
pGen.Init(genParam);
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
eng = new RsaEngine();
if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768)
{
Fail("failed key generation (768) length test");
}
eng.Init(true, pair.Public);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
eng.Init(false, pair.Private);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed key generation (768) Test");
}
genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);
pGen.Init(genParam);
pair = pGen.GenerateKeyPair();
eng.Init(true, pair.Public);
if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024)
{
Fail("failed key generation (1024) length test");
}
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
eng.Init(false, pair.Private);
try
{
data = eng.ProcessBlock(data, 0, data.Length);
}
catch (Exception e)
{
Fail("failed - exception " + e.ToString());
}
if (!input.Equals(Hex.ToHexString(data)))
{
Fail("failed key generation (1024) test");
}
genParam = new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x11), new SecureRandom(), 16, 25);
pGen.Init(genParam);
for (int i = 0; i < 100; ++i)
{
pair = pGen.GenerateKeyPair();
RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters) pair.Private;
BigInteger pqDiff = privKey.P.Subtract(privKey.Q).Abs();
if (pqDiff.BitLength < 5)
{
Fail("P and Q too close in RSA key pair");
}
}
doTestBadSig();
doTestOaep(pubParameters, privParameters);
doTestStrictPkcs1Length(pubParameters, privParameters);
doTestDudPkcs1Block(pubParameters, privParameters);
doTestMissingDataPkcs1Block(pubParameters, privParameters);
doTestTruncatedPkcs1Block(pubParameters, privParameters);
doTestWrongPaddingPkcs1Block(pubParameters, privParameters);
try
{
new RsaEngine().ProcessBlock(new byte[]{ 1 }, 0, 1);
Fail("failed initialisation check");
}
catch (InvalidOperationException)
{
// expected
}
}
public static void Main(
string[] args)
{
ITest test = new RsaTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
/*
* Copyright 2013 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using ZXing.Common;
using ZXing.PDF417.Internal.EC;
namespace ZXing.PDF417.Internal
{
/// <summary>
///
/// </summary>
/// <author>Guenther Grau</author>
public static class PDF417ScanningDecoder
{
private const int CODEWORD_SKEW_SIZE = 2;
private const int MAX_ERRORS = 3;
private const int MAX_EC_CODEWORDS = 512;
private static readonly ErrorCorrection errorCorrection = new ErrorCorrection();
/// <summary>
/// Decode the specified image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight, minCodewordWidth
/// and maxCodewordWidth.
/// TODO: don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern
/// columns. That way width can be deducted from the pattern column.
/// This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider
/// than it should be. This can happen if the scanner used a bad blackpoint.
/// </summary>
/// <param name="image">Image.</param>
/// <param name="imageTopLeft">Image top left.</param>
/// <param name="imageBottomLeft">Image bottom left.</param>
/// <param name="imageTopRight">Image top right.</param>
/// <param name="imageBottomRight">Image bottom right.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
public static DecoderResult decode(BitMatrix image,
ResultPoint imageTopLeft,
ResultPoint imageBottomLeft,
ResultPoint imageTopRight,
ResultPoint imageBottomRight,
int minCodewordWidth,
int maxCodewordWidth)
{
BoundingBox boundingBox = BoundingBox.Create(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight);
if (boundingBox == null)
return null;
DetectionResultRowIndicatorColumn leftRowIndicatorColumn = null;
DetectionResultRowIndicatorColumn rightRowIndicatorColumn = null;
DetectionResult detectionResult = null;
for (int i = 0; i < 2; i++)
{
if (imageTopLeft != null)
{
leftRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth);
}
if (imageTopRight != null)
{
rightRowIndicatorColumn = getRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth);
}
detectionResult = merge(leftRowIndicatorColumn, rightRowIndicatorColumn);
if (detectionResult == null)
{
// TODO Based on Owen's Comments in <see cref="ZXing.ReaderException"/>, this method has been modified to continue silently
// if a barcode was not decoded where it was detected instead of throwing a new exception object.
return null;
}
if (i == 0 && detectionResult.Box != null &&
(detectionResult.Box.MinY < boundingBox.MinY || detectionResult.Box.MaxY > boundingBox.MaxY))
{
boundingBox = detectionResult.Box;
}
else
{
detectionResult.Box = boundingBox;
break;
}
}
int maxBarcodeColumn = detectionResult.ColumnCount + 1;
detectionResult.DetectionResultColumns[0] = leftRowIndicatorColumn;
detectionResult.DetectionResultColumns[maxBarcodeColumn] = rightRowIndicatorColumn;
bool leftToRight = leftRowIndicatorColumn != null;
for (int barcodeColumnCount = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++)
{
int barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount;
if (detectionResult.DetectionResultColumns[barcodeColumn] != null)
{
// This will be the case for the opposite row indicator column, which doesn't need to be decoded again.
continue;
}
DetectionResultColumn detectionResultColumn;
if (barcodeColumn == 0 || barcodeColumn == maxBarcodeColumn)
{
detectionResultColumn = new DetectionResultRowIndicatorColumn(boundingBox, barcodeColumn == 0);
}
else
{
detectionResultColumn = new DetectionResultColumn(boundingBox);
}
detectionResult.DetectionResultColumns[barcodeColumn] = detectionResultColumn;
int startColumn = -1;
int previousStartColumn = startColumn;
// TODO start at a row for which we know the start position, then detect upwards and downwards from there.
for (int imageRow = boundingBox.MinY; imageRow <= boundingBox.MaxY; imageRow++)
{
startColumn = getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight);
if (startColumn < 0 || startColumn > boundingBox.MaxX)
{
if (previousStartColumn == -1)
{
continue;
}
startColumn = previousStartColumn;
}
Codeword codeword = detectCodeword(image, boundingBox.MinX, boundingBox.MaxX, leftToRight,
startColumn, imageRow, minCodewordWidth, maxCodewordWidth);
if (codeword != null)
{
detectionResultColumn.setCodeword(imageRow, codeword);
previousStartColumn = startColumn;
minCodewordWidth = Math.Min(minCodewordWidth, codeword.Width);
maxCodewordWidth = Math.Max(maxCodewordWidth, codeword.Width);
}
}
}
if(IsFlippedVerically(detectionResult))
{
detectionResult.FlipVertically();
}
return createDecoderResult(detectionResult);
}
private static bool IsFlippedVerically(DetectionResult detectionResult)
{
var N = detectionResult.DetectionResultColumns.Length - 1;
int col0Slope = 0;
int colNSlope = 0;
Codeword pc0 = null;
Codeword pcN = null;
var h = Math.Min(detectionResult.DetectionResultColumns[0].Codewords.Length, detectionResult.DetectionResultColumns[N].Codewords.Length);
for (int i = 0; i < h; i++)
{
var cw0 = detectionResult.DetectionResultColumns[0].Codewords[i];
var cwN = detectionResult.DetectionResultColumns[N].Codewords[i];
if (cw0 != null) { if (pc0 != null) col0Slope += cw0.RowNumber - pc0.RowNumber; pc0 = cw0; }
if (cwN != null) { if (pcN != null) colNSlope += cwN.RowNumber - pcN.RowNumber; pcN = cwN; }
}
return col0Slope < 0 && colNSlope < 0;
}
/// <summary>
/// Merge the specified leftRowIndicatorColumn and rightRowIndicatorColumn.
/// </summary>
/// <param name="leftRowIndicatorColumn">Left row indicator column.</param>
/// <param name="rightRowIndicatorColumn">Right row indicator column.</param>
private static DetectionResult merge(DetectionResultRowIndicatorColumn leftRowIndicatorColumn,
DetectionResultRowIndicatorColumn rightRowIndicatorColumn)
{
if (leftRowIndicatorColumn == null && rightRowIndicatorColumn == null)
{
return null;
}
BarcodeMetadata barcodeMetadata = getBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn);
if (barcodeMetadata == null)
{
return null;
}
BoundingBox boundingBox = BoundingBox.merge(adjustBoundingBox(leftRowIndicatorColumn),
adjustBoundingBox(rightRowIndicatorColumn));
return new DetectionResult(barcodeMetadata, boundingBox);
}
/// <summary>
/// Adjusts the bounding box.
/// </summary>
/// <returns>The bounding box.</returns>
/// <param name="rowIndicatorColumn">Row indicator column.</param>
private static BoundingBox adjustBoundingBox(DetectionResultRowIndicatorColumn rowIndicatorColumn)
{
if (rowIndicatorColumn == null)
{
return null;
}
int[] rowHeights = rowIndicatorColumn.getRowHeights();
if (rowHeights == null)
{
return null;
}
int maxRowHeight = getMax(rowHeights);
int missingStartRows = 0;
foreach (int rowHeight in rowHeights)
{
missingStartRows += maxRowHeight - rowHeight;
if (rowHeight > 0)
{
break;
}
}
Codeword[] codewords = rowIndicatorColumn.Codewords;
for (int row = 0; missingStartRows > 0 && codewords[row] == null; row++)
{
missingStartRows--;
}
int missingEndRows = 0;
for (int row = rowHeights.Length - 1; row >= 0; row--)
{
missingEndRows += maxRowHeight - rowHeights[row];
if (rowHeights[row] > 0)
{
break;
}
}
for (int row = codewords.Length - 1; missingEndRows > 0 && codewords[row] == null; row--)
{
missingEndRows--;
}
return rowIndicatorColumn.Box.addMissingRows(missingStartRows, missingEndRows, rowIndicatorColumn.IsLeft);
}
private static int getMax(int[] values)
{
int maxValue = -1;
for (var index = values.Length - 1; index >= 0; index--)
{
maxValue = Math.Max(maxValue, values[index]);
}
return maxValue;
}
/// <summary>
/// Gets the barcode metadata.
/// </summary>
/// <returns>The barcode metadata.</returns>
/// <param name="leftRowIndicatorColumn">Left row indicator column.</param>
/// <param name="rightRowIndicatorColumn">Right row indicator column.</param>
private static BarcodeMetadata getBarcodeMetadata(DetectionResultRowIndicatorColumn leftRowIndicatorColumn,
DetectionResultRowIndicatorColumn rightRowIndicatorColumn)
{
BarcodeMetadata leftBarcodeMetadata;
if (leftRowIndicatorColumn == null ||
(leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()) == null)
{
return rightRowIndicatorColumn == null ? null : rightRowIndicatorColumn.getBarcodeMetadata();
}
BarcodeMetadata rightBarcodeMetadata;
if (rightRowIndicatorColumn == null ||
(rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()) == null)
{
return leftBarcodeMetadata;
}
if (leftBarcodeMetadata.ColumnCount != rightBarcodeMetadata.ColumnCount &&
leftBarcodeMetadata.ErrorCorrectionLevel != rightBarcodeMetadata.ErrorCorrectionLevel &&
leftBarcodeMetadata.RowCount != rightBarcodeMetadata.RowCount)
{
return null;
}
return leftBarcodeMetadata;
}
/// <summary>
/// Gets the row indicator column.
/// </summary>
/// <returns>The row indicator column.</returns>
/// <param name="image">Image.</param>
/// <param name="boundingBox">Bounding box.</param>
/// <param name="startPoint">Start point.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static DetectionResultRowIndicatorColumn getRowIndicatorColumn(BitMatrix image,
BoundingBox boundingBox,
ResultPoint startPoint,
bool leftToRight,
int minCodewordWidth,
int maxCodewordWidth)
{
DetectionResultRowIndicatorColumn rowIndicatorColumn = new DetectionResultRowIndicatorColumn(boundingBox, leftToRight);
for (int i = 0; i < 2; i++)
{
int increment = i == 0 ? 1 : -1;
int startColumn = (int)startPoint.X;
for (int imageRow = (int)startPoint.Y; imageRow <= boundingBox.MaxY &&
imageRow >= boundingBox.MinY; imageRow += increment)
{
Codeword codeword = detectCodeword(image, 0, image.Width, leftToRight, startColumn, imageRow,
minCodewordWidth, maxCodewordWidth);
if (codeword != null)
{
rowIndicatorColumn.setCodeword(imageRow, codeword);
if (leftToRight)
{
startColumn = codeword.StartX;
}
else
{
startColumn = codeword.EndX;
}
}
}
}
return rowIndicatorColumn;
}
/// <summary>
/// Adjusts the codeword count.
/// </summary>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeMatrix">Barcode matrix.</param>
private static bool adjustCodewordCount(DetectionResult detectionResult, BarcodeValue[][] barcodeMatrix)
{
int[] numberOfCodewords = barcodeMatrix[0][1].getValue();
int calculatedNumberOfCodewords = detectionResult.ColumnCount *
detectionResult.RowCount -
getNumberOfECCodeWords(detectionResult.ErrorCorrectionLevel);
if (numberOfCodewords.Length == 0)
{
if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > PDF417Common.MAX_CODEWORDS_IN_BARCODE)
{
return false;
}
barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords);
}
else if (numberOfCodewords[0] != calculatedNumberOfCodewords)
{
// The calculated one is more reliable as it is derived from the row indicator columns
barcodeMatrix[0][1].setValue(calculatedNumberOfCodewords);
}
return true;
}
/// <summary>
/// Creates the decoder result.
/// </summary>
/// <returns>The decoder result.</returns>
/// <param name="detectionResult">Detection result.</param>
private static DecoderResult createDecoderResult(DetectionResult detectionResult)
{
BarcodeValue[][] barcodeMatrix = createBarcodeMatrix(detectionResult);
if (barcodeMatrix == null)
return null;
if (!adjustCodewordCount(detectionResult, barcodeMatrix))
{
return null;
}
List<int> erasures = new List<int>();
int[] codewords = new int[detectionResult.RowCount * detectionResult.ColumnCount];
List<int[]> ambiguousIndexValuesList = new List<int[]>();
List<int> ambiguousIndexesList = new List<int>();
for (int row = 0; row < detectionResult.RowCount; row++)
{
for (int column = 0; column < detectionResult.ColumnCount; column++)
{
int[] values = barcodeMatrix[row][column + 1].getValue();
int codewordIndex = row * detectionResult.ColumnCount + column;
if (values.Length == 0)
{
erasures.Add(codewordIndex);
}
else if (values.Length == 1)
{
codewords[codewordIndex] = values[0];
}
else
{
ambiguousIndexesList.Add(codewordIndex);
ambiguousIndexValuesList.Add(values);
}
}
}
int[][] ambiguousIndexValues = new int[ambiguousIndexValuesList.Count][];
for (int i = 0; i < ambiguousIndexValues.Length; i++)
{
ambiguousIndexValues[i] = ambiguousIndexValuesList[i];
}
return createDecoderResultFromAmbiguousValues(detectionResult.ErrorCorrectionLevel, codewords,
erasures.ToArray(), ambiguousIndexesList.ToArray(), ambiguousIndexValues);
}
/// <summary>
/// This method deals with the fact, that the decoding process doesn't always yield a single most likely value. The
/// current error correction implementation doesn't deal with erasures very well, so it's better to provide a value
/// for these ambiguous codewords instead of treating it as an erasure. The problem is that we don't know which of
/// the ambiguous values to choose. We try decode using the first value, and if that fails, we use another of the
/// ambiguous values and try to decode again. This usually only happens on very hard to read and decode barcodes,
/// so decoding the normal barcodes is not affected by this.
/// </summary>
/// <returns>The decoder result from ambiguous values.</returns>
/// <param name="ecLevel">Ec level.</param>
/// <param name="codewords">Codewords.</param>
/// <param name="erasureArray">contains the indexes of erasures.</param>
/// <param name="ambiguousIndexes">array with the indexes that have more than one most likely value.</param>
/// <param name="ambiguousIndexValues">two dimensional array that contains the ambiguous values. The first dimension must
/// be the same Length as the ambiguousIndexes array.</param>
private static DecoderResult createDecoderResultFromAmbiguousValues(int ecLevel,
int[] codewords,
int[] erasureArray,
int[] ambiguousIndexes,
int[][] ambiguousIndexValues)
{
int[] ambiguousIndexCount = new int[ambiguousIndexes.Length];
int tries = 100;
while (tries-- > 0)
{
for (int i = 0; i < ambiguousIndexCount.Length; i++)
{
codewords[ambiguousIndexes[i]] = ambiguousIndexValues[i][ambiguousIndexCount[i]];
}
try
{
var result = decodeCodewords(codewords, ecLevel, erasureArray);
if (result != null)
return result;
}
catch (ReaderException)
{
// ignored, should not happen
}
if (ambiguousIndexCount.Length == 0)
{
return null;
}
for (int i = 0; i < ambiguousIndexCount.Length; i++)
{
if (ambiguousIndexCount[i] < ambiguousIndexValues[i].Length - 1)
{
ambiguousIndexCount[i]++;
break;
}
else
{
ambiguousIndexCount[i] = 0;
if (i == ambiguousIndexCount.Length - 1)
{
return null;
}
}
}
}
return null;
}
/// <summary>
/// Creates the barcode matrix.
/// </summary>
/// <returns>The barcode matrix.</returns>
/// <param name="detectionResult">Detection result.</param>
private static BarcodeValue[][] createBarcodeMatrix(DetectionResult detectionResult)
{
// Manually setup Jagged Array in C#
var barcodeMatrix = new BarcodeValue[detectionResult.RowCount][];
for (int row = 0; row < barcodeMatrix.Length; row++)
{
barcodeMatrix[row] = new BarcodeValue[detectionResult.ColumnCount + 2];
for (int col = 0; col < barcodeMatrix[row].Length; col++)
{
barcodeMatrix[row][col] = new BarcodeValue();
}
}
int column = 0;
foreach (DetectionResultColumn detectionResultColumn in detectionResult.getDetectionResultColumns())
{
if (detectionResultColumn != null)
{
foreach (Codeword codeword in detectionResultColumn.Codewords)
{
if (codeword != null)
{
int rowNumber = codeword.RowNumber;
if (rowNumber >= 0)
{
if (rowNumber >= barcodeMatrix.Length)
{
return null;
}
barcodeMatrix[rowNumber][column].setValue(codeword.Value);
}
}
}
}
column++;
}
return barcodeMatrix;
}
/// <summary>
/// Tests to see if the Barcode Column is Valid
/// </summary>
/// <returns><c>true</c>, if barcode column is valid, <c>false</c> otherwise.</returns>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeColumn">Barcode column.</param>
private static bool isValidBarcodeColumn(DetectionResult detectionResult, int barcodeColumn)
{
return (barcodeColumn >= 0) && (barcodeColumn < detectionResult.DetectionResultColumns.Length);
}
/// <summary>
/// Gets the start column.
/// </summary>
/// <returns>The start column.</returns>
/// <param name="detectionResult">Detection result.</param>
/// <param name="barcodeColumn">Barcode column.</param>
/// <param name="imageRow">Image row.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
private static int getStartColumn(DetectionResult detectionResult,
int barcodeColumn,
int imageRow,
bool leftToRight)
{
int offset = leftToRight ? 1 : -1;
Codeword codeword = null;
if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodeword(imageRow);
}
if (codeword != null)
{
return leftToRight ? codeword.EndX : codeword.StartX;
}
codeword = detectionResult.DetectionResultColumns[barcodeColumn].getCodewordNearby(imageRow);
if (codeword != null)
{
return leftToRight ? codeword.StartX : codeword.EndX;
}
if (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
codeword = detectionResult.DetectionResultColumns[barcodeColumn - offset].getCodewordNearby(imageRow);
}
if (codeword != null)
{
return leftToRight ? codeword.EndX : codeword.StartX;
}
int skippedColumns = 0;
while (isValidBarcodeColumn(detectionResult, barcodeColumn - offset))
{
barcodeColumn -= offset;
foreach (Codeword previousRowCodeword in detectionResult.DetectionResultColumns[barcodeColumn].Codewords)
{
if (previousRowCodeword != null)
{
return (leftToRight ? previousRowCodeword.EndX : previousRowCodeword.StartX) +
offset *
skippedColumns *
(previousRowCodeword.EndX - previousRowCodeword.StartX);
}
}
skippedColumns++;
}
return leftToRight ? detectionResult.Box.MinX : detectionResult.Box.MaxX;
}
/// <summary>
/// Detects the codeword.
/// </summary>
/// <returns>The codeword.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="startColumn">Start column.</param>
/// <param name="imageRow">Image row.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static Codeword detectCodeword(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int startColumn,
int imageRow,
int minCodewordWidth,
int maxCodewordWidth)
{
startColumn = adjustCodewordStartColumn(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
// we usually know fairly exact now how long a codeword is. We should provide minimum and maximum expected length
// and try to adjust the read pixels, e.g. remove single pixel errors or try to cut off exceeding pixels.
// min and maxCodewordWidth should not be used as they are calculated for the whole barcode an can be inaccurate
// for the current position
int[] moduleBitCount = getModuleBitCount(image, minColumn, maxColumn, leftToRight, startColumn, imageRow);
if (moduleBitCount == null)
{
return null;
}
int endColumn;
int codewordBitCount = PDF417Common.getBitCountSum(moduleBitCount);
if (leftToRight)
{
endColumn = startColumn + codewordBitCount;
}
else
{
for (int i = 0; i < (moduleBitCount.Length >> 1); i++)
{
int tmpCount = moduleBitCount[i];
moduleBitCount[i] = moduleBitCount[moduleBitCount.Length - 1 - i];
moduleBitCount[moduleBitCount.Length - 1 - i] = tmpCount;
}
endColumn = startColumn;
startColumn = endColumn - codewordBitCount;
}
// TODO implement check for width and correction of black and white bars
// use start (and maybe stop pattern) to determine if blackbars are wider than white bars. If so, adjust.
// should probably done only for codewords with a lot more than 17 bits.
// The following fixes 10-1.png, which has wide black bars and small white bars
// for (int i = 0; i < moduleBitCount.Length; i++) {
// if (i % 2 == 0) {
// moduleBitCount[i]--;
// } else {
// moduleBitCount[i]++;
// }
// }
// We could also use the width of surrounding codewords for more accurate results, but this seems
// sufficient for now
if (!checkCodewordSkew(codewordBitCount, minCodewordWidth, maxCodewordWidth))
{
// We could try to use the startX and endX position of the codeword in the same column in the previous row,
// create the bit count from it and normalize it to 8. This would help with single pixel errors.
return null;
}
int decodedValue = PDF417CodewordDecoder.getDecodedValue(moduleBitCount);
int codeword = PDF417Common.getCodeword(decodedValue);
if (codeword == -1)
{
return null;
}
return new Codeword(startColumn, endColumn, getCodewordBucketNumber(decodedValue), codeword);
}
/// <summary>
/// Gets the module bit count.
/// </summary>
/// <returns>The module bit count.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="startColumn">Start column.</param>
/// <param name="imageRow">Image row.</param>
private static int[] getModuleBitCount(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int startColumn,
int imageRow)
{
int imageColumn = startColumn;
int[] moduleBitCount = new int[8];
int moduleNumber = 0;
int increment = leftToRight ? 1 : -1;
bool previousPixelValue = leftToRight;
while (((leftToRight && imageColumn < maxColumn) || (!leftToRight && imageColumn >= minColumn)) &&
moduleNumber < moduleBitCount.Length)
{
if (image[imageColumn, imageRow] == previousPixelValue)
{
moduleBitCount[moduleNumber]++;
imageColumn += increment;
}
else
{
moduleNumber++;
previousPixelValue = !previousPixelValue;
}
}
if (moduleNumber == moduleBitCount.Length ||
(((leftToRight && imageColumn == maxColumn) || (!leftToRight && imageColumn == minColumn)) && moduleNumber == moduleBitCount.Length - 1))
{
return moduleBitCount;
}
return null;
}
/// <summary>
/// Gets the number of EC code words.
/// </summary>
/// <returns>The number of EC code words.</returns>
/// <param name="barcodeECLevel">Barcode EC level.</param>
private static int getNumberOfECCodeWords(int barcodeECLevel)
{
return 2 << barcodeECLevel;
}
/// <summary>
/// Adjusts the codeword start column.
/// </summary>
/// <returns>The codeword start column.</returns>
/// <param name="image">Image.</param>
/// <param name="minColumn">Minimum column.</param>
/// <param name="maxColumn">Max column.</param>
/// <param name="leftToRight">If set to <c>true</c> left to right.</param>
/// <param name="codewordStartColumn">Codeword start column.</param>
/// <param name="imageRow">Image row.</param>
private static int adjustCodewordStartColumn(BitMatrix image,
int minColumn,
int maxColumn,
bool leftToRight,
int codewordStartColumn,
int imageRow)
{
int correctedStartColumn = codewordStartColumn;
int increment = leftToRight ? -1 : 1;
// there should be no black pixels before the start column. If there are, then we need to start earlier.
for (int i = 0; i < 2; i++)
{
while (((leftToRight && correctedStartColumn >= minColumn) || (!leftToRight && correctedStartColumn < maxColumn)) &&
leftToRight == image[correctedStartColumn, imageRow])
{
if (Math.Abs(codewordStartColumn - correctedStartColumn) > CODEWORD_SKEW_SIZE)
{
return codewordStartColumn;
}
correctedStartColumn += increment;
}
increment = -increment;
leftToRight = !leftToRight;
}
return correctedStartColumn;
}
/// <summary>
/// Checks the codeword for any skew.
/// </summary>
/// <returns><c>true</c>, if codeword is within the skew, <c>false</c> otherwise.</returns>
/// <param name="codewordSize">Codeword size.</param>
/// <param name="minCodewordWidth">Minimum codeword width.</param>
/// <param name="maxCodewordWidth">Max codeword width.</param>
private static bool checkCodewordSkew(int codewordSize, int minCodewordWidth, int maxCodewordWidth)
{
return minCodewordWidth - CODEWORD_SKEW_SIZE <= codewordSize &&
codewordSize <= maxCodewordWidth + CODEWORD_SKEW_SIZE;
}
/// <summary>
/// Decodes the codewords.
/// </summary>
/// <returns>The codewords.</returns>
/// <param name="codewords">Codewords.</param>
/// <param name="ecLevel">Ec level.</param>
/// <param name="erasures">Erasures.</param>
private static DecoderResult decodeCodewords(int[] codewords, int ecLevel, int[] erasures)
{
if (codewords.Length == 0)
{
return null;
}
int numECCodewords = 1 << (ecLevel + 1);
int correctedErrorsCount = correctErrors(codewords, erasures, numECCodewords);
if (correctedErrorsCount < 0)
{
return null;
}
if (!verifyCodewordCount(codewords, numECCodewords))
{
return null;
}
// Decode the codewords
DecoderResult decoderResult = DecodedBitStreamParser.decode(codewords, ecLevel.ToString());
if (decoderResult != null)
{
decoderResult.ErrorsCorrected = correctedErrorsCount;
decoderResult.Erasures = erasures.Length;
}
return decoderResult;
}
/// <summary>
/// Given data and error-correction codewords received, possibly corrupted by errors, attempts to
/// correct the errors in-place.
/// </summary>
/// <returns>The errors.</returns>
/// <param name="codewords">data and error correction codewords.</param>
/// <param name="erasures">positions of any known erasures.</param>
/// <param name="numECCodewords">number of error correction codewords that are available in codewords.</param>
private static int correctErrors(int[] codewords, int[] erasures, int numECCodewords)
{
if (erasures != null &&
erasures.Length > numECCodewords / 2 + MAX_ERRORS ||
numECCodewords < 0 ||
numECCodewords > MAX_EC_CODEWORDS)
{
// Too many errors or EC Codewords is corrupted
return -1;
}
int errorCount;
if (!errorCorrection.decode(codewords, numECCodewords, erasures, out errorCount))
{
return -1;
}
return errorCount;
}
/// <summary>
/// Verifies that all is well with the the codeword array.
/// </summary>
/// <param name="codewords">Codewords.</param>
/// <param name="numECCodewords">Number EC codewords.</param>
private static bool verifyCodewordCount(int[] codewords, int numECCodewords)
{
if (codewords.Length < 4)
{
// Codeword array size should be at least 4 allowing for
// Count CW, At least one Data CW, Error Correction CW, Error Correction CW
return false;
}
// The first codeword, the Symbol Length Descriptor, shall always encode the total number of data
// codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad
// codewords, but excluding the number of error correction codewords.
int numberOfCodewords = codewords[0];
if (numberOfCodewords > codewords.Length)
{
return false;
}
if (numberOfCodewords == 0)
{
// Reset to the Length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)
if (numECCodewords < codewords.Length)
{
codewords[0] = codewords.Length - numECCodewords;
}
else
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the bit count for codeword.
/// </summary>
/// <returns>The bit count for codeword.</returns>
/// <param name="codeword">Codeword.</param>
private static int[] getBitCountForCodeword(int codeword)
{
int[] result = new int[8];
int previousValue = 0;
int i = result.Length - 1;
while (true)
{
if ((codeword & 0x1) != previousValue)
{
previousValue = codeword & 0x1;
i--;
if (i < 0)
{
break;
}
}
result[i]++;
codeword >>= 1;
}
return result;
}
/// <summary>
/// Gets the codeword bucket number.
/// </summary>
/// <returns>The codeword bucket number.</returns>
/// <param name="codeword">Codeword.</param>
private static int getCodewordBucketNumber(int codeword)
{
return getCodewordBucketNumber(getBitCountForCodeword(codeword));
}
/// <summary>
/// Gets the codeword bucket number.
/// </summary>
/// <returns>The codeword bucket number.</returns>
/// <param name="moduleBitCount">Module bit count.</param>
private static int getCodewordBucketNumber(int[] moduleBitCount)
{
return (moduleBitCount[0] - moduleBitCount[2] + moduleBitCount[4] - moduleBitCount[6] + 9) % 9;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the <see cref="ZXing.PDF417.Internal.BarcodeValue"/> jagged array.</returns>
/// <param name="barcodeMatrix">Barcode matrix as a jagged array.</param>
public static String ToString(BarcodeValue[][] barcodeMatrix)
{
StringBuilder formatter = new StringBuilder();
for (int row = 0; row < barcodeMatrix.Length; row++)
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "Row {0,2}: ", row);
for (int column = 0; column < barcodeMatrix[row].Length; column++)
{
BarcodeValue barcodeValue = barcodeMatrix[row][column];
int[] values = barcodeValue.getValue();
if (values.Length == 0)
{
formatter.Append(" ");
}
else
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "{0,4}({1,2})", values[0], barcodeValue.getConfidence(values[0]));
}
}
formatter.Append("\n");
}
return formatter.ToString();
}
}
}
| |
/* InstantVR Oculus Rift head controller
* author: Pascal Serrarens
* email: support@passervr.com
* version: 3.0.9
* date: June 28, 2015
*
* - Unity 5.1: Fixed issue when avatar is not at 0,0,0
*/
using UnityEngine;
using System.Collections;
#if !(UNITY_4_5 || UNITY_4_6 || UNITY_5_0)
using UnityEngine.VR;
#endif
public class IVR_RiftHead : IVR_Controller
{
#if (UNITY_4_5 || UNITY_4_6 || UNITY_5_0)
[HideInInspector] private OVRCameraRig ovrCR;
[HideInInspector] private Transform headcam;
[HideInInspector] private Vector3 ovrCRstartPoint;
[HideInInspector] private Vector3 baseStartPoint;
[HideInInspector] private Quaternion ovrCRstartRotation;
[HideInInspector] private float baseStartAngle;
[HideInInspector] private Vector3 neckOffset;
void Start() {
}
public override void StartController(InstantVR ivr) {
headcam = this.transform.FindChild("Headcam").GetComponentInChildren<Camera>().transform;
OVRCameraRig ovrCRprefab = Resources.Load <OVRCameraRig>("OVRCameraRig");
ovrCR = (OVRCameraRig) Instantiate(ovrCRprefab, headcam.position, headcam.rotation);
if (ovrCR != null) {
ovrCR.transform.parent = ivr.transform;
if (ovrCR.centerEyeAnchor == null)
Debug.LogWarning("centerEyeAnchor not found in OVR Camera Rift. Head animation will not work.");
} else
Debug.LogError("Could not instantiate OVRCameraRig. Prefab is missin?");
ovrCRstartPoint = ovrCR.transform.position;
baseStartPoint = ivr.BasePosition;
ovrCRstartRotation = ovrCR.transform.rotation;
baseStartAngle = ivr.BaseRotation.eulerAngles.y;
neckOffset = -headcam.localPosition;
present = CheckRiftPresent();
if (!present) {
ovrCR.gameObject.SetActive(false);
}
base.StartController(ivr);
startRotation = Quaternion.Inverse(ivr.BaseRotation);
}
private bool CheckRiftPresent() {
if (OVRManager.display != null)
return (OVRManager.display.isPresent);
else
return false;
}
public override void UpdateController() {
if (present && this.enabled)
UpdateRift();
else
tracking = false;
}
private void UpdateRift() {
if (ovrCR != null) {
Vector3 baseDelta = ivr.BasePosition - baseStartPoint;
ovrCR.transform.position = ovrCRstartPoint + baseDelta;
float baseAngleDelta = ivr.BaseRotation.eulerAngles.y - baseStartAngle;
ovrCR.transform.rotation = ovrCRstartRotation * Quaternion.AngleAxis(baseAngleDelta, Vector3.up);
if (ovrCR.centerEyeAnchor != null) {
Vector3 thisNeckOffset = ovrCR.centerEyeAnchor.rotation * -neckOffset;
this.position = ovrCR.centerEyeAnchor.position - thisNeckOffset - baseDelta;
this.rotation = ovrCR.centerEyeAnchor.rotation * Quaternion.AngleAxis(-baseAngleDelta, Vector3.up);;
if (this.position.z > 1000) {
//Debug.LogWarning("Head position out of range");
tracking = false;
this.position = Vector3.zero;
this.rotation = Quaternion.identity;
} else if (!tracking) {
Calibrate(false);
tracking = true;
}
base.UpdateController();
}
}
}
public override void OnTargetReset() {
if (selected) {
Vector3 referencePosBefore = this.referencePosition;
Calibrate(false);
ovrCRstartPoint += this.referencePosition - referencePosBefore;
this.referencePosition = referencePosBefore;
}
}
#else
[HideInInspector] private GameObject vrCamera;
[HideInInspector] private Transform headcam;
[HideInInspector] private Vector3 ovrCRstartPoint;
[HideInInspector] private Vector3 baseStartPoint;
[HideInInspector] private Quaternion ovrCRstartRotation;
[HideInInspector] private float baseStartAngle;
[HideInInspector] private Vector3 neckOffset;
// This dummy code is here to ensure the checkbox is present in editor
void Start() {}
public override void StartController(InstantVR ivr) {
headcam = this.transform.FindChild("Headcam").GetComponentInChildren<Camera>().transform;
vrCamera = new GameObject("VRCameraRoot");
vrCamera.transform.parent = ivr.transform;
vrCamera.transform.position = this.transform.position;
vrCamera.transform.rotation = this.transform.rotation;
GameObject vrCameraObj = new GameObject("VRCamera");
Camera hmdCam = vrCameraObj.AddComponent<Camera>();
hmdCam.nearClipPlane = 0.01f;
hmdCam.farClipPlane = 1000;
vrCameraObj.transform.position = headcam.position;
vrCameraObj.transform.rotation = headcam.rotation;
vrCameraObj.transform.parent = vrCamera.transform;
ovrCRstartPoint = vrCamera.transform.position;
baseStartPoint = ivr.BasePosition;
ovrCRstartRotation = vrCamera.transform.rotation;
baseStartAngle = ivr.BaseRotation.eulerAngles.y;
neckOffset = -headcam.localPosition;
present = VRDevice.isPresent;
if (!present)
vrCamera.SetActive(false);
else
headcam.gameObject.SetActive(false);
headcam = vrCameraObj.transform;
base.StartController(ivr);
referencePosition = Vector3.zero;
startRotation = Quaternion.Inverse(ivr.BaseRotation);
startRotation = Quaternion.identity;
InputTracking.Recenter();
}
public override void UpdateController() {
if (present && this.enabled)
UpdateRift();
else
tracking = false;
}
private void UpdateRift() {
Vector3 baseDelta = ivr.BasePosition - baseStartPoint;
vrCamera.transform.position = ovrCRstartPoint + baseDelta;
float baseAngleDelta = ivr.BaseRotation.eulerAngles.y - baseStartAngle;
vrCamera.transform.rotation = ovrCRstartRotation * Quaternion.AngleAxis(baseAngleDelta, Vector3.up);
Vector3 centerPos = InputTracking.GetLocalPosition(VRNode.CenterEye);
Quaternion centerRot = InputTracking.GetLocalRotation(VRNode.CenterEye);
if (centerPos.magnitude < 10 && centerPos.magnitude > 0) {
Vector3 thisNeckOffset = centerRot * -neckOffset;
this.position = vrCamera.transform.position + centerPos - thisNeckOffset - baseDelta;
this.rotation = vrCamera.transform.rotation * centerRot * Quaternion.AngleAxis(-baseAngleDelta, Vector3.up);
if (this.position.z > 1000) {
Debug.LogWarning("Head position out of range");
tracking = false;
this.position = Vector3.zero;
this.rotation = Quaternion.identity;
} else if (!tracking) {
Calibrate(false);
tracking = true;
}
if (referencePosition.magnitude > 1000)
Debug.Log ("Head reference position is out of range");
base.UpdateController();
}
}
public override void OnTargetReset() {
if (selected) {
Vector3 referencePosBefore = this.referencePosition;
Calibrate(false);
ovrCRstartPoint += this.referencePosition - referencePosBefore;
this.referencePosition = referencePosBefore;
}
}
#endif
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Threading;
using System.Collections.Generic;
using System.Configuration.Provider;
using System.Collections;
namespace System.Web
{
public partial class StaticSiteMapProviderEx
{
private List<SiteMapProvider> _childProviders;
private Dictionary<SiteMapProvider, SiteMapNode> _childProviderRootNodes;
//private ReaderWriterLockSlim _childProviderRwLock = new ReaderWriterLockSlim();
private SiteMapNode FindSiteMapNodeFromChildProvider(string rawUrl)
{
foreach (var provider in ChildProviders)
{
EnsureChildSiteMapProviderUpToDate(provider);
var node = provider.FindSiteMapNode(rawUrl);
if (node != null)
return node;
}
return null;
}
protected bool HasChildProviders
{
get { return !EnumerableEx.IsNullOrEmpty(ChildProviders); }
}
private SiteMapNode FindSiteMapNodeFromChildProviderKey(string key)
{
foreach (var provider in ChildProviders)
{
EnsureChildSiteMapProviderUpToDate(provider);
var node = provider.FindSiteMapNodeFromKey(key);
if (node != null)
return node;
}
return null;
}
public void AddProvider(string providerName, SiteMapNode parentNode) { AddProvider(providerName, parentNode, null); }
public void AddProvider(string providerName, SiteMapNode parentNode, Action<SiteMapNode> rebaseAction)
{
if (parentNode == null)
throw new ArgumentNullException("parentNode");
if (parentNode.Provider != this)
throw new ArgumentException(string.Format("StaticSiteMapProviderEx_cannot_add_node", parentNode.ToString()), "parentNode");
var rootNode = GetNodeFromProvider(providerName, rebaseAction);
AddNode(rootNode, parentNode);
}
private SiteMapNode GetNodeFromProvider(string providerName, Action<SiteMapNode> rebaseAction)
{
var providerFromName = GetProviderFromName(providerName);
var rootNode = providerFromName.RootNode;
if (rootNode == null)
throw new InvalidOperationException(string.Format("StaticSiteMapProviderEx_invalid_GetRootNodeCore", providerFromName.Name));
if (!ChildProviderRootNodes.ContainsKey(providerFromName))
{
ChildProviderRootNodes.Add(providerFromName, rootNode);
_childProviders = null;
providerFromName.ParentProvider = this;
if (rebaseAction != null)
rebaseAction(rootNode);
}
return rootNode;
}
protected override void RemoveNode(SiteMapNode node)
{
if (node == null)
throw new ArgumentNullException("node");
var provider = node.Provider;
if (provider != this)
for (var parentProvider = provider.ParentProvider; parentProvider != this; parentProvider = parentProvider.ParentProvider)
if (parentProvider == null)
throw new InvalidOperationException(string.Format("StaticSiteMapProviderEx_cannot_remove_node", node.ToString(), Name, provider.Name));
if (node.Equals(provider.RootNode))
throw new InvalidOperationException("StaticSiteMapProviderEx_cannot_remove_root_node");
if (provider != this)
_providerRemoveNode.Invoke(provider, new[] { node });
base.RemoveNode(node);
}
protected virtual void RemoveProvider(string providerName)
{
if (providerName == null)
throw new ArgumentNullException("providerName");
lock (_providerLock)
{
var providerFromName = GetProviderFromName(providerName);
var node = ChildProviderRootNodes[providerFromName];
if (node == null)
throw new InvalidOperationException(string.Format("StaticSiteMapProviderEx_cannot_find_provider", providerFromName.Name, Name));
providerFromName.ParentProvider = null;
ChildProviderRootNodes.Remove(providerFromName);
_childProviders = null;
base.RemoveNode(node);
}
}
private List<SiteMapProvider> ChildProviders
{
get
{
if (_childProviders == null)
lock (_providerLock)
if (_childProviders == null)
_childProviders = new List<SiteMapProvider>(ChildProviderRootNodes.Keys);
return _childProviders;
}
}
private Dictionary<SiteMapProvider, SiteMapNode> ChildProviderRootNodes
{
get
{
if (_childProviderRootNodes == null)
lock (_providerLock)
if (_childProviderRootNodes == null)
_childProviderRootNodes = new Dictionary<SiteMapProvider, SiteMapNode>();
return _childProviderRootNodes;
}
}
private void EnsureChildSiteMapProviderUpToDate(SiteMapProvider childProvider)
{
var node = ChildProviderRootNodes[childProvider];
if (node == null)
return;
var rootNode = childProvider.RootNode;
if (rootNode == null)
throw new InvalidOperationException(string.Format("XmlSiteMapProvider_invalid_sitemapnode_returned", childProvider.Name));
if (!node.Equals(rootNode))
lock (_providerLock)
{
node = ChildProviderRootNodes[childProvider];
if (node != null)
{
rootNode = childProvider.RootNode;
if (rootNode == null)
throw new InvalidOperationException(string.Format("XmlSiteMapProvider_invalid_sitemapnode_returned", childProvider.Name));
if (!node.Equals(rootNode))
{
// double-lock reached
if (_rootNode.Equals(node))
{
RemoveNode(node);
AddNode(rootNode);
_rootNode = rootNode;
}
//var node3 = (SiteMapNode)base.ParentNodeTable[node];
//if (node3 != null)
//{
// var nodes = (SiteMapNodeCollection)base.ChildNodeCollectionTable[node3];
// int index = nodes.IndexOf(node);
// if (index != -1)
// {
// nodes.Remove(node);
// nodes.Insert(index, rootNode);
// }
// else
// nodes.Add(rootNode);
// base.ParentNodeTable[rootNode] = node3;
// base.ParentNodeTable.Remove(node);
// RemoveNode(node);
// AddNode(rootNode);
//}
//else
//{
// var parentProvider = (ParentProvider as StaticSiteMapProviderEx);
// if (parentProvider != null)
// parentProvider.EnsureChildSiteMapProviderUpToDate(this);
//}
ChildProviderRootNodes[childProvider] = rootNode;
_childProviders = null;
}
}
}
}
}
}
| |
#if __ANDROID__
namespace XPlat.Storage
{
using System;
using System.IO;
using System.Threading.Tasks;
using XPlat.Storage.Extensions;
using XPlat.Storage.FileProperties;
using XPlat.Storage.Helpers;
using File = System.IO.File;
/// <summary>Represents a file. Provides information about the file and its contents, and ways to manipulate them.</summary>
public sealed class StorageFile : IStorageFile
{
/// <summary>
/// Initializes a new instance of the <see cref="StorageFile"/> class.
/// </summary>
/// <param name="path">
/// The path to the file.
/// </param>
public StorageFile(string path)
{
this.Path = path;
}
/// <summary>Gets the date and time when the current item was created.</summary>
public DateTime DateCreated => File.GetCreationTime(this.Path);
/// <summary>Gets the name of the item including the file name extension if there is one.</summary>
public string Name => System.IO.Path.GetFileName(this.Path);
/// <summary>Gets the user-friendly name of the item.</summary>
public string DisplayName => System.IO.Path.GetFileNameWithoutExtension(this.Path);
/// <summary>Gets the full file-system path of the item, if the item has a path.</summary>
public string Path { get; private set; }
/// <summary>Gets a value indicating whether the item exists.</summary>
public bool Exists => File.Exists(this.Path);
/// <summary>Gets the attributes of a storage item.</summary>
public FileAttributes Attributes => File.GetAttributes(this.Path).ToInternalFileAttributes();
/// <summary>Gets the type (file name extension) of the file.</summary>
public string FileType => System.IO.Path.GetExtension(this.Path);
/// <summary>Gets the MIME type of the contents of the file.</summary>
public string ContentType => MimeTypeHelper.GetMimeType(this.FileType);
/// <summary>Gets an object that provides access to the content-related properties of the item.</summary>
public IStorageItemContentProperties Properties => new StorageItemContentProperties(new WeakReference(this));
/// <summary>
/// Retrieves a <see cref="IStorageFile"/> by the given <paramref name="path"/>.
/// </summary>
/// <param name="path">The path to the file.</param>
/// <returns>The <see cref="IStorageFile"/>.</returns>
/// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="path"/> is <see langword="null"/>.</exception>
public static Task<IStorageFile> GetFileFromPathAsync(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
throw new ArgumentNullException(nameof(path));
}
IStorageFile resultFile = new StorageFile(path);
return Task.FromResult(resultFile);
}
/// <summary>Renames the current item.</summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
/// <param name="desiredName">The desired, new name of the item.</param>
/// <exception cref="T:XPlat.Storage.StorageItemCreationException">Thrown if a file with the same desired name already exists.</exception>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to rename does not exist.</exception>
/// <exception cref="T:System.ArgumentNullException">Thrown if desiredName is <see langword="null"/>.</exception>
/// <exception cref="T:System.ArgumentException">Thrown if the desired new name is the same as the current name.</exception>
/// <exception cref="T:System.InvalidOperationException">Thrown if the file cannot be renamed.</exception>
public Task RenameAsync(string desiredName)
{
return this.RenameAsync(desiredName, NameCollisionOption.FailIfExists);
}
/// <summary>Renames the current item. This method also specifies what to do if an existing item in the current item's location has the same name.</summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
/// <param name="desiredName">The desired, new name of the current item. If there is an existing item in the current item's location that already has the specified desiredName, the specified NameCollisionOption determines how Windows responds to the conflict.</param>
/// <param name="option">The enum value that determines how the system responds if the desiredName is the same as the name of an existing item in the current item's location.</param>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to rename does not exist.</exception>
/// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="desiredName"/> is <see langword="null"/>.</exception>
/// <exception cref="T:System.ArgumentException">Thrown if the desired new name is the same as the current name.</exception>
/// <exception cref="T:System.InvalidOperationException">Thrown if the file cannot be renamed.</exception>
/// <exception cref="T:XPlat.Storage.StorageItemCreationException">Thrown if a file with the same desired name already exists.</exception>
public Task RenameAsync(string desiredName, NameCollisionOption option)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot rename a file that does not exist.");
}
if (string.IsNullOrWhiteSpace(desiredName))
{
throw new ArgumentNullException(nameof(desiredName));
}
if (desiredName.Equals(this.Name, StringComparison.CurrentCultureIgnoreCase))
{
throw new ArgumentException("The desired new name is the same as the current name.");
}
FileInfo fileInfo = new FileInfo(this.Path);
if (fileInfo.Directory == null)
{
throw new InvalidOperationException("This file cannot be renamed.");
}
string newPath = System.IO.Path.Combine(fileInfo.Directory.FullName, desiredName);
switch (option)
{
case NameCollisionOption.GenerateUniqueName:
newPath = System.IO.Path.Combine(fileInfo.Directory.FullName, $"{desiredName}-{Guid.NewGuid()}");
fileInfo.MoveTo(newPath);
break;
case NameCollisionOption.ReplaceExisting:
if (File.Exists(newPath))
{
File.Delete(newPath);
}
fileInfo.MoveTo(newPath);
break;
default:
if (File.Exists(newPath))
{
throw new StorageItemCreationException(
desiredName,
"A file with the same name already exists.");
}
fileInfo.MoveTo(newPath);
break;
}
this.Path = newPath;
return Task.CompletedTask;
}
/// <summary>Deletes the current item.</summary>
/// <returns>No object or value is returned by this method when it completes.</returns>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to delete does not exist.</exception>
public Task DeleteAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot delete a file that does not exist.");
}
File.Delete(this.Path);
return Task.CompletedTask;
}
/// <summary>Determines whether the current IStorageItem matches the specified StorageItemTypes value.</summary>
/// <returns>True if the IStorageItem matches the specified value; otherwise false.</returns>
/// <param name="type">The value to match against.</param>
public bool IsOfType(StorageItemTypes type)
{
return type == StorageItemTypes.File;
}
/// <summary>Gets the basic properties of the current item (like a file or folder).</summary>
/// <returns>When this method completes successfully, it returns the basic properties of the current item as a BasicProperties object.</returns>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to get basic properties for does not exist.</exception>
public Task<IBasicProperties> GetBasicPropertiesAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(
this.Name,
"Cannot get properties for a folder that does not exist.");
}
IBasicProperties props = new BasicProperties(this.Path);
return Task.FromResult(props);
}
/// <summary>Gets the parent folder of the current storage item.</summary>
/// <returns>When this method completes, it returns the parent folder as a StorageFolder.</returns>
public Task<IStorageFolder> GetParentAsync()
{
IStorageFolder result = default(IStorageFolder);
DirectoryInfo parent = Directory.GetParent(this.Path);
if (parent != null)
{
result = new StorageFolder(parent.FullName);
}
return Task.FromResult(result);
}
/// <summary>Indicates whether the current item is the same as the specified item.</summary>
/// <returns>Returns true if the current storage item is the same as the specified storage item; otherwise false.</returns>
/// <param name="item">The IStorageItem object that represents a storage item to compare against.</param>
/// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="item"/> is <see langword="null"/>.</exception>
public bool IsEqual(IStorageItem item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return item.Path.Equals(this.Path, StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// Opens a stream over the current file for reading file contents.
/// </summary>
/// <returns>
/// When this method completes, it returns the stream.
/// </returns>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to open does not exist.</exception>
/// <exception cref="T:XPlat.Storage.StorageFileIOException">Thrown if the file could not be opened.</exception>
public Task<Stream> OpenReadAsync()
{
return this.OpenAsync(FileAccessMode.Read);
}
/// <summary>Opens a stream over the file.</summary>
/// <returns>When this method completes, it returns the stream.</returns>
/// <param name="accessMode">The type of access to allow.</param>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to open does not exist.</exception>
/// <exception cref="T:XPlat.Storage.StorageFileIOException">Thrown if the file could not be opened.</exception>
public Task<Stream> OpenAsync(FileAccessMode accessMode)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot open a file that does not exist.");
}
Stream stream;
switch (accessMode)
{
case FileAccessMode.Read:
stream = File.OpenRead(this.Path);
break;
case FileAccessMode.ReadWrite:
stream = File.Open(this.Path, FileMode.Open, FileAccess.ReadWrite);
break;
default: throw new StorageFileIOException(this.Name, "The file could not be opened.");
}
return Task.FromResult(stream);
}
/// <summary>Creates a copy of the file in the specified folder.</summary>
/// <returns>When this method completes, it returns a StorageFile that represents the copy.</returns>
/// <param name="destinationFolder">The destination folder where the copy is created.</param>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to copy or folder to copy to does not exist.</exception>
/// <exception cref="T:XPlat.Storage.StorageItemCreationException">Thrown if a file with the same name already exists at the destination.</exception>
/// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="destinationFolder"/> is <see langword="null"/>.</exception>
public Task<IStorageFile> CopyAsync(IStorageFolder destinationFolder)
{
return this.CopyAsync(destinationFolder, this.Name);
}
/// <summary>Creates a copy of the file in the specified folder, using the desired name.</summary>
/// <returns>When this method completes, it returns a StorageFile that represents the copy.</returns>
/// <param name="destinationFolder">The destination folder where the copy is created.</param>
/// <param name="desiredNewName">The desired name of the copy. If there is an existing file in the destination folder that already has the specified desiredNewName, Windows generates a unique name for the copy.</param>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to copy or folder to copy to does not exist.</exception>
/// <exception cref="T:XPlat.Storage.StorageItemCreationException">Thrown if a file with the same name already exists at the destination.</exception>
/// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="destinationFolder"/> or <paramref name="desiredNewName"/> is <see langword="null"/>.</exception>
public Task<IStorageFile> CopyAsync(IStorageFolder destinationFolder, string desiredNewName)
{
return this.CopyAsync(destinationFolder, desiredNewName, NameCollisionOption.FailIfExists);
}
/// <summary>Creates a copy of the file in the specified folder, using the desired name. This method also specifies what to do if an existing file in the specified folder has the same name.</summary>
/// <returns>When this method completes, it returns a StorageFile that represents the copy.</returns>
/// <param name="destinationFolder">The destination folder where the copy is created.</param>
/// <param name="desiredNewName">The desired name of the copy. If there is an existing file in the destination folder that already has the specified desiredNewName, the specified NameCollisionOption determines how Windows responds to the conflict.</param>
/// <param name="option">An enum value that determines how Windows responds if the desiredNewName is the same as the name of an existing file in the destination folder.</param>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to copy or folder to copy to does not exist.</exception>
/// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="destinationFolder"/> or <paramref name="desiredNewName"/> is <see langword="null"/>.</exception>
/// <exception cref="T:XPlat.Storage.StorageItemCreationException">Thrown if a file with the same name already exists at the destination.</exception>
public Task<IStorageFile> CopyAsync(
IStorageFolder destinationFolder,
string desiredNewName,
NameCollisionOption option)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot copy a file that does not exist.");
}
if (destinationFolder == null)
{
throw new ArgumentNullException(nameof(destinationFolder));
}
if (!destinationFolder.Exists)
{
throw new StorageItemNotFoundException(
destinationFolder.Name,
"Cannot copy a file to a folder that does not exist.");
}
if (string.IsNullOrWhiteSpace(desiredNewName))
{
throw new ArgumentNullException(nameof(desiredNewName));
}
string newPath = System.IO.Path.Combine(destinationFolder.Path, desiredNewName);
switch (option)
{
case NameCollisionOption.GenerateUniqueName:
newPath = System.IO.Path.Combine(destinationFolder.Path, $"{Guid.NewGuid()}-{desiredNewName}");
File.Copy(this.Path, newPath);
break;
case NameCollisionOption.ReplaceExisting:
if (File.Exists(newPath))
{
File.Delete(newPath);
}
File.Copy(this.Path, newPath);
break;
default:
if (File.Exists(newPath))
{
throw new StorageItemCreationException(
desiredNewName,
"A file with the same name already exists.");
}
File.Copy(this.Path, newPath);
break;
}
IStorageFile file = new StorageFile(newPath);
return Task.FromResult(file);
}
/// <summary>Replaces the specified file with a copy of the current file.</summary>
/// <returns>No object or value is returned when this method completes.</returns>
/// <param name="fileToReplace">The file to replace.</param>
/// <exception cref="T:XPlat.Storage.StorageItemNotFoundException">Thrown if the file to copy and replace does not exist.</exception>
/// <exception cref="T:System.ArgumentNullException">Thrown if <paramref name="fileToReplace"/> is <see langword="null"/>.</exception>
public Task CopyAndReplaceAsync(IStorageFile fileToReplace)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot copy a file that does not exist.");
}
if (fileToReplace == null)
{
throw new ArgumentNullException(nameof(fileToReplace));
}
if (!fileToReplace.Exists)
{
throw new StorageItemNotFoundException(
fileToReplace.Name,
"Cannot copy to and replace a file that does not exist.");
}
File.Copy(this.Path, fileToReplace.Path, true);
return Task.CompletedTask;
}
/// <summary>Moves the current file to the specified folder.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="destinationFolder">The destination folder where the file is moved. This destination folder must be a physical location. Otherwise, if the destination folder exists only in memory, like a file group, this method fails and throws an exception.</param>
public Task MoveAsync(IStorageFolder destinationFolder)
{
return this.MoveAsync(destinationFolder, this.Name);
}
/// <summary>Moves the current file to the specified folder and renames the file according to the desired name.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="destinationFolder">The destination folder where the file is moved. This destination folder must be a physical location. Otherwise, if the destination folder exists only in memory, like a file group, this method fails and throws an exception.</param>
/// <param name="desiredNewName">The desired name of the file after it is moved. If there is an existing file in the destination folder that already has the specified desiredNewName, Windows generates a unique name for the file.</param>
public Task MoveAsync(IStorageFolder destinationFolder, string desiredNewName)
{
return this.MoveAsync(destinationFolder, desiredNewName, NameCollisionOption.ReplaceExisting);
}
/// <summary>Moves the current file to the specified folder and renames the file according to the desired name. This method also specifies what to do if a file with the same name already exists in the specified folder.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="destinationFolder">The destination folder where the file is moved. This destination folder must be a physical location. Otherwise, if the destination folder exists only in memory, like a file group, this method fails and throws an exception.</param>
/// <param name="desiredNewName">The desired name of the file after it is moved. If there is an existing file in the destination folder that already has the specified desiredNewName, the specified NameCollisionOption determines how Windows responds to the conflict.</param>
/// <param name="option">An enum value that determines how Windows responds if the desiredNewName is the same as the name of an existing file in the destination folder.</param>
public Task MoveAsync(IStorageFolder destinationFolder, string desiredNewName, NameCollisionOption option)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot move a file that does not exist.");
}
if (destinationFolder == null)
{
throw new ArgumentNullException(nameof(destinationFolder));
}
if (!destinationFolder.Exists)
{
throw new StorageItemNotFoundException(
destinationFolder.Name,
"Cannot move a file to a folder that does not exist.");
}
if (string.IsNullOrWhiteSpace(desiredNewName))
{
throw new ArgumentNullException(nameof(desiredNewName));
}
string newPath = System.IO.Path.Combine(destinationFolder.Path, desiredNewName);
switch (option)
{
case NameCollisionOption.GenerateUniqueName:
newPath = System.IO.Path.Combine(destinationFolder.Path, $"{Guid.NewGuid()}-{desiredNewName}");
File.Move(this.Path, newPath);
break;
case NameCollisionOption.ReplaceExisting:
if (File.Exists(newPath))
{
File.Delete(newPath);
}
File.Move(this.Path, newPath);
break;
default:
if (File.Exists(newPath))
{
throw new StorageItemCreationException(
desiredNewName,
"A file with the same name already exists.");
}
File.Move(this.Path, newPath);
break;
}
this.Path = newPath;
return Task.CompletedTask;
}
/// <summary>Moves the current file to the location of the specified file and replaces the specified file in that location.</summary>
/// <returns>No object or value is returned by this method.</returns>
/// <param name="fileToReplace">The file to replace.</param>
public Task MoveAndReplaceAsync(IStorageFile fileToReplace)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot move a file that does not exist.");
}
if (fileToReplace == null)
{
throw new ArgumentNullException(nameof(fileToReplace));
}
if (!fileToReplace.Exists)
{
throw new StorageItemNotFoundException(
fileToReplace.Name,
"Cannot move to and replace a file that does not exist.");
}
string newPath = fileToReplace.Path;
File.Delete(newPath);
File.Move(this.Path, newPath);
this.Path = newPath;
return Task.CompletedTask;
}
/// <summary>
/// Writes a string to the current file.
/// </summary>
/// <param name="text">
/// The text to write out.
/// </param>
/// <returns>
/// An object that is used to manage the asynchronous operation.
/// </returns>
public async Task WriteTextAsync(string text)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot write to a file that does not exist.");
}
using (Stream stream = await this.OpenAsync(FileAccessMode.ReadWrite))
{
stream.SetLength(0);
using (StreamWriter writer = new StreamWriter(stream))
{
await writer.WriteAsync(text);
}
}
}
/// <summary>
/// Reads the current file as a string.
/// </summary>
/// <returns>
/// When this method completes, it returns the file's content as a string.
/// </returns>
public async Task<string> ReadTextAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot read from a file that does not exist.");
}
string text;
using (Stream stream = await this.OpenAsync(FileAccessMode.Read))
{
using (StreamReader reader = new StreamReader(stream))
{
text = await reader.ReadToEndAsync();
}
}
return text;
}
/// <summary>
/// Writes a byte array to the current file.
/// </summary>
/// <param name="bytes">
/// The byte array to write out.
/// </param>
/// <returns>
/// An object that is used to manage the asynchronous operation.
/// </returns>
public Task WriteBytesAsync(byte[] bytes)
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot write to a file that does not exist.");
}
File.WriteAllBytes(this.Path, bytes);
return Task.CompletedTask;
}
/// <summary>
/// Reads the current file as a byte array.
/// </summary>
/// <returns>
/// When this method completes, it returns the file's content as a byte array.
/// </returns>
public Task<byte[]> ReadBytesAsync()
{
if (!this.Exists)
{
throw new StorageItemNotFoundException(this.Name, "Cannot read from a file that does not exist.");
}
byte[] bytes = File.ReadAllBytes(this.Path);
return Task.FromResult(bytes);
}
}
}
#endif
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Collections.Generic;
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem.Core;
using Boo.Lang.Environments;
namespace Boo.Lang.Compiler.TypeSystem.Internal
{
public class InternalMethod : InternalEntity<Method>, IMethod, INamespace
{
protected InternalTypeSystemProvider _provider;
protected IMethod _override;
protected ExpressionCollection _returnExpressions;
protected List _yieldStatements;
internal InternalMethod(InternalTypeSystemProvider provider, Method method) : base(method)
{
_provider = provider;
}
public bool IsDuckTyped
{
get { return My<TypeSystemServices>.Instance.IsDuckType(ReturnType); }
}
public bool IsPInvoke
{
get { return IsAttributeDefined(Types.DllImportAttribute); }
}
public bool IsAbstract
{
get { return _node.IsAbstract; }
}
public bool IsVirtual
{
get { return _node.IsVirtual || _node.IsAbstract || _node.IsOverride; }
}
public bool IsFinal
{
get { return _node.IsFinal; }
}
public bool IsSpecialName
{
get { return false; }
}
public bool AcceptVarArgs
{
get { return _node.Parameters.HasParamArray; }
}
override public EntityType EntityType
{
get { return EntityType.Method; }
}
public ICallableType CallableType
{
get { return My<TypeSystemServices>.Instance.GetCallableType(this); }
}
public IType Type
{
get { return CallableType; }
}
public Method Method
{
get { return _node; }
}
public IMethod Overriden
{
get { return _override; }
set { _override = value; }
}
public IParameter[] GetParameters()
{
return _provider.Map(_node.Parameters);
}
public virtual IType ReturnType
{
get
{
if (null == _node.ReturnType)
return _node.DeclaringType.NodeType == NodeType.ClassDefinition
? Unknown.Default
: _provider.VoidType;
return TypeSystemServices.GetType(_node.ReturnType);
}
}
public INamespace ParentNamespace
{
get { return DeclaringType; }
}
public bool IsGenerator
{
get { return null != _yieldStatements; }
}
public ExpressionCollection ReturnExpressions
{
get { return _returnExpressions; }
}
public ExpressionCollection YieldExpressions
{
get
{
ExpressionCollection expressions = new ExpressionCollection();
foreach (YieldStatement stmt in _yieldStatements)
if (null != stmt.Expression) expressions.Add(stmt.Expression);
return expressions;
}
}
sealed class LabelCollector : FastDepthFirstVisitor
{
private static readonly InternalLabel[] EmptyInternalLabelArray = new InternalLabel[0];
List _labels;
public override void OnLabelStatement(LabelStatement node)
{
if (null == _labels) _labels = new List();
_labels.Add(node.Entity);
}
public InternalLabel[] Labels
{
get
{
if (null == _labels) return EmptyInternalLabelArray;
return (InternalLabel[])_labels.ToArray(new InternalLabel[_labels.Count]);
}
}
}
public InternalLabel[] Labels
{
get
{
LabelCollector collector = new LabelCollector();
_node.Accept(collector);
return collector.Labels;
}
}
public void AddYieldStatement(YieldStatement stmt)
{
if (null == _yieldStatements) _yieldStatements = new List();
_yieldStatements.Add(stmt);
}
public void AddReturnExpression(Expression expression)
{
if (null == _returnExpressions) _returnExpressions = new ExpressionCollection();
_returnExpressions.Add(expression);
}
public Local ResolveLocal(string name)
{
var locals = _node.Locals;
for (int i = 0; i < locals.Count; i++)
{
var local = locals[i];
if (local.PrivateScope) continue;
if (string.CompareOrdinal(name, local.Name) == 0) return local;
}
return null;
}
public ParameterDeclaration ResolveParameter(string name)
{
foreach (ParameterDeclaration parameter in _node.Parameters)
{
if (name == parameter.Name) return parameter;
}
return null;
}
public virtual bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider)
{
if (Entities.IsFlagSet(typesToConsider, EntityType.Local))
{
Local local = ResolveLocal(name);
if (null != local)
{
resultingSet.Add(TypeSystemServices.GetEntity(local));
return true;
}
}
if (Entities.IsFlagSet(typesToConsider, EntityType.Parameter))
{
ParameterDeclaration parameter = ResolveParameter(name);
if (null != parameter)
{
resultingSet.Add(TypeSystemServices.GetEntity(parameter));
return true;
}
}
return false;
}
IEnumerable<IEntity> INamespace.GetMembers()
{
return NullNamespace.EmptyEntityArray;
}
override public string ToString()
{
return _node.FullName;
}
public virtual IConstructedMethodInfo ConstructedInfo
{
get { return null; }
}
public virtual IGenericMethodInfo GenericInfo
{
get { return null; }
}
public bool IsNew
{
get { return _node.IsNew; }
}
}
}
| |
// 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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences
{
internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged, INamingStylesInfoDialogViewModel
{
public Guid ID { get; set; }
public List<SymbolKindViewModel> SymbolKindList { get; set; }
public List<AccessibilityViewModel> AccessibilityList { get; set; }
public List<ModifierViewModel> ModifierList { get; set; }
private string _symbolSpecName;
public bool CanBeDeleted { get; set; }
private readonly INotificationService _notificationService;
public SymbolSpecificationViewModel(
string languageName,
bool canBeDeleted,
INotificationService notificationService) : this(languageName, CreateDefaultSymbolSpecification(), canBeDeleted, notificationService) { }
public SymbolSpecificationViewModel(string languageName, SymbolSpecification specification, bool canBeDeleted, INotificationService notificationService)
{
CanBeDeleted = canBeDeleted;
_notificationService = notificationService;
ItemName = specification.Name;
ID = specification.ID;
// The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753.
if (languageName == LanguageNames.CSharp)
{
SymbolKindList = new List<SymbolKindViewModel>
{
new SymbolKindViewModel(TypeKind.Class, "class", specification),
new SymbolKindViewModel(TypeKind.Struct, "struct", specification),
new SymbolKindViewModel(TypeKind.Interface, "interface", specification),
new SymbolKindViewModel(TypeKind.Enum, "enum", specification),
new SymbolKindViewModel(SymbolKind.Property, "property", specification),
new SymbolKindViewModel(SymbolKind.Method, "method", specification),
new SymbolKindViewModel(SymbolKind.Field, "field", specification),
new SymbolKindViewModel(SymbolKind.Event, "event", specification),
new SymbolKindViewModel(TypeKind.Delegate, "delegate", specification),
new SymbolKindViewModel(SymbolKind.Parameter, "parameter", specification)
};
AccessibilityList = new List<AccessibilityViewModel>
{
new AccessibilityViewModel(Accessibility.Public, "public", specification),
new AccessibilityViewModel(Accessibility.Internal, "internal", specification),
new AccessibilityViewModel(Accessibility.Private, "private", specification),
new AccessibilityViewModel(Accessibility.Protected, "protected", specification),
new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification),
};
ModifierList = new List<ModifierViewModel>
{
new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification),
new ModifierViewModel(DeclarationModifiers.Async, "async", specification),
new ModifierViewModel(DeclarationModifiers.Const, "const", specification),
new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification),
new ModifierViewModel(DeclarationModifiers.Static, "static", specification)
};
}
else if (languageName == LanguageNames.VisualBasic)
{
SymbolKindList = new List<SymbolKindViewModel>
{
new SymbolKindViewModel(TypeKind.Class, "Class", specification),
new SymbolKindViewModel(TypeKind.Struct, "Structure", specification),
new SymbolKindViewModel(TypeKind.Interface, "Interface", specification),
new SymbolKindViewModel(TypeKind.Enum, "Enum", specification),
new SymbolKindViewModel(TypeKind.Module, "Module", specification),
new SymbolKindViewModel(SymbolKind.Property, "Property", specification),
new SymbolKindViewModel(SymbolKind.Method, "Method", specification),
new SymbolKindViewModel(SymbolKind.Field, "Field", specification),
new SymbolKindViewModel(SymbolKind.Event, "Event", specification),
new SymbolKindViewModel(TypeKind.Delegate, "Delegate", specification),
new SymbolKindViewModel(SymbolKind.Parameter, "Parameter", specification)
};
AccessibilityList = new List<AccessibilityViewModel>
{
new AccessibilityViewModel(Accessibility.Public, "Public", specification),
new AccessibilityViewModel(Accessibility.Friend, "Friend", specification),
new AccessibilityViewModel(Accessibility.Private, "Private", specification),
new AccessibilityViewModel(Accessibility.Protected , "Protected", specification),
new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification),
};
ModifierList = new List<ModifierViewModel>
{
new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification),
new ModifierViewModel(DeclarationModifiers.Async, "Async", specification),
new ModifierViewModel(DeclarationModifiers.Const, "Const", specification),
new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification),
new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification)
};
}
else
{
throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName));
}
}
public string ItemName
{
get { return _symbolSpecName; }
set { SetProperty(ref _symbolSpecName, value); }
}
internal SymbolSpecification GetSymbolSpecification()
{
return new SymbolSpecification(
ID,
ItemName,
SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolKindOrTypeKind()).ToImmutableArray(),
AccessibilityList.Where(a => a.IsChecked).Select(a => a._accessibility).ToImmutableArray(),
ModifierList.Where(m => m.IsChecked).Select(m => new ModifierKind(m._modifier)).ToImmutableArray());
}
internal bool TrySubmit()
{
if (string.IsNullOrWhiteSpace(ItemName))
{
_notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Naming_Style);
return false;
}
return true;
}
internal interface ISymbolSpecificationViewModelPart
{
bool IsChecked { get; set; }
}
public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart
{
public string Name { get; set; }
public bool IsChecked
{
get { return _isChecked; }
set { SetProperty(ref _isChecked, value); }
}
private readonly SymbolKind? _symbolKind;
private readonly TypeKind? _typeKind;
private bool _isChecked;
public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification)
{
_symbolKind = symbolKind;
Name = name;
IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind);
}
public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification)
{
_typeKind = typeKind;
Name = name;
IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind);
}
internal SymbolKindOrTypeKind CreateSymbolKindOrTypeKind()
{
if (_symbolKind.HasValue)
{
return new SymbolKindOrTypeKind(_symbolKind.Value);
}
else
{
return new SymbolKindOrTypeKind(_typeKind.Value);
}
}
}
public class AccessibilityViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart
{
internal readonly Accessibility _accessibility;
public string Name { get; set; }
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set { SetProperty(ref _isChecked, value); }
}
public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification)
{
_accessibility = accessibility;
Name = name;
IsChecked = specification.ApplicableAccessibilityList.Any(a => a == accessibility);
}
}
public class ModifierViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart
{
public string Name { get; set; }
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set { SetProperty(ref _isChecked, value); }
}
internal readonly DeclarationModifiers _modifier;
public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification)
{
_modifier = modifier;
Name = name;
IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier);
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using SharpFileSystem;
using NUnit.Framework;
using System;
namespace SharpFileSystem.Tests
{
/// <summary>
///This is a test class for FileSystemPathTest and is intended
///to contain all FileSystemPathTest Unit Tests
///</summary>
[TestFixture]
public class FileSystemPathTest
{
private FileSystemPath[] _paths = new[]
{
root,
directoryA,
fileA,
directoryB,
fileB
};
private IEnumerable<FileSystemPath> Directories { get { return _paths.Where(p => p.IsDirectory); } }
private IEnumerable<FileSystemPath> Files { get { return _paths.Where(p => p.IsFile); } }
private static readonly FileSystemPath directoryA = FileSystemPath.Parse("/directorya/");
private static FileSystemPath fileA = FileSystemPath.Parse("/filea");
private static FileSystemPath directoryB = FileSystemPath.Parse("/directorya/directoryb/");
private static FileSystemPath fileB = FileSystemPath.Parse("/directorya/fileb.txt");
private static FileSystemPath root = FileSystemPath.Root;
private FileSystemPath fileC;
public FileSystemPathTest()
{
}
/// <summary>
///A test for Root
///</summary>
[Test]
public void RootTest()
{
Assert.AreEqual(FileSystemPath.Parse("/"), root);
}
/// <summary>
///A test for ParentPath
///</summary>
[Test]
public void ParentPathTest()
{
Assert.IsTrue(
Directories
.Where(d => d.GetDirectorySegments().Length == 1)
.All(d => d.ParentPath == root)
);
Assert.IsFalse(!Files.All(f => f.RemoveChild(root.AppendFile(f.EntityName)) == f.ParentPath));
EAssert.Throws<InvalidOperationException>(() => Assert.AreEqual(root.ParentPath, root.ParentPath));
}
/// <summary>
///A test for IsRoot
///</summary>
[Test]
public void IsRootTest()
{
Assert.IsTrue(root.IsRoot);
Assert.IsFalse(directoryA.IsRoot);
Assert.IsFalse(fileA.IsRoot);
}
/// <summary>
///A test for IsFile
///</summary>
[Test]
public void IsFileTest()
{
Assert.IsTrue(fileA.IsFile);
Assert.IsFalse(directoryA.IsFile);
Assert.IsFalse(root.IsFile);
}
/// <summary>
///A test for IsDirectory
///</summary>
[Test]
public void IsDirectoryTest()
{
Assert.IsTrue(directoryA.IsDirectory);
Assert.IsTrue(root.IsDirectory);
Assert.IsFalse(fileA.IsDirectory);
}
/// <summary>
///A test for EntityName
///</summary>
[Test]
public void EntityNameTest()
{
Assert.AreEqual(fileA.EntityName, "filea");
Assert.AreEqual(fileB.EntityName, "fileb.txt");
Assert.AreEqual(root.EntityName, null);
}
/// <summary>
///A test for ToString
///</summary>
[Test]
public void ToStringTest()
{
string s = "/directorya/";
Assert.AreEqual(s, FileSystemPath.Parse(s).ToString());
}
/// <summary>
///A test for RemoveParent
///</summary>
[Test]
public void RemoveParentTest()
{
Assert.AreEqual(directoryB.RemoveParent(directoryB), root);
Assert.AreEqual(fileB.RemoveParent(directoryA), FileSystemPath.Parse("/fileb.txt"));
Assert.AreEqual(root.RemoveParent(root), root);
Assert.AreEqual(directoryB.RemoveParent(root), directoryB);
EAssert.Throws<ArgumentException>(() => fileB.RemoveParent(FileSystemPath.Parse("/nonexistantparent/")));
EAssert.Throws<ArgumentException>(() => fileB.RemoveParent(FileSystemPath.Parse("/nonexistantparent")));
EAssert.Throws<ArgumentException>(() => fileB.RemoveParent(FileSystemPath.Parse("/fileb.txt")));
EAssert.Throws<ArgumentException>(() => fileB.RemoveParent(FileSystemPath.Parse("/directorya")));
}
/// <summary>
///A test for RemoveChild
///</summary>
[Test]
public void RemoveChildTest()
{
Assert.AreEqual(fileB.RemoveChild(FileSystemPath.Parse("/fileb.txt")), directoryA);
Assert.AreEqual(directoryB.RemoveChild(FileSystemPath.Parse("/directoryb/")), directoryA);
Assert.AreEqual(directoryB.RemoveChild(directoryB), root);
Assert.AreEqual(fileB.RemoveChild(fileB), root);
EAssert.Throws<ArgumentException>(() => directoryA.RemoveChild(FileSystemPath.Parse("/nonexistantchild")));
EAssert.Throws<ArgumentException>(() => directoryA.RemoveChild(FileSystemPath.Parse("/directorya")));
}
/// <summary>
///A test for Parse
///</summary>
[Test]
public void ParseTest()
{
Assert.IsTrue(_paths.All(p => p == FileSystemPath.Parse(p.ToString())));
EAssert.Throws<ArgumentNullException>(() => FileSystemPath.Parse(null));
EAssert.Throws<ParseException>(() => FileSystemPath.Parse("thisisnotapath"));
EAssert.Throws<ParseException>(() => FileSystemPath.Parse("/thisisainvalid//path"));
}
/// <summary>
///A test for IsRooted
///</summary>
[Test]
public void IsRootedTest()
{
Assert.IsTrue(FileSystemPath.IsRooted("/filea"));
Assert.IsTrue(FileSystemPath.IsRooted("/directorya/"));
Assert.IsFalse(FileSystemPath.IsRooted("filea"));
Assert.IsFalse(FileSystemPath.IsRooted("directorya/"));
Assert.IsTrue(_paths.All(p => FileSystemPath.IsRooted(p.ToString())));
}
/// <summary>
///A test for IsParentOf
///</summary>
[Test]
public void IsParentOfTest()
{
Assert.IsTrue(directoryA.IsParentOf(fileB));
Assert.IsTrue(directoryA.IsParentOf(directoryB));
Assert.IsTrue(root.IsParentOf(fileA));
Assert.IsTrue(root.IsParentOf(directoryA));
Assert.IsTrue(root.IsParentOf(fileB));
Assert.IsTrue(root.IsParentOf(directoryB));
Assert.IsFalse(fileB.IsParentOf(directoryA));
Assert.IsFalse(directoryB.IsParentOf(directoryA));
Assert.IsFalse(fileA.IsParentOf(root));
Assert.IsFalse(directoryA.IsParentOf(root));
Assert.IsFalse(fileB.IsParentOf(root));
Assert.IsFalse(directoryB.IsParentOf(root));
}
/// <summary>
///A test for IsChildOf
///</summary>
[Test]
public void IsChildOfTest()
{
Assert.IsTrue(fileB.IsChildOf(directoryA));
Assert.IsTrue(directoryB.IsChildOf(directoryA));
Assert.IsTrue(fileA.IsChildOf(root));
Assert.IsTrue(directoryA.IsChildOf(root));
Assert.IsTrue(fileB.IsChildOf(root));
Assert.IsTrue(directoryB.IsChildOf(root));
Assert.IsFalse(directoryA.IsChildOf(fileB));
Assert.IsFalse(directoryA.IsChildOf(directoryB));
Assert.IsFalse(root.IsChildOf(fileA));
Assert.IsFalse(root.IsChildOf(directoryA));
Assert.IsFalse(root.IsChildOf(fileB));
Assert.IsFalse(root.IsChildOf(directoryB));
}
/// <summary>
///A test for GetExtension
///</summary>
[Test]
public void GetExtensionTest()
{
Assert.AreEqual(fileA.GetExtension(), "");
Assert.AreEqual(fileB.GetExtension(), ".txt");
fileC = FileSystemPath.Parse("/directory.txt/filec");
Assert.AreEqual(fileC.GetExtension(), "");
EAssert.Throws<ArgumentException>(() => directoryA.GetExtension());
}
/// <summary>
///A test for GetDirectorySegments
///</summary>
[Test]
public void GetDirectorySegmentsTest()
{
Assert.AreEqual(0, root.GetDirectorySegments().Length);
Directories
.Where(d => !d.IsRoot)
.All(d => d.GetDirectorySegments().Length == d.ParentPath.GetDirectorySegments().Length - 1);
Files.All(f => f.GetDirectorySegments().Length == f.ParentPath.GetDirectorySegments().Length);
}
/// <summary>
///A test for CompareTo
///</summary>
[Test]
public void CompareToTest()
{
foreach(var pa in _paths)
foreach(var pb in _paths)
Assert.AreEqual(Math.Sign(pa.CompareTo(pb)), Math.Sign(String.Compare(pa.ToString(), pb.ToString(), StringComparison.Ordinal)));
}
/// <summary>
///A test for ChangeExtension
///</summary>
[Test]
public void ChangeExtensionTest()
{
foreach(var p in _paths.Where(p => p.IsFile))
Assert.IsTrue( p.ChangeExtension(".exe").GetExtension() == ".exe");
EAssert.Throws<ArgumentException>(() => directoryA.ChangeExtension(".exe"));
}
/// <summary>
///A test for AppendPath
///</summary>
[Test]
public void AppendPathTest()
{
Assert.IsTrue(Directories.All(p => p.AppendPath(root) == p));
Assert.IsTrue(Directories.All(p => p.AppendPath("") == p));
var subpath = FileSystemPath.Parse("/dir/file");
var subpathstr = "dir/file";
foreach(var p in Directories)
Assert.IsTrue(p.AppendPath(subpath).ParentPath.ParentPath == p);
foreach(var p in Directories)
Assert.IsTrue(p.AppendPath(subpathstr).ParentPath.ParentPath == p);
foreach(var pa in Directories)
foreach (var pb in _paths.Where(pb => !pb.IsRoot))
Assert.IsTrue(pa.AppendPath(pb).IsChildOf(pa));
EAssert.Throws<InvalidOperationException>(() => fileA.AppendPath(subpath));
EAssert.Throws<InvalidOperationException>(() => fileA.AppendPath(subpathstr));
EAssert.Throws<ArgumentException>(() => directoryA.AppendPath("/rootedpath/"));
}
/// <summary>
///A test for AppendFile
///</summary>
[Test]
public void AppendFileTest()
{
foreach(var d in Directories)
Assert.IsTrue(d.AppendFile("file").IsFile);
foreach (var d in Directories)
Assert.IsTrue(d.AppendFile("file").EntityName == "file");
foreach(var d in Directories)
Assert.IsTrue(d.AppendFile("file").ParentPath == d);
EAssert.Throws<InvalidOperationException>(() => fileA.AppendFile("file"));
EAssert.Throws<ArgumentException>(() => directoryA.AppendFile("dir/file"));
}
/// <summary>
///A test for AppendDirectory
///</summary>
[Test]
public void AppendDirectoryTest()
{
foreach(var d in Directories)
Assert.IsTrue(d.AppendDirectory("dir").IsDirectory);
foreach(var d in Directories)
Assert.IsTrue(d.AppendDirectory("dir").EntityName == "dir");
foreach (var d in Directories)
Assert.IsTrue(d.AppendDirectory("dir").ParentPath == d);
EAssert.Throws<InvalidOperationException>(() => fileA.AppendDirectory("dir"));
EAssert.Throws<ArgumentException>(() => root.AppendDirectory("dir/dir"));
}
}
}
| |
datablock CameraData(Observer) {};
datablock PlayerData(Monster) {
shapeFile = "art/monster.dae";
mass = 90;
swimForce = 90 * 5;
maxUnderwaterForwardSpeed = 25;
maxUnderwaterBackwardSpeed = 25;
maxUnderwaterSideSpeed = 25;
groundImpactMinSpeed = 100;
};
datablock PlayerData(Tourist) {
class = Person;
shapeFile = "art/tourist.dae";
mass = 90;
runSurfaceAngle = 85;
runForce = 90 * 12;
maxForwardSpeed = 8;
maxBackwardSpeed = 8;
maxSideSpeed = 8;
swimForce = 90 * 1;
maxUnderwaterForwardSpeed = 3;
maxUnderwaterBackwardSpeed = 3;
maxUnderwaterSideSpeed = 3;
};
datablock PlayerData(Ranger : Tourist) {
shapeFile = "art/ranger.dae";
};
datablock ParticleData(AttackRippleParticle) {
textureName = "art/wake";
dragCoefficient = 0.0;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.0;
lifetimeMS = 4000;
lifetimeVarianceMS = 1000;
windCoefficient = 0.0;
useInvAlpha = true;
spinRandomMin = 30.0;
spinRandomMax = 30.0;
spinSpeed = 0;
animateTexture = true;
framesPerSec = 1;
animTexTiling = "2 1";
animTexFrames = "0 1";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 1.0";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 2.0;
sizes[1] = 14.0;
sizes[2] = 22.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock particleData(BubbleRippleParticle) {
textureName = "art/wake";
dragCoefficient = 0.0;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 200;
windCoefficient = 0.0;
useInvAlpha = true;
spinRandomMin = 30.0;
spinRandomMax = 30.0;
spinSpeed = 0;
animateTexture = true;
framesPerSec = 1;
animTexTiling = "2 1";
animTexFrames = "0 1";
colors[0] = "1 1 1 1.0";
colors[1] = "1 1 1 0.8";
colors[2] = "1 1 1 0.0";
sizes[0] = 2.0;
sizes[1] = 8.0;
sizes[2] = 12.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleData(BubbleParticle)
{
textureName = "art/bubble";
dragCoefficient = 0.0;
windCoefficient = 0.0;
gravityCoefficient = -0.1;
inheritedVelFactor = 0.00;
lifetimeMS = 1600;
lifetimeVarianceMS = 500;
useInvAlpha = false;
colors[0] = "0.7 0.7 0.7 1";
colors[1] = "0.7 0.7 0.7 1";
colors[2] = "0.7 0.7 0.7 1";
colors[3] = "0.7 0.7 0.7 0";
sizes[0] = 0.4;
sizes[1] = 0.5;
sizes[2] = 0.55;
sizes[3] = 0.55;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 0.98;
times[3] = 1.0;
};
datablock ParticleData(AttackSplashParticle) {
textureName = "art/smoke";
dragCoefficient = 0.0;
windCoefficient = 0.0;
gravityCoefficient = 1;
inheritedVelFactor = 0.00;
lifetimeMS = 3000;
lifetimeVarianceMS = 500;
useInvAlpha = false;
colors[0] = "0.7 0.7 0.7 1";
colors[1] = "0.7 0.7 0.7 1";
colors[2] = "0.7 0.7 0.7 1";
colors[3] = "0.7 0.7 0.7 0";
sizes[0] = 6;
sizes[1] = 9;
sizes[2] = 10.5;
sizes[3] = 10.5;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 0.98;
times[3] = 1.0;
};
datablock ParticleData(AttackJetParticle : AttackSplashParticle) {
textureName = "art/splash";
gravityCoefficient = 2;
lifetimeMS = 3500;
lifetimeVarianceMS = 100;
spinRandomMin = 00.0;
spinRandomMax = 90.0;
spinSpeed = 0.5;
colors[0] = "0.7 0.7 0.7 0.7";
colors[1] = "0.7 0.7 0.7 0.6";
colors[2] = "0.7 0.7 0.7 0.4";
colors[3] = "0.7 0.7 0.7 0";
sizes[0] = 3;
sizes[1] = 5;
sizes[2] = 6.5;
sizes[3] = 6.5;
};
datablock ParticleData(WakeParticle) {
textureName = "art/smoke";
dragCoefficient = 0.3;
gravityCoefficient = 0;
inheritedVelFactor = 0.3;
lifetimeMS = 3000;
lifetimeVarianceMS = 250;
useInvAlpha = true;
spinRandomMin = -30.0;
spinRandomMax = 30.0;
colors[0] = "0.7 0.8 1.0 0.1";
colors[1] = "0.7 0.8 1.0 0.3";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 1;
sizes[1] = 3.75;
sizes[2] = 7.5;
times[0] = 0.0;
times[1] = 0.3;
times[2] = 1.0;
};
datablock ParticleEmitterData(BubbleEmitter)
{
ejectionPeriodMS = 150;
periodVarianceMS = 0;
ejectionVelocity = 0.50;
velocityVariance = 0.00;
ejectionOffset = 0.0;
thetaMin = 1.0;
thetaMax = 100.0;
particles = BubbleParticle;
};
datablock ParticleEmitterData(AttackJetEmitter) {
ejectionPeriodMS = 20;
periodVarianceMS = 0;
ejectionVelocity = 14;
velocityVariance = 2;
ejectionOffset = 0;
thetaMin = 1.0;
thetaMax = 10.0;
particles = AttackJetParticle;
};
datablock ParticleEmitterData(AttackSplashEmitter) {
ejectionPeriodMS = 15;
periodVarianceMS = 0;
ejectionVelocity = 7;
velocityVariance = 2;
ejectionOffset = 0;
thetaMin = 1.0;
thetaMax = 50.0;
particles = AttackSplashParticle;
};
datablock ParticleEmitterData(AttackRippleEmitter) {
lifetimeMS = 100;
ejectionPeriodMS = 200;
periodVarianceMS = 10;
ejectionVelocity = 0;
velocityVariance = 0;
ejectionOffset = 0;
thetaMin = 89;
thetaMax = 90;
phiReferenceVel = 0;
phiVariance = 1;
alignParticles = 1;
alignDirection = "0 0 1";
particles = AttackRippleParticle;
};
datablock ParticleEmitterData(WakeEmitter : AttackRippleEmitter) {
particles = WakeParticle;
};
datablock ParticleEmitterData(BubbleRippleEmitter : AttackRippleEmitter) {
particles = BubbleRippleParticle;
};
datablock ParticleEmitterNodeData(DefaultNode) {
timeMultiple = 1;
};
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Codentia.Common.Net.FTP;
using NUnit.Framework;
namespace Codentia.Common.Net.Test.FTP
{
/// <summary>
/// Unit testing framework for FTPClient class
/// </summary>
[TestFixture]
public class FTPClientTest
{
private static string _ftpHost = "srv01.mattchedit.com";
private static string _ftpUser = "backup";
private static string _ftpPass = "959530A8-F945-4F73-B18A-03785440661E";
private TcpListener _tcpListener;
private TcpListener _tcpListenerData;
/// <summary>
/// Perform set up
/// </summary>
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
}
/// <summary>
/// Perform clean up
/// </summary>
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
// delete all files in test folder
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot/test", _ftpUser, _ftpPass);
string[] files = client.GetFiles("test*.txt");
for (int i = 0; i < files.Length; i++)
{
client.DeleteRemoteFile(files[i]);
}
}
/// <summary>
/// Scenario: Create object with default constructor
/// Expected: Properties match default values
/// </summary>
[Test]
public void _001_Constructor_Default()
{
FTPClient client = new FTPClient();
Assert.That(client.Connected, Is.False);
Assert.That(client.Credentials, Is.Null);
Assert.That(client.Port, Is.EqualTo(21));
Assert.That(client.Mode, Is.EqualTo(FTPTransferMode.ASCII));
}
/// <summary>
/// Scenario: Create object with first constructor (Host, Port, Path, Credentials)
/// Expected: Properties match input values where specified, else default
/// </summary>
[Test]
public void _002_Constructor_HostPortPathCredentials()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass);
Assert.That(client.Connected, Is.False);
Assert.That(client.Credentials, Is.Not.Null);
Assert.That(client.Credentials.UserName, Is.EqualTo(_ftpUser));
Assert.That(client.Credentials.Password, Is.EqualTo(_ftpPass));
Assert.That(client.Port, Is.EqualTo(21));
Assert.That(client.Mode, Is.EqualTo(FTPTransferMode.ASCII));
Assert.That(client.RemotePath, Is.EqualTo("/ftproot"));
Assert.That(client.RemoteHost, Is.EqualTo(_ftpHost));
}
/// <summary>
/// Scenario: Create object with second constructor (Host, Port, Path, Credentials, Mode)
/// Expected: Properties match input values where specified, else default
/// </summary>
[Test]
public void _003_Constructor_HostPortPathCredentialsMode()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
Assert.That(client.Connected, Is.False);
Assert.That(client.Credentials, Is.Not.Null);
Assert.That(client.Credentials.UserName, Is.EqualTo(_ftpUser));
Assert.That(client.Credentials.Password, Is.EqualTo(_ftpPass));
Assert.That(client.Port, Is.EqualTo(21));
Assert.That(client.Mode, Is.EqualTo(FTPTransferMode.Binary));
Assert.That(client.RemotePath, Is.EqualTo("/ftproot"));
Assert.That(client.RemoteHost, Is.EqualTo(_ftpHost));
}
/// <summary>
/// Scenario: Create object with overload (path, mode)
/// Expected: Properties match input values where specified, else default from app.config (host, user, password)
/// </summary>
[Test]
public void _003b_Constructor_HostPortPathCredentialsMode()
{
FTPClient client = new FTPClient("/ftproot", FTPTransferMode.Binary);
Assert.That(client.Connected, Is.False);
Assert.That(client.Credentials, Is.Not.Null);
Assert.That(client.Credentials.UserName, Is.EqualTo(ConfigurationManager.AppSettings["DefaultFTPUser"]));
Assert.That(client.Credentials.Password, Is.EqualTo(ConfigurationManager.AppSettings["DefaultFTPPassword"]));
Assert.That(client.Port, Is.EqualTo(21));
Assert.That(client.Mode, Is.EqualTo(FTPTransferMode.Binary));
Assert.That(client.RemotePath, Is.EqualTo("/ftproot"));
Assert.That(client.RemoteHost, Is.EqualTo(ConfigurationManager.AppSettings["DefaultFTPHost"]));
}
/// <summary>
/// Scenario: Try to connect to an unknown host (unresolvable hostname)
/// Expected: SocketException(No such host is known)
/// </summary>
[Test]
public void _004_Connect_UnknownHost()
{
FTPClient client = new FTPClient(string.Format("{0}.com", Guid.NewGuid()), 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
Assert.That(delegate { client.Connect(); }, Throws.Exception);
}
/// <summary>
/// Scenario: Attempt to connect to a valid server, but on a port where there is no ftp server
/// Expected: FTPException(0, Unable to connect to remote server)
/// </summary>
[Test]
public void _005_Connect_NoFTPServerRunning()
{
FTPClient client = new FTPClient("192.168.0.1", 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
Assert.That(delegate { client.Connect(); }, Throws.Exception.With.Message.EqualTo("Unable to connect to remote server"));
}
/// <summary>
/// Scenario: Attempt to connect to a valid server, with an invalid username
/// Expected: FTPException(530, User xx cannot log in)
/// </summary>
[Test]
public void _006_Connect_IncorrectUser()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", "wibble", "wobble", FTPTransferMode.Binary);
Assert.That(delegate { client.Connect(); }, Throws.InstanceOf<FTPException>());
}
/// <summary>
/// Scenario: Attempt to connect to a valid server, but with an invalid password
/// Expected: FTPException(530, User xx cannot log in)
/// </summary>
[Test]
public void _007_Connect_IncorrectPassword()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, "wobble", FTPTransferMode.Binary);
Assert.That(delegate { client.Connect(); }, Throws.InstanceOf<FTPException>());
}
/// <summary>
/// Scenario: Connect to a valid host and port using a valid username and password
/// Expected: Completes without error, connected flag is true after connection
/// </summary>
[Test]
public void _008_Connect_ValidUserNamePassword()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
Assert.That(client.Connected, Is.True);
client.Close();
}
/// <summary>
/// Scenario: Change the RemotePath of an FTPClient once it is connected
/// Expected: Path changes, ChDir command executed.
/// </summary>
[Test]
public void _009_RemotePath_Connected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
Assert.That(client.RemotePath, Is.EqualTo("/ftproot/test"));
client.Close();
}
/// <summary>
/// Scenario: Change the RemotePath of an FTPClient which is not connected
/// Expected: Client connects, Path changes, ChDir command executed.
/// </summary>
[Test]
public void _010_RemotePath_NotConnected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.RemotePath = "/ftproot/test";
Assert.That(client.RemotePath, Is.EqualTo("/ftproot/test"));
client.Close();
}
/// <summary>
/// Scenario: Change the RemotePath of an FTPClient once it is connected to an invalid value
/// Expected: FTPException(550, xxx: The system cannot find the file specified)
/// </summary>
[Test]
public void _011_RemotePath_Invalid()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
string path = client.RemotePath;
string message = string.Empty;
Assert.That(delegate { client.RemotePath = "/invalidpath/"; }, Throws.InstanceOf<FTPException>());
Assert.That(client.RemotePath, Is.EqualTo(path), "Path changed - should not be");
client.Close();
}
/// <summary>
/// Scenario: Generate and upload a test file, resume disabled
/// Expected: File uploaded successfully
/// </summary>
[Test]
public void _012_UploadFile_Connected_NoResume()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test/";
client.UploadFile(filename);
client.Close();
}
// <summary>
// Scenario: Generate and upload a test file, resume enabled but not required
// Expected: File uploaded successfully
// </summary>
/*
[Test]
public void _013_UploadFile_Connected_Resume_NotRequired()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient(_FTPHost, 21, "/ftproot", _FTPUser, _FTPPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
client.UploadFile(filename, true);
client.Close();
}*/
/// <summary>
/// Scenario: Generate and upload a test file, then delete it
/// Expected: File uploaded and deleted
/// </summary>
[Test]
public void _014_DeleteFile_Connected_ValidFile()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
client.UploadFile(filename);
client.DeleteRemoteFile(filename);
client.Close();
}
/// <summary>
/// Scenario: Generate and upload a test file, then delete it (not connected)
/// Expected: File uploaded and deleted
/// </summary>
[Test]
public void _015_DeleteFile_NotConnected_ValidFile()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
client.UploadFile(filename);
client.Close();
client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.RemotePath = "/ftproot/test";
client.DeleteRemoteFile(filename);
client.Close();
}
/// <summary>
/// Scenario: Attempt to delete a non-existant remote file
/// Expected: FTPException(550, xxx: The system cannot find the file specified)
/// </summary>
[Test]
public void _016_DeleteFile_Connected_InvalidFilename()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
Assert.That(delegate { client.DeleteRemoteFile(filename); }, Throws.InstanceOf<FTPException>());
client.Close();
}
/// <summary>
/// Scenario: Get/Set Port while not connected
/// Expected: Value set is retrieved
/// </summary>
[Test]
public void _017_Port_GetSet_NotConnected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Port = 100;
Assert.That(client.Port, Is.EqualTo(100));
}
/// <summary>
/// Scenario: Get/Set Port while connected
/// Expected: FTPException(0, Cannot change Port while connected)
/// </summary>
[Test]
public void _018_Port_GetSet_Connected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.Port = 100; }, Throws.InstanceOf<FTPException>().With.Message.EqualTo("Cannot change Port while connected"));
Assert.That(client.Port, Is.EqualTo(21));
client.Close();
}
/// <summary>
/// Scenario: Get/Set RemoteHost while not connected
/// Expected: Value set is retrieved
/// </summary>
[Test]
public void _019_RemoteHost_GetSet_NotConnected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.RemoteHost = "flibble.com";
Assert.That(client.RemoteHost, Is.EqualTo("flibble.com"));
}
/// <summary>
/// Scenario: Get/Set RemoteHost while connected
/// Expected: FTPException(0, Cannot change RemoteHost while connected)
/// </summary>
[Test]
public void _020_RemoteHost_GetSet_Connected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.RemoteHost = "flibble.com"; }, Throws.InstanceOf<FTPException>().With.Message.EqualTo("Cannot change RemoteHost while connected"));
Assert.That(client.RemoteHost, Is.EqualTo(_ftpHost));
client.Close();
}
/// <summary>
/// Scenario: Get/Set Credentials while not connected
/// Expected: Value set is retrieved
/// </summary>
[Test]
public void _021_Credentials_GetSet_NotConnected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
NetworkCredential credentials = new NetworkCredential("test", "test");
client.Credentials = credentials;
Assert.That(client.Credentials, Is.EqualTo(credentials));
}
/// <summary>
/// Scenario: Get/Set Credentials while connected
/// Expected: FTPException(0, Cannot change Credentials while connected)
/// </summary>
[Test]
public void _022_Credentials_GetSet_Connected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
NetworkCredential credentials = client.Credentials;
client.Connect();
Assert.That(delegate { client.Credentials = new NetworkCredential("test", "test"); }, Throws.InstanceOf<FTPException>().With.Message.EqualTo("Cannot change Credentials while connected"));
Assert.That(client.Credentials, Is.EqualTo(credentials));
client.Close();
}
/// <summary>
/// Scenario: Create and Delete a test folder
/// Expected: No errors occur
/// </summary>
[Test]
public void _023_MKDir_RMDir_Valid_Connected()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot/test", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
string dirname = string.Format("testdir{0}", Guid.NewGuid());
client.MKDir(dirname);
client.RMDir(dirname);
client.Close();
}
/// <summary>
/// Scenario: Create and Delete a test folder (not connected)
/// Expected: No errors occur
/// </summary>
[Test]
public void _024_MKDir_RMDir_Valid_NotConnected()
{
string dirname = string.Format("testdir{0}", Guid.NewGuid());
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot/test", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.MKDir(dirname);
client.Close();
client = new FTPClient(_ftpHost, 21, "/ftproot/test", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.RMDir(dirname);
client.Close();
}
/// <summary>
/// Scenario: Attempt to create a directory within a non-existant path
/// Expected: FTPException(550, xxx: The system cannot find the path specified.)
/// </summary>
[Test]
public void _025_MKDir_InvalidName()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.MKDir("/flibble/flobble/"); }, Throws.InstanceOf<FTPException>());
client.Close();
}
/// <summary>
/// Scenario: Attempt to delete a directory within a non-existant path
/// Expected: FTPException(550, xxx: The system cannot find the path specified.)
/// </summary>
[Test]
public void _026_RMDir_InvalidName()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.RMDir("/flibble/flobble/"); }, Throws.InstanceOf<FTPException>());
client.Close();
}
/// <summary>
/// Scenario: Upload a file, rename it (without connecting).
/// Expected: Connects, renames file
/// </summary>
[Test]
public void _027_RenameRemoteFile_NotConnected_Valid()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
string filename2 = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
client.UploadFile(filename);
client.Close();
client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.RemotePath = "/ftproot/test";
client.RenameRemoteFile(filename, filename2);
client.Close();
}
/// <summary>
/// Scenario: Upload a file, rename it (already connected)
/// Expected: Renames file
/// </summary>
[Test]
public void _028_RenameRemoteFile_Connected_Valid()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
string filename2 = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
client.UploadFile(filename);
client.RenameRemoteFile(filename, filename2);
client.Close();
}
/// <summary>
/// Scenario: Attempt to rename a file to an invalid name
/// Expected: FTPException(550, xxx: The system cannot find the path specified.)
/// </summary>
[Test]
public void _029_RenameRemoteFile_Connected_ValidFromOnly()
{
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
client.UploadFile(filename);
Assert.That(delegate { client.RenameRemoteFile(filename, "/flibble/flobble.txt"); }, Throws.InstanceOf<FTPException>());
client.Close();
}
/// <summary>
/// Scenario: Attempt to rename a file from an invalid name
/// Expected: FTPException(550, xxx: The system cannot find the path specified.)
/// </summary>
[Test]
public void _030_RenameRemoteFile_Connected_ValidToOnly()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
client.RemotePath = "/ftproot/test";
Assert.That(delegate { client.RenameRemoteFile("/flibble/flobble.txt", "/flibble/ftproot/test.txt"); }, Throws.InstanceOf<FTPException>());
client.Close();
}
/// <summary>
/// Scenario: Get Files (by mask) when not connected. None found.
/// Expected: zero length array
/// </summary>
[Test]
public void _031_GetFiles_NotConnected_ByMask_NoneFound()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
string[] files = client.GetFiles("*.txt");
Assert.That(files.Length, Is.EqualTo(0));
}
/// <summary>
/// Scenario: Get Files (by mask) when connected. None found.
/// Expected: zero length array
/// </summary>
[Test]
public void _032_GetFiles_Connected_ByMask_NoneFound()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
string[] files = client.GetFiles("*.txt");
Assert.That(files.Length, Is.EqualTo(0));
}
/// <summary>
/// Scenario: Get Files (by mask and path) when not connected. None found.k
/// Expected: zero length array
/// </summary>
/// [Test]
public void _034_GetFiles_NotConnected_ByMaskAndPath_NoneFound()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
string[] files = client.GetFiles("/ftproot", "*.txt");
Assert.That(files.Length, Is.EqualTo(0));
}
/// <summary>
/// Scenario: Get Files (by mask and path) when connected. None found.
/// Expected: zero length array
/// </summary>
[Test]
public void _035_GetFiles_Connected_ByMaskAndPath_NoneFound()
{
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot", _ftpUser, _ftpPass, FTPTransferMode.Binary);
client.Connect();
string[] files = client.GetFiles("/ftproot", "*.txt");
Assert.That(files.Length, Is.EqualTo(0));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 220 (ready for user) immediately
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _036_Connect_NoServer220()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtLogin));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
Assert.That(delegate { client.Connect(); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return appropriately on the USER command
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _037_Connect_ErrorCodeOnUSER()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtUSER));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
Assert.That(delegate { client.Connect(); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 227 to PASV
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _038_Connect_ErrorCodeOnPASV()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtPASV));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.GetFiles("*"); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Handle bad PASV response (malformed IP)
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _039_Connect_MalformedPASVReply1()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_BadPASVResponse1));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.GetFiles("*"); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(227));
}
/// <summary>
/// Scenario: PASV response is valid but data socket is not available
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _040_Connect_ValidPASV_UnableToConnectDataSocket()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_ValidPASVResponse));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.GetFiles("*"); }, Throws.InstanceOf<FTPException>().With.Message.EqualTo("Unable to connect to remote server"));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 125/150 to NLST
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _041_GetFiles_ErrorCodeOnNLST()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtNLST));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.GetFiles("*"); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 226 at end of data from NLST
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _042_GetFiles_ErrorCodeAfterNLST()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AfterNLST));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.GetFiles("*"); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Create a test file, send it to the server, get the length back
/// Expected: Matches local length of test file
/// </summary>
[Test]
public void _043_GetFileSize_NotConnected()
{
FTPClient ftp = new FTPClient(_ftpHost, 21, "/ftproot/test", _ftpUser, _ftpPass, FTPTransferMode.Binary);
// create test file
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
ftp.UploadFile(filename);
ftp.Close();
long sizeInBytes = ftp.GetFileSize(filename);
FileInfo fi = new FileInfo(filename);
Assert.That(sizeInBytes, Is.EqualTo(fi.Length));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 200 to TYPE
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _044_Connect_ErrorCodeOnTYPE()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtTYPE));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
Assert.That(delegate { client.Connect(); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 125/150 to NLST
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _045_UploadFile_ErrorCodeOnSTOR()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtSTOR));
testThread.Start();
// create test file
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.UploadFile(filename); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 226 at end of data from NLST
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _046_UploadFile_ErrorCodeAfterSTOR()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AfterSTOR));
testThread.Start();
// create test file
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.UploadFile(filename); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Create a file, upload it, rename it, download it
/// Expected: Downloads correctly
/// </summary>
[Test]
public void _047_DownloadFile_DoesNotExistLocally()
{
// create test file
string filename = string.Format("test{0}.txt", Guid.NewGuid());
StreamWriter sw = File.CreateText(filename);
sw.WriteLine("This is a test file");
sw.Close();
sw.Dispose();
string filename2 = string.Format("test{0}.txt", Guid.NewGuid());
FTPClient client = new FTPClient(_ftpHost, 21, "/ftproot/test", _ftpUser, _ftpPass, FTPTransferMode.ASCII);
client.Connect();
client.UploadFile(filename);
client.RenameRemoteFile(filename, filename2);
client.Close();
Assert.That(delegate { client.DownloadFile(filename2, string.Empty); }, Throws.InstanceOf<FTPException>().With.Message.EqualTo("LocalFileName is required"));
client.DownloadFile(filename2, filename2);
Assert.That(File.Exists(filename2));
}
/// <summary>
/// Scenario: attempt to get file size, code returned is not 213
/// Expected: Matches local length of test file
/// </summary>
[Test]
public void _048_GetFileSize_ErrorCodeReturned()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtSIZE));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.GetFileSize("testfile.txt"); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 125/150 to NLST
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _049_DownloadFile_ErrorCodeOnRETR()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AtRETR));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.DownloadFile("test049", "test049"); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
/// <summary>
/// Scenario: Connect to a dummy, local server which does not return 226 at end of data from NLST
/// Expected: Client closes, exception thrown
/// </summary>
[Test]
public void _050_Download_ErrorCodeAfterRETR()
{
Thread testThread = new Thread(new ThreadStart(FtpServer_Return_421_AfterRETR));
testThread.Start();
FTPClient client = new FTPClient("127.0.0.1", 3000, "/", "test", "test", FTPTransferMode.Binary);
client.Connect();
Assert.That(delegate { client.DownloadFile("test050", "test050"); }, Throws.InstanceOf<FTPException>().With.Property("ResponseCode").EqualTo(421));
}
private void FtpServer_Return_421_AtLogin()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_421_AtUSER()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_421_AtPASV()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("pasv"))
{
buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_BadPASVResponse1()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("pasv"))
{
buffer = encoder.GetBytes("227 (192-168,0,1)\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_ValidPASVResponse()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("pasv"))
{
buffer = encoder.GetBytes("227 (127,0,0,1,3,100)\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_421_AtNLST()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("nlst"))
{
buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("pasv"))
{
_tcpListenerData = new TcpListener(IPAddress.Loopback, 5220);
_tcpListenerData.Start();
buffer = encoder.GetBytes("227 (127,0,0,1,20,100)\n"); // port 5220 ((20*256) +100)
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
if (_tcpListenerData != null)
{
_tcpListenerData.Stop();
}
}
private void FtpServer_Return_421_AfterNLST()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("nlst"))
{
buffer = encoder.GetBytes("150 Sending data\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
TcpClient client2 = _tcpListenerData.AcceptTcpClient();
NetworkStream clientStream2 = client2.GetStream();
// buffer = encoder.GetBytes("random data\n");
// clientStream.Write(buffer, 0, buffer.Length);
clientStream2.Flush();
clientStream2.Close();
client2.Close();
_tcpListenerData.Stop();
buffer = encoder.GetBytes("421 Shutting down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("pasv"))
{
_tcpListenerData = new TcpListener(IPAddress.Loopback, 5220);
_tcpListenerData.Start();
buffer = encoder.GetBytes("227 (127,0,0,1,20,100)\n"); // port 5220 ((20*256) +100)
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_421_AtTYPE()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
// if (messageString.ToLower().StartsWith("type"))
// {
// buffer = encoder.GetBytes("200 OK\n");
// clientStream.Write(buffer, 0, buffer.Length);
// clientStream.Flush();
// }
// else
// {
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
// }
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_421_AtSTOR()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("stor"))
{
buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("pasv"))
{
_tcpListenerData = new TcpListener(IPAddress.Loopback, 5220);
_tcpListenerData.Start();
buffer = encoder.GetBytes("227 (127,0,0,1,20,100)\n"); // port 5220 ((20*256) +100)
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
if (_tcpListenerData != null)
{
_tcpListenerData.Stop();
}
}
private void FtpServer_Return_421_AfterSTOR()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("stor"))
{
buffer = encoder.GetBytes("150 receiving data\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
TcpClient client2 = _tcpListenerData.AcceptTcpClient();
NetworkStream clientStream2 = client2.GetStream();
// buffer = encoder.GetBytes("random data\n");
// clientStream.Write(buffer, 0, buffer.Length);
clientStream2.Flush();
clientStream2.Close();
client2.Close();
_tcpListenerData.Stop();
buffer = encoder.GetBytes("421 Shutting down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("pasv"))
{
_tcpListenerData = new TcpListener(IPAddress.Loopback, 5220);
_tcpListenerData.Start();
buffer = encoder.GetBytes("227 (127,0,0,1,20,100)\n"); // port 5220 ((20*256) +100)
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
private void FtpServer_Return_421_AtSIZE()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("size"))
{
buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("pasv"))
{
_tcpListenerData = new TcpListener(IPAddress.Loopback, 5220);
_tcpListenerData.Start();
buffer = encoder.GetBytes("227 (127,0,0,1,20,100)\n"); // port 5220 ((20*256) +100)
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
if (_tcpListenerData != null)
{
_tcpListenerData.Stop();
}
}
private void FtpServer_Return_421_AtRETR()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("retr"))
{
buffer = encoder.GetBytes("421 Server Shutting Down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("pasv"))
{
_tcpListenerData = new TcpListener(IPAddress.Loopback, 5220);
_tcpListenerData.Start();
buffer = encoder.GetBytes("227 (127,0,0,1,20,100)\n"); // port 5220 ((20*256) +100)
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
if (_tcpListenerData != null)
{
_tcpListenerData.Stop();
}
}
private void FtpServer_Return_421_AfterRETR()
{
_tcpListener = new TcpListener(IPAddress.Loopback, 3000);
_tcpListener.Start();
TcpClient client = _tcpListener.AcceptTcpClient();
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("220 OK Please Login\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
while (true)
{
byte[] message = new byte[4096];
int bytesRead = 0;
bytesRead = 0;
bytesRead = clientStream.Read(message, 0, 4096);
// message has successfully been received
string messageString = encoder.GetString(message, 0, bytesRead);
if (messageString.ToLower().StartsWith("retr"))
{
buffer = encoder.GetBytes("150 receiving data\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
TcpClient client2 = _tcpListenerData.AcceptTcpClient();
NetworkStream clientStream2 = client2.GetStream();
// buffer = encoder.GetBytes("random data\n");
// clientStream.Write(buffer, 0, buffer.Length);
clientStream2.Flush();
clientStream2.Close();
client2.Close();
_tcpListenerData.Stop();
buffer = encoder.GetBytes("421 Shutting down\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
break;
}
else
{
if (messageString.ToLower().StartsWith("pasv"))
{
_tcpListenerData = new TcpListener(IPAddress.Loopback, 5220);
_tcpListenerData.Start();
buffer = encoder.GetBytes("227 (127,0,0,1,20,100)\n"); // port 5220 ((20*256) +100)
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("user"))
{
buffer = encoder.GetBytes("230 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("type"))
{
buffer = encoder.GetBytes("200 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
if (messageString.ToLower().StartsWith("cwd "))
{
buffer = encoder.GetBytes("250 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
else
{
buffer = encoder.GetBytes("220 OK\n");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
}
}
}
clientStream.Close();
client.Close();
_tcpListener.Stop();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Security;
using System.Security.Principal;
using System.Threading;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using Microsoft.Win32.SafeHandles;
namespace System.Net.Security
{
//
// The class maintains the state of the authentication process and the security context.
// It encapsulates security context and does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
internal static partial class NegotiateStreamPal
{
// value should match the Windows sspicli NTE_FAIL value
// defined in winerror.h
private const int NTE_FAIL = unchecked((int)0x80090020);
internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
internal static string QueryContextAuthenticationPackage(SafeDeleteContext securityContext)
{
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)securityContext;
return negoContext.IsNtlmUsed ? NegotiationInfoClass.NTLM : NegotiationInfoClass.Kerberos;
}
static byte[] GssWrap(
SafeGssContextHandle context,
bool encrypt,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Encrypt");
Debug.Assert((offset >= 0) && (offset < buffer.Length), "Invalid input offset passed to Encrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Encrypt");
Interop.NetSecurityNative.GssBuffer encryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.WrapBuffer(out minorStatus, context, encrypt, buffer, offset, count, ref encryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return encryptedBuffer.ToByteArray();
}
finally
{
encryptedBuffer.Dispose();
}
}
private static int GssUnwrap(
SafeGssContextHandle context,
byte[] buffer,
int offset,
int count)
{
Debug.Assert((buffer != null) && (buffer.Length > 0), "Invalid input buffer passed to Decrypt");
Debug.Assert((offset >= 0) && (offset <= buffer.Length), "Invalid input offset passed to Decrypt");
Debug.Assert((count >= 0) && (count <= (buffer.Length - offset)), "Invalid input count passed to Decrypt");
Interop.NetSecurityNative.GssBuffer decryptedBuffer = default(Interop.NetSecurityNative.GssBuffer);
try
{
Interop.NetSecurityNative.Status minorStatus;
Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.UnwrapBuffer(out minorStatus, context, buffer, offset, count, ref decryptedBuffer);
if (status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE)
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
return decryptedBuffer.Copy(buffer, offset);
}
finally
{
decryptedBuffer.Dispose();
}
}
private static bool GssInitSecurityContext(
ref SafeGssContextHandle context,
SafeGssCredHandle credential,
bool isNtlm,
SafeGssNameHandle targetName,
Interop.NetSecurityNative.GssFlags inFlags,
byte[] buffer,
out byte[] outputBuffer,
out uint outFlags,
out int isNtlmUsed)
{
outputBuffer = null;
outFlags = 0;
// EstablishSecurityContext is called multiple times in a session.
// In each call, we need to pass the context handle from the previous call.
// For the first call, the context handle will be null.
if (context == null)
{
context = new SafeGssContextHandle();
}
Interop.NetSecurityNative.GssBuffer token = default(Interop.NetSecurityNative.GssBuffer);
Interop.NetSecurityNative.Status status;
try
{
Interop.NetSecurityNative.Status minorStatus;
status = Interop.NetSecurityNative.InitSecContext(out minorStatus,
credential,
ref context,
isNtlm,
targetName,
(uint)inFlags,
buffer,
(buffer == null) ? 0 : buffer.Length,
ref token,
out outFlags,
out isNtlmUsed);
if ((status != Interop.NetSecurityNative.Status.GSS_S_COMPLETE) && (status != Interop.NetSecurityNative.Status.GSS_S_CONTINUE_NEEDED))
{
throw new Interop.NetSecurityNative.GssApiException(status, minorStatus);
}
outputBuffer = token.ToByteArray();
}
finally
{
token.Dispose();
}
return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE;
}
private static SecurityStatusPal EstablishSecurityContext(
SafeFreeNegoCredentials credential,
ref SafeDeleteContext context,
string targetName,
ContextFlagsPal inFlags,
SecurityBuffer inputBuffer,
SecurityBuffer outputBuffer,
ref ContextFlagsPal outFlags)
{
bool isNtlmOnly = credential.IsNtlmOnly;
if (context == null)
{
// Empty target name causes the failure on Linux, hence passing a non-empty string
context = isNtlmOnly ? new SafeDeleteNegoContext(credential, credential.UserName) : new SafeDeleteNegoContext(credential, targetName);
}
SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)context;
try
{
Interop.NetSecurityNative.GssFlags inputFlags = ContextFlagsAdapterPal.GetInteropFromContextFlagsPal(inFlags, isServer: false);
uint outputFlags;
int isNtlmUsed;
SafeGssContextHandle contextHandle = negoContext.GssContext;
bool done = GssInitSecurityContext(
ref contextHandle,
credential.GssCredential,
isNtlmOnly,
negoContext.TargetName,
inputFlags,
inputBuffer?.token,
out outputBuffer.token,
out outputFlags,
out isNtlmUsed);
Debug.Assert(outputBuffer.token != null, "Unexpected null buffer returned by GssApi");
outputBuffer.size = outputBuffer.token.Length;
outputBuffer.offset = 0;
outFlags = ContextFlagsAdapterPal.GetContextFlagsPalFromInterop((Interop.NetSecurityNative.GssFlags)outputFlags, isServer: false);
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
// Save the inner context handle for further calls to NetSecurity
Debug.Assert(negoContext.GssContext == null || contextHandle == negoContext.GssContext);
if (null == negoContext.GssContext)
{
negoContext.SetGssContext(contextHandle);
}
// Populate protocol used for authentication
if (done)
{
negoContext.SetAuthenticationPackage(Convert.ToBoolean(isNtlmUsed));
}
SecurityStatusPalErrorCode errorCode = done ?
(negoContext.IsNtlmUsed && outputBuffer.size > 0 ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.CompleteNeeded) :
SecurityStatusPalErrorCode.ContinueNeeded;
return new SecurityStatusPal(errorCode);
}
catch (Exception ex)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
return new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, ex);
}
}
internal static SecurityStatusPal InitializeSecurityContext(
SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
string spn,
ContextFlagsPal requestedContextFlags,
SecurityBuffer[] inSecurityBufferArray,
SecurityBuffer outSecurityBuffer,
ref ContextFlagsPal contextFlags)
{
// TODO (Issue #3718): The second buffer can contain a channel binding which is not supported
if ((null != inSecurityBufferArray) && (inSecurityBufferArray.Length > 1))
{
throw new PlatformNotSupportedException(SR.net_nego_channel_binding_not_supported);
}
SafeFreeNegoCredentials negoCredentialsHandle = (SafeFreeNegoCredentials)credentialsHandle;
if (negoCredentialsHandle.IsDefault && string.IsNullOrEmpty(spn))
{
throw new PlatformNotSupportedException(SR.net_nego_not_supported_empty_target_with_defaultcreds);
}
SecurityStatusPal status = EstablishSecurityContext(
negoCredentialsHandle,
ref securityContext,
spn,
requestedContextFlags,
((inSecurityBufferArray != null && inSecurityBufferArray.Length != 0) ? inSecurityBufferArray[0] : null),
outSecurityBuffer,
ref contextFlags);
// Confidentiality flag should not be set if not requested
if (status.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded)
{
ContextFlagsPal mask = ContextFlagsPal.Confidentiality;
if ((requestedContextFlags & mask) != (contextFlags & mask))
{
throw new PlatformNotSupportedException(SR.net_nego_protection_level_not_supported);
}
}
return status;
}
internal static SecurityStatusPal AcceptSecurityContext(
SafeFreeCredentials credentialsHandle,
ref SafeDeleteContext securityContext,
ContextFlagsPal requestedContextFlags,
SecurityBuffer[] inSecurityBufferArray,
SecurityBuffer outSecurityBuffer,
ref ContextFlagsPal contextFlags)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
internal static Win32Exception CreateExceptionFromError(SecurityStatusPal statusCode)
{
return new Win32Exception(NTE_FAIL, (statusCode.Exception != null) ? statusCode.Exception.Message : statusCode.ErrorCode.ToString());
}
internal static int QueryMaxTokenSize(string package)
{
// This value is not used on Unix
return 0;
}
internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer)
{
return AcquireCredentialsHandle(package, isServer, new NetworkCredential(string.Empty, string.Empty, string.Empty));
}
internal static SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, NetworkCredential credential)
{
if (isServer)
{
throw new PlatformNotSupportedException(SR.net_nego_server_not_supported);
}
bool isEmptyCredential = string.IsNullOrWhiteSpace(credential.UserName) ||
string.IsNullOrWhiteSpace(credential.Password);
bool ntlmOnly = string.Equals(package, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase);
if (ntlmOnly && isEmptyCredential)
{
// NTLM authentication is not possible with default credentials which are no-op
throw new PlatformNotSupportedException(SR.net_ntlm_not_possible_default_cred);
}
try
{
return isEmptyCredential ?
new SafeFreeNegoCredentials(false, string.Empty, string.Empty, string.Empty) :
new SafeFreeNegoCredentials(ntlmOnly, credential.UserName, credential.Password, credential.Domain);
}
catch(Exception ex)
{
throw new Win32Exception(NTE_FAIL, ex.Message);
}
}
internal static SecurityStatusPal CompleteAuthToken(
ref SafeDeleteContext securityContext,
SecurityBuffer[] inSecurityBufferArray)
{
return new SecurityStatusPal(SecurityStatusPalErrorCode.OK);
}
internal static int Encrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
ref byte[] output,
uint sequenceNumber)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext) securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, isConfidential, buffer, offset, count);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal static int Decrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
out int newOffset,
uint sequenceNumber)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
NetEventSource.Fail(securityContext, "Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
NetEventSource.Fail(securityContext, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
newOffset = offset;
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count);
}
internal static int VerifySignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
NetEventSource.Fail(securityContext, "Argument 'offset' out of range");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
NetEventSource.Fail(securityContext, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer, offset, count);
}
internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output)
{
SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext;
byte[] tempOutput = GssWrap(gssContext.GssContext, false, buffer, offset, count);
// Create space for prefixing with the length
const int prefixLength = 4;
output = new byte[tempOutput.Length + prefixLength];
Array.Copy(tempOutput, 0, output, prefixLength, tempOutput.Length);
int resultSize = tempOutput.Length;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.