context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using UnityEngine;
namespace UnitySampleAssets.ImageEffects
{
public enum Dof34QualitySetting
{
OnlyBackground = 1,
BackgroundAndForeground = 2,
}
public enum DofResolution
{
High = 2,
Medium = 3,
Low = 4,
}
public enum DofBlurriness
{
Low = 1,
High = 2,
VeryHigh = 4,
}
[Flags]
public enum BokehDestination
{
Background = 0x1,
Foreground = 0x2,
BackgroundAndForeground = 0x3,
}
[ExecuteInEditMode]
[RequireComponent(typeof (Camera))]
[AddComponentMenu("Image Effects/Depth of Field (3.4)")]
public class DepthOfField34 : PostEffectsBase
{
private static int SMOOTH_DOWNSAMPLE_PASS = 6;
private static float BOKEH_EXTRA_BLUR = 2.0f;
public Dof34QualitySetting quality = Dof34QualitySetting.OnlyBackground;
public DofResolution resolution = DofResolution.Low;
public bool simpleTweakMode = true;
public float focalPoint = 1.0f;
public float smoothness = 0.5f;
public float focalZDistance = 0.0f;
public float focalZStartCurve = 1.0f;
public float focalZEndCurve = 1.0f;
private float focalStartCurve = 2.0f;
private float focalEndCurve = 2.0f;
private float focalDistance01 = 0.1f;
public Transform objectFocus = null;
public float focalSize = 0.0f;
public DofBlurriness bluriness = DofBlurriness.High;
public float maxBlurSpread = 1.75f;
public float foregroundBlurExtrude = 1.15f;
public Shader dofBlurShader;
private Material dofBlurMaterial = null;
public Shader dofShader;
private Material dofMaterial = null;
public bool visualize = false;
public BokehDestination bokehDestination = BokehDestination.Background;
private float widthOverHeight = 1.25f;
private float oneOverBaseSize = 1.0f/512.0f;
public bool bokeh = false;
public bool bokehSupport = true;
public Shader bokehShader;
public Texture2D bokehTexture;
public float bokehScale = 2.4f;
public float bokehIntensity = 0.15f;
public float bokehThreshholdContrast = 0.1f;
public float bokehThreshholdLuminance = 0.55f;
public int bokehDownsample = 1;
private Material bokehMaterial;
private void CreateMaterials()
{
dofBlurMaterial = CheckShaderAndCreateMaterial(dofBlurShader, dofBlurMaterial);
dofMaterial = CheckShaderAndCreateMaterial(dofShader, dofMaterial);
bokehSupport = bokehShader.isSupported;
if (bokeh && bokehSupport && bokehShader)
bokehMaterial = CheckShaderAndCreateMaterial(bokehShader, bokehMaterial);
}
protected override bool CheckResources()
{
CheckSupport(true);
dofBlurMaterial = CheckShaderAndCreateMaterial(dofBlurShader, dofBlurMaterial);
dofMaterial = CheckShaderAndCreateMaterial(dofShader, dofMaterial);
bokehSupport = bokehShader.isSupported;
if (bokeh && bokehSupport && bokehShader)
bokehMaterial = CheckShaderAndCreateMaterial(bokehShader, bokehMaterial);
if (!isSupported)
ReportAutoDisable();
return isSupported;
}
private void OnDisable()
{
Quads.Cleanup();
}
private void OnEnable()
{
GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
}
private float FocalDistance01(float worldDist)
{
return
GetComponent<Camera>().WorldToViewportPoint((worldDist - GetComponent<Camera>().nearClipPlane)*GetComponent<Camera>().transform.forward +
GetComponent<Camera>().transform.position).z/(GetComponent<Camera>().farClipPlane - GetComponent<Camera>().nearClipPlane);
}
private int GetDividerBasedOnQuality()
{
int divider = 1;
if (resolution == DofResolution.Medium)
divider = 2;
else if (resolution == DofResolution.Low)
divider = 2;
return divider;
}
private int GetLowResolutionDividerBasedOnQuality(int baseDivider)
{
int lowTexDivider = baseDivider;
if (resolution == DofResolution.High)
lowTexDivider *= 2;
if (resolution == DofResolution.Low)
lowTexDivider *= 2;
return lowTexDivider;
}
private RenderTexture foregroundTexture = null;
private RenderTexture mediumRezWorkTexture = null;
private RenderTexture finalDefocus = null;
private RenderTexture lowRezWorkTexture = null;
private RenderTexture bokehSource = null;
private RenderTexture bokehSource2 = null;
private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
if (CheckResources() == false)
{
Graphics.Blit(source, destination);
}
if (smoothness < 0.1f)
smoothness = 0.1f;
// update needed focal & rt size parameter
bokeh = bokeh && bokehSupport;
float bokehBlurAmplifier = bokeh ? BOKEH_EXTRA_BLUR : 1.0f;
bool blurForeground = quality > Dof34QualitySetting.OnlyBackground;
float focal01Size = focalSize/(GetComponent<Camera>().farClipPlane - GetComponent<Camera>().nearClipPlane);
;
if (simpleTweakMode)
{
focalDistance01 = objectFocus
? (GetComponent<Camera>().WorldToViewportPoint(objectFocus.position)).z/(GetComponent<Camera>().farClipPlane)
: FocalDistance01(focalPoint);
focalStartCurve = focalDistance01*smoothness;
focalEndCurve = focalStartCurve;
blurForeground = blurForeground && (focalPoint > (GetComponent<Camera>().nearClipPlane + Mathf.Epsilon));
}
else
{
if (objectFocus)
{
var vpPoint = GetComponent<Camera>().WorldToViewportPoint(objectFocus.position);
vpPoint.z = (vpPoint.z)/(GetComponent<Camera>().farClipPlane);
focalDistance01 = vpPoint.z;
}
else
focalDistance01 = FocalDistance01(focalZDistance);
focalStartCurve = focalZStartCurve;
focalEndCurve = focalZEndCurve;
blurForeground = blurForeground && (focalPoint > (GetComponent<Camera>().nearClipPlane + Mathf.Epsilon));
}
widthOverHeight = (1.0f*source.width)/(1.0f*source.height);
oneOverBaseSize = 1.0f/512.0f;
dofMaterial.SetFloat("_ForegroundBlurExtrude", foregroundBlurExtrude);
dofMaterial.SetVector("_CurveParams",
new Vector4(simpleTweakMode ? 1.0f/focalStartCurve : focalStartCurve,
simpleTweakMode ? 1.0f/focalEndCurve : focalEndCurve, focal01Size*0.5f,
focalDistance01));
dofMaterial.SetVector("_InvRenderTargetSize",
new Vector4(1.0f/(1.0f*source.width), 1.0f/(1.0f*source.height), 0.0f, 0.0f));
int divider = GetDividerBasedOnQuality();
int lowTexDivider = GetLowResolutionDividerBasedOnQuality(divider);
AllocateTextures(blurForeground, source, divider, lowTexDivider);
// WRITE COC to alpha channel
// source is only being bound to detect y texcoord flip
Graphics.Blit(source, source, dofMaterial, 3);
// better DOWNSAMPLE (could actually be weighted for higher quality)
Downsample(source, mediumRezWorkTexture);
// BLUR A LITTLE first, which has two purposes
// 1.) reduce jitter, noise, aliasing
// 2.) produce the little-blur buffer used in composition later
Blur(mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread);
if ((bokeh) && ((BokehDestination.Background & bokehDestination) != 0))
{
dofMaterial.SetVector("_Threshhold",
new Vector4(bokehThreshholdContrast, bokehThreshholdLuminance, 0.95f, 0.0f));
// add and mark the parts that should end up as bokeh shapes
Graphics.Blit(mediumRezWorkTexture, bokehSource2, dofMaterial, 11);
// remove those parts (maybe even a little tittle bittle more) from the regurlarly blurred buffer
//Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10);
Graphics.Blit(mediumRezWorkTexture, lowRezWorkTexture); //, dofMaterial, 10);
// maybe you want to reblur the small blur ... but not really needed.
//Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread);
// bigger BLUR
Blur(lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread*bokehBlurAmplifier);
}
else
{
// bigger BLUR
Downsample(mediumRezWorkTexture, lowRezWorkTexture);
Blur(lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread);
}
dofBlurMaterial.SetTexture("_TapLow", lowRezWorkTexture);
dofBlurMaterial.SetTexture("_TapMedium", mediumRezWorkTexture);
Graphics.Blit(null, finalDefocus, dofBlurMaterial, 3);
// we are only adding bokeh now if the background is the only part we have to deal with
if ((bokeh) && ((BokehDestination.Background & bokehDestination) != 0))
AddBokeh(bokehSource2, bokehSource, finalDefocus);
dofMaterial.SetTexture("_TapLowBackground", finalDefocus);
dofMaterial.SetTexture("_TapMedium", mediumRezWorkTexture); // needed for debugging/visualization
// FINAL DEFOCUS (background)
Graphics.Blit(source, blurForeground ? foregroundTexture : destination, dofMaterial, visualize ? 2 : 0);
// FINAL DEFOCUS (foreground)
if (blurForeground)
{
// WRITE COC to alpha channel
Graphics.Blit(foregroundTexture, source, dofMaterial, 5);
// DOWNSAMPLE (unweighted)
Downsample(source, mediumRezWorkTexture);
// BLUR A LITTLE first, which has two purposes
// 1.) reduce jitter, noise, aliasing
// 2.) produce the little-blur buffer used in composition later
BlurFg(mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 2, maxBlurSpread);
if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0))
{
dofMaterial.SetVector("_Threshhold",
new Vector4(bokehThreshholdContrast*0.5f, bokehThreshholdLuminance, 0.0f, 0.0f));
// add and mark the parts that should end up as bokeh shapes
Graphics.Blit(mediumRezWorkTexture, bokehSource2, dofMaterial, 11);
// remove the parts (maybe even a little tittle bittle more) that will end up in bokeh space
//Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10);
Graphics.Blit(mediumRezWorkTexture, lowRezWorkTexture); //, dofMaterial, 10);
// big BLUR
BlurFg(lowRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread*bokehBlurAmplifier);
}
else
{
// big BLUR
BlurFg(mediumRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread);
}
// simple upsample once
Graphics.Blit(lowRezWorkTexture, finalDefocus);
dofMaterial.SetTexture("_TapLowForeground", finalDefocus);
Graphics.Blit(source, destination, dofMaterial, visualize ? 1 : 4);
if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0))
AddBokeh(bokehSource2, bokehSource, destination);
}
ReleaseTextures();
}
private void Blur(RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread)
{
RenderTexture tmp = RenderTexture.GetTemporary(to.width, to.height);
if (iterations > (DofBlurriness) 1)
{
BlurHex(from, to, blurPass, spread, tmp);
if (iterations > (DofBlurriness) 2)
{
dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit(to, tmp, dofBlurMaterial, blurPass);
dofBlurMaterial.SetVector("offsets",
new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(tmp, to, dofBlurMaterial, blurPass);
}
}
else
{
dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit(from, tmp, dofBlurMaterial, blurPass);
dofBlurMaterial.SetVector("offsets",
new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(tmp, to, dofBlurMaterial, blurPass);
}
RenderTexture.ReleaseTemporary(tmp);
}
private void BlurFg(RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread)
{
// we want a nice, big coc, hence we need to tap once from this (higher resolution) texture
dofBlurMaterial.SetTexture("_TapHigh", from);
RenderTexture tmp = RenderTexture.GetTemporary(to.width, to.height);
if (iterations > (DofBlurriness) 1)
{
BlurHex(from, to, blurPass, spread, tmp);
if (iterations > (DofBlurriness) 2)
{
dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit(to, tmp, dofBlurMaterial, blurPass);
dofBlurMaterial.SetVector("offsets",
new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(tmp, to, dofBlurMaterial, blurPass);
}
}
else
{
dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit(from, tmp, dofBlurMaterial, blurPass);
dofBlurMaterial.SetVector("offsets",
new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(tmp, to, dofBlurMaterial, blurPass);
}
RenderTexture.ReleaseTemporary(tmp);
}
private void BlurHex(RenderTexture from, RenderTexture to, int blurPass, float spread, RenderTexture tmp)
{
dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f));
Graphics.Blit(from, tmp, dofBlurMaterial, blurPass);
dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f));
Graphics.Blit(tmp, to, dofBlurMaterial, blurPass);
dofBlurMaterial.SetVector("offsets",
new Vector4(spread/widthOverHeight*oneOverBaseSize, spread*oneOverBaseSize, 0.0f,
0.0f));
Graphics.Blit(to, tmp, dofBlurMaterial, blurPass);
dofBlurMaterial.SetVector("offsets",
new Vector4(spread/widthOverHeight*oneOverBaseSize, -spread*oneOverBaseSize, 0.0f,
0.0f));
Graphics.Blit(tmp, to, dofBlurMaterial, blurPass);
}
private void Downsample(RenderTexture from, RenderTexture to)
{
dofMaterial.SetVector("_InvRenderTargetSize",
new Vector4(1.0f/(1.0f*to.width), 1.0f/(1.0f*to.height), 0.0f, 0.0f));
Graphics.Blit(from, to, dofMaterial, SMOOTH_DOWNSAMPLE_PASS);
}
private void AddBokeh(RenderTexture bokehInfo, RenderTexture tempTex, RenderTexture finalTarget)
{
if (bokehMaterial)
{
Mesh[] meshes = Quads.GetMeshes(tempTex.width, tempTex.height);
// quads: exchanging more triangles with less overdraw
RenderTexture.active = tempTex;
GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
GL.PushMatrix();
GL.LoadIdentity();
// point filter mode is important, otherwise we get bokeh shape & size artefacts
bokehInfo.filterMode = FilterMode.Point;
float arW = (bokehInfo.width*1.0f)/(bokehInfo.height*1.0f);
float sc = 2.0f/(1.0f*bokehInfo.width);
sc += bokehScale*maxBlurSpread*BOKEH_EXTRA_BLUR*oneOverBaseSize;
bokehMaterial.SetTexture("_Source", bokehInfo);
bokehMaterial.SetTexture("_MainTex", bokehTexture);
bokehMaterial.SetVector("_ArScale", new Vector4(sc, sc*arW, 0.5f, 0.5f*arW));
bokehMaterial.SetFloat("_Intensity", bokehIntensity);
bokehMaterial.SetPass(0);
foreach (var m in meshes)
if (m) Graphics.DrawMeshNow(m, Matrix4x4.identity);
GL.PopMatrix();
Graphics.Blit(tempTex, finalTarget, dofMaterial, 8);
// important to set back as we sample from this later on
bokehInfo.filterMode = FilterMode.Bilinear;
}
}
private void ReleaseTextures()
{
if (foregroundTexture) RenderTexture.ReleaseTemporary(foregroundTexture);
if (finalDefocus) RenderTexture.ReleaseTemporary(finalDefocus);
if (mediumRezWorkTexture) RenderTexture.ReleaseTemporary(mediumRezWorkTexture);
if (lowRezWorkTexture) RenderTexture.ReleaseTemporary(lowRezWorkTexture);
if (bokehSource) RenderTexture.ReleaseTemporary(bokehSource);
if (bokehSource2) RenderTexture.ReleaseTemporary(bokehSource2);
}
private void AllocateTextures(bool blurForeground, RenderTexture source, int divider, int lowTexDivider)
{
foregroundTexture = null;
if (blurForeground)
foregroundTexture = RenderTexture.GetTemporary(source.width, source.height, 0);
mediumRezWorkTexture = RenderTexture.GetTemporary(source.width/divider, source.height/divider, 0);
finalDefocus = RenderTexture.GetTemporary(source.width/divider, source.height/divider, 0);
lowRezWorkTexture = RenderTexture.GetTemporary(source.width/lowTexDivider, source.height/lowTexDivider, 0);
bokehSource = null;
bokehSource2 = null;
if (bokeh)
{
bokehSource = RenderTexture.GetTemporary(source.width/(lowTexDivider*bokehDownsample),
source.height/(lowTexDivider*bokehDownsample), 0,
RenderTextureFormat.ARGBHalf);
bokehSource2 = RenderTexture.GetTemporary(source.width/(lowTexDivider*bokehDownsample),
source.height/(lowTexDivider*bokehDownsample), 0,
RenderTextureFormat.ARGBHalf);
bokehSource.filterMode = FilterMode.Bilinear;
bokehSource2.filterMode = FilterMode.Bilinear;
RenderTexture.active = bokehSource2;
GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
}
// to make sure: always use bilinear filter setting
source.filterMode = FilterMode.Bilinear;
finalDefocus.filterMode = FilterMode.Bilinear;
mediumRezWorkTexture.filterMode = FilterMode.Bilinear;
lowRezWorkTexture.filterMode = FilterMode.Bilinear;
if (foregroundTexture)
foregroundTexture.filterMode = FilterMode.Bilinear;
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.Reflection;
using System.Collections;
namespace NUnit.Core
{
/// <summary>
/// Helper methods for inspecting a type by reflection.
///
/// Many of these methods take a MemberInfo as an argument to avoid
/// duplication, even though certain attributes can only appear on
/// specific types of members, like MethodInfo or Type.
///
/// In the case where a type is being examined for the presence of
/// an attribute, interface or named member, the Reflect methods
/// operate with the full name of the member being sought. This
/// removes the necessity of the caller having a reference to the
/// assembly that defines the item being sought and allows the
/// NUnit core to inspect assemblies that reference an older
/// version of the NUnit framework.
/// </summary>
public class Reflect
{
#region Attributes
/// <summary>
/// Check presence of attribute of a given type on a member.
/// </summary>
/// <param name="member">The member to examine</param>
/// <param name="attrName">The FullName of the attribute type to look for</param>
/// <param name="inherit">True to include inherited attributes</param>
/// <returns>True if the attribute is present</returns>
public static bool HasAttribute( MemberInfo member, string attrName, bool inherit )
{
object[] attributes = member.GetCustomAttributes( inherit );
foreach( Attribute attribute in attributes )
if ( attribute.GetType().FullName == attrName )
return true;
return false;
}
/// <summary>
/// Get attribute of a given type on a member. If multiple attributes
/// of a type are present, the first one found is returned.
/// </summary>
/// <param name="member">The member to examine</param>
/// <param name="attrName">The FullName of the attribute type to look for</param>
/// <param name="inherit">True to include inherited attributes</param>
/// <returns>The attribute or null</returns>
public static System.Attribute GetAttribute(MemberInfo member, string attrName, bool inherit)
{
object[] attributes = member.GetCustomAttributes(inherit);
foreach (Attribute attribute in attributes)
if (attribute.GetType().FullName == attrName)
return attribute;
return null;
}
/// <summary>
/// Get attribute of a given type on an assembly. If multiple attributes
/// of a type are present, the first one found is returned.
/// </summary>
/// <param name="assembly">The assembly to examine</param>
/// <param name="attrName">The FullName of the attribute type to look for</param>
/// <param name="inherit">True to include inherited attributes</param>
/// <returns>The attribute or null</returns>
public static System.Attribute GetAttribute(Assembly assembly, string attrName, bool inherit)
{
object[] attributes = assembly.GetCustomAttributes(inherit);
foreach (Attribute attribute in attributes)
if (attribute.GetType().FullName == attrName)
return attribute;
return null;
}
/// <summary>
/// Get all attributes of a given type on a member.
/// </summary>
/// <param name="member">The member to examine</param>
/// <param name="attrName">The FullName of the attribute type to look for</param>
/// <param name="inherit">True to include inherited attributes</param>
/// <returns>The attribute or null</returns>
public static System.Attribute[] GetAttributes( MemberInfo member, string attrName, bool inherit )
{
object[] attributes = member.GetCustomAttributes( inherit );
ArrayList result = new ArrayList();
foreach( Attribute attribute in attributes )
if ( attribute.GetType().FullName == attrName )
result.Add( attribute );
return (System.Attribute[])result.ToArray( typeof( System.Attribute ) );
}
/// <summary>
/// Get all attributes on a member.
/// </summary>
/// <param name="member">The member to examine</param>
/// <param name="inherit">True to include inherited attributes</param>
/// <returns>The attribute or null</returns>
public static System.Attribute[] GetAttributes(MemberInfo member, bool inherit)
{
object[] attributes = member.GetCustomAttributes(inherit);
System.Attribute[] result = new System.Attribute[attributes.Length];
int n = 0;
foreach (Attribute attribute in attributes)
result[n++] = attribute;
return result;
}
/// <summary>
/// Get all attributes on an assembly.
/// </summary>
/// <param name="assembly">The assembly to examine</param>
/// <param name="inherit">True to include inherited attributes</param>
/// <returns>The attributes or null</returns>
public static System.Attribute[] GetAttributes(Assembly assembly, bool inherit)
{
object[] attributes = assembly.GetCustomAttributes(inherit);
System.Attribute[] result = new System.Attribute[attributes.Length];
int n = 0;
foreach (Attribute attribute in attributes)
result[n++] = attribute;
return result;
}
#endregion
#region Interfaces
/// <summary>
/// Check to see if a type implements a named interface.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="interfaceName">The FullName of the interface to check for</param>
/// <returns>True if the interface is implemented by the type</returns>
public static bool HasInterface( Type fixtureType, string interfaceName )
{
foreach( Type type in fixtureType.GetInterfaces() )
if ( type.FullName == interfaceName )
return true;
return false;
}
#endregion
#region Inheritance
//SHMARYA: [ 10/12/2005 ]
/// <summary>
/// Checks to see if a type inherits from a named type.
/// </summary>
/// <param name="type">The type to examine</param>
/// <param name="parentType">The FullName of the inherited type to look for</param>
/// <returns>True if the type inherits from the named type.</returns>
public static bool InheritsFrom( Type type, string parentType )
{
Type current = type;
while( current != typeof( object ) )
if( current.BaseType.FullName == parentType )
return true;
else
current = current.BaseType;
return false;
}
public static bool IsOrInheritsFrom( Type type, string parentType )
{
return type.FullName == parentType || InheritsFrom( type, parentType );
}
#endregion
#region Get Methods of a type
/// <summary>
/// Find the default constructor on a type
/// </summary>
/// <param name="fixtureType"></param>
/// <returns></returns>
public static ConstructorInfo GetConstructor( Type fixtureType )
{
return fixtureType.GetConstructor( Type.EmptyTypes );
}
/// <summary>
/// Examine a fixture type and return a method having a particular attribute.
/// In the case of multiple methods, the first one found is returned.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="attributeName">The FullName of the attribute to look for</param>
/// <param name="bindingFlags">BindingFlags to use in looking for method</param>
/// <returns>A MethodInfo or null</returns>
public static MethodInfo GetMethodWithAttribute( Type fixtureType, string attributeName, BindingFlags bindingFlags, bool inherit )
{
foreach(MethodInfo method in fixtureType.GetMethods( bindingFlags ) )
{
if( HasAttribute( method, attributeName, inherit ) )
return method;
}
return null;
}
/// <summary>
/// Examine a fixture type and return a count of the methods having a
/// particular attribute.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="attributeName">The FullName of the attribute to look for</param>
/// <param name="bindingFlags">BindingFlags to use in looking for method</param>
/// <returns>The number of such methods found</returns>
public static int CountMethodsWithAttribute( Type fixtureType, string attributeName, BindingFlags bindingFlags, bool inherit )
{
int count = 0;
foreach(MethodInfo method in fixtureType.GetMethods( bindingFlags ) )
{
if( HasAttribute( method, attributeName, inherit ) )
count++;
}
return count;
}
/// <summary>
/// Examine a fixture type and get a method with a particular name.
/// In the case of overloads, the first one found is returned.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="methodName">The name of the method</param>
/// <param name="bindingFlags">BindingFlags to use in the search</param>
/// <returns>A MethodInfo or null</returns>
public static MethodInfo GetNamedMethod(Type fixtureType, string methodName, BindingFlags bindingFlags)
{
foreach (MethodInfo method in fixtureType.GetMethods(bindingFlags))
{
if (method.Name == methodName)
return method;
}
return null;
}
/// <summary>
/// Examine a fixture type and get a method with a particular name and list
/// of arguments. In the case of overloads, the first one found is returned.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="methodName">The name of the method</param>
/// <param name="argTypes">The full names of the argument types to search for</param>
/// <param name="bindingFlags">BindingFlags to use in the search</param>
/// <returns>A MethodInfo or null</returns>
public static MethodInfo GetNamedMethod(Type fixtureType, string methodName,
string[] argTypes, BindingFlags bindingFlags)
{
foreach (MethodInfo method in fixtureType.GetMethods(bindingFlags))
{
if (method.Name == methodName)
{
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == argTypes.Length)
{
bool match = true;
for (int i = 0; i < argTypes.Length; i++)
if (parameters[i].ParameterType.FullName != argTypes[i])
{
match = false;
break;
}
if (match)
return method;
}
}
}
return null;
}
#endregion
#region Get Properties of a type
/// <summary>
/// Examine a type and return a property having a particular attribute.
/// In the case of multiple methods, the first one found is returned.
/// </summary>
/// <param name="fixtureType">The type to examine</param>
/// <param name="attributeName">The FullName of the attribute to look for</param>
/// <param name="bindingFlags">Binding flags to use in searching</param>
/// <returns>A PropertyInfo or null</returns>
public static PropertyInfo GetPropertyWithAttribute( Type fixtureType, string attributeName, BindingFlags bindingFlags )
{
foreach(PropertyInfo property in fixtureType.GetProperties( bindingFlags ) )
{
if( HasAttribute( property, attributeName, true ) )
return property;
}
return null;
}
/// <summary>
/// Examine a type and get a property with a particular name.
/// In the case of overloads, the first one found is returned.
/// </summary>
/// <param name="type">The type to examine</param>
/// <param name="bindingFlags">BindingFlags to use</param>
/// <returns>A PropertyInfo or null</returns>
public static PropertyInfo GetNamedProperty( Type type, string name, BindingFlags bindingFlags )
{
return type.GetProperty( name, bindingFlags );
}
/// <summary>
/// Get the value of a named property on an object using binding flags of Public and Instance
/// </summary>
/// <param name="obj">The object for which the property value is needed</param>
/// <param name="name">The name of a non-indexed property of the object</param>
/// <returns></returns>
public static object GetPropertyValue( object obj, string name )
{
return GetPropertyValue( obj, name, BindingFlags.Public | BindingFlags.Instance );
}
/// <summary>
/// Get the value of a named property on an object
/// </summary>
/// <param name="obj">The object for which the property value is needed</param>
/// <param name="name">The name of a non-indexed property of the object</param>
/// <param name="bindingFlags">BindingFlags for use in determining which properties are needed</param>param>
/// <returns></returns>
public static object GetPropertyValue( object obj, string name, BindingFlags bindingFlags )
{
PropertyInfo property = GetNamedProperty( obj.GetType(), name, bindingFlags );
if ( property != null )
return property.GetValue( obj, null );
return null;
}
#endregion
#region Invoke Methods
/// <summary>
/// Invoke the default constructor on a type
/// </summary>
/// <param name="type">The type to be constructed</param>
/// <returns>An instance of the type</returns>
public static object Construct( Type type )
{
ConstructorInfo ctor = GetConstructor( type );
if ( ctor == null )
throw new InvalidTestFixtureException(type.FullName + " does not have a valid constructor");
return ctor.Invoke( Type.EmptyTypes );
}
/// <summary>
/// Invoke a parameterless method on an object.
/// </summary>
/// <param name="method">A MethodInfo for the method to be invoked</param>
/// <param name="fixture">The object on which to invoke the method</param>
public static void InvokeMethod( MethodInfo method, object fixture )
{
InvokeMethod( method, fixture, null );
}
/// <summary>
/// Invoke a parameterless method on an object.
/// </summary>
/// <param name="method">A MethodInfo for the method to be invoked</param>
/// <param name="fixture">The object on which to invoke the method</param>
public static void InvokeMethod( MethodInfo method, object fixture, params object[] args )
{
if(method != null)
{
try
{
method.Invoke( fixture, args );
}
catch(TargetInvocationException e)
{
Exception inner = e.InnerException;
throw new NUnitException("Rethrown",inner);
}
}
}
#endregion
#region Private Constructor for static-only class
private Reflect() { }
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using Windows.Foundation;
namespace System.Threading.Tasks
{
/// <summary>
/// Implements a wrapper that allows to expose managed <code>System.Threading.Tasks.Task</code> objects as
/// through the WinRT <code>Windows.Foundation.IAsyncInfo</code> interface.
/// </summary>
internal class TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>
: IAsyncInfo, IProgress<TProgressInfo>
where TCompletedHandler : class
where TProgressHandler : class
{
#region Private Types, Statics and Constants
// ! THIS DIAGRAM ILLUSTRATES THE CONSTANTS BELOW. UPDATE THIS IF UPDATING THE CONSTANTS BELOW!:
// 3 2 1 0
// 10987654321098765432109876543210
// X............................... Reserved such that we can use Int32 and not worry about negative-valued state constants
// ..X............................. STATEFLAG_COMPLETED_SYNCHRONOUSLY
// ...X............................ STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET
// ....X........................... STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED
// ................................ STATE_NOT_INITIALIZED
// ...............................X STATE_STARTED
// ..............................X. STATE_RUN_TO_COMPLETION
// .............................X.. STATE_CANCELLATION_REQUESTED
// ............................X... STATE_CANCELLATION_COMPLETED
// ...........................X.... STATE_ERROR
// ..........................X..... STATE_CLOSED
// ..........................XXXXXX STATEMASK_SELECT_ANY_ASYNC_STATE
// XXXXXXXXXXXXXXXXXXXXXXXXXX...... STATEMASK_CLEAR_ALL_ASYNC_STATES
// 3 2 1 0
// 10987654321098765432109876543210
// These STATE_XXXX constants describe the async state of this object.
// Objects of this type are in exactly in one of these states at any given time:
private const int STATE_NOT_INITIALIZED = 0; // 0x00
private const int STATE_STARTED = 1; // 0x01
private const int STATE_RUN_TO_COMPLETION = 2; // 0x02
private const int STATE_CANCELLATION_REQUESTED = 4; // 0x04
private const int STATE_CANCELLATION_COMPLETED = 8; // 0x08
private const int STATE_ERROR = 16; // 0x10
private const int STATE_CLOSED = 32; // 0x20
// The STATEFLAG_XXXX constants can be bitmasked with the states to describe additional
// state info that cannot be easily inferred from the async state:
private const int STATEFLAG_COMPLETED_SYNCHRONOUSLY = 0x20000000;
private const int STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET = 0x10000000;
private const int STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED = 0x8000000;
// These two masks are used to select any STATE_XXXX bits and clear all other (i.e. STATEFLAG_XXXX) bits.
// It is set to (next power of 2 after the largest STATE_XXXX value) - 1.
// !!! Make sure to update this if a new STATE_XXXX value is added above !!
private const int STATEMASK_SELECT_ANY_ASYNC_STATE = (64 - 1);
// These two masks are used to clear all STATE_XXXX bits and leave any STATEFLAG_XXXX bits.
private const int STATEMASK_CLEAR_ALL_ASYNC_STATES = ~STATEMASK_SELECT_ANY_ASYNC_STATE;
private static InvalidOperationException CreateCannotGetResultsFromIncompleteOperationException(Exception cause)
{
InvalidOperationException ex = (cause == null)
? new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation)
: new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation, cause);
ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL);
return ex;
}
#endregion Private Types, Statics and Constants
#region Instance variables
/// <summary>The token source used to cancel running operations.</summary>
private CancellationTokenSource _cancelTokenSource = null;
/// <summary>The async info's ID. InvalidAsyncId stands for not yet been initialised.</summary>
private uint _id = AsyncInfoIdGenerator.InvalidId;
/// <summary>The cached error code used to avoid creating several exception objects if the <code>ErrorCode</code>
/// property is accessed several times. <code>null</code> indicates either no error or that <code>ErrorCode</code>
/// has not yet been called.</summary>
private Exception _error = null;
/// <summary>The state of the async info. Interlocked operations are used to manipulate this field.</summary>
private volatile int _state = STATE_NOT_INITIALIZED;
/// <summary>For IAsyncInfo instances that completed synchronously (at creation time) this field holds the result;
/// for instances backed by an actual Task, this field holds a reference to the task generated by the task generator.
/// Since we always know which of the above is the case, we can always cast this field to TResult in the former case
/// or to one of Task or Task{TResult} in the latter case. This approach allows us to save a field on all IAsyncInfos.
/// Notably, this makes us pay the added cost of boxing for synchronously completing IAsyncInfos where TResult is a
/// value type, however, this is expected to occur rather rare compared to non-synchronously completed user-IAsyncInfos.</summary>
private object _dataContainer;
/// <summary>Registered completed handler.</summary>
private TCompletedHandler _completedHandler;
/// <summary>Registered progress handler.</summary>
private TProgressHandler _progressHandler;
/// <summary>The synchronization context on which this instance was created/started. Used to callback invocations.</summary>
private SynchronizationContext _startingContext;
#endregion Instance variables
#region Constructors and Destructor
/// <summary>Creates an IAsyncInfo from the specified delegate. The delegate will be called to construct a task that will
/// represent the future encapsulated by this IAsyncInfo.</summary>
/// <param name="taskProvider">The task generator to use for creating the task.</param>
internal TaskToAsyncInfoAdapter(Delegate taskProvider)
{
Debug.Assert(taskProvider != null);
Debug.Assert((null != (taskProvider as Func<Task>))
|| (null != (taskProvider as Func<CancellationToken, Task>))
|| (null != (taskProvider as Func<IProgress<TProgressInfo>, Task>))
|| (null != (taskProvider as Func<CancellationToken, IProgress<TProgressInfo>, Task>)));
// The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers.
// Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later.
_startingContext = GetStartingContext();
// Construct task from the specified provider:
Task task = InvokeTaskProvider(taskProvider);
if (task == null)
throw new NullReferenceException(SR.NullReference_TaskProviderReturnedNull);
if (task.Status == TaskStatus.Created)
throw new InvalidOperationException(SR.InvalidOperation_TaskProviderReturnedUnstartedTask);
_dataContainer = task;
_state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED);
// Set the completion routine and let the task running:
task.ContinueWith(
(_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(),
this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
/// <summary>
/// Creates an IAsyncInfo from the Task object. The specified task represents the future encapsulated by this IAsyncInfo.
/// The specified CancellationTokenSource and Progress are assumed to be the source of the specified Task's cancellation and
/// the Progress that receives reports from the specified Task.
/// </summary>
/// <param name="underlyingTask">The Task whose operation is represented by this IAsyncInfo</param>
/// <param name="underlyingCancelTokenSource">The cancellation control for the cancellation token observed
/// by <code>underlyingTask</code>.</param>
/// <param name="underlyingProgressDispatcher">A progress listener/pugblisher that receives progress notifications
/// form <code>underlyingTask</code>.</param>
internal TaskToAsyncInfoAdapter(Task underlyingTask,
CancellationTokenSource underlyingCancelTokenSource, Progress<TProgressInfo> underlyingProgressDispatcher)
{
if (underlyingTask == null)
throw new ArgumentNullException(nameof(underlyingTask));
// Throw InvalidOperation and not Argument for parity with the constructor that takes Delegate taskProvider:
if (underlyingTask.Status == TaskStatus.Created)
throw new InvalidOperationException(SR.InvalidOperation_UnstartedTaskSpecified);
// The IAsyncInfo is reasonably expected to be created/started by the same code that wires up the Completed and Progress handlers.
// Record the current SynchronizationContext so that we can invoke completion and progress callbacks in it later.
_startingContext = GetStartingContext();
// We do not need to invoke any delegates to get the task, it is provided for us:
_dataContainer = underlyingTask;
// This must be the cancellation source for the token that the specified underlyingTask observes for cancellation:
// (it may also be null in cases where the specified underlyingTask does nto support cancellation)
_cancelTokenSource = underlyingCancelTokenSource;
// Iff the specified underlyingTask reports progress, chain the reports to this IAsyncInfo's reporting method:
if (underlyingProgressDispatcher != null)
underlyingProgressDispatcher.ProgressChanged += OnReportChainedProgress;
_state = (STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED | STATE_STARTED);
underlyingTask.ContinueWith(
(_, this_) => ((TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>)this_).TaskCompleted(),
this, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
/// <summary>
/// Creates an IAsyncInfo from the specified result value. The IAsyncInfo is created in the Completed state and the
/// specified <code>synchronousResult</code> is used as the result value.
/// </summary>
/// <param name="synchronousResult">The result of this synchronously completed IAsyncInfo.</param>
internal TaskToAsyncInfoAdapter(TResult synchronousResult)
{
// We already completed. There will be no progress callback invokations and a potential completed handler invokation will be synchronous.
// We do not need the starting SynchronizationContext:
_startingContext = null;
// Set the synchronous result:
_dataContainer = synchronousResult;
// CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + RUN_TO_COMPLETION:
// (same state as assigned by DangerousSetCompleted())
_state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY
| STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET
| STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED
| STATE_RUN_TO_COMPLETION);
}
~TaskToAsyncInfoAdapter()
{
TransitionToClosed();
}
#endregion Constructors and Destructor
#region Synchronous completion controls
/// <summary> This method sets the result on a *synchronously completed* IAsyncInfo.
/// It does not try to deal with the inherit races: Use it only when constructing a synchronously
/// completed IAsyncInfo in a desired state when you understand the threading conditions well.</summary>
/// <param name="synchronousResult">The new result of this synchronously completed IAsyncInfo (may be <code>default(TResult)</code>)</param>
/// <returns>FALSE if this IAsyncInfo has not actually completed synchronously and this method had no effects, TRUE otherwise.</returns>
internal bool DangerousSetCompleted(TResult synchronousResult)
{
if (!CompletedSynchronously)
return false;
_dataContainer = synchronousResult;
_error = null;
// CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + RUN_TO_COMPLETION:
_state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY
| STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET
| STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED
| STATE_RUN_TO_COMPLETION);
return true;
}
internal bool DangerousSetCanceled()
{
if (!CompletedSynchronously)
return false;
// Here we do not try to deal with the inherit races: Use this method only when constructing a synchronously
// completed IAsyncInfo in a desired state when you understand the threading conditions well.
_dataContainer = null;
_error = null;
// CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + CANCELLATION_COMPLETED:
_state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY
| STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET
| STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED
| STATE_CANCELLATION_COMPLETED);
return true;
}
internal bool DangerousSetError(Exception error)
{
if (!CompletedSynchronously)
return false;
if (error == null)
throw new ArgumentNullException(nameof(error));
// Here we do not try to deal with the inherit races: Use this method only when constructing a synchronously
// completed IAsyncInfo in a desired state when you understand the threading conditions well.
_dataContainer = null;
_error = error;
// CompletedSynchronously + MustRunCompletionHandleImmediatelyWhenSet + CompletionHandlerNotYetInvoked + ERROR:
_state = (STATEFLAG_COMPLETED_SYNCHRONOUSLY
| STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET
| STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED
| STATE_ERROR);
return true;
}
#endregion Synchronous completion controls
#region State bit field operations
internal bool CompletedSynchronously { [Pure] get { return (0 != (_state & STATEFLAG_COMPLETED_SYNCHRONOUSLY)); } }
private bool IsInStartedState { [Pure] get { return (0 != (_state & STATE_STARTED)); } }
private bool IsInRunToCompletionState { [Pure] get { return (0 != (_state & STATE_RUN_TO_COMPLETION)); } }
private bool IsInErrorState { [Pure] get { return (0 != (_state & STATE_ERROR)); } }
private bool IsInClosedState { [Pure] get { return (0 != (_state & STATE_CLOSED)); } }
private bool IsInRunningState
{
[Pure]
get
{
return (0 != (_state & (STATE_STARTED
| STATE_CANCELLATION_REQUESTED)));
}
}
private bool IsInTerminalState
{
[Pure]
get
{
return (0 != (_state & (STATE_RUN_TO_COMPLETION
| STATE_CANCELLATION_COMPLETED
| STATE_ERROR)));
}
}
[Pure]
private bool CheckUniqueAsyncState(int state)
{
unchecked
{
uint asyncState = (uint)state;
return (asyncState & (~asyncState + 1)) == asyncState; // This checks if asyncState is 0 or a power of 2.
}
}
#endregion State bit field operations
#region Infrastructure methods
private SynchronizationContext GetStartingContext()
{
#if DESKTOP // as a reminder that on most platforms we want a different behavior
return SynchronizationContext.CurrentNoFlow;
#else
return SynchronizationContext.Current;
#endif
}
internal Task Task
{
get
{
EnsureNotClosed();
if (CompletedSynchronously)
return null;
return (Task)_dataContainer;
}
}
internal CancellationTokenSource CancelTokenSource
{
get { return _cancelTokenSource; }
}
[Pure]
internal void EnsureNotClosed()
{
if (!IsInClosedState)
return;
ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_AsyncInfoIsClosed);
ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL);
throw ex;
}
internal virtual void OnCompleted(TCompletedHandler userCompletionHandler, AsyncStatus asyncStatus)
{
Debug.Fail("This (sub-)type of IAsyncInfo does not support completion notifications "
+ " (" + this.GetType().ToString() + ")");
}
internal virtual void OnProgress(TProgressHandler userProgressHandler, TProgressInfo progressInfo)
{
Debug.Fail("This (sub-)type of IAsyncInfo does not support progress notifications "
+ " (" + this.GetType().ToString() + ")");
}
private void OnCompletedInvoker(AsyncStatus status)
{
bool conditionFailed;
// Get the handler:
TCompletedHandler handler = Volatile.Read(ref _completedHandler);
// If we might not run the handler now, we need to remember that if it is set later, it will need to be run then:
if (handler == null)
{
// Remember to run the handler when it is set:
SetState(STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET, ~STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET,
conditionBitMask: 0, useCondition: false, conditionFailed: out conditionFailed);
// The handler may have been set concurrently before we managed to SetState, so check for it again:
handler = Volatile.Read(ref _completedHandler);
// If handler was not set cuncurrently after all, then no worries:
if (handler == null)
return;
}
// This method might be running cuncurrently. Create a block by emulating an interlocked un-set of
// the STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED-bit in the m_state bit field. Only the thread that wins the race
// for unsetting this bit, wins, others give up:
SetState(0, ~STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED,
conditionBitMask: STATEFLAG_COMPLETION_HNDL_NOT_YET_INVOKED, useCondition: true, conditionFailed: out conditionFailed);
if (conditionFailed)
return;
// Invoke the user handler:
OnCompleted(handler, status);
}
// This is a separate method from IProgress<TProgressInfo>.Report to avoid alocating the closure if it is not used.
private void OnProgressInvokerCrossContext(TProgressHandler handler, TProgressInfo progressInfo)
{
Debug.Assert(handler != null);
Debug.Assert(_startingContext != null);
_startingContext.Post((tupleObject) =>
{
var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>,
TProgressHandler,
TProgressInfo>)tupleObject;
tuple.Item1.OnProgress(tuple.Item2, tuple.Item3);
}, Tuple.Create(this, handler, progressInfo));
}
/// <summary>Reports a progress update.</summary>
/// <param name="value">The new progress value to report.</param>
void IProgress<TProgressInfo>.Report(TProgressInfo value)
{
// If no progress handler is set, there is nothing to do:
TProgressHandler handler = Volatile.Read(ref _progressHandler);
if (handler == null)
return;
// Try calling progress handler in the right synchronization context.
// If the user callback throws an exception, it will bubble up through here and reach the
// user worker code running as this async future. The user should catch it.
// If the user does not catch it, it will be treated just as any other exception coming from the async execution code:
// this AsyncInfo will be faulted.
if (_startingContext == null)
{
// The starting context is null, invoke directly:
OnProgress(handler, value);
}
else
{
// Invoke callback in the right context:
OnProgressInvokerCrossContext(handler, value);
}
}
private void OnReportChainedProgress(object sender, TProgressInfo progressInfo)
{
((IProgress<TProgressInfo>)this).Report(progressInfo);
}
/// <summary>
/// Sets the <code>m_state</code> bit field to reflect the specified async state with the corresponding STATE_XXX bit mask.
/// </summary>
/// <param name="newAsyncState">Must be one of the STATE_XXX (not STATEYYY_ZZZ !) constants defined in this class.</param>
/// <param name="conditionBitMask">If <code>useCondition</code> is FALSE: this field is ignored.
/// If <code>useCondition</code> is TRUE: Unless this value has at least one bit with <code>m_state</code> in
/// common, this method will not perform any action.</param>
/// <param name="useCondition">If TRUE, use <code>conditionBitMask</code> to determine whether the state should be set;
/// If FALSE, ignore <code>conditionBitMask</code>.</param>
/// <param name="conditionFailed">If <code>useCondition</code> is FALSE: this field is set to FALSE;
/// If <code>useCondition</code> is TRUE: this field indicated whether the specified <code>conditionBitMask</code>
/// had at least one bit in common with <code>m_state</code> (TRUE)
/// or not (FALSE).
/// (!) Note that the meaning of this parameter to the caller is not quite the same as whether <code>m_state</code>
/// is/was set to the specified value, because <code>m_state</code> may already have had the specified value, or it
/// may be set and then immediately changed by another thread. The true meaning of this parameter is whether or not
/// the specified condition did hold before trying to change the state.</param>
/// <returns>The value at which the current invocation of this method left <code>m_state</code>.</returns>
private int SetAsyncState(int newAsyncState, int conditionBitMask, bool useCondition, out bool conditionFailed)
{
Debug.Assert(CheckUniqueAsyncState(newAsyncState & STATEMASK_SELECT_ANY_ASYNC_STATE));
Debug.Assert(CheckUniqueAsyncState(_state & STATEMASK_SELECT_ANY_ASYNC_STATE));
int resultState = SetState(newAsyncState, STATEMASK_CLEAR_ALL_ASYNC_STATES, conditionBitMask, useCondition, out conditionFailed);
Debug.Assert(CheckUniqueAsyncState(resultState & STATEMASK_SELECT_ANY_ASYNC_STATE));
return resultState;
}
/// <summary>
/// Sets the specified bits in the <code>m_state</code> bit field according to the specified bit-mask parameters.
/// </summary>
/// <param name="newStateSetMask">The bits to turn ON in the <code>m_state</code> bit field</param>
/// <param name="newStateIgnoreMask">Any bits that are OFF in this value will get turned OFF,
/// unless they are explicitly switched on by <code>newStateSetMask</code>.</param>
/// <param name="conditionBitMask">If <code>useCondition</code> is FALSE: this field is ignored.
/// If <code>useCondition</code> is TRUE: Unless this value has at least one bit with <code>m_state</code> in
/// common, this method will not perform any action.</param>
/// <param name="useCondition">If TRUE, use <code>conditionBitMask</code> to determine whether the state should be set;
/// If FALSE, ignore <code>conditionBitMask</code>.</param>
/// <param name="conditionFailed">If <code>useCondition</code> is FALSE: this field is set to FALSE;
/// If <code>useCondition</code> is TRUE: this field indicated whether the specified <code>conditionBitMask</code>
/// had at least one bit in common with <code>m_state</code> (TRUE)
/// or not (FALSE).
/// (!) Note that the meaning of this parameter to the caller is not quite the same as whether <code>m_state</code>
/// is/was set to the specified value, because <code>m_state</code> may already have had the specified value, or it
/// may be set and then immediately changed by another thread. The true meaning of this parameter is whether or not
/// the specified condition did hold before trying to change the state.</param>
/// <returns>The value at which the current invocation of this method left <code>m_state</code>.</returns>
private int SetState(int newStateSetMask, int newStateIgnoreMask, int conditionBitMask, bool useCondition, out bool conditionFailed)
{
int origState = _state;
if (useCondition && 0 == (origState & conditionBitMask))
{
conditionFailed = true;
return origState;
}
int newState = (origState & newStateIgnoreMask) | newStateSetMask;
int prevState = Interlocked.CompareExchange(ref _state, newState, origState);
// If m_state changed concurrently, we want to make sure that the change being made is based on a bitmask that is up to date:
// (this relies of the fact that all state machines that save their state in m_state have no cycles)
while (true)
{
if (prevState == origState)
{
conditionFailed = false;
return newState;
}
origState = _state;
if (useCondition && 0 == (origState & conditionBitMask))
{
conditionFailed = true;
return origState;
}
newState = (origState & newStateIgnoreMask) | newStateSetMask;
prevState = Interlocked.CompareExchange(ref _state, newState, origState);
}
}
private int TransitionToTerminalState()
{
Debug.Assert(IsInRunningState);
Debug.Assert(!CompletedSynchronously);
Task task = _dataContainer as Task;
Debug.Assert(task != null);
Debug.Assert(task.IsCompleted);
// Recall that STATE_CANCELLATION_REQUESTED and STATE_CANCELLATION_COMPLETED both map to the public CANCELED state.
// So, we are STARTED or CANCELED. We will ask the task how it completed and possibly transition out of CANCELED.
// This may happen if cancellation was requested while in STARTED state, but the task does not support cancellation,
// or if it can support cancellation in principle, but the Cancel request came in while still STARTED, but after the
// last opportunity to cancel.
// If the underlying operation was not able to react to the cancellation request and instead either run to completion
// or faulted, then the state will transition into COMPLETED or ERROR accordingly. If the operation was really cancelled,
// the state will remain CANCELED.
// If the switch below defaults, we have an erroneous implementation.
int terminalAsyncState = STATE_ERROR;
switch (task.Status)
{
case TaskStatus.RanToCompletion:
terminalAsyncState = STATE_RUN_TO_COMPLETION;
break;
case TaskStatus.Canceled:
terminalAsyncState = STATE_CANCELLATION_COMPLETED;
break;
case TaskStatus.Faulted:
terminalAsyncState = STATE_ERROR;
break;
default:
Debug.Fail("Unexpected task.Status: It should be terminal if TaskCompleted() is called.");
break;
}
bool ignore;
int newState = SetAsyncState(terminalAsyncState,
conditionBitMask: STATEMASK_SELECT_ANY_ASYNC_STATE, useCondition: true, conditionFailed: out ignore);
Debug.Assert((newState & STATEMASK_SELECT_ANY_ASYNC_STATE) == terminalAsyncState);
Debug.Assert((_state & STATEMASK_SELECT_ANY_ASYNC_STATE) == terminalAsyncState || IsInClosedState,
"We must either be in a state we just entered or we were concurrently closed");
return newState;
}
private void TaskCompleted()
{
int terminalState = TransitionToTerminalState();
Debug.Assert(IsInTerminalState);
// We transitioned into a terminal state, so it became legal to close us concurrently.
// So we use data from this stack and not m_state to get the completion status.
// On this code path we will also fetch m_completedHandler, however that race is benign because in CLOSED the handler
// can only change to null, so it won't be invoked, which is appropriate for CLOSED.
AsyncStatus terminationStatus = GetStatus(terminalState);
// Try calling completed handler in the right synchronization context.
// If the user callback throws an exception, it will bubble up through here.
// If we let it though, it will be caught and swallowed by the Task subsystem, which is just below us on the stack.
// Instead we follow the same pattern as Task and other parallel libs and re-throw the excpetion on the threadpool
// to ensure a diagnostic message and a fail-fast-like teardown.
try
{
if (_startingContext == null)
{
// The starting context is null, invoking directly:
OnCompletedInvoker(terminationStatus);
}
else
{
// Invoke callback in the right context (delegate cached by compiler):
_startingContext.Post((tupleObject) =>
{
var tuple = (Tuple<TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>, AsyncStatus>)tupleObject;
tuple.Item1.OnCompletedInvoker(tuple.Item2);
}, Tuple.Create(this, terminationStatus));
}
}
catch (Exception ex)
{
ExceptionDispatchHelper.ThrowAsync(ex, _startingContext);
}
}
private AsyncStatus GetStatus(int state)
{
int asyncState = state & STATEMASK_SELECT_ANY_ASYNC_STATE;
Debug.Assert(CheckUniqueAsyncState(asyncState));
switch (asyncState)
{
case STATE_NOT_INITIALIZED:
Debug.Fail("STATE_NOT_INITIALIZED should only occur when this object was not"
+ " fully constructed, in which case we should never get here");
return AsyncStatus.Error;
case STATE_STARTED:
return AsyncStatus.Started;
case STATE_RUN_TO_COMPLETION:
return AsyncStatus.Completed;
case STATE_CANCELLATION_REQUESTED:
case STATE_CANCELLATION_COMPLETED:
return AsyncStatus.Canceled;
case STATE_ERROR:
return AsyncStatus.Error;
case STATE_CLOSED:
Debug.Fail("This method should never be called is this IAsyncInfo is CLOSED");
return AsyncStatus.Error;
}
Debug.Fail("The switch above is missing a case");
return AsyncStatus.Error;
}
internal TResult GetResultsInternal()
{
EnsureNotClosed();
// If this IAsyncInfo has actually faulted, GetResults will throw the same error as returned by ErrorCode:
if (IsInErrorState)
{
Exception error = ErrorCode;
Debug.Assert(error != null);
ExceptionDispatchInfo.Capture(error).Throw();
}
// IAsyncInfo throws E_ILLEGAL_METHOD_CALL when called in a state other than COMPLETED:
if (!IsInRunToCompletionState)
throw CreateCannotGetResultsFromIncompleteOperationException(null);
// If this is a synchronous operation, use the cached result:
if (CompletedSynchronously)
return (TResult)_dataContainer;
// The operation is asynchronous:
Task<TResult> task = _dataContainer as Task<TResult>;
// Since CompletedSynchronously is false and EnsureNotClosed() did not throw, task can only be null if:
// - this IAsyncInfo has completed synchronously, however we checked for this above;
// - it was not converted to Task<TResult>, which means it is a non-generic Task. In that case we cannot get a result from Task.
if (task == null)
return default(TResult);
Debug.Assert(IsInRunToCompletionState);
// Pull out the task result and return.
// Any exceptions thrown in the task will be rethrown.
// If this exception is a cancelation exception, meaning there was actually no error except for being cancelled,
// return an error code appropriate for WinRT instead (InvalidOperation with E_ILLEGAL_METHOD_CALL).
try
{
return task.GetAwaiter().GetResult();
}
catch (TaskCanceledException tcEx)
{
throw CreateCannotGetResultsFromIncompleteOperationException(tcEx);
}
}
private Task InvokeTaskProvider(Delegate taskProvider)
{
var funcVoidTask = taskProvider as Func<Task>;
if (funcVoidTask != null)
{
return funcVoidTask();
}
var funcCTokTask = taskProvider as Func<CancellationToken, Task>;
if (funcCTokTask != null)
{
_cancelTokenSource = new CancellationTokenSource();
return funcCTokTask(_cancelTokenSource.Token);
}
var funcIPrgrTask = taskProvider as Func<IProgress<TProgressInfo>, Task>;
if (funcIPrgrTask != null)
{
return funcIPrgrTask(this);
}
var funcCTokIPrgrTask = taskProvider as Func<CancellationToken, IProgress<TProgressInfo>, Task>;
if (funcCTokIPrgrTask != null)
{
_cancelTokenSource = new CancellationTokenSource();
return funcCTokIPrgrTask(_cancelTokenSource.Token, this);
}
Debug.Fail("We should never get here!"
+ " Public methods creating instances of this class must be typesafe to ensure that taskProvider"
+ " can always be cast to one of the above Func types."
+ " The taskProvider is " + (taskProvider == null
? "null."
: "a " + taskProvider.GetType().ToString()) + ".");
return null;
}
private void TransitionToClosed()
{
// From the finaliser we always call this Close version since finalisation can happen any time, even when STARTED (e.g. process ends)
// and we do not want to throw in those cases.
// Always go to closed, even from STATE_NOT_INITIALIZED.
// Any checking whether it is legal to call CLosed inthe current state, should occur in Close().
bool ignore;
SetAsyncState(STATE_CLOSED, 0, useCondition: false, conditionFailed: out ignore);
_cancelTokenSource = null;
_dataContainer = null;
_error = null;
_completedHandler = null;
_progressHandler = null;
_startingContext = null;
}
#endregion Infrastructure methods
#region Implementation of IAsyncInfo
/// <summary>
/// Gets or sets the completed handler.
///
/// We will set the completion handler even when this IAsyncInfo is already started (no other choice).
/// If we the completion handler is set BEFORE this IAsyncInfo completed, then the handler will be called upon completion as normal.
/// If we the completion handler is set AFTER this IAsyncInfo already completed, then this setter will invoke the handler synchronously
/// on the current context.
/// </summary>
public virtual TCompletedHandler Completed
{
get
{
TCompletedHandler handler = Volatile.Read(ref _completedHandler);
EnsureNotClosed();
return handler;
}
set
{
EnsureNotClosed();
// Try setting completion handler, but only if this has not yet been done:
// (Note: We allow setting Completed to null multiple times iff it has not yet been set to anything else than null.
// Some other WinRT projection languages do not allow setting the Completed handler more than once, even if it is set to null.
// We could do the same by introducing a new STATEFLAG_COMPLETION_HNDL_SET bit-flag constant and saving a this state into
// the m_state field to indicate that the completion handler has been set previously, but we choose not to do this.)
TCompletedHandler handlerBefore = Interlocked.CompareExchange(ref _completedHandler, value, null);
if (handlerBefore != null)
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetCompletionHanlderMoreThanOnce);
ex.SetErrorCode(__HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT);
throw ex;
}
if (value == null)
return;
// If STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET is OFF then we are done (i.e. no need to invoke the handler synchronously)
if (0 == (_state & STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET))
return;
// We have changed the handler and at some point this IAsyncInfo may have transitioned to the Closed state.
// This is OK, but if this happened we need to ensure that we only leave a null handler behind:
if (IsInClosedState)
{
Interlocked.Exchange(ref _completedHandler, null);
return;
}
// The STATEFLAG_MUST_RUN_COMPLETION_HNDL_WHEN_SET-flag was set, so we need to call the completion handler now:
Debug.Assert(IsInTerminalState);
OnCompletedInvoker(Status);
}
}
/// <summary>Gets or sets the progress handler.</summary>
public virtual TProgressHandler Progress
{
get
{
TProgressHandler handler = Volatile.Read(ref _progressHandler);
EnsureNotClosed();
return handler;
}
set
{
EnsureNotClosed();
Interlocked.Exchange(ref _progressHandler, value);
// We transitioned into CLOSED after the above check, we will need to null out m_progressHandler:
if (IsInClosedState)
Interlocked.Exchange(ref _progressHandler, null);
}
}
/// <summary>Cancels the async info.</summary>
public virtual void Cancel()
{
// Cancel will be ignored in any terminal state including CLOSED.
// In other words, it is ignored in any state except STARTED.
bool stateWasNotStarted;
SetAsyncState(STATE_CANCELLATION_REQUESTED, conditionBitMask: STATE_STARTED, useCondition: true, conditionFailed: out stateWasNotStarted);
if (!stateWasNotStarted)
{ // i.e. if state was different from STATE_STARTED:
if (_cancelTokenSource != null)
_cancelTokenSource.Cancel();
}
}
/// <summary>Close the async info.</summary>
public virtual void Close()
{
if (IsInClosedState)
return;
// Cannot Close from a non-terminal state:
if (!IsInTerminalState)
{
// If we are STATE_NOT_INITIALIZED, the we probably threw from the ctor.
// The finalizer will be called anyway and we need to free this partially constructed object correctly.
// So we avoid throwing when we are in STATE_NOT_INITIALIZED.
// In other words throw only if *some* async state is set:
if (0 != (_state & STATEMASK_SELECT_ANY_ASYNC_STATE))
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_IllegalStateChange);
ex.SetErrorCode(__HResults.E_ILLEGAL_STATE_CHANGE);
throw ex;
}
}
TransitionToClosed();
}
/// <summary>Gets the error code for the async info.</summary>
public virtual Exception ErrorCode
{
get
{
EnsureNotClosed();
// If the task is faulted, hand back an HR representing its first exception.
// Otherwise, hand back S_OK (which is a null Exception).
if (!IsInErrorState)
return null;
Exception error = Volatile.Read(ref _error);
// ERROR is a terminal state. SO if we have an error, just return it.
// If we completed synchronously, we return the current error iven if it is null since we do not expect this to change:
if (error != null || CompletedSynchronously)
return error;
Task task = _dataContainer as Task;
Debug.Assert(task != null);
AggregateException aggregateException = task.Exception;
// By spec, if task.IsFaulted is true, then task.Exception must not be null and its InnerException must
// also not be null. However, in case something is unexpected on the Task side of the road, let?s be defensive
// instead of failing with an inexplicable NullReferenceException:
if (aggregateException == null)
{
error = new Exception(SR.WinRtCOM_Error);
error.SetErrorCode(__HResults.E_FAIL);
}
else
{
Exception innerException = aggregateException.InnerException;
error = (innerException == null)
? aggregateException
: innerException;
}
// If m_error was set concurrently, setError will be non-null. Then we use that - as it is the first m_error
// that was set. If setError we know that we won any races and we can return error:
Exception setError = Interlocked.CompareExchange(ref _error, error, null);
return setError ?? error;
}
}
public virtual uint Id
{
get
{
EnsureNotClosed();
if (_id != AsyncInfoIdGenerator.InvalidId)
return _id;
return AsyncInfoIdGenerator.EnsureInitializedThreadsafe(ref _id);
}
}
/// <summary>Gets the status of the async info.</summary>
public virtual AsyncStatus Status
{
get
{
EnsureNotClosed();
return GetStatus(_state);
}
}
#endregion Implementation of IAsyncInfo
} // class TaskToAsyncInfoAdapter<TCompletedHandler, TProgressHandler, TResult, TProgressInfo>
} // namespace
// TaskToAsyncInfoAdapter.cs
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
internal class WinHttpRequestStream : Stream
{
private static byte[] s_crLfTerminator = new byte[] { 0x0d, 0x0a }; // "\r\n"
private static byte[] s_endChunk = new byte[] { 0x30, 0x0d, 0x0a, 0x0d, 0x0a }; // "0\r\n\r\n"
private volatile bool _disposed;
private WinHttpRequestState _state;
private bool _chunkedMode;
// TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache.
private GCHandle _cachedSendPinnedBuffer;
internal WinHttpRequestStream(WinHttpRequestState state, bool chunkedMode)
{
_state = state;
_chunkedMode = chunkedMode;
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return !_disposed;
}
}
public override long Length
{
get
{
CheckDisposed();
throw new NotSupportedException();
}
}
public override long Position
{
get
{
CheckDisposed();
throw new NotSupportedException();
}
set
{
CheckDisposed();
throw new NotSupportedException();
}
}
public override void Flush()
{
// Nothing to do.
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count");
}
if (count > buffer.Length - offset)
{
throw new ArgumentException("buffer");
}
if (token.IsCancellationRequested)
{
var tcs = new TaskCompletionSource<int>();
tcs.TrySetCanceled(token);
return tcs.Task;
}
CheckDisposed();
if (_state.TcsInternalWriteDataToRequestStream != null &&
!_state.TcsInternalWriteDataToRequestStream.Task.IsCompleted)
{
throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed);
}
return InternalWriteAsync(buffer, offset, count, token);
}
public override void Write(byte[] buffer, int offset, int count)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckDisposed();
throw new NotSupportedException();
}
public override void SetLength(long value)
{
CheckDisposed();
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
CheckDisposed();
throw new NotSupportedException();
}
internal async Task EndUploadAsync(CancellationToken token)
{
if (_chunkedMode)
{
await InternalWriteDataAsync(s_endChunk, 0, s_endChunk.Length, token).ConfigureAwait(false);
}
}
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
// TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further
// operations will be made to the send/receive buffers.
if (_cachedSendPinnedBuffer.IsAllocated)
{
_cachedSendPinnedBuffer.Free();
}
}
base.Dispose(disposing);
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
private Task InternalWriteAsync(byte[] buffer, int offset, int count, CancellationToken token)
{
return _chunkedMode ?
InternalWriteChunkedModeAsync(buffer, offset, count, token) :
InternalWriteDataAsync(buffer, offset, count, token);
}
private async Task InternalWriteChunkedModeAsync(byte[] buffer, int offset, int count, CancellationToken token)
{
// WinHTTP does not fully support chunked uploads. It simply allows one to omit the 'Content-Length' header
// and instead use the 'Transfer-Encoding: chunked' header. The caller is still required to encode the
// request body according to chunking rules.
Debug.Assert(_chunkedMode);
string chunkSizeString = String.Format("{0:x}\r\n", count);
byte[] chunkSize = Encoding.UTF8.GetBytes(chunkSizeString);
await InternalWriteDataAsync(chunkSize, 0, chunkSize.Length, token).ConfigureAwait(false);
await InternalWriteDataAsync(buffer, offset, count, token).ConfigureAwait(false);
await InternalWriteDataAsync(s_crLfTerminator, 0, s_crLfTerminator.Length, token).ConfigureAwait(false);
}
private Task<bool> InternalWriteDataAsync(byte[] buffer, int offset, int count, CancellationToken token)
{
Debug.Assert(count >= 0);
if (count == 0)
{
return Task.FromResult<bool>(true);
}
// TODO (Issue 2505): replace with PinnableBufferCache.
if (!_cachedSendPinnedBuffer.IsAllocated || _cachedSendPinnedBuffer.Target != buffer)
{
if (_cachedSendPinnedBuffer.IsAllocated)
{
_cachedSendPinnedBuffer.Free();
}
_cachedSendPinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
}
_state.TcsInternalWriteDataToRequestStream =
new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (_state.Lock)
{
if (!Interop.WinHttp.WinHttpWriteData(
_state.RequestHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset),
(uint)count,
IntPtr.Zero))
{
_state.TcsInternalWriteDataToRequestStream.TrySetException(
new IOException(SR.net_http_io_write, WinHttpException.CreateExceptionUsingLastError()));
}
}
// TODO: Issue #2165. Register callback on cancellation token to cancel WinHTTP operation.
return _state.TcsInternalWriteDataToRequestStream.Task;
}
}
}
| |
/****************************************************************************
* Class Name : ErrorWarnInfoProvider.cs
* Author : Kenneth J. Koteles
* Created : 10/04/2007 2:14 PM
* C# Version : .NET 2.0
* Description : This code is designed to create a new provider object to
* work specifically with CSLA BusinessBase objects. In
* addition to providing the red error icon for items in the
* BrokenRulesCollection with Csla.Rules.RuleSeverity.Error,
* this object also provides a yellow warning icon for items
* with Csla.Rules.RuleSeverity.Warning and a blue
* information icon for items with
* Csla.Rules.RuleSeverity.Information. Since warnings
* and information type items do not need to be fixed /
* corrected prior to the object being saved, the tooltip
* displayed when hovering over the respective icon contains
* all the control's associated (by severity) broken rules.
* Revised : 11/20/2007 8:32 AM
* Change : Warning and information icons were not being updated for
* dependant properties (controls without the focus) when
* changes were being made to a related property (control with
* the focus). Added a list of controls to be recursed
* through each time a change was made to any control. This
* obviously could result in performance issues; however,
* there is no consistent way to question the BusinessObject
* in order to get a list of dependant properties based on a
* property name. It can be exposed to the UI (using
* ValidationRules.GetRuleDescriptions()); however, it is up
* to each developer to implement their own public method on
* on the Business Object to do so. To make this generic for
* all CSLA Business Objects, I cannot assume the developer
* always exposes the dependant properties (nor do I know what
* they'll call the method); therefore, this is the best I can
* do right now.
* Revised : 11/23/2007 9:02 AM
* Change : Added new property ProcessDependantProperties to allow for
* controlling when all controls are recursed through (for
* dependant properties or not). Default value is 'false'.
* This allows the developer to ba able to choose whether or
* not to use the control in this manner (which could have
* performance implications).
* Revised : 10/05/2009, Jonny Bekkum
* Change : Added initialization of controls list (controls attached to BindingSource)
* and will update errors on all controls. Optimized retrieval of error, warn, info
* messages and setting these on the controls.
* Revised : 23/02/2018, Tiago Freitas Leal
* Change : Added support for INotifyPropertyChanged objects (instead of BindingSource).
* Can discover controls only when the DataSource is set.
* Fix long standing issue on Information message (incomplete message).
****************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using Wisej.Web;
using Csla.Core;
namespace CslaContrib.WisejWeb
{
/// <summary>
/// Wisej.Web extender control that automatically
/// displays error, warning, or information icons and
/// text for the form controls based on the
/// BrokenRulesCollection of a CSLA .NET business object.
/// </summary>
[DesignerCategory("")]
[ToolboxItem(true), ToolboxBitmap(typeof(ErrorWarnInfoProvider), "Cascade.ico")]
public class ErrorWarnInfoProvider : ErrorProvider, IExtenderProvider, ISupportInitialize
{
#region private variables
private readonly IContainer components;
private readonly ErrorProvider _errorProviderInfo;
private readonly ErrorProvider _errorProviderWarn;
private readonly List<Control> _controls = new List<Control>();
private static readonly Image DefaultIconInformation;
private static readonly Image DefaultIconWarning;
private int _offsetInformation = 32;
private int _offsetWarning = 16;
private bool _showInformation = true;
private bool _showWarning = true;
private bool _showMostSevereOnly = true;
private readonly Dictionary<string, string> _errorList = new Dictionary<string, string>();
private readonly Dictionary<string, string> _warningList = new Dictionary<string, string>();
private readonly Dictionary<string, string> _infoList = new Dictionary<string, string>();
private bool _isInitializing;
#endregion
#region Constructors
/// <summary>
/// Initializes the <see cref="ErrorWarnInfoProvider"/> class.
/// </summary>
static ErrorWarnInfoProvider()
{
DefaultIconInformation = Properties.Resources.InformationIcon;
DefaultIconWarning = Properties.Resources.WarningIcon;
}
/// <summary>
/// Initializes a new instance of the <see cref="ErrorWarnInfoProvider"/> class.
/// </summary>
public ErrorWarnInfoProvider()
{
components = new Container();
_errorProviderInfo = new ErrorProvider(components);
_errorProviderWarn = new ErrorProvider(components);
BlinkRate = 0;
_errorProviderInfo.BlinkRate = 0;
_errorProviderInfo.Icon = DefaultIconInformation;
_errorProviderWarn.BlinkRate = 0;
_errorProviderWarn.Icon = DefaultIconWarning;
}
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="container">The container of the control.</param>
public ErrorWarnInfoProvider(IContainer container)
: this()
{
container.Add(this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.ComponentModel.Component"></see> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
components?.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region IExtenderProvider Members
/// <summary>
/// Gets a value indicating whether the extender control
/// can extend the specified control.
/// </summary>
/// <param name="extendee">The control to be extended.</param>
/// <remarks>
/// Any control implementing either a ReadOnly property or
/// Enabled property can be extended.
/// </remarks>
bool IExtenderProvider.CanExtend(object extendee)
{
//if (extendee is ErrorProvider)
//{
// return true;
//}
if ((extendee is Control && !(extendee is Form)))
{
return !(extendee is ToolBar);
}
else
{
return false;
}
}
#endregion
#region Public properties
/// <summary>
/// Gets or sets the rate at which the error icon flashes.
/// </summary>
/// <value>The rate, in milliseconds, at which the error icon should flash. The default is 250 milliseconds.</value>
/// <exception cref="T:System.ArgumentOutOfRangeException">The value is less than zero. </exception>
[Category("Behavior")]
[DefaultValue(0)]
[Description("The rate in milliseconds at which the error icon blinks.")]
public new int BlinkRate
{
get { return base.BlinkRate; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, "Blink rate must be zero or more");
}
base.BlinkRate = value;
if (value == 0)
{
BlinkStyle = ErrorBlinkStyle.NeverBlink;
}
}
}
/// <summary>
/// Gets or sets the rate at which the information icon flashes.
/// </summary>
/// <value>The rate, in milliseconds, at which the information icon should flash. The default is 250 milliseconds.</value>
/// <exception cref="T:System.ArgumentOutOfRangeException">The value is less than zero. </exception>
[Category("Behavior")]
[DefaultValue(0)]
[Description("The rate in milliseconds at which the information icon blinks.")]
public int BlinkRateInformation
{
get { return _errorProviderInfo.BlinkRate; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "Blink rate must be zero or more");
_errorProviderInfo.BlinkRate = value;
if (value == 0)
_errorProviderInfo.BlinkStyle = ErrorBlinkStyle.NeverBlink;
}
}
/// <summary>
/// Gets or sets the rate at which the warning icon flashes.
/// </summary>
/// <value>The rate, in milliseconds, at which the warning icon should flash.
/// The default is 250 milliseconds.</value>
/// <exception cref="T:System.ArgumentOutOfRangeException">The value is less than zero. </exception>
[Category("Behavior")]
[DefaultValue(0)]
[Description("The rate in milliseconds at which the warning icon blinks.")]
public int BlinkRateWarning
{
get { return _errorProviderWarn.BlinkRate; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), value, "Blink rate must be zero or more");
_errorProviderWarn.BlinkRate = value;
if (value == 0)
_errorProviderWarn.BlinkStyle = ErrorBlinkStyle.NeverBlink;
}
}
/// <summary>
/// Gets or sets a value indicating when the error icon flashes.
/// </summary>
/// <value>One of the <see cref="T:Wisej.Web.ErrorBlinkStyle"/> values.
/// The default is <see cref="F:Wisej.Web.ErrorBlinkStyle.BlinkIfDifferentError"/>.</value>
/// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The assigned value is not one of the <see cref="T:Wisej.Web.ErrorBlinkStyle"/> values. </exception>
[Category("Behavior")]
[DefaultValue(ErrorBlinkStyle.NeverBlink)]
[Description("Controls whether the error icon blinks when an error is set.")]
public new ErrorBlinkStyle BlinkStyle
{
get { return base.BlinkStyle; }
set { base.BlinkStyle = value; }
}
/// <summary>
/// Gets or sets a value indicating when the information icon flashes.
/// </summary>
/// <value>One of the <see cref="T:Wisej.Web.ErrorBlinkStyle"/> values.
/// The default is <see cref="F:Wisej.Web.ErrorBlinkStyle.BlinkIfDifferentError"/>.</value>
/// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The assigned value is not one of the <see cref="T:Wisej.Web.ErrorBlinkStyle"/> values. </exception>
[Category("Behavior")]
[DefaultValue(ErrorBlinkStyle.NeverBlink)]
[Description("Controls whether the information icon blinks when information is set.")]
public ErrorBlinkStyle BlinkStyleInformation
{
get { return _errorProviderInfo.BlinkStyle; }
set { _errorProviderWarn.BlinkStyle = value; }
}
/// <summary>
/// Gets or sets a value indicating when the warning icon flashes.
/// </summary>
/// <value>One of the <see cref="T:Wisej.Web.ErrorBlinkStyle"/> values. The default is <see cref="F:Wisej.Web.ErrorBlinkStyle.BlinkIfDifferentError"/>.</value>
/// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The assigned value is not one of the <see cref="T:Wisej.Web.ErrorBlinkStyle"/> values. </exception>
[Category("Behavior")]
[DefaultValue(ErrorBlinkStyle.NeverBlink)]
[Description("Controls whether the warning icon blinks when a warning is set.")]
public ErrorBlinkStyle BlinkStyleWarning
{
get { return _errorProviderWarn.BlinkStyle; }
set { _errorProviderWarn.BlinkStyle = value; }
}
/// <summary>
/// Gets or sets the data source that the <see cref="T:Wisej.Web.ErrorProvider"></see> monitors.
/// </summary>
/// <value></value>
/// <value>A data source based on the <see cref="T:System.Collections.IList"></see> interface to be monitored for errors. Typically, this is a <see cref="T:System.Data.DataSet"></see> to be monitored for errors.</value>
/// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
[DefaultValue(null)]
public new object DataSource
{
get { return base.DataSource; }
set
{
if (base.DataSource != value)
{
var bs1 = base.DataSource as BindingSource;
if (bs1 != null)
{
bs1.CurrentItemChanged -= DataSource_CurrentItemChanged;
}
else
{
var npc1 = base.DataSource as INotifyPropertyChanged;
if (npc1 != null)
{
npc1.PropertyChanged -= DataSource_CurrentItemChanged;
}
}
}
base.DataSource = value;
var bs = value as BindingSource;
if (bs != null)
{
bs.CurrentItemChanged += DataSource_CurrentItemChanged;
}
else
{
var npc = value as INotifyPropertyChanged;
if (npc != null)
{
npc.PropertyChanged += DataSource_CurrentItemChanged;
}
}
if (_controls.Count == 0)
{
UpdateBindingsAndProcessAllControls();
}
}
}
private void UpdateBindingsAndProcessAllControls()
{
if (ContainerControl != null)
{
InitializeAllControls(ContainerControl.Controls);
}
ProcessAllControls();
}
/// <summary>
/// Gets or sets the icon information.
/// </summary>
/// <value>The icon information.</value>
[Category("Behavior")]
[Description("The icon used to indicate information.")]
public Image IconInformation
{
get { return _errorProviderInfo.Icon; }
set
{
if (value == null)
value = DefaultIconInformation;
_errorProviderInfo.Icon = value;
}
}
/// <summary>
/// Gets or sets the icon warning.
/// </summary>
/// <value>The icon warning.</value>
[Category("Behavior")]
[Description("The icon used to indicate a warning.")]
public Image IconWarning
{
get { return _errorProviderWarn.Icon; }
set
{
if (value == null)
value = DefaultIconWarning;
_errorProviderWarn.Icon = value;
}
}
/// <summary>
/// Gets or sets the offset information.
/// </summary>
/// <value>The offset information.</value>
[Category("Behavior")]
[DefaultValue(32), Description("The number of pixels the information icon will be offset from the error icon.")]
public int OffsetInformation
{
get { return _offsetInformation; }
set { _offsetInformation = value; }
}
/// <summary>
/// Gets or sets the offset warning.
/// </summary>
/// <value>The offset warning.</value>
[Category("Behavior")]
[DefaultValue(16), Description("The number of pixels the warning icon will be offset from the error icon.")]
public int OffsetWarning
{
get { return _offsetWarning; }
set { _offsetWarning = value; }
}
/// <summary>
/// Gets or sets a value indicating whether broken rules with severity information should be visible.
/// </summary>
/// <value><c>true</c> if information is visible; otherwise, <c>false</c>.</value>
[Category("Behavior")]
[DefaultValue(true), Description("Determines if the information icon should be displayed when information exists.")]
public bool ShowInformation
{
get { return _showInformation; }
set { _showInformation = value; }
}
/// <summary>
/// Gets or sets a value indicating whether broken rules with severity Warning should be visible.
/// </summary>
/// <value><c>true</c> if Warning is visible; otherwise, <c>false</c>.</value>
[Category("Behavior")]
[DefaultValue(true), Description("Determines if the warning icon should be displayed when warnings exist.")]
public bool ShowWarning
{
get { return _showWarning; }
set { _showWarning = value; }
}
/// <summary>
/// Gets or sets a value indicating whether show only most severe broken rules message.
/// </summary>
/// <value><c>true</c> if show only most severe; otherwise, <c>false</c>.</value>
[Category("Behavior")]
[DefaultValue(true),
Description("Determines if the broken rules are show by severity - if true only most severe level is shown.")]
public bool ShowOnlyMostSevere
{
get { return _showMostSevereOnly; }
set
{
if (_showMostSevereOnly != value)
{
_showMostSevereOnly = value;
//Refresh controls
ProcessAllControls();
}
}
}
#endregion
#region Methods
/// <summary>
/// Clears all errors associated with this component.
/// </summary>
/// <PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
public new void Clear()
{
base.Clear();
_errorProviderInfo.Clear();
_errorProviderWarn.Clear();
}
/// <summary>
/// Returns the current information description string for the specified control.
/// </summary>
/// <param name="control">The item to get the error description string for.</param>
/// <returns>The information description string for the specified control.</returns>
public string GetInformation(Control control)
{
return _errorProviderInfo.GetError(control);
}
/// <summary>
/// Returns the current warning description string for the specified control.
/// </summary>
/// <param name="control">The item to get the error description string for.</param>
/// <returns>The warning description string for the specified control.</returns>
public string GetWarning(Control control)
{
return _errorProviderWarn.GetError(control);
}
private void InitializeAllControls(Control.ControlCollection controls)
{
// clear internal
_controls.Clear();
// run recursive initialize of controls
Initialize(controls);
}
private void Initialize(Control.ControlCollection controls)
{
//We don't provide an extended property, so if the control is
// not a Label then 'hook' the validating event here!
foreach (Control control in controls)
{
if (control is Label)
continue;
// Initialize bindings
foreach (Binding binding in control.DataBindings)
{
// get the Binding if appropriate
if (binding.DataSource == DataSource)
{
_controls.Add(control);
}
}
// Initialize any subcontrols
if (control.Controls.Count > 0)
{
Initialize(control.Controls);
}
}
}
private void DataSource_CurrentItemChanged(object sender, EventArgs e)
{
Debug.Print("ErrorWarnInfo: CurrentItemChanged, {0}", DateTime.Now.Ticks);
ProcessAllControls();
}
private void ProcessAllControls()
{
if (_isInitializing)
return;
// get error/warn/info list from business object
GetWarnInfoList();
// process controls in window
ProcessControls();
}
private void GetWarnInfoList()
{
_infoList.Clear();
_warningList.Clear();
_errorList.Clear();
// we can only deal with CSLA BusinessBase objects
// try to get the BusinessBase object as a BindingSource
var bb = GetAsBindingSource();
// if not a BindingSource, try to get it as an INotifyPropertyChanged
if (bb == null)
bb = GetAsNotifyPropertyChanged();
if (bb != null)
{
foreach (Csla.Rules.BrokenRule br in bb.BrokenRulesCollection)
{
// we do not want to import result of object level broken rules
if (br.Property == null)
continue;
switch (br.Severity)
{
case Csla.Rules.RuleSeverity.Error:
if (_errorList.ContainsKey(br.Property))
{
_errorList[br.Property] =
string.Concat(_errorList[br.Property], Environment.NewLine, br.Description);
}
else
{
_errorList.Add(br.Property, br.Description);
}
break;
case Csla.Rules.RuleSeverity.Warning:
if (_warningList.ContainsKey(br.Property))
{
_warningList[br.Property] =
string.Concat(_warningList[br.Property], Environment.NewLine, br.Description);
}
else
{
_warningList.Add(br.Property, br.Description);
}
break;
default: // consider it an Info
if (_infoList.ContainsKey(br.Property))
{
_infoList[br.Property] =
string.Concat(_infoList[br.Property], Environment.NewLine, br.Description);
}
else
{
_infoList.Add(br.Property, br.Description);
}
break;
}
}
}
}
private BusinessBase GetAsBindingSource()
{
BindingSource bs = DataSource as BindingSource;
if (bs == null)
return null;
if (bs.Position == -1)
return null;
return bs.Current as BusinessBase;
}
private BusinessBase GetAsNotifyPropertyChanged()
{
INotifyPropertyChanged npc = DataSource as INotifyPropertyChanged;
return npc as BusinessBase;
}
private void ProcessControls()
{
foreach (Control control in _controls)
{
ProcessControl(control);
}
}
/// <summary>
/// Processes the control.
/// </summary>
/// <param name="control">The control.</param>
private void ProcessControl(Control control)
{
if (control == null)
throw new ArgumentNullException(nameof(control));
bool hasWarning = false;
bool hasInfo = false;
var sbError = new StringBuilder();
var sbWarn = new StringBuilder();
var sbInfo = new StringBuilder();
foreach (Binding binding in control.DataBindings)
{
// get the Binding if appropriate
if (binding.DataSource == DataSource)
{
string propertyName = binding.BindingMemberInfo.BindingField;
if (_errorList.ContainsKey(propertyName))
sbError.AppendLine(_errorList[propertyName]);
if (_warningList.ContainsKey(propertyName))
sbWarn.AppendLine(_warningList[propertyName]);
if (_infoList.ContainsKey(propertyName))
sbInfo.AppendLine(_infoList[propertyName]);
}
}
bool bError = sbError.Length > 0;
bool bWarn = sbWarn.Length > 0;
bool bInfo = sbInfo.Length > 0;
// set flags to indicat if Warning or Info is highest severity; else false
if (_showMostSevereOnly)
{
bInfo = bInfo && !bWarn && !bError;
bWarn = bWarn && !bError;
}
int offsetInformation = _offsetInformation;
int offsetWarning = _offsetWarning;
// Set / fix offsets
// by default the setting are correct for Error (0), Warning and Info
if (!bError)
{
if (bWarn)
{
// warning and possibly info, no error
offsetInformation = _offsetInformation - _offsetWarning;
offsetWarning = 0;
}
else
{
// Info only
offsetInformation = 0;
}
}
else if (!bWarn)
{
offsetInformation = _offsetInformation - _offsetWarning;
}
// should warning be visible
if (_showWarning && bWarn)
{
_errorProviderWarn.SetError(control, sbWarn.ToString());
_errorProviderWarn.SetIconPadding(control,
GetIconPadding(control) +
offsetWarning);
_errorProviderWarn.SetIconAlignment(control,
GetIconAlignment(control));
hasWarning = true;
}
// should info be shown
if (_showInformation && bInfo)
{
_errorProviderInfo.SetError(control, sbInfo.ToString());
_errorProviderInfo.SetIconPadding(control,
GetIconPadding(control) +
offsetInformation);
_errorProviderInfo.SetIconAlignment(control,
GetIconAlignment(control));
hasInfo = true;
}
if (!hasWarning)
_errorProviderWarn.SetError(control, string.Empty);
if (!hasInfo)
_errorProviderInfo.SetError(control, string.Empty);
}
private void ResetBlinkStyleInformation()
{
BlinkStyleInformation = ErrorBlinkStyle.BlinkIfDifferentError;
}
private void ResetBlinkStyleWarning()
{
BlinkStyleWarning = ErrorBlinkStyle.BlinkIfDifferentError;
}
private void ResetIconInformation()
{
IconInformation = DefaultIconInformation;
}
private void ResetIconWarning()
{
IconWarning = DefaultIconWarning;
}
/// <summary>
/// Sets the information description string for the specified control.
/// </summary>
/// <param name="control">The control to set the information description string for.</param>
/// <param name="value">The information description string, or null or System.string.Empty to remove the information description.</param>
public void SetInformation(Control control, string value)
{
_errorProviderInfo.SetError(control, value);
}
/// <summary>
/// Sets the warning description string for the specified control.
/// </summary>
/// <param name="control">The control to set the warning description string for.</param>
/// <param name="value">The warning description string, or null or System.string.Empty to remove the warning description.</param>
public void SetWarning(Control control, string value)
{
_errorProviderWarn.SetError(control, value);
}
private bool ShouldSerializeIconInformation()
{
return (IconInformation != DefaultIconInformation);
}
private bool ShouldSerializeIconWarning()
{
return (IconWarning != DefaultIconWarning);
}
private bool ShouldSerializeBlinkStyleInformation()
{
return (BlinkStyleInformation != ErrorBlinkStyle.BlinkIfDifferentError);
}
private bool ShouldSerializeBlinkStyleWarning()
{
return (BlinkStyleWarning != ErrorBlinkStyle.BlinkIfDifferentError);
}
/// <summary>
/// Provides a method to update the bindings of the <see cref="P:Wisej.Web.ErrorProvider.DataSource"></see>, <see cref="P:Wisej.Web.ErrorProvider.DataMember"></see>, and the error text.
/// </summary>
/// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
public new void UpdateBinding()
{
base.UpdateBinding();
_errorProviderInfo.UpdateBinding();
_errorProviderWarn.UpdateBinding();
}
#endregion
#region ISupportInitialize Members
void ISupportInitialize.BeginInit()
{
_isInitializing = true;
}
void ISupportInitialize.EndInit()
{
_isInitializing = false;
if (ContainerControl != null)
{
InitializeAllControls(ContainerControl.Controls);
}
}
#endregion
}
}
| |
namespace DepAnalyzer
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem("asd", 2);
System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem("asdasdasdasdasd", 1);
System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem("asdasd", 0);
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.ProjectList = new System.Windows.Forms.ListBox();
this.SolutionTextBox = new System.Windows.Forms.TextBox();
this.BrowseButton = new System.Windows.Forms.Button();
this.ParseButton = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.ProjectTabControl = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.depGraph = new DepAnalyzer.ProjectsDepGraph();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.depMatrix = new DepAnalyzer.ProjectsDepMatrix();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.LogTextBoxRich = new System.Windows.Forms.RichTextBox();
this.LogCombo = new System.Windows.Forms.ComboBox();
this.label5 = new System.Windows.Forms.Label();
this.ConfigTextBox = new System.Windows.Forms.TextBox();
this.BuildList = new System.Windows.Forms.ListView();
this.ProjectColumn = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.BuildContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.showLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.rebuildToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.ProjectStatusImages = new System.Windows.Forms.ImageList(this.components);
this.label4 = new System.Windows.Forms.Label();
this.BuildButton = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.ShowSingleCheckBox = new System.Windows.Forms.CheckBox();
this.ShowChildrenCheckBox = new System.Windows.Forms.CheckBox();
this.ProjectTabControl.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
this.BuildContextMenu.SuspendLayout();
this.SuspendLayout();
//
// ProjectList
//
this.ProjectList.FormattingEnabled = true;
this.ProjectList.Location = new System.Drawing.Point(12, 97);
this.ProjectList.Name = "ProjectList";
this.ProjectList.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.ProjectList.Size = new System.Drawing.Size(136, 628);
this.ProjectList.TabIndex = 2;
this.ProjectList.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
//
// SolutionTextBox
//
this.SolutionTextBox.Location = new System.Drawing.Point(90, 12);
this.SolutionTextBox.Name = "SolutionTextBox";
this.SolutionTextBox.Size = new System.Drawing.Size(752, 20);
this.SolutionTextBox.TabIndex = 3;
//
// BrowseButton
//
this.BrowseButton.Location = new System.Drawing.Point(848, 9);
this.BrowseButton.Name = "BrowseButton";
this.BrowseButton.Size = new System.Drawing.Size(75, 23);
this.BrowseButton.TabIndex = 4;
this.BrowseButton.Text = "Browse...";
this.BrowseButton.UseVisualStyleBackColor = true;
this.BrowseButton.Click += new System.EventHandler(this.button1_Click);
//
// ParseButton
//
this.ParseButton.Location = new System.Drawing.Point(929, 9);
this.ParseButton.Name = "ParseButton";
this.ParseButton.Size = new System.Drawing.Size(75, 23);
this.ParseButton.TabIndex = 5;
this.ParseButton.Text = "Parse";
this.ParseButton.UseVisualStyleBackColor = true;
this.ParseButton.Click += new System.EventHandler(this.button2_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 15);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 13);
this.label1.TabIndex = 6;
this.label1.Text = "Solution path:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 81);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(101, 13);
this.label2.TabIndex = 7;
this.label2.Text = "Project Dep graphs:";
//
// ProjectTabControl
//
this.ProjectTabControl.Controls.Add(this.tabPage1);
this.ProjectTabControl.Controls.Add(this.tabPage2);
this.ProjectTabControl.Controls.Add(this.tabPage3);
this.ProjectTabControl.Location = new System.Drawing.Point(154, 38);
this.ProjectTabControl.Name = "ProjectTabControl";
this.ProjectTabControl.SelectedIndex = 0;
this.ProjectTabControl.Size = new System.Drawing.Size(850, 687);
this.ProjectTabControl.TabIndex = 8;
//
// tabPage1
//
this.tabPage1.BackColor = System.Drawing.Color.Transparent;
this.tabPage1.Controls.Add(this.depGraph);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.tabPage1.Size = new System.Drawing.Size(842, 661);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Graph";
//
// depGraph
//
this.depGraph.AutoScroll = true;
this.depGraph.Location = new System.Drawing.Point(6, 6);
this.depGraph.Name = "depGraph";
this.depGraph.Size = new System.Drawing.Size(830, 649);
this.depGraph.TabIndex = 1;
//
// tabPage2
//
this.tabPage2.BackColor = System.Drawing.Color.Transparent;
this.tabPage2.Controls.Add(this.depMatrix);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(842, 661);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Matrix";
//
// depMatrix
//
this.depMatrix.Location = new System.Drawing.Point(6, 6);
this.depMatrix.Name = "depMatrix";
this.depMatrix.Size = new System.Drawing.Size(830, 649);
this.depMatrix.TabIndex = 0;
//
// tabPage3
//
this.tabPage3.BackColor = System.Drawing.Color.Transparent;
this.tabPage3.Controls.Add(this.LogTextBoxRich);
this.tabPage3.Controls.Add(this.LogCombo);
this.tabPage3.Controls.Add(this.label5);
this.tabPage3.Controls.Add(this.ConfigTextBox);
this.tabPage3.Controls.Add(this.BuildList);
this.tabPage3.Controls.Add(this.label4);
this.tabPage3.Controls.Add(this.BuildButton);
this.tabPage3.Controls.Add(this.label3);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Padding = new System.Windows.Forms.Padding(3);
this.tabPage3.Size = new System.Drawing.Size(842, 661);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Build";
//
// LogTextBoxRich
//
this.LogTextBoxRich.BackColor = System.Drawing.SystemColors.Window;
this.LogTextBoxRich.DetectUrls = false;
this.LogTextBoxRich.HideSelection = false;
this.LogTextBoxRich.Location = new System.Drawing.Point(162, 35);
this.LogTextBoxRich.Name = "LogTextBoxRich";
this.LogTextBoxRich.ReadOnly = true;
this.LogTextBoxRich.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical;
this.LogTextBoxRich.Size = new System.Drawing.Size(674, 620);
this.LogTextBoxRich.TabIndex = 16;
this.LogTextBoxRich.Text = "";
//
// LogCombo
//
this.LogCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.LogCombo.FormattingEnabled = true;
this.LogCombo.Items.AddRange(new object[] {
"<Build Log>"});
this.LogCombo.Location = new System.Drawing.Point(218, 8);
this.LogCombo.Name = "LogCombo";
this.LogCombo.Size = new System.Drawing.Size(409, 21);
this.LogCombo.TabIndex = 15;
this.LogCombo.DropDown += new System.EventHandler(this.LogCombo_DropDown);
this.LogCombo.SelectedIndexChanged += new System.EventHandler(this.LogCombo_SelectedIndexChanged);
this.LogCombo.DropDownClosed += new System.EventHandler(this.LogCombo_DropDownClosed);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(633, 12);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(97, 13);
this.label5.TabIndex = 14;
this.label5.Text = "Build configuration:";
//
// ConfigTextBox
//
this.ConfigTextBox.Location = new System.Drawing.Point(736, 9);
this.ConfigTextBox.Name = "ConfigTextBox";
this.ConfigTextBox.Size = new System.Drawing.Size(100, 20);
this.ConfigTextBox.TabIndex = 13;
//
// BuildList
//
this.BuildList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.ProjectColumn});
this.BuildList.ContextMenuStrip = this.BuildContextMenu;
listViewItem1.StateImageIndex = 0;
listViewItem2.Checked = true;
listViewItem2.StateImageIndex = 1;
listViewItem3.Checked = true;
listViewItem3.StateImageIndex = 2;
this.BuildList.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
listViewItem1,
listViewItem2,
listViewItem3});
this.BuildList.LargeImageList = this.ProjectStatusImages;
this.BuildList.Location = new System.Drawing.Point(6, 35);
this.BuildList.MultiSelect = false;
this.BuildList.Name = "BuildList";
this.BuildList.ShowGroups = false;
this.BuildList.Size = new System.Drawing.Size(150, 620);
this.BuildList.StateImageList = this.ProjectStatusImages;
this.BuildList.TabIndex = 12;
this.BuildList.UseCompatibleStateImageBehavior = false;
this.BuildList.View = System.Windows.Forms.View.Details;
this.BuildList.MouseClick += new System.Windows.Forms.MouseEventHandler(this.BuildList_MouseClick);
this.BuildList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.BuildList_MouseDoubleClick);
//
// ProjectColumn
//
this.ProjectColumn.Text = "Projects";
this.ProjectColumn.Width = 146;
//
// BuildContextMenu
//
this.BuildContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.showLogToolStripMenuItem,
this.rebuildToolStripMenuItem});
this.BuildContextMenu.Name = "BuildContextMenu";
this.BuildContextMenu.Size = new System.Drawing.Size(160, 48);
//
// showLogToolStripMenuItem
//
this.showLogToolStripMenuItem.Name = "showLogToolStripMenuItem";
this.showLogToolStripMenuItem.Size = new System.Drawing.Size(159, 22);
this.showLogToolStripMenuItem.Text = "Show log";
this.showLogToolStripMenuItem.Click += new System.EventHandler(this.showLogToolStripMenuItem_Click);
//
// rebuildToolStripMenuItem
//
this.rebuildToolStripMenuItem.Name = "rebuildToolStripMenuItem";
this.rebuildToolStripMenuItem.Size = new System.Drawing.Size(159, 22);
this.rebuildToolStripMenuItem.Text = "Mark for rebuild";
this.rebuildToolStripMenuItem.Click += new System.EventHandler(this.rebuildToolStripMenuItem_Click);
//
// ProjectStatusImages
//
this.ProjectStatusImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ProjectStatusImages.ImageStream")));
this.ProjectStatusImages.TransparentColor = System.Drawing.Color.Transparent;
this.ProjectStatusImages.Images.SetKeyName(0, "wait.png");
this.ProjectStatusImages.Images.SetKeyName(1, "process.png");
this.ProjectStatusImages.Images.SetKeyName(2, "success.png");
this.ProjectStatusImages.Images.SetKeyName(3, "failed.png");
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(162, 11);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(50, 13);
this.label4.TabIndex = 10;
this.label4.Text = "Build log:";
//
// BuildButton
//
this.BuildButton.Location = new System.Drawing.Point(72, 6);
this.BuildButton.Name = "BuildButton";
this.BuildButton.Size = new System.Drawing.Size(75, 23);
this.BuildButton.TabIndex = 9;
this.BuildButton.Text = "Start Build";
this.BuildButton.UseVisualStyleBackColor = true;
this.BuildButton.Click += new System.EventHandler(this.button3_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 11);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Build order:";
//
// ShowSingleCheckBox
//
this.ShowSingleCheckBox.AutoSize = true;
this.ShowSingleCheckBox.Location = new System.Drawing.Point(12, 38);
this.ShowSingleCheckBox.Name = "ShowSingleCheckBox";
this.ShowSingleCheckBox.Size = new System.Drawing.Size(115, 17);
this.ShowSingleCheckBox.TabIndex = 9;
this.ShowSingleCheckBox.Text = "Show single nodes";
this.ShowSingleCheckBox.UseVisualStyleBackColor = true;
//
// ShowChildrenCheckBox
//
this.ShowChildrenCheckBox.AutoSize = true;
this.ShowChildrenCheckBox.Location = new System.Drawing.Point(12, 61);
this.ShowChildrenCheckBox.Name = "ShowChildrenCheckBox";
this.ShowChildrenCheckBox.Size = new System.Drawing.Size(110, 17);
this.ShowChildrenCheckBox.TabIndex = 10;
this.ShowChildrenCheckBox.Text = "Show child nodes";
this.ShowChildrenCheckBox.UseVisualStyleBackColor = true;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1016, 741);
this.Controls.Add(this.ShowChildrenCheckBox);
this.Controls.Add(this.ShowSingleCheckBox);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.ProjectTabControl);
this.Controls.Add(this.SolutionTextBox);
this.Controls.Add(this.ParseButton);
this.Controls.Add(this.ProjectList);
this.Controls.Add(this.BrowseButton);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "MainForm";
this.Text = "Solution Dependency Analyzer";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load);
this.ProjectTabControl.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.tabPage3.PerformLayout();
this.BuildContextMenu.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox ProjectList;
private System.Windows.Forms.TextBox SolutionTextBox;
private System.Windows.Forms.Button BrowseButton;
private System.Windows.Forms.Button ParseButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TabControl ProjectTabControl;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.CheckBox ShowSingleCheckBox;
private System.Windows.Forms.CheckBox ShowChildrenCheckBox;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button BuildButton;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ImageList ProjectStatusImages;
private System.Windows.Forms.ListView BuildList;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.TextBox ConfigTextBox;
private System.Windows.Forms.ColumnHeader ProjectColumn;
private System.Windows.Forms.ContextMenuStrip BuildContextMenu;
private System.Windows.Forms.ToolStripMenuItem rebuildToolStripMenuItem;
private System.Windows.Forms.ComboBox LogCombo;
private System.Windows.Forms.ToolStripMenuItem showLogToolStripMenuItem;
private ProjectsDepGraph depGraph;
private ProjectsDepMatrix depMatrix;
private System.Windows.Forms.RichTextBox LogTextBoxRich;
}
}
| |
using MFUnit;
namespace Rinsen.WebServer.UnitTests
{
public class UriTests
{
public void WhenNewUri_WithSimpleAbsoluteUri_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://www.testuri.com");
// Assert
Assert.AreEqual("http", uri.UriScheme);
Assert.AreEqual("www.testuri.com", uri.Host);
Assert.AreEqual("/", uri.AbsolutePath);
Assert.AreEqual(80, uri.Port);
}
public void WhenNewUri_WithSimplePartsUri_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "www.testuri.com", "", 80);
// Assert
Assert.AreEqual("http", uri.UriScheme);
Assert.AreEqual("www.testuri.com", uri.Host);
Assert.AreEqual("/", uri.AbsolutePath);
Assert.AreEqual(80, uri.Port);
}
public void WhenNewUri_WithSimpleAbsoluteUriWithSlash_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://www.testuri.com/");
// Assert
Assert.AreEqual("http", uri.UriScheme);
Assert.AreEqual("www.testuri.com", uri.Host);
Assert.AreEqual("/", uri.AbsolutePath);
Assert.AreEqual(80, uri.Port);
}
public void WhenNewUri_WithSimplePartsUriWithSlash_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "www.testuri.com", "/", 80);
// Assert
Assert.AreEqual("http", uri.UriScheme);
Assert.AreEqual("www.testuri.com", uri.Host);
Assert.AreEqual("/", uri.AbsolutePath);
Assert.AreEqual(80, uri.Port);
}
public void WhenNewUri_WithAbsoluteUriAndSpecificPath_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://www.testuri.com/relative/path");
// Assert
Assert.AreEqual("/relative/path", uri.AbsolutePath);
}
public void WhenNewUri_WithPartsUriAndSpecificPath_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "www.testuri.com", "/relative/path", 80);
// Assert
Assert.AreEqual("/relative/path", uri.AbsolutePath);
}
public void WhenNewUri_WithAbsoluteUriAndQuery_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://www.testuri.com/?MyInput=15");
// Assert
Assert.AreEqual("/", uri.AbsolutePath);
Assert.AreEqual("MyInput=15", uri.QueryString);
}
public void WhenNewUri_WithPartsUriAndQuery_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "www.testuri.com", "/?MyInput=15", 80);
// Assert
Assert.AreEqual("/", uri.AbsolutePath);
Assert.AreEqual("MyInput=15", uri.QueryString);
}
public void WhenNewUri_WithAbsoluteUriAndSpecificPathWithQuery_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://www.testuri.com/test/test/test?MyInput=15");
// Assert
Assert.AreEqual("/test/test/test", uri.AbsolutePath);
Assert.AreEqual("MyInput=15", uri.QueryString);
}
public void WhenNewUri_WithPartsUriAndSpecificPathWithQuery_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "www.testuri.com", "/test/test/test?MyInput=15", 80);
// Assert
Assert.AreEqual("/test/test/test", uri.AbsolutePath);
Assert.AreEqual("MyInput=15", uri.QueryString);
}
public void WhenNewUri_WithAbsoluteUriAndSpecificPathWithQueryAndEndSlash_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://www.testuri.com/test/test/test/?MyInput=15");
// Assert
Assert.AreEqual("/test/test/test/", uri.AbsolutePath);
Assert.AreEqual("MyInput=15", uri.QueryString);
}
public void WhenNewUri_WithPartsUriAndSpecificPathWithQueryAndEndSlash_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "www.testuri.com", "/test/test/test/?MyInput=15", 80);
// Assert
Assert.AreEqual("/test/test/test/", uri.AbsolutePath);
Assert.AreEqual("MyInput=15", uri.QueryString);
}
public void WhenNewUri_WithSpecificPort_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://www.testuri.com:5000/");
// Assert
Assert.AreEqual(5000, uri.Port);
}
public void WhenNewUri_WithSpecificPortInParts_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "www.testuri.com", "", 5000);
// Assert
Assert.AreEqual(5000, uri.Port);
}
public void WhenNewUri_WithIpAddressAndDefaultPort_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://192.168.1.56/");
// Assert
Assert.AreEqual("192.168.1.56", uri.Host);
Assert.AreEqual(80, uri.Port);
}
public void WhenNewUri_WithIpAddressAndSpecificPort_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http://192.168.1.57:5000/");
// Assert
Assert.AreEqual("192.168.1.57", uri.Host);
Assert.AreEqual(5000, uri.Port);
}
public void WhenNewUri_WithIpAddressAndSpecificPortInParts_GetCorrespondingResultInUri()
{
// Act
var uri = new Uri("http", "192.168.1.57", "/", 5000);
// Assert
Assert.AreEqual("192.168.1.57", uri.Host);
Assert.AreEqual(5000, uri.Port);
}
public void WhenNewUri_WithFileInPartsRelativeUri_GetTrue()
{
// Act
var uri = new Uri("http", "192.168.1.57", "/First/Second.html", 5000);
// Assert
Assert.IsTrue(uri.IsFile);
}
public void WhenNewUri_WithNoFileInPath_GetFalse()
{
// Act
var uri = new Uri("http://192.168.1.57:5000/First/Second/Third");
// Assert
Assert.IsFalse(uri.IsFile);
}
public void WhenNewUri_WithNoFileInPartsRelativeUri_GetFalse()
{
// Act
var uri = new Uri("http", "192.168.1.57", "/First/Second/Third", 5000);
// Assert
Assert.IsFalse(uri.IsFile);
}
public void WhenToStringWithDefaultPort_GetStringRepresentationUfUriWithoutPort()
{
// Arrange
var uri = new Uri("http", "testuri.se", "/testPath?Value=10", 80);
// Act & Assert
Assert.AreEqual("http://testuri.se/testPath?Value=10", uri.AbsoluteUri);
}
public void WhenToString_GetStringRepresentationUfUriWithPort()
{
// Arrange
var uri = new Uri("http", "testuri.se", "/testPath?Value=10", 2500);
// Act & Assert
Assert.AreEqual("http://testuri.se:2500/testPath?Value=10", uri.AbsoluteUri);
}
public void WhenToStringWithNoQueryString_GetStringRepresentationUfUriWithNoQueryString()
{
// Arrange
var uri = new Uri("http", "testuri.se", "/testPath", 2500);
// Act
var stringUri = uri.ToString();
// Assert
Assert.AreEqual("http://testuri.se:2500/testPath", uri.AbsoluteUri);
}
public void WhenGetLocalPath_GetCorrectLocalPath()
{
// Arrange
var uri = new Uri("http", "testuri.se", "/folder1/folder2", 2500);
// Act & Assert
Assert.AreEqual("\\folder1\\folder2", uri.LocalPath);
}
public void WhenGetEmptyQueryString_GetEmptyStringAndNotNull()
{
// Arrange
var uri = new Uri("http", "testuri.se", "/", 2500);
// Act & Assert
Assert.AreEqual(string.Empty, uri.QueryString);
}
}
}
| |
// 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;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
internal static partial class Interop
{
private const String KERNEL32DLL = "kernel32.dll";
private const String LOCALIZATIONDLL = "api-ms-win-core-localization-l1-2-0.dll";
private const String HANDLEDLL = "api-ms-win-core-handle-l1-1-0.dll";
private const String PROCESSTHREADSDLL = "api-ms-win-core-processthreads-l1-1-0.dll";
private const String FILEDLL = "api-ms-win-core-file-l1-1-0.dll";
private const String NAMEDPIPEDLL = "api-ms-win-core-namedpipe-l1-1-0.dll";
private const String IODLL = "api-ms-win-core-io-l1-1-0.dll";
internal static readonly IntPtr NULL = IntPtr.Zero;
//
// Win32 IO
//
internal const int CREDUI_MAX_USERNAME_LENGTH = 513;
// WinError.h codes:
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
// Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_LOCK_VIOLATION = 0x21; // 33
internal const int ERROR_HANDLE_EOF = 0x26; // 38
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57; // 87
internal const int ERROR_BROKEN_PIPE = 0x6D; // 109
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long
internal const int ERROR_PIPE_BUSY = 0xE7; // 231
internal const int ERROR_NO_DATA = 0xE8; // 232
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259
internal const int ERROR_PIPE_CONNECTED = 0x217; // 535
internal const int ERROR_PIPE_LISTENING = 0x218; // 536
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_IO_PENDING = 0x3E5; // 997
internal const int ERROR_NOT_FOUND = 0x490; // 1168
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534
internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815
// Event log specific codes:
internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;
internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028;
internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029;
internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030;
internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031;
internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033;
internal const int ERROR_MUI_FILE_NOT_FOUND = 15100;
internal const int SECURITY_SQOS_PRESENT = 0x00100000;
internal const int SECURITY_ANONYMOUS = 0 << 16;
internal const int SECURITY_IDENTIFICATION = 1 << 16;
internal const int SECURITY_IMPERSONATION = 2 << 16;
internal const int SECURITY_DELEGATION = 3 << 16;
internal const int GENERIC_READ = unchecked((int)0x80000000);
internal const int GENERIC_WRITE = 0x40000000;
internal const int STD_INPUT_HANDLE = -10;
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
internal const int DUPLICATE_SAME_ACCESS = 0x00000002;
internal const int PIPE_ACCESS_INBOUND = 1;
internal const int PIPE_ACCESS_OUTBOUND = 2;
internal const int PIPE_ACCESS_DUPLEX = 3;
internal const int PIPE_TYPE_BYTE = 0;
internal const int PIPE_TYPE_MESSAGE = 4;
internal const int PIPE_READMODE_BYTE = 0;
internal const int PIPE_READMODE_MESSAGE = 2;
internal const int PIPE_UNLIMITED_INSTANCES = 255;
internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
internal const int FILE_SHARE_READ = 0x00000001;
internal const int FILE_SHARE_WRITE = 0x00000002;
internal const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
internal const int FILE_FLAG_OVERLAPPED = 0x40000000;
internal const int OPEN_EXISTING = 3;
// From WinBase.h
internal const int FILE_TYPE_DISK = 0x0001;
internal const int FILE_TYPE_CHAR = 0x0002;
internal const int FILE_TYPE_PIPE = 0x0003;
// Memory mapped file constants
internal const int MEM_COMMIT = 0x1000;
internal const int MEM_RESERVE = 0x2000;
internal const int INVALID_FILE_SIZE = -1;
internal const int PAGE_READWRITE = 0x04;
internal const int PAGE_READONLY = 0x02;
internal const int PAGE_WRITECOPY = 0x08;
internal const int PAGE_EXECUTE_READ = 0x20;
internal const int PAGE_EXECUTE_READWRITE = 0x40;
internal const int FILE_MAP_COPY = 0x0001;
internal const int FILE_MAP_WRITE = 0x0002;
internal const int FILE_MAP_READ = 0x0004;
internal const int FILE_MAP_EXECUTE = 0x0020;
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
internal static partial class mincore
{
//
// Pipe
//
[DllImport(HANDLEDLL, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[SecurityCritical]
internal static extern bool CloseHandle(IntPtr handle);
[DllImport(PROCESSTHREADSDLL, SetLastError = true)]
[SecurityCritical]
internal static extern IntPtr GetCurrentProcess();
[DllImport(HANDLEDLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
SafePipeHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafePipeHandle lpTargetHandle,
uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
[DllImport(FILEDLL)]
[SecurityCritical]
internal static extern int GetFileType(SafePipeHandle handle);
[DllImport(NAMEDPIPEDLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CreatePipe(out SafePipeHandle hReadPipe,
out SafePipeHandle hWritePipe, ref Interop.SECURITY_ATTRIBUTES pipeSecAttrs, int nSize);
[DllImport(FILEDLL, EntryPoint = "CreateFile", CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
[SecurityCritical]
internal static extern SafePipeHandle CreateNamedPipeClient(String lpFileName,
int dwDesiredAccess, System.IO.FileShare dwShareMode,
ref Interop.SECURITY_ATTRIBUTES secAttrs, System.IO.FileMode dwCreationDisposition,
int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport(NAMEDPIPEDLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
unsafe internal static extern bool ConnectNamedPipe(SafePipeHandle handle, NativeOverlapped* overlapped);
[DllImport(NAMEDPIPEDLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ConnectNamedPipe(SafePipeHandle handle, IntPtr overlapped);
[DllImport(NAMEDPIPEDLL, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false, EntryPoint = "WaitNamedPipeW")]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WaitNamedPipe(String name, int timeout);
[DllImport(KERNEL32DLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, out int lpState,
IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout,
IntPtr lpUserName, int nMaxUserNameSize);
[DllImport(KERNEL32DLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState,
out int lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout,
IntPtr lpUserName, int nMaxUserNameSize);
[DllImport(KERNEL32DLL, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false, EntryPoint = "GetNamedPipeHandleStateW")]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState,
IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout,
StringBuilder lpUserName, int nMaxUserNameSize);
[DllImport(KERNEL32DLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe,
out int lpFlags,
IntPtr lpOutBufferSize,
IntPtr lpInBufferSize,
IntPtr lpMaxInstances
);
[DllImport(KERNEL32DLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe,
IntPtr lpFlags,
out int lpOutBufferSize,
IntPtr lpInBufferSize,
IntPtr lpMaxInstances
);
[DllImport(KERNEL32DLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe,
IntPtr lpFlags,
IntPtr lpOutBufferSize,
out int lpInBufferSize,
IntPtr lpMaxInstances
);
[DllImport(NAMEDPIPEDLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static unsafe extern bool SetNamedPipeHandleState(
SafePipeHandle hNamedPipe,
int* lpMode,
IntPtr lpMaxCollectionCount,
IntPtr lpCollectDataTimeout
);
[DllImport(NAMEDPIPEDLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DisconnectNamedPipe(SafePipeHandle hNamedPipe);
[DllImport(FILEDLL, SetLastError = true)]
[SecurityCritical]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FlushFileBuffers(SafePipeHandle hNamedPipe);
[DllImport(NAMEDPIPEDLL, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false, EntryPoint = "CreateNamedPipeW")]
[SecurityCritical]
internal static extern SafePipeHandle CreateNamedPipe(string pipeName,
int openMode, int pipeMode, int maxInstances,
int outBufferSize, int inBufferSize, int defaultTimeout,
ref Interop.SECURITY_ATTRIBUTES securityAttributes);
// Note there are two different ReadFile prototypes - this is to use
// the type system to force you to not trip across a "feature" in
// Win32's async IO support. You can't do the following three things
// simultaneously: overlapped IO, free the memory for the overlapped
// struct in a callback (or an EndRead method called by that callback),
// and pass in an address for the numBytesRead parameter.
// <STRIP> See Windows Bug 105512 for details. -- </STRIP>
[DllImport(FILEDLL, SetLastError = true)]
[SecurityCritical]
unsafe internal static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead,
IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped);
[DllImport(FILEDLL, SetLastError = true)]
[SecurityCritical]
unsafe internal static extern int ReadFile(SafePipeHandle handle, byte* bytes, int numBytesToRead,
out int numBytesRead, IntPtr mustBeZero);
// Note there are two different WriteFile prototypes - this is to use
// the type system to force you to not trip across a "feature" in
// Win32's async IO support. You can't do the following three things
// simultaneously: overlapped IO, free the memory for the overlapped
// struct in a callback (or an EndWrite method called by that callback),
// and pass in an address for the numBytesRead parameter.
// <STRIP> See Windows Bug 105512 for details. -- </STRIP>
[DllImport(FILEDLL, SetLastError = true)]
[SecurityCritical]
internal static unsafe extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite,
IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
[DllImport(FILEDLL, SetLastError = true)]
[SecurityCritical]
internal static unsafe extern int WriteFile(SafePipeHandle handle, byte* bytes, int numBytesToWrite,
out int numBytesWritten, IntPtr mustBeZero);
[DllImport(IODLL, SetLastError = true)]
internal static unsafe extern bool CancelIoEx(SafeHandle handle, NativeOverlapped* lpOverlapped);
[DllImport(LOCALIZATIONDLL, EntryPoint = "FormatMessageW", SetLastError = true, CharSet = CharSet.Unicode)]
internal unsafe static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, char[] lpBuffer, uint nSize, IntPtr Arguments);
}
[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;
using antilunchbox;
[Serializable]
/// <summary>
/// Class that contains all the data needed to bind an AudioSourceAction to an event. AudioSubscriptions are bound at run-time to keep serialization intact.
/// </summary>
public class AudioSubscription {
/// <summary>
/// The owner.
/// </summary>
public AudioSourcePro owner;
/// <summary>
/// Whether this is a standard event binding.
/// </summary>
public bool isStandardEvent = true;
/// <summary>
/// The standard event to bind to. Only used if isStandardEvent is <c>true</c>.
/// </summary>
public AudioSourceStandardEvent standardEvent;
/// <summary>
/// The source component if it's a custom event binding.
/// </summary>
public Component sourceComponent;
/// <summary>
/// The name of the method if it's a custom event binding.
/// </summary>
public string methodName = "";
private bool isBound = false;
/// <summary>
/// The action to take when the event is triggered.
/// </summary>
public AudioSourceAction actionType = AudioSourceAction.None;
/// <summary>
/// If the action is to play a capped SFX, then this is the cap name.
/// </summary>
public string cappedName;
/// <summary>
/// Whether triggers will be filtered by layer.
/// </summary>
public bool filterLayers;
/// <summary>
/// Whether triggers will be filtered by tags.
/// </summary>
public bool filterTags;
/// <summary>
/// Whether triggers will be filtered by gameObject name.
/// </summary>
public bool filterNames;
/// <summary>
/// Editor variable -- IGNORE AND DO NOT MODIFY
/// </summary>
public int tagMask;
/// <summary>
/// Editor variable -- IGNORE AND DO NOT MODIFY
/// </summary>
public int nameMask;
/// <summary>
/// Editor variable -- IGNORE AND DO NOT MODIFY
/// </summary>
public string nameToAdd = "";
/// <summary>
/// Editor variable -- IGNORE AND DO NOT MODIFY
/// </summary>
public List<string> allNames = new List<string>();
/// <summary>
/// If filterLayers is <c>true</c>, only trigger for this layer mask.
/// </summary>
public int layerMask;
/// <summary>
/// If filterTags is <c>true</c>, only trigger for these tags.
/// </summary>
public List<string> tags = new List<string>() { "Default" };
/// <summary>
/// If filterNames is <c>true</c>, only trigger for these gameObject names.
/// </summary>
public List<string> names = new List<string>();
#if !(UNITY_WP8 || UNITY_METRO)
private Component targetComponent;
#endif
private FieldInfo eventField;
private Delegate eventDelegate;
private MethodInfo handlerProxy;
private ParameterInfo[] handlerParameters;
/// <summary>
/// Binds event and action on the specified AudioSourcePro.
/// </summary>
/// <param name='sourcePro'>
/// The AudioSourcePro.
/// </param>
public void Bind(AudioSourcePro sourcePro)
{
if(isBound || isStandardEvent || sourceComponent == null)
return;
#if !(UNITY_WP8 || UNITY_METRO)
owner = sourcePro;
if(!componentIsValid)
{
Debug.LogError(string.Format( "Invalid binding configuration - Source:{0}", sourceComponent));
return;
}
MethodInfo eventHandlerMethodInfo = getMethodInfoForAction(actionType);
targetComponent = owner;
eventField = getField(sourceComponent, methodName);
if(eventField == null)
{
Debug.LogError( "Event definition not found: " + sourceComponent.GetType().Name + "." + methodName );
return;
}
try
{
var eventMethod = eventField.FieldType.GetMethod("Invoke");
var eventParams = eventMethod.GetParameters();
eventDelegate = createProxyEventDelegate(targetComponent, eventField.FieldType, eventParams, eventHandlerMethodInfo);
}
catch(Exception err)
{
Debug.LogError("Event binding failed - Failed to create event handler: " + err.ToString());
return;
}
var combinedDelegate = Delegate.Combine( eventDelegate, (Delegate)eventField.GetValue( sourceComponent ) );
eventField.SetValue( sourceComponent, combinedDelegate );
#else
Debug.LogError("Windows Store and Windows Phone apps don't support automatic custom binding. You must do it yourself in code.");
#endif
isBound = true;
}
/// <summary>
/// Unbind this instance.
/// </summary>
public void Unbind()
{
if(!isBound)
return;
isBound = false;
#if !(UNITY_WP8 || UNITY_METRO)
var currentDelegate = (Delegate)eventField.GetValue(sourceComponent);
var newDelegate = Delegate.Remove(currentDelegate, eventDelegate);
eventField.SetValue(sourceComponent, newDelegate);
eventField = null;
eventDelegate = null;
handlerProxy = null;
targetComponent = null;
#endif
}
/// <summary>
/// Gets a value indicating whether this <see cref="AudioSubscription"/> component is valid.
/// </summary>
/// <value>
/// <c>true</c> if component is valid; otherwise, <c>false</c>.
/// </value>
public bool componentIsValid {
get {
if(standardEventIsValid)
return true;
var propertiesSet =
sourceComponent != null &&
!string.IsNullOrEmpty( methodName );
if(!propertiesSet)
return false;
#if !(UNITY_WP8 || UNITY_METRO)
var member = sourceComponent.GetType().GetMember(methodName).FirstOrDefault();
if(member == null)
return false;
return true;
#else
return false;
#endif
}
}
/// <summary>
/// Gets a value indicating whether this <see cref="AudioSubscription"/> standard event is valid.
/// </summary>
/// <value>
/// <c>true</c> if standard event is valid; otherwise, <c>false</c>.
/// </value>
public bool standardEventIsValid {
get {
if(isStandardEvent && Enum.IsDefined(typeof(AudioSourceStandardEvent), methodName))
return true;
return false;
}
}
#if !(UNITY_WP8 || UNITY_METRO)
private FieldInfo getField(Component sourceComponent, string fieldName)
{
return sourceComponent.GetType()
.GetAllFieldInfos()
.Where(f => f.Name == fieldName)
.FirstOrDefault();
}
#endif
private bool signatureIsCompatible(ParameterInfo[] lhs, ParameterInfo[] rhs)
{
if(lhs == null || rhs == null)
return false;
if(lhs.Length != rhs.Length)
return false;
for(int i = 0; i < lhs.Length; i++)
{
if(!areTypesCompatible(lhs[i], rhs[i]))
return false;
}
return true;
}
private bool areTypesCompatible(ParameterInfo lhs, ParameterInfo rhs)
{
if(lhs.ParameterType.Equals(rhs.ParameterType))
return true;
#if !(UNITY_WP8 || UNITY_METRO)
if(lhs.ParameterType.IsAssignableFrom(rhs.ParameterType))
return true;
#endif
return false;
}
#if !(UNITY_WP8 || UNITY_METRO)
[ProxyEvent]
private void CallbackProxy()
{
callProxyEventHandler();
}
private Delegate createProxyEventDelegate(object target, Type delegateType, ParameterInfo[] eventParams, MethodInfo eventHandler)
{
var proxyMethod = typeof(AudioSubscription)
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(m =>
m.IsDefined(typeof(ProxyEventAttribute), true ) &&
signatureIsCompatible(eventParams, m.GetParameters())
)
.FirstOrDefault();
if(proxyMethod == null)
return null;
handlerProxy = eventHandler;
handlerParameters = eventHandler.GetParameters();
var eventDelegate = Delegate.CreateDelegate( delegateType, this, proxyMethod, true );
return eventDelegate;
}
private void callProxyEventHandler(params object[] arguments)
{
if(handlerProxy == null)
return;
if(handlerParameters.Length == 0)
arguments = null;
var result = new object();
switch(actionType)
{
case AudioSourceAction.Play:
result = handlerProxy.Invoke(targetComponent, new object[] {});
break;
case AudioSourceAction.PlayCapped:
result = handlerProxy.Invoke(targetComponent, new object[] {cappedName});
break;
case AudioSourceAction.PlayLoop:
result = handlerProxy.Invoke(targetComponent, new object[] {});
break;
case AudioSourceAction.Stop:
result = handlerProxy.Invoke(targetComponent, new object[] {});
break;
case AudioSourceAction.None:
default:
break;
}
if(result is IEnumerator)
{
if(targetComponent is MonoBehaviour)
{
((MonoBehaviour)targetComponent).StartCoroutine((IEnumerator)result);
}
}
}
private MethodInfo getMethodInfoForAction(AudioSourceAction act)
{
MethodInfo methodinfo = null;
switch(act)
{
case AudioSourceAction.Play:
methodinfo = typeof(AudioSourcePro).GetMethod( "PlayHandler",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
Type.DefaultBinder,
new Type[] {},
null) as MethodInfo;
break;
case AudioSourceAction.PlayCapped:
methodinfo = typeof(AudioSourcePro).GetMethod( "PlayCappedHandler",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
Type.DefaultBinder,
new[] {typeof(string)},
null) as MethodInfo;
break;
case AudioSourceAction.PlayLoop:
methodinfo = typeof(AudioSourcePro).GetMethod( "PlayLoopHandler",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
Type.DefaultBinder,
new Type[] {},
null) as MethodInfo;
break;
case AudioSourceAction.Stop:
methodinfo = typeof(AudioSourcePro).GetMethod( "StopHandler",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
Type.DefaultBinder,
new Type[] {},
null) as MethodInfo;
break;
case AudioSourceAction.None:
default:
break;
}
return methodinfo;
}
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Security.Cryptography;
namespace Internal.Cryptography
{
//
// A cross-platform ICryptoTransform implementation for decryption.
//
// - Implements the various padding algorithms (as we support padding algorithms that the underlying native apis don't.)
//
// - Parameterized by a BasicSymmetricCipher which encapsulates the algorithm, key, IV, chaining mode, direction of encryption
// and the underlying native apis implementing the encryption.
//
internal sealed class UniversalCryptoDecryptor : UniversalCryptoTransform
{
public UniversalCryptoDecryptor(PaddingMode paddingMode, BasicSymmetricCipher basicSymmetricCipher)
: base(paddingMode, basicSymmetricCipher)
{
}
protected sealed override int UncheckedTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
//
// If we're decrypting, it's possible to be called with the last blocks of the data, and then
// have TransformFinalBlock called with an empty array. Since we don't know if this is the case,
// we won't decrypt the last block of the input until either TransformBlock or
// TransformFinalBlock is next called.
//
// We don't need to do this for PaddingMode.None because there is no padding to strip, and
// we also don't do this for PaddingMode.Zeros since there is no way for us to tell if the
// zeros at the end of a block are part of the plaintext or the padding.
//
int decryptedBytes = 0;
if (DepaddingRequired)
{
// If we have data saved from a previous call, decrypt that into the output first
if (_heldoverCipher != null)
{
int depadDecryptLength = BasicSymmetricCipher.Transform(_heldoverCipher, 0, _heldoverCipher.Length, outputBuffer, outputOffset);
outputOffset += depadDecryptLength;
decryptedBytes += depadDecryptLength;
}
else
{
_heldoverCipher = new byte[InputBlockSize];
}
// Postpone the last block to the next round.
Debug.Assert(inputCount >= _heldoverCipher.Length, "inputCount >= _heldoverCipher.Length");
int startOfLastBlock = inputOffset + inputCount - _heldoverCipher.Length;
Buffer.BlockCopy(inputBuffer, startOfLastBlock, _heldoverCipher, 0, _heldoverCipher.Length);
inputCount -= _heldoverCipher.Length;
Debug.Assert(inputCount % InputBlockSize == 0, "Did not remove whole blocks for depadding");
}
if (inputCount > 0)
{
decryptedBytes += BasicSymmetricCipher.Transform(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset);
}
return decryptedBytes;
}
protected sealed override byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
// We can't complete decryption on a partial block
if (inputCount % InputBlockSize != 0)
throw new CryptographicException(SR.Cryptography_PartialBlock);
//
// If we have postponed cipher bits from the prior round, copy that into the decryption buffer followed by the input data.
// Otherwise the decryption buffer is just the input data.
//
byte[] ciphertext = null;
if (_heldoverCipher == null)
{
ciphertext = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, 0, inputCount);
}
else
{
ciphertext = new byte[_heldoverCipher.Length + inputCount];
Buffer.BlockCopy(_heldoverCipher, 0, ciphertext, 0, _heldoverCipher.Length);
Buffer.BlockCopy(inputBuffer, inputOffset, ciphertext, _heldoverCipher.Length, inputCount);
}
// Decrypt the data, then strip the padding to get the final decrypted data. Note that even if the cipherText length is 0, we must
// invoke TransformFinal() so that the cipher object knows to reset for the next cipher operation.
byte[] decryptedBytes = BasicSymmetricCipher.TransformFinal(ciphertext, 0, ciphertext.Length);
byte[] outputData;
if (ciphertext.Length > 0)
{
unsafe
{
fixed (byte* decryptedBytesPtr = decryptedBytes)
{
outputData = DepadBlock(decryptedBytes, 0, decryptedBytes.Length);
if (outputData != decryptedBytes)
{
CryptographicOperations.ZeroMemory(decryptedBytes);
}
}
}
}
else
{
outputData = Array.Empty<byte>();
}
Reset();
return outputData;
}
protected sealed override void Dispose(bool disposing)
{
if (disposing)
{
byte[] heldoverCipher = _heldoverCipher;
_heldoverCipher = null;
if (heldoverCipher != null)
{
Array.Clear(heldoverCipher, 0, heldoverCipher.Length);
}
}
base.Dispose(disposing);
}
private void Reset()
{
if (_heldoverCipher != null)
{
Array.Clear(_heldoverCipher, 0, _heldoverCipher.Length);
_heldoverCipher = null;
}
}
private bool DepaddingRequired
{
get
{
// Some padding modes encode sufficient information to allow for automatic depadding to happen.
switch (PaddingMode)
{
case PaddingMode.PKCS7:
case PaddingMode.ANSIX923:
case PaddingMode.ISO10126:
return true;
case PaddingMode.Zeros:
case PaddingMode.None:
return false;
default:
Debug.Fail($"Unknown padding mode {PaddingMode}.");
throw new CryptographicException(SR.Cryptography_UnknownPaddingMode);
}
}
}
/// <summary>
/// Remove the padding from the last blocks being decrypted
/// </summary>
private byte[] DepadBlock(byte[] block, int offset, int count)
{
Debug.Assert(block != null && count >= block.Length - offset);
Debug.Assert(0 <= offset);
Debug.Assert(0 <= count);
int padBytes = 0;
// See PadBlock for a description of the padding modes.
switch (PaddingMode)
{
case PaddingMode.ANSIX923:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize)
{
throw new CryptographicException(SR.Cryptography_InvalidPadding);
}
// Verify that all the padding bytes are 0s
for (int i = offset + count - padBytes; i < offset + count - 1; i++)
{
if (block[i] != 0)
{
throw new CryptographicException(SR.Cryptography_InvalidPadding);
}
}
break;
case PaddingMode.ISO10126:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize)
{
throw new CryptographicException(SR.Cryptography_InvalidPadding);
}
// Since the padding consists of random bytes, we cannot verify the actual pad bytes themselves
break;
case PaddingMode.PKCS7:
padBytes = block[offset + count - 1];
// Verify the amount of padding is reasonable
if (padBytes <= 0 || padBytes > InputBlockSize)
throw new CryptographicException(SR.Cryptography_InvalidPadding);
// Verify all the padding bytes match the amount of padding
for (int i = offset + count - padBytes; i < offset + count; i++)
{
if (block[i] != padBytes)
throw new CryptographicException(SR.Cryptography_InvalidPadding);
}
break;
// We cannot remove Zeros padding because we don't know if the zeros at the end of the block
// belong to the padding or the plaintext itself.
case PaddingMode.Zeros:
case PaddingMode.None:
padBytes = 0;
break;
default:
throw new CryptographicException(SR.Cryptography_UnknownPaddingMode);
}
// Copy everything but the padding to the output
byte[] depadded = new byte[count - padBytes];
Buffer.BlockCopy(block, offset, depadded, 0, depadded.Length);
return depadded;
}
//
// For padding modes that support automatic depadding, TransformBlock() leaves the last block it is given undone since it has no way of knowing
// whether this is the final block that needs depadding. This block is held (in encrypted form) in _heldoverCipher. The next call to TransformBlock
// or TransformFinalBlock must include the decryption of _heldoverCipher in the results.
//
private byte[] _heldoverCipher;
}
}
| |
using System;
using NUnit.Framework;
using Braintree;
namespace Braintree.Tests
{
[TestFixture]
public class TransparentRedirectTest
{
private BraintreeGateway gateway;
private BraintreeService service;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
service = new BraintreeService(gateway.Configuration);
}
[Test]
[Category("Unit")]
public void Url_ReturnsCorrectUrl()
{
var host = System.Environment.GetEnvironmentVariable("GATEWAY_HOST") ?? "localhost";
var port = System.Environment.GetEnvironmentVariable("GATEWAY_PORT") ?? "3000";
var url = "http://" + host + ":" + port + "/merchants/integration_merchant_id/transparent_redirect_requests";
Assert.AreEqual(url, gateway.TransparentRedirect.Url);
}
[Test]
[Category("Unit")]
public void BuildTrData_BuildsAQueryStringWithApiVersion()
{
string tr_data = gateway.TransparentRedirect.BuildTrData(new TransactionRequest(), "example.com");
TestHelper.AssertIncludes("api_version=4", tr_data);
}
[Test]
[Category("Integration")]
public void CreateTransactionFromTransparentRedirect()
{
TransactionRequest trParams = new TransactionRequest
{
Type = TransactionType.SALE
};
TransactionRequest request = new TransactionRequest
{
Amount = SandboxValues.TransactionAmount.AUTHORIZE,
CreditCard = new TransactionCreditCardRequest
{
Number = SandboxValues.CreditCardNumber.VISA,
ExpirationDate = "05/2009",
}
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<Transaction> result = gateway.TransparentRedirect.ConfirmTransaction(queryString);
Assert.IsTrue(result.IsSuccess());
Transaction transaction = result.Target;
Assert.AreEqual(1000.00, transaction.Amount);
Assert.AreEqual(TransactionType.SALE, transaction.Type);
Assert.AreEqual(TransactionStatus.AUTHORIZED, transaction.Status);
Assert.AreEqual(DateTime.Now.Year, transaction.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, transaction.UpdatedAt.Value.Year);
CreditCard creditCard = transaction.CreditCard;
Assert.AreEqual("411111", creditCard.Bin);
Assert.AreEqual("1111", creditCard.LastFour);
Assert.AreEqual("05", creditCard.ExpirationMonth);
Assert.AreEqual("2009", creditCard.ExpirationYear);
Assert.AreEqual("05/2009", creditCard.ExpirationDate);
}
[Test]
[Category("Integration")]
public void CreateCustomerFromTransparentRedirect()
{
CustomerRequest trParams = new CustomerRequest
{
FirstName = "John"
};
CustomerRequest request = new CustomerRequest
{
LastName = "Doe"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<Customer> result = gateway.TransparentRedirect.ConfirmCustomer(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
}
[Test]
[Category("Integration")]
public void UpdateCustomerFromTransparentRedirect()
{
var createRequest = new CustomerRequest
{
FirstName = "Miranda",
LastName = "Higgenbottom"
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
CustomerRequest trParams = new CustomerRequest
{
CustomerId = createdCustomer.Id,
FirstName = "Penelope"
};
CustomerRequest request = new CustomerRequest
{
LastName = "Lambert"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<Customer> result = gateway.TransparentRedirect.ConfirmCustomer(queryString);
Assert.IsTrue(result.IsSuccess());
Customer updatedCustomer = gateway.Customer.Find(createdCustomer.Id);
Assert.AreEqual("Penelope", updatedCustomer.FirstName);
Assert.AreEqual("Lambert", updatedCustomer.LastName);
}
[Test]
[Category("Integration")]
public void CreateCreditCardFromTransparentRedirect()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
CreditCardRequest trParams = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "4111111111111111",
ExpirationDate = "10/10"
};
CreditCardRequest request = new CreditCardRequest
{
CardholderName = "John Doe"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<CreditCard> result = gateway.TransparentRedirect.ConfirmCreditCard(queryString);
Assert.IsTrue(result.IsSuccess());
CreditCard creditCard = result.Target;
Assert.AreEqual("John Doe", creditCard.CardholderName);
Assert.AreEqual("411111", creditCard.Bin);
Assert.AreEqual("1111", creditCard.LastFour);
Assert.AreEqual("10/2010", creditCard.ExpirationDate);
}
[Test]
[Category("Integration")]
public void UpdateCreditCardFromTransparentRedirect()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardRequest = new CreditCardRequest
{
CustomerId = customer.Id,
Number = "5105105105105100",
ExpirationDate = "05/12",
CardholderName = "Beverly D'angelo"
};
CreditCard createdCreditCard = gateway.CreditCard.Create(creditCardRequest).Target;
CreditCardRequest trParams = new CreditCardRequest
{
PaymentMethodToken = createdCreditCard.Token,
Number = "4111111111111111",
ExpirationDate = "10/10"
};
CreditCardRequest request = new CreditCardRequest
{
CardholderName = "Sampsonite"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.TransparentRedirect.Url, service);
Result<CreditCard> result = gateway.TransparentRedirect.ConfirmCreditCard(queryString);
Assert.IsTrue(result.IsSuccess());
CreditCard creditCard = gateway.CreditCard.Find(createdCreditCard.Token);
Assert.AreEqual("Sampsonite", creditCard.CardholderName);
Assert.AreEqual("411111", creditCard.Bin);
Assert.AreEqual("1111", creditCard.LastFour);
Assert.AreEqual("10/2010", creditCard.ExpirationDate);
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public sealed class ClothScene : IDemoScene
{
Demo demo;
PhysicsScene scene;
string name;
string instanceIndexName;
string info;
public PhysicsScene PhysicsScene { get { return scene; } }
public string SceneName { get { return name; } }
public string SceneInfo { get { return info; } }
// Declare objects in the scene
Sky skyInstance1;
Quad quadInstance1;
Cursor cursorInstance;
Shot shotInstance;
Column columnInstance1;
CargoJack cargoJackInstance1;
PointCloth pointClothInstance1;
Camera2 camera2Instance1;
Lights lightInstance;
// Declare controllers in the scene
SkyDraw1 skyDraw1Instance1;
CursorDraw1 cursorDraw1Instance;
CargoJackAnimation1 cargoJackAnimation1Instance1;
Camera2Animation1 camera2Animation1Instance1;
Camera2Draw1 camera2Draw1Instance1;
public ClothScene(Demo demo, string name, int instanceIndex, string info)
{
this.demo = demo;
this.name = name;
this.instanceIndexName = " " + instanceIndex.ToString();
this.info = info;
// Create a new objects in the scene
skyInstance1 = new Sky(demo, 1);
quadInstance1 = new Quad(demo, 1);
cursorInstance = new Cursor(demo);
shotInstance = new Shot(demo);
columnInstance1 = new Column(demo, 1);
cargoJackInstance1 = new CargoJack(demo, 1);
pointClothInstance1 = new PointCloth(demo, 1);
camera2Instance1 = new Camera2(demo, 1);
lightInstance = new Lights(demo);
// Create a new controllers in the scene
skyDraw1Instance1 = new SkyDraw1(demo, 1);
cursorDraw1Instance = new CursorDraw1(demo);
cargoJackAnimation1Instance1 = new CargoJackAnimation1(demo, 1);
camera2Animation1Instance1 = new Camera2Animation1(demo, 1);
camera2Draw1Instance1 = new Camera2Draw1(demo, 1);
}
public void Create()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null) return;
scene = demo.Engine.Factory.PhysicsSceneManager.Create(sceneInstanceIndexName);
// Initialize maximum number of solver iterations for the scene
scene.MaxIterationCount = 10;
// Initialize time of simulation for the scene
scene.TimeOfSimulation = 1.0f / 15.0f;
Initialize();
// Initialize objects in the scene
skyInstance1.Initialize(scene);
quadInstance1.Initialize(scene);
cursorInstance.Initialize(scene);
shotInstance.Initialize(scene);
columnInstance1.Initialize(scene);
cargoJackInstance1.Initialize(scene);
pointClothInstance1.Initialize(scene);
camera2Instance1.Initialize(scene);
lightInstance.Initialize(scene);
// Initialize controllers in the scene
skyDraw1Instance1.Initialize(scene);
cursorDraw1Instance.Initialize(scene);
cargoJackAnimation1Instance1.Initialize(scene);
camera2Animation1Instance1.Initialize(scene);
camera2Draw1Instance1.Initialize(scene);
// Create shapes shared for all physics objects in the scene
// These shapes are used by all objects in the scene
Demo.CreateSharedShapes(demo, scene);
// Create shapes for objects in the scene
Sky.CreateShapes(demo, scene);
Quad.CreateShapes(demo, scene);
Cursor.CreateShapes(demo, scene);
Shot.CreateShapes(demo, scene);
Column.CreateShapes(demo, scene);
CargoJack.CreateShapes(demo, scene);
PointCloth.CreateShapes(demo, scene);
Camera2.CreateShapes(demo, scene);
Lights.CreateShapes(demo, scene);
// Create physics objects for objects in the scene
skyInstance1.Create(new Vector3(0.0f, 0.0f, 0.0f));
quadInstance1.Create(new Vector3(0.0f, -40.0f, 20.0f), new Vector3(1000.0f, 31.0f, 1000.0f), Quaternion.Identity);
cursorInstance.Create();
shotInstance.Create();
columnInstance1.Create(new Vector3(12.0f, -9.0f, 0.0f), Vector3.One, Quaternion.Identity, "Box", 4, new Vector3(4.0f, 4.0f, 4.0f), 0.001f, true, 1.0f, 1.0f);
cargoJackInstance1.Create(new Vector3(-14.0f, -9.0f, 0.0f), Vector3.One, Quaternion.Identity);
pointClothInstance1.Create(new Vector3(0.0f, -1.0f, 0.0f), Vector3.One, Quaternion.Identity, 16, 16, 1.0f, 1.0f, true, 1.0f, 0.1f);
pointClothInstance1.Join(1, "Cargo Jack Arm Handle Bottom", "Cargo Jack Arm Handle Bottom", "Cargo Jack Arm Handle Top", "Cargo Jack Arm Handle Top");
camera2Instance1.Create(new Vector3(0.0f, 5.0f, -22.0f), Quaternion.Identity, Quaternion.Identity, Quaternion.Identity, true);
lightInstance.CreateLightPoint(0, "Glass", new Vector3(-20.0f, -3.0f, 40.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(1, "Glass", new Vector3(0.0f, -3.0f, 40.0f), new Vector3(0.5f, 0.7f, 0.1f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(2, "Glass", new Vector3(20.0f, -3.0f, 40.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(3, "Glass", new Vector3(-40.0f, -3.0f, 0.0f), new Vector3(1.0f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(4, "Glass", new Vector3(0.0f, -3.0f, 0.0f), new Vector3(1.0f, 1.0f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(5, "Glass", new Vector3(30.0f, -3.0f, 0.0f), new Vector3(0.3f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(0, "Glass", new Vector3(-30.0f, -3.0f, 15.0f), new Vector3(0.1f, 0.7f, 1.0f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(1, "Glass", new Vector3(0.0f, -3.0f, 15.0f), new Vector3(1.0f, 0.5f, 0.2f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(2, "Glass", new Vector3(45.0f, -3.0f, 15.0f), new Vector3(0.5f, 1.0f, 0.2f), 20.0f, 1.0f);
// Set controllers for objects in the scene
SetControllers();
}
public void Initialize()
{
scene.UserControllers.PostDrawMethods += demo.DrawInfo;
if (scene.Light == null)
{
scene.CreateLight(true);
scene.Light.Type = PhysicsLightType.Directional;
scene.Light.SetDirection(-0.4f, -0.8f, 0.4f, 0.0f);
}
}
public void SetControllers()
{
skyDraw1Instance1.SetControllers();
cursorDraw1Instance.SetControllers();
cargoJackAnimation1Instance1.SetControllers();
camera2Animation1Instance1.SetControllers(true);
camera2Draw1Instance1.SetControllers(false, false, false, false, false, false);
}
public void Refresh(double time)
{
camera2Animation1Instance1.RefreshControllers();
camera2Draw1Instance1.RefreshControllers();
GL.Clear(ClearBufferMask.DepthBufferBit);
scene.Simulate(time);
scene.Draw(time);
if (demo.EnableMenu)
{
GL.Clear(ClearBufferMask.DepthBufferBit);
demo.MenuScene.PhysicsScene.Draw(time);
}
demo.SwapBuffers();
}
public void Remove()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null)
demo.Engine.Factory.PhysicsSceneManager.Remove(sceneInstanceIndexName);
}
public void CreateResources()
{
}
public void DisposeResources()
{
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Summary description for StyleCtl.
/// </summary>
internal class ReportXmlCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty
{
private DesignXmlDraw _Draw;
private System.Windows.Forms.Label label1;
private Oranikle.Studio.Controls.CustomTextControl tbDataTransform;
private Oranikle.Studio.Controls.CustomTextControl tbDataSchema;
private System.Windows.Forms.Label label2;
private Oranikle.Studio.Controls.CustomTextControl tbDataElementName;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private Oranikle.Studio.Controls.StyledComboBox cbElementStyle;
private Oranikle.Studio.Controls.StyledButton bOpenXsl;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal ReportXmlCtl(DesignXmlDraw dxDraw)
{
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues();
}
private void InitValues()
{
XmlNode rNode = _Draw.GetReportNode();
tbDataTransform.Text = _Draw.GetElementValue(rNode, "DataTransform", "");
tbDataSchema.Text = _Draw.GetElementValue(rNode, "DataSchema", "");
tbDataElementName.Text = _Draw.GetElementValue(rNode, "DataElementName", "Report");
cbElementStyle.Text = _Draw.GetElementValue(rNode, "DataElementStyle", "AttributeNormal");
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.tbDataTransform = new Oranikle.Studio.Controls.CustomTextControl();
this.tbDataSchema = new Oranikle.Studio.Controls.CustomTextControl();
this.label2 = new System.Windows.Forms.Label();
this.tbDataElementName = new Oranikle.Studio.Controls.CustomTextControl();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.cbElementStyle = new Oranikle.Studio.Controls.StyledComboBox();
this.bOpenXsl = new Oranikle.Studio.Controls.StyledButton();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 31);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(112, 23);
this.label1.TabIndex = 0;
this.label1.Text = "XSL Data Transform";
//
// tbDataTransform
//
this.tbDataTransform.AddX = 0;
this.tbDataTransform.AddY = 0;
this.tbDataTransform.AllowSpace = false;
this.tbDataTransform.BorderColor = System.Drawing.Color.LightGray;
this.tbDataTransform.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbDataTransform.ChangeVisibility = false;
this.tbDataTransform.ChildControl = null;
this.tbDataTransform.ConvertEnterToTab = true;
this.tbDataTransform.ConvertEnterToTabForDialogs = false;
this.tbDataTransform.Decimals = 0;
this.tbDataTransform.DisplayList = new object[0];
this.tbDataTransform.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbDataTransform.Location = new System.Drawing.Point(136, 32);
this.tbDataTransform.Name = "tbDataTransform";
this.tbDataTransform.OnDropDownCloseFocus = true;
this.tbDataTransform.SelectType = 0;
this.tbDataTransform.Size = new System.Drawing.Size(248, 20);
this.tbDataTransform.TabIndex = 1;
this.tbDataTransform.Text = "textBox1";
this.tbDataTransform.UseValueForChildsVisibilty = false;
this.tbDataTransform.Value = true;
//
// tbDataSchema
//
this.tbDataSchema.AddX = 0;
this.tbDataSchema.AddY = 0;
this.tbDataSchema.AllowSpace = false;
this.tbDataSchema.BorderColor = System.Drawing.Color.LightGray;
this.tbDataSchema.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbDataSchema.ChangeVisibility = false;
this.tbDataSchema.ChildControl = null;
this.tbDataSchema.ConvertEnterToTab = true;
this.tbDataSchema.ConvertEnterToTabForDialogs = false;
this.tbDataSchema.Decimals = 0;
this.tbDataSchema.DisplayList = new object[0];
this.tbDataSchema.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbDataSchema.Location = new System.Drawing.Point(136, 72);
this.tbDataSchema.Name = "tbDataSchema";
this.tbDataSchema.OnDropDownCloseFocus = true;
this.tbDataSchema.SelectType = 0;
this.tbDataSchema.Size = new System.Drawing.Size(248, 20);
this.tbDataSchema.TabIndex = 3;
this.tbDataSchema.Text = "textBox1";
this.tbDataSchema.UseValueForChildsVisibilty = false;
this.tbDataSchema.Value = true;
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 71);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 23);
this.label2.TabIndex = 2;
this.label2.Text = "Data Schema";
//
// tbDataElementName
//
this.tbDataElementName.AddX = 0;
this.tbDataElementName.AddY = 0;
this.tbDataElementName.AllowSpace = false;
this.tbDataElementName.BorderColor = System.Drawing.Color.LightGray;
this.tbDataElementName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbDataElementName.ChangeVisibility = false;
this.tbDataElementName.ChildControl = null;
this.tbDataElementName.ConvertEnterToTab = true;
this.tbDataElementName.ConvertEnterToTabForDialogs = false;
this.tbDataElementName.Decimals = 0;
this.tbDataElementName.DisplayList = new object[0];
this.tbDataElementName.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbDataElementName.Location = new System.Drawing.Point(136, 112);
this.tbDataElementName.Name = "tbDataElementName";
this.tbDataElementName.OnDropDownCloseFocus = true;
this.tbDataElementName.SelectType = 0;
this.tbDataElementName.Size = new System.Drawing.Size(248, 20);
this.tbDataElementName.TabIndex = 5;
this.tbDataElementName.Text = "textBox1";
this.tbDataElementName.UseValueForChildsVisibilty = false;
this.tbDataElementName.Value = true;
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 111);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(104, 23);
this.label3.TabIndex = 4;
this.label3.Text = "Top Element Name";
//
// label4
//
this.label4.Location = new System.Drawing.Point(16, 151);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(88, 23);
this.label4.TabIndex = 6;
this.label4.Text = "Element Style";
//
// cbElementStyle
//
this.cbElementStyle.AutoAdjustItemHeight = false;
this.cbElementStyle.BorderColor = System.Drawing.Color.LightGray;
this.cbElementStyle.ConvertEnterToTabForDialogs = false;
this.cbElementStyle.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbElementStyle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbElementStyle.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbElementStyle.Items.AddRange(new object[] {
"AttributeNormal",
"ElementNormal"});
this.cbElementStyle.Location = new System.Drawing.Point(136, 152);
this.cbElementStyle.Name = "cbElementStyle";
this.cbElementStyle.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbElementStyle.SeparatorMargin = 1;
this.cbElementStyle.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbElementStyle.SeparatorWidth = 1;
this.cbElementStyle.Size = new System.Drawing.Size(144, 21);
this.cbElementStyle.TabIndex = 7;
//
// bOpenXsl
//
this.bOpenXsl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bOpenXsl.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bOpenXsl.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bOpenXsl.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bOpenXsl.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bOpenXsl.Font = new System.Drawing.Font("Arial", 9F);
this.bOpenXsl.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bOpenXsl.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bOpenXsl.Location = new System.Drawing.Point(400, 32);
this.bOpenXsl.Name = "bOpenXsl";
this.bOpenXsl.OverriddenSize = null;
this.bOpenXsl.Size = new System.Drawing.Size(24, 21);
this.bOpenXsl.TabIndex = 8;
this.bOpenXsl.Text = "...";
this.bOpenXsl.UseVisualStyleBackColor = true;
this.bOpenXsl.Click += new System.EventHandler(this.bOpenXsl_Click);
//
// ReportXmlCtl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.bOpenXsl);
this.Controls.Add(this.cbElementStyle);
this.Controls.Add(this.label4);
this.Controls.Add(this.tbDataElementName);
this.Controls.Add(this.label3);
this.Controls.Add(this.tbDataSchema);
this.Controls.Add(this.label2);
this.Controls.Add(this.tbDataTransform);
this.Controls.Add(this.label1);
this.Name = "ReportXmlCtl";
this.Size = new System.Drawing.Size(472, 288);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
return true;
}
public void Apply()
{
XmlNode rNode = _Draw.GetReportNode();
if (tbDataTransform.Text.Length > 0)
_Draw.SetElement(rNode, "DataTransform", tbDataTransform.Text);
else
_Draw.RemoveElement(rNode, "DataTransform");
if (tbDataSchema.Text.Length > 0)
_Draw.SetElement(rNode, "DataSchema", tbDataSchema.Text);
else
_Draw.RemoveElement(rNode, "DataSchema");
if (tbDataElementName.Text.Length > 0)
_Draw.SetElement(rNode, "DataElementName", tbDataElementName.Text);
else
_Draw.RemoveElement(rNode, "DataElementName");
_Draw.SetElement(rNode, "DataElementStyle", cbElementStyle.Text);
}
private void bOpenXsl_Click(object sender, System.EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "XSL files (*.xsl)|*.xsl" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 1;
ofd.FileName = "*.xsl";
ofd.Title = "Specify DataTransform File Name";
// ofd.DefaultExt = "xsl";
// ofd.AddExtension = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
string file = Path.GetFileName(ofd.FileName);
tbDataTransform.Text = file;
}
}
}
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Generator.Enums;
using Generator.Enums.Encoder;
namespace Generator.Tables {
sealed class OpCodeOperandKindDefsReader {
readonly string filename;
readonly Dictionary<string, EnumValue> toRegister;
readonly Dictionary<string, EnumValue> toOpCodeOperandKind;
public OpCodeOperandKindDefsReader(GenTypes genTypes, string filename) {
this.filename = filename;
toRegister = CreateEnumDict(genTypes[TypeIds.Register], true);
toOpCodeOperandKind = CreateEnumDict(genTypes[TypeIds.OpCodeOperandKind]);
}
static Dictionary<string, EnumValue> CreateEnumDict(EnumType enumType, bool ignoreCase = false) =>
enumType.Values.ToDictionary(a => a.RawName, a => a, ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
public OpCodeOperandKindDef[] Read() {
var defs = new List<OpCodeOperandKindDef>();
var argCounts = new Dictionary<string, int>(StringComparer.Ordinal) {
{ "br-near", 2 },
{ "br-near-x", 1 },
{ "br-disp", 1 },
{ "br-far", 1 },
{ "imm8-const", 1 },
{ "imm", 2 },
{ "imp-reg", 1 },
{ "isx", 2 },
{ "opcode", 1 },
{ "reg", 1 },
{ "rm-reg", 1 },
{ "vvvv", 1 },
{ "rm", 1 },
{ "vsib", 2 },
};
var lines = File.ReadAllLines(filename);
for (int i = 0; i < lines.Length; i++) {
var line = lines[i];
if (line.Length == 0 || line[0] == '#')
continue;
var parts = line.Split(',').Select(a => a.Trim()).ToArray();
if (parts.Length != 3)
throw new InvalidOperationException($"Line {i + 1}: Expected 2 commas");
if (!toOpCodeOperandKind.TryGetValue(parts[0], out var enumValue))
throw new InvalidOperationException($"Line {i + 1}: Invalid enum name or duplicate def: {parts[0]}");
toOpCodeOperandKind.Remove(parts[0]);
var flags = OpCodeOperandKindDefFlags.None;
foreach (var flagStr in parts[2].Split(' ', StringSplitOptions.RemoveEmptyEntries)) {
flags |= flagStr switch {
"lock-bit" => OpCodeOperandKindDefFlags.LockBit,
"p1" => OpCodeOperandKindDefFlags.RegPlus1,
"p3" => OpCodeOperandKindDefFlags.RegPlus3,
"mem" => OpCodeOperandKindDefFlags.Memory,
"mpx" => OpCodeOperandKindDefFlags.MPX,
"mib" => OpCodeOperandKindDefFlags.MIB,
"sib" => OpCodeOperandKindDefFlags.SibRequired,
_ => throw new InvalidOperationException($"Line {i + 1}: Invalid flag: {flagStr}"),
};
}
var (key, value) = ParserUtils.GetKeyValue(parts[1]);
argCounts.TryGetValue(key, out var argCount);
var args = value == string.Empty ? Array.Empty<string>() : value.Split(';');
if (args.Length != argCount)
throw new InvalidOperationException($"Line {i + 1}: Expected {argCount} args but got {args.Length}: {value}");
OpCodeOperandKindDef def;
int arg1, arg2;
Register register;
switch (key) {
case "none":
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.None, 0, 0, Register.None);
break;
case "br-near":
arg1 = int.Parse(args[0]);
arg2 = int.Parse(args[1]);
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.NearBranch, arg1, arg2, Register.None);
break;
case "br-near-x":
arg1 = int.Parse(args[0]);
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.Xbegin, arg1, 0, Register.None);
break;
case "br-disp":
arg1 = int.Parse(args[0]);
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.AbsNearBranch, arg1, 0, Register.None);
break;
case "br-far":
arg1 = int.Parse(args[0]);
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.FarBranch, arg1, 0, Register.None);
break;
case "imm4":
flags |= OpCodeOperandKindDefFlags.M2Z;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.Immediate, 4, 4, Register.None);
break;
case "imm8-const":
arg1 = int.Parse(args[0]);
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.ImpliedConst, arg1, 0, Register.None);
break;
case "imm":
arg1 = int.Parse(args[0]);
arg2 = int.Parse(args[1]);
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.Immediate, arg1, arg2, Register.None);
break;
case "imp-reg":
register = (Register)toRegister[args[0]].Value;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.ImpliedRegister, 0, 0, register);
break;
case "seg-rbx-al":
flags |= OpCodeOperandKindDefFlags.Memory;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.SegRBX, 0, 0, Register.None);
break;
case "seg-rsi":
flags |= OpCodeOperandKindDefFlags.Memory;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.SegRSI, 0, 0, Register.None);
break;
case "seg-rdi":
flags |= OpCodeOperandKindDefFlags.Memory;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.SegRDI, 0, 0, Register.None);
break;
case "es-rdi":
flags |= OpCodeOperandKindDefFlags.Memory;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.ESRDI, 0, 0, Register.None);
break;
case "isx":
register = (Register)toRegister[args[0]].Value;
switch (int.Parse(args[1])) {
case 4: break;
case 5: flags |= OpCodeOperandKindDefFlags.Is5; break;
default: throw new InvalidOperationException();
}
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.RegImm, 0, 0, register);
break;
case "opcode":
register = (Register)toRegister[args[0]].Value;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.RegOpCode, 0, 0, register);
break;
case "reg":
flags |= OpCodeOperandKindDefFlags.Modrm;
register = (Register)toRegister[args[0]].Value;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.RegModrmReg, 0, 0, register);
break;
case "rm-reg":
flags |= OpCodeOperandKindDefFlags.Modrm;
register = (Register)toRegister[args[0]].Value;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.RegModrmRm, 0, 0, register);
break;
case "vvvv":
register = (Register)toRegister[args[0]].Value;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.RegVvvvv, 0, 0, register);
break;
case "rm":
flags |= OpCodeOperandKindDefFlags.Modrm;
flags |= OpCodeOperandKindDefFlags.Memory;
register = (Register)toRegister[args[0]].Value;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.RegMemModrmRm, 0, 0, register);
break;
case "rm-mem":
flags |= OpCodeOperandKindDefFlags.Modrm;
flags |= OpCodeOperandKindDefFlags.Memory;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.MemModrmRm, 0, 0, Register.None);
break;
case "vsib":
flags |= OpCodeOperandKindDefFlags.Modrm;
flags |= OpCodeOperandKindDefFlags.Memory;
register = (Register)toRegister[args[0]].Value;
flags |= (int.Parse(args[1])) switch {
32 => OpCodeOperandKindDefFlags.Vsib32,
64 => OpCodeOperandKindDefFlags.Vsib64,
_ => throw new InvalidOperationException($"Line {i + 1}: Unknown vsib size: {args[1]}"),
};
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.MemModrmRm, 0, 0, register);
break;
case "moffs":
flags |= OpCodeOperandKindDefFlags.Memory;
def = new OpCodeOperandKindDef(enumValue, flags, OperandEncoding.MemOffset, 0, 0, Register.None);
break;
default:
throw new InvalidOperationException($"Line {i + 1}: Unknown key: {key}");
}
defs.Add(def);
}
if (toOpCodeOperandKind.Count != 0)
throw new InvalidOperationException($"Missing {nameof(OpCodeOperandKind)} definitions");
return defs.OrderBy(a => a.EnumValue.Value).ToArray();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Text;
using Epi.Analysis;
using Epi.Windows.Dialogs;
using Epi.Windows.Analysis;
namespace Epi.Windows.Analysis.Dialogs
{
/// <summary>
/// Dialog for KMSurvival command
/// </summary>
public partial class KaplanMeierSurvivalDialog : CommandDesignDialog
{
#region Constructor
/// <summary>
/// Default constructor - NOT TO BE USED FOR INSTANTIATION
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public KaplanMeierSurvivalDialog()
{
InitializeComponent();
Construct();
}
/// <summary>
/// KaplanMeierSurvivalDialog constructor
/// </summary>
/// <param name="frm"></param>
public KaplanMeierSurvivalDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm)
: base(frm)
{
InitializeComponent();
Construct();
}
#endregion Constructors
#region Private Properties
private string txtCensoredVar;
private string txtTimeVar;
private string txtGroupVar;
private string txtWeightVar;
private string txtOtherVar;
private string txtStrataVar;
#endregion Private Properties
#region Private Methods
private void Construct()
{
if (!this.DesignMode)
{
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
this.btnModifyTerm.Click += new System.EventHandler(this.btnModifyTerm_Click);
this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click);
}
}
private void KaplanMeierSurvivalDialog_Load(object sender, EventArgs e)
{
VariableType scopeWord = VariableType.DataSource | VariableType.DataSourceRedefined |
VariableType.Standard;
FillVariableCombo(cmbCensoredVar, scopeWord);
FillVariableCombo(cmbTimeVar, scopeWord);
FillVariableCombo(cmbGroupVar, scopeWord);
FillVariableCombo(cmbWeightVar, scopeWord);
cmbWeightVar.SelectedIndex = -1;
FillVariableCombo(cmbOther, scopeWord);
FillVariableCombo(cmbStrataVar, scopeWord);
cmbTimeUnit.Items.Add("");
cmbTimeUnit.Items.Add("Days");
cmbTimeUnit.Items.Add("Hours");
cmbTimeUnit.Items.Add("Months");
cmbTimeUnit.Items.Add("Weeks");
cmbTimeUnit.Items.Add("Years");
cmbGraphType.Items.Add("None");
//cmbGraphType.Items.Add("Hazard Function"); 'commented graph types are available in Epi 3 CoxPH, but not KMSurv (yet)
//cmbGraphType.Items.Add("Log-Log Survival");
//cmbGraphType.Items.Add("Log-Log-Observed");
//cmbGraphType.Items.Add("Observed");
cmbGraphType.Items.Add("Survival Probability");
//cmbGraphType.Items.Add("Survival-Observed");
cmbGraphType.Items.Add("Data Table Only");
cmbGraphType.SelectedIndex = 1;
}
#endregion Private Methods
#region Public Methods
/// <summary>
/// Sets enabled property of OK and Save Only
/// </summary>
public override void CheckForInputSufficiency()
{
bool inputValid = ValidateInput();
btnOK.Enabled = inputValid;
btnSaveOnly.Enabled = inputValid;
}
#endregion Public Methods
#region Protected Methods
/// <summary>
/// Generates the command text
/// </summary>
protected override void GenerateCommand()
{
StringBuilder sb = new StringBuilder();
sb.Append(CommandNames.KMSURVIVAL);
sb.Append(StringLiterals.SPACE);
sb.Append(FieldNameNeedsBrackets(cmbTimeVar.Text) ? Util.InsertInSquareBrackets(cmbTimeVar.Text) : cmbTimeVar.Text);
sb.Append(StringLiterals.SPACE);
sb.Append(StringLiterals.EQUAL);
sb.Append(StringLiterals.SPACE);
sb.Append(FieldNameNeedsBrackets(cmbGroupVar.Text) ? Util.InsertInSquareBrackets(cmbGroupVar.Text) : cmbGroupVar.Text);
sb.Append(StringLiterals.SPACE);
//foreach (object obj in lbxOther.Items)
//{
// sb.Append(obj.ToString());
// sb.Append(StringLiterals.SPACE);
//}
/*
foreach (object obj in lbxExtendedTerms.Items)
{
sb.Append(obj.ToString());
sb.Append(StringLiterals.SPACE);
}
foreach (object obj in lbxInteractionTerms.Items)
{
sb.Append(obj.ToString());
sb.Append(StringLiterals.SPACE);
}
*/
sb.Append(StringLiterals.STAR);
sb.Append(StringLiterals.SPACE);
sb.Append(FieldNameNeedsBrackets(cmbCensoredVar.Text) ? Util.InsertInSquareBrackets(cmbCensoredVar.Text) : cmbCensoredVar.Text);
sb.Append(StringLiterals.SPACE);
sb.Append(StringLiterals.PARANTHESES_OPEN);
sb.Append(StringLiterals.SPACE);
if (this.EpiInterpreter.Context.CurrentRead != null)
{
List<System.Data.DataRow> Rows = this.EpiInterpreter.Context.GetOutput();
System.Data.DataTable tempTbl = this.EpiInterpreter.Context.DataSet.Tables["output"];
Dictionary<string,string> table = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase);
//System.Data.DataTable table = Epi.Data.DBReadExecute.GetDataTable(this.EpiInterpreter.Context.CurrentRead.File, "Select Distinct [" + cmbCensoredVar.Text + "] from [" + this.EpiInterpreter.Context.CurrentRead.Identifier + "]");
// System.Data.DataTable table = Epi.Data.DBReadExecute.GetDataTable(this.EpiInterpreter.Context.CurrentRead.File, "Select Distinct [" + cmbCensoredVar.Text + "] " + this.EpiInterpreter.Context.CurrentProject.GetViewByName(this.EpiInterpreter.Context.CurrentRead.Identifier).FromViewSQL);
string type;
type = tempTbl.Columns[cmbCensoredVar.Text].DataType.ToString();
if (type.Equals("System.Byte") || type.Equals("System.Int16") || type.Equals("System.Boolean"))
{
Dictionary<string, string> setProperties = this.EpiInterpreter.Context.GetGlobalSettingProperties();
if (cmbUncensoredValue.Text.ToString().Equals(setProperties["RepresentationOfYes"].ToString()))
{
sb.Append(StringLiterals.EPI_REPRESENTATION_OF_TRUE);
}
else if (cmbUncensoredValue.Text.ToString().Equals(setProperties["RepresentationOfNo"].ToString()))
{
sb.Append(StringLiterals.EPI_REPRESENTATION_OF_FALSE);
}
else if (cmbUncensoredValue.Text.ToString().Equals(setProperties["RepresentationOfMissing"].ToString()))
{
sb.Append(StringLiterals.EPI_REPRESENTATION_OF_MISSING);
}
else
{
sb.Append(cmbUncensoredValue.Text.ToString());
}
}
else if (!IsNumeric(cmbUncensoredValue.Text))
{
sb.Append(StringLiterals.DOUBLEQUOTES);
sb.Append(cmbUncensoredValue.Text);
sb.Append(StringLiterals.DOUBLEQUOTES);
}
else
{
sb.Append(cmbUncensoredValue.Text);
}
}
sb.Append(StringLiterals.SPACE);
sb.Append(StringLiterals.PARANTHESES_CLOSE);
sb.Append(StringLiterals.SPACE);
if (!string.IsNullOrEmpty(cmbTimeUnit.Text))
{
sb.Append("TIMEUNIT=");
sb.Append(StringLiterals.DOUBLEQUOTES).Append(cmbTimeUnit.Text).Append(StringLiterals.DOUBLEQUOTES);
sb.Append(StringLiterals.SPACE);
}
if (!string.IsNullOrEmpty(cmbWeightVar.Text))
{
sb.Append("WEIGHTVAR=");
sb.Append(FieldNameNeedsBrackets(cmbWeightVar.Text) ? Util.InsertInSquareBrackets(cmbWeightVar.Text) : cmbWeightVar.Text);
sb.Append(StringLiterals.SPACE);
}
if (!string.IsNullOrEmpty(txtOutput.Text))
{
sb.Append("OUTTABLE=");
sb.Append(txtOutput.Text);
sb.Append(StringLiterals.SPACE);
}
if (!string.IsNullOrEmpty(cmbGraphType.Text))
{
sb.Append("GRAPHTYPE=");
sb.Append(StringLiterals.DOUBLEQUOTES).Append(cmbGraphType.Text).Append(StringLiterals.DOUBLEQUOTES);
sb.Append(StringLiterals.SPACE);
}
//if (!string.IsNullOrEmpty(cmbConfLimits.Text))
//{
// sb.Append("PVALUE=");
// sb.Append(cmbConfLimits.Text);
//}
//if (!string.IsNullOrEmpty(cmbStrataVar.Text))
//{
// sb.Append("STRATAVAR=");
// foreach (string s in this.lbxStrataVar.Items)
// {
// sb.Append(s).Append(StringLiterals.SPACE);
// }
//}
CommandText = sb.ToString();
}
/// <summary>
/// Determines if an object's value can be parsed to an int
/// </summary>
/// <returns>true if the value of the object is a number; else false</returns>
public bool IsNumeric(object value)
{
var isNumeric = false;
int actualValue;
if (value != null && int.TryParse(value.ToString(), out actualValue))
{
isNumeric = true;
}
return isNumeric;
}
/// <summary>
/// Validates user input
/// </summary>
/// <returns>true if there is no error; else false</returns>
protected override bool ValidateInput()
{
base.ValidateInput();
//if (cmbOther.Text.Length == 0)
//{
// ErrorMessages.Add(SharedStrings.MUST_SELECT_TERMS);
//}
if (cmbCensoredVar.SelectedIndex == -1)
{
ErrorMessages.Add(SharedStrings.MUST_SELECT_CENSORED);
}
if (cmbUncensoredValue.SelectedIndex == -1)
{
ErrorMessages.Add(SharedStrings.MUST_SELECT_UNCENSORED_VALUE);
}
if (cmbTimeVar.SelectedIndex == -1)
{
ErrorMessages.Add(SharedStrings.MUST_SELECT_TIME_VAR);
}
if (cmbGroupVar.SelectedIndex == -1)
{
ErrorMessages.Add(SharedStrings.MUST_SELECT_GROUP);
}
// cmbStratifyby doubles as cmbMatchVar (which doesn't exist)
//if (cbxMatch.Checked && string.IsNullOrEmpty(cmbStratifyBy.ToString()))
//{
// ErrorMessages.Add(SharedStrings.NO_MATCHVAR);
//}
return (ErrorMessages.Count == 0);
}
#endregion Protected Methods
#region Event Handlers
/// <summary>
/// Handles the btnClear_Click event
/// </summary>
/// <remarks>Removes all items from comboboxes and other dialog controls</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void btnClear_Click(object sender, System.EventArgs e)
{
//First column on KaplanMeierSurvivalDialog
//variable cmb's cleared when dialog loads during FillVariableValues()
cmbConfLimits.SelectedIndex = -1;
txtOutput.Text = string.Empty;
//Second column on KaplanMeierSurvivalDialog
cmbUncensoredValue.Items.Clear();
cmbTimeUnit.SelectedIndex = -1;
lbxOther.Items.Clear(); //Predictor variables
lbxInteractionTerms.Items.Clear();
//Third column
lbxStrataVars.Items.Clear();
//Fourth col
lbxExtendedTerms.Items.Clear();
//Last col
cmbGraphType.Items.Clear();
lbxGraphVars.Items.Clear();
//chkCustomGraph; Checkbox checked or unchecked when dialog cleared?
KaplanMeierSurvivalDialog_Load(this, null);
CheckForInputSufficiency();
}
/// <summary>
/// Handles the cmbCensoredVar_SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbCensoredVar_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCensoredVar.SelectedIndex >= 0) // prevent the remove below from re-entering
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtCensoredVar;
string strNew = cmbCensoredVar.Text;
//make sure s isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
//add the former variable chosen back into the other lists
cmbTimeVar.Items.Add(strOld);
cmbGroupVar.Items.Add(strOld);
cmbWeightVar.Items.Add(strOld);
cmbOther.Items.Add(strOld);
cmbStrataVar.Items.Add(strOld);
}
//remove the new variable chosen from the other lists
cmbTimeVar.Items.Remove(strNew);
cmbGroupVar.Items.Remove(strNew);
cmbWeightVar.Items.Remove(strNew);
cmbOther.Items.Remove(strNew);
cmbStrataVar.Items.Remove(strNew);
lbxOther.Items.Remove(strNew);
//check that recordset not null
if (this.EpiInterpreter.Context.CurrentRead != null)
{
List<System.Data.DataRow> Rows = this.EpiInterpreter.Context.GetOutput();
System.Data.DataTable tempTbl = this.EpiInterpreter.Context.DataSet.Tables["output"];
Dictionary<string, string> table = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
string type;
type = tempTbl.Columns[cmbCensoredVar.Text].DataType.ToString();
foreach (System.Data.DataRow row in tempTbl.Rows)
{
string Key = row[cmbCensoredVar.Text].ToString();
if(!table.ContainsKey(Key))
{
table.Add(Key, Key);
}
}
cmbUncensoredValue.Items.Clear();
Dictionary<string, string> setProperties = this.EpiInterpreter.Context.GetGlobalSettingProperties();
if (type.Equals("System.Byte") || type.Equals("System.Int16") || type.Equals("System.Boolean"))
{
cmbUncensoredValue.Items.Add(setProperties["RepresentationOfYes"]);
cmbUncensoredValue.Items.Add(setProperties["RepresentationOfNo"]);
if (! type.Equals("System.Boolean"))
{
cmbUncensoredValue.Items.Add(setProperties["RepresentationOfMissing"]);
}
}
else
{
int i = 0;
foreach(KeyValuePair<string,string> kvp in table)
{
if (kvp.Key.Length > 0)
{
cmbUncensoredValue.Items.Add(kvp.Key);
}
i++;
}
cmbUncensoredValue.Items.Add(setProperties["RepresentationOfMissing"]);
if (i > 2)
{
MsgBox.ShowInformation(SharedStrings.WARNING_HIGH_CENSOR_VAL_COUNT);
}
}
if (cmbUncensoredValue.Items.Count > 0)
{
cmbUncensoredValue.Enabled = true;
}
}
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the cmbTimeVar_SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbTimeVar_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbTimeVar.SelectedIndex >= 0) // prevent the remove below from re-entering
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtTimeVar;
string strNew = cmbTimeVar.Text;
//make sure s isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
//add the former variable chosen back into the other lists
cmbCensoredVar.Items.Add(strOld);
//cmbTimeVar.Items.Add(strOld);
cmbGroupVar.Items.Add(strOld);
cmbWeightVar.Items.Add(strOld);
cmbOther.Items.Add(strOld);
cmbStrataVar.Items.Add(strOld);
}
//remove the new variable chosen from the other lists
cmbCensoredVar.Items.Remove(strNew);
//cmbTimeVar.Items.Remove(strNew);
cmbGroupVar.Items.Remove(strNew);
cmbWeightVar.Items.Remove(strNew);
cmbOther.Items.Remove(strNew);
cmbStrataVar.Items.Remove(strNew);
lbxOther.Items.Remove(strNew);
}
CheckForInputSufficiency();
}
/// <summary>
/// Handles the lbxOther SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void lbxOther_SelectedIndexChanged(object sender, EventArgs e)
{
if (lbxOther.SelectedItems.Count >= 1 && lbxOther.SelectedItems.Count <= 2)
{
btnModifyTerm.Enabled = true;
}
else
{
btnModifyTerm.Enabled = false;
}
if (lbxOther.SelectedItems.Count == 2)
{
btnModifyTerm.Text = "Make Interaction";
}
else
{
btnModifyTerm.Text = "Make Dummy";
if (lbxOther.SelectedItems.Count == 1 && lbxOther.SelectedItem.ToString().Contains("("))
{
btnModifyTerm.Text = "Make Continuous";
}
}
}
/// <summary>
/// Handles the cmbOther SelectedIndexChanged event
/// </summary>
/// <remarks>Removes item from other comboboxes</remarks>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void cmbOther_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbOther.SelectedIndex >= 0)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtOtherVar;
string strNew = cmbOther.Text;
//make sure s isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
//add the former variable chosen back into the other lists
cmbCensoredVar.Items.Add(strOld);
cmbTimeVar.Items.Add(strOld);
cmbGroupVar.Items.Add(strOld);
cmbWeightVar.Items.Add(strOld);
//cmbOther.Items.Add(strOld);
cmbStrataVar.Items.Add(strOld);
}
//remove the new variable chosen from the other lists
cmbCensoredVar.Items.Remove(strNew);
cmbTimeVar.Items.Remove(strNew);
cmbGroupVar.Items.Remove(strNew);
cmbWeightVar.Items.Remove(strNew);
//cmbOther.Items.Remove(strNew);
cmbStrataVar.Items.Remove(strNew);
lbxOther.Items.Remove(strNew);
//add the new variable to the lbxOther ListBox
if (!((lbxOther.Items.Contains(strNew)) || (lbxOther.Items.Contains("(" + strNew + ")"))))
{
lbxOther.Items.Add(strNew);
}
}
CheckForInputSufficiency();
}
private void btnModifyTerm_Click(object sender, EventArgs e)
{
if (lbxOther.SelectedItems.Count == 1 && !lbxOther.SelectedItem.ToString().Contains("("))
{
string s = lbxOther.SelectedItem.ToString();
lbxOther.Items.Remove(s);
lbxOther.Items.Add("(" + s + ")");
}
else if (lbxOther.SelectedItems.Count == 1 && lbxOther.SelectedItem.ToString().Contains("("))
{
string s = lbxOther.SelectedItem.ToString();
lbxOther.Items.Remove(s);
lbxOther.Items.Add(s.Replace("(", string.Empty).Replace(")", string.Empty));
}
else if (lbxOther.SelectedItems.Count == 2)
{
string interactionTerm = string.Empty;
foreach (object obj in lbxOther.SelectedItems)
{
string s = obj.ToString();
if (!(s.Contains("(") || (s.Contains(")"))))
{
interactionTerm = interactionTerm + s.ToString();
interactionTerm = interactionTerm + StringLiterals.SPACE;
}
else
{
return;
}
}
interactionTerm = interactionTerm.Trim();
interactionTerm = interactionTerm.Replace(StringLiterals.SPACE, StringLiterals.STAR);
lbxOther.SelectedItems.Clear();
lbxInteractionTerms.Items.Add(interactionTerm);
}
}
private void cmbGroupVar_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbGroupVar.SelectedIndex >= 0) // prevent the remove below from re-entering
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtGroupVar;
string strNew = cmbGroupVar.Text;
//make sure s isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
//add the former variable chosen back into the other lists
cmbCensoredVar.Items.Add(strOld);
cmbTimeVar.Items.Add(strOld);
//cmbGroupVar.Items.Add(strOld);
cmbWeightVar.Items.Add(strOld);
cmbOther.Items.Add(strOld);
cmbStrataVar.Items.Add(strOld);
}
//remove the new variable chosen from the other lists
cmbCensoredVar.Items.Remove(strNew);
cmbTimeVar.Items.Remove(strNew);
//cmbGroupVar.Items.Remove(strNew);
cmbWeightVar.Items.Remove(strNew);
cmbOther.Items.Remove(strNew);
cmbStrataVar.Items.Remove(strNew);
lbxOther.Items.Remove(strNew);
}
CheckForInputSufficiency();
}
private void cmbWeightVar_SelectedIndexChanged(object sender, EventArgs e)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtWeightVar;
string strNew = cmbWeightVar.Text;
//make sure it isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
//add the former variable chosen back into the other lists
cmbCensoredVar.Items.Add(strOld);
cmbTimeVar.Items.Add(strOld);
cmbGroupVar.Items.Add(strOld);
cmbOther.Items.Add(strOld);
cmbStrataVar.Items.Add(strOld);
}
if (cmbWeightVar.SelectedIndex >= 0) // prevent the remove below from re-entering
{
//remove the new variable chosen from the other lists
cmbCensoredVar.Items.Remove(strNew);
cmbTimeVar.Items.Remove(strNew);
cmbGroupVar.Items.Remove(strNew);
cmbOther.Items.Remove(strNew);
cmbStrataVar.Items.Remove(strNew);
lbxOther.Items.Remove(strNew);
}
}
private void cmbStrataVar_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbStrataVar.SelectedIndex >= 0)
{
//Get the old variable chosen that was saved to the txt string.
string strOld = txtStrataVar;
string strNew = cmbStrataVar.Text;
//make sure s isn't "" or the same as the new variable picked.
if ((strOld.Length > 0) && (strOld != strNew))
{
//add the former variable chosen back into the other lists
cmbCensoredVar.Items.Add(strOld);
cmbTimeVar.Items.Add(strOld);
cmbGroupVar.Items.Add(strOld);
cmbWeightVar.Items.Add(strOld);
cmbOther.Items.Add(strOld);
//cmbStrataVar.Items.Add(strOld);
}
//remove the new variable chosen from the other lists
cmbCensoredVar.Items.Remove(strNew);
cmbTimeVar.Items.Remove(strNew);
cmbGroupVar.Items.Remove(strNew);
cmbWeightVar.Items.Remove(strNew);
cmbOther.Items.Remove(strNew);
//cmbStrataVar.Items.Remove(strNew);
lbxOther.Items.Remove(strNew);
}
}
private void lbxOther_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Delete)||(e.KeyCode == Keys.Back))
{
lbxOther.Items.Remove(lbxOther.SelectedItem);
}
}
private void lbxStrataVars_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Delete) || (e.KeyCode == Keys.Back))
{
lbxStrataVars.Items.Remove(lbxStrataVars.SelectedItem);
}
}
private void lbxInteractionTerms_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Delete) || (e.KeyCode == Keys.Back))
{
lbxInteractionTerms.Items.Remove(lbxInteractionTerms.SelectedItem);
}
}
private void lbxExtendedTerms_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Delete) || (e.KeyCode == Keys.Back))
{
lbxExtendedTerms.Items.Remove(lbxExtendedTerms.SelectedItem);
}
}
private void cmbCensoredVar_Click(object sender, EventArgs e)
{
if (cmbCensoredVar.SelectedIndex >= 0)
{
txtCensoredVar = cmbCensoredVar.Text;
}
else
{
txtCensoredVar = "";
}
}
private void cmbTimeVar_Click(object sender, EventArgs e)
{
if (cmbTimeVar.SelectedIndex >= 0)
{
txtTimeVar = cmbTimeVar.Text;
}
else
{
txtTimeVar = "";
}
}
private void cmbGroupVar_Click(object sender, EventArgs e)
{
if (cmbGroupVar.SelectedIndex >= 0)
{
txtGroupVar = cmbGroupVar.Text;
}
else
{
txtGroupVar = "";
}
}
private void cmbWeightVar_Click(object sender, EventArgs e)
{
if (cmbWeightVar.SelectedIndex >= 0)
{
txtWeightVar = cmbWeightVar.Text;
}
else
{
txtWeightVar = "";
}
}
private void cmbOther_Click(object sender, EventArgs e)
{
if (cmbOther.SelectedIndex >= 0)
{
txtOtherVar = cmbOther.Text;
}
else
{
txtOtherVar = "";
}
}
private void cmbStrataVar_Click(object sender, EventArgs e)
{
if (cmbStrataVar.SelectedIndex >= 0)
{
txtStrataVar = cmbStrataVar.Text;
}
else
{
txtStrataVar = "";
}
}
private void cmbWeightVar_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
//SelectedIndexChanged will add the var back to the other DDLs
cmbWeightVar.Text = "";
cmbWeightVar.SelectedIndex = -1;
}
}
/// <summary>
/// Opens a process to show the related help topic
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnHelp_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-KMSURVIVAL.html");
}
#endregion Event Handlers
private void cmbUncensoredValue_SelectedIndexChanged(object sender, EventArgs e)
{
CheckForInputSufficiency();
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif ASPNETCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
{
Person person = new Person();
person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.Name = "Name!";
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
Assert.AreEqual(person.LastModified, deserializedPerson.LastModified);
Assert.AreEqual(person.Name, deserializedPerson.Name);
json = JsonConvert.SerializeObject(person, Formatting.Indented);
StringAssert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
JTokenWriter writer = new JTokenWriter();
serializer.Serialize(writer, ignoreAttributeOnClassTestClass);
JObject o = (JObject)writer.Token;
JProperty p = o.Property("theField");
Assert.IsNotNull(p);
Assert.AreEqual(int.MinValue, (int)p.Value);
string json = o.ToString();
}
#if !(NETFX_CORE || PORTABLE || ASPNETCORE50 || PORTABLE40)
#pragma warning disable 618
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
StringAssert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.DeserializeObject<PrivateMembersClass>(@"{
""_privateString"": ""Private!"",
""i"": -2,
""_internalString"": ""Internal!""
}", new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
Assert.AreEqual("Internal!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_internalString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
// readonly
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
}
#pragma warning restore 618
#endif
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
StringAssert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || PORTABLE40)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""explicit"": false,
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "First", "Value1!" },
{ "Second", "Value2!" }
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.Serialization;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
[Serializable]
internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
private volatile RuntimeType m_declaringType;
private RuntimeTypeCache m_reflectedTypeCache;
private string m_toString;
private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called.
#pragma warning disable 169
private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar
private object _empty2;
private object _empty3;
#pragma warning restore 169
private IntPtr m_handle;
private MethodAttributes m_methodAttributes;
private BindingFlags m_bindingFlags;
private volatile Signature m_signature;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given
Type declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (declaringType == typeof(void) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
{
// We don't need other flags if this method cannot be invoked
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else if (IsStatic || declaringType != null && declaringType.IsAbstract)
{
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE;
}
else
{
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this);
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 &&
((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
(declaringType != null && declaringType.NeedsReflectionSecurityCheck)))
{
// If method is non-public, or declaring type is not visible
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
}
// Check for attempt to create a delegate class, we demand unmanaged
// code permission for this since it's hard to validate the target address.
if (typeof(Delegate).IsAssignableFrom(DeclaringType))
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR;
}
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
#endregion
#region Constructor
internal RuntimeConstructorInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache,
MethodAttributes methodAttributes, BindingFlags bindingFlags)
{
Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaringType;
m_handle = handle.Value;
m_methodAttributes = methodAttributes;
}
#endregion
#region NonPublic Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
get
{
return new RuntimeMethodHandleInternal(m_handle);
}
}
internal override bool CacheEquals(object o)
{
RuntimeConstructorInfo m = o as RuntimeConstructorInfo;
if ((object)m == null)
return false;
return m.m_handle == m_handle;
}
private Signature Signature
{
get
{
if (m_signature == null)
m_signature = new Signature(this, m_declaringType);
return m_signature;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
private void CheckConsistency(Object target)
{
if (target == null && IsStatic)
return;
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg);
throw new TargetException(SR.RFLCT_Targ_ITargMismatch);
}
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
#endregion
#region Object Overrides
public override String ToString()
{
// "Void" really doesn't make sense here. But we'll keep it for compat reasons.
if (m_toString == null)
m_toString = "Void " + FormatNameAndSig();
return m_toString;
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override String Name
{
get { return RuntimeMethodHandle.GetName(this); }
}
public override MemberTypes MemberType { get { return MemberTypes.Constructor; } }
public override Type DeclaringType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
}
}
public override Type ReflectedType
{
get
{
return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
}
}
public override int MetadataToken
{
get { return RuntimeMethodHandle.GetMethodDef(this); }
}
public override Module Module
{
get { return GetRuntimeModule(); }
}
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
#endregion
#region MethodBase Overrides
// This seems to always returns System.Void.
internal override Type GetReturnType() { return Signature.ReturnType; }
internal override ParameterInfo[] GetParametersNoCopy()
{
if (m_parameters == null)
m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature);
return m_parameters;
}
[Pure]
public override ParameterInfo[] GetParameters()
{
ParameterInfo[] parameters = GetParametersNoCopy();
if (parameters.Length == 0)
return parameters;
ParameterInfo[] ret = new ParameterInfo[parameters.Length];
Array.Copy(parameters, ret, parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
public override RuntimeMethodHandle MethodHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
return new RuntimeMethodHandle(this);
}
}
public override MethodAttributes Attributes
{
get
{
return m_methodAttributes;
}
}
public override CallingConventions CallingConvention
{
get
{
return Signature.CallingConvention;
}
}
internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg)
{
if (declaringType == null)
throw new ArgumentNullException(nameof(declaringType));
Contract.EndContractBlock();
// ctor is ReflectOnly
if (declaringType is ReflectionOnlyType)
throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
// ctor is declared on interface class
else if (declaringType.IsInterface)
throw new MemberAccessException(
String.Format(CultureInfo.CurrentUICulture, SR.Acc_CreateInterfaceEx, declaringType));
// ctor is on an abstract class
else if (declaringType.IsAbstract)
throw new MemberAccessException(
String.Format(CultureInfo.CurrentUICulture, SR.Acc_CreateAbstEx, declaringType));
// ctor is on a class that contains stack pointers
else if (declaringType.GetRootElementType() == typeof(ArgIterator))
throw new NotSupportedException();
// ctor is vararg
else if (isVarArg)
throw new NotSupportedException();
// ctor is generic or on a generic class
else if (declaringType.ContainsGenericParameters)
{
throw new MemberAccessException(
String.Format(CultureInfo.CurrentUICulture, SR.Acc_CreateGenericEx, declaringType));
}
// ctor is declared on System.Void
else if (declaringType == typeof(void))
throw new MemberAccessException(SR.Access_Void);
}
internal void ThrowNoInvokeException()
{
CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs);
// ctor is .cctor
if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static)
throw new MemberAccessException(SR.Acc_NotClassInit);
throw new TargetException();
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Object Invoke(
Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
if (obj != null)
{
// For unverifiable code, we require the caller to be critical.
// Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
}
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(SR.Arg_ParmCnt);
// if we are here we passed all the previous checks. Time to look at the arguments
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false);
}
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb.m_methodBase = this;
return mb;
}
public override bool IsSecurityCritical
{
get { return true; }
}
public override bool IsSecuritySafeCritical
{
get { return false; }
}
public override bool IsSecurityTransparent
{
get { return false; }
}
public override bool ContainsGenericParameters
{
get
{
return (DeclaringType != null && DeclaringType.ContainsGenericParameters);
}
}
#endregion
#region ConstructorInfo Overrides
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context
RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle;
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0)
ThrowNoInvokeException();
// get the signature
Signature sig = Signature;
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
throw new TargetParameterCountException(SR.Arg_ParmCnt);
// We don't need to explicitly invoke the class constructor here,
// JIT/NGen will insert the call to .cctor in the instance ctor.
// if we are here we passed all the previous checks. Time to look at the arguments
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(null, null, sig, true);
}
#endregion
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(info, this);
}
internal string SerializationToString()
{
// We don't need the return type for constructors.
return FormatNameAndSig(true);
}
#endregion
}
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if NET45PLUS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
/// <author>Sam Harwell</author>
public class RuleDependencyChecker
{
private static readonly HashSet<string> checkedAssemblies = new HashSet<string>();
public static void CheckDependencies(Assembly assembly)
{
if (IsChecked(assembly))
{
return;
}
IEnumerable<TypeInfo> typesToCheck = GetTypesToCheck(assembly);
List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
foreach (TypeInfo clazz in typesToCheck)
{
dependencies.AddRange(GetDependencies(clazz));
}
if (dependencies.Count > 0)
{
IDictionary<TypeInfo, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> recognizerDependencies = new Dictionary<TypeInfo, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>>();
foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)
{
TypeInfo recognizerType = dependency.Item1.Recognizer.GetTypeInfo();
IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> list;
if (!recognizerDependencies.TryGetValue(recognizerType, out list))
{
list = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
recognizerDependencies[recognizerType] = list;
}
list.Add(dependency);
}
foreach (KeyValuePair<TypeInfo, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> entry in recognizerDependencies)
{
//processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, String.format("ANTLR 4: Validating {0} dependencies on rules in {1}.", entry.getValue().size(), entry.getKey().toString()));
CheckDependencies(entry.Value, entry.Key);
}
}
MarkChecked(assembly);
}
private static IEnumerable<TypeInfo> GetTypesToCheck(Assembly assembly)
{
return assembly.DefinedTypes;
}
private static bool IsChecked(Assembly assembly)
{
lock (checkedAssemblies)
{
return checkedAssemblies.Contains(assembly.FullName);
}
}
private static void MarkChecked(Assembly assembly)
{
lock (checkedAssemblies)
{
checkedAssemblies.Add(assembly.FullName);
}
}
private static void CheckDependencies(IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies, TypeInfo recognizerType)
{
string[] ruleNames = GetRuleNames(recognizerType);
int[] ruleVersions = GetRuleVersions(recognizerType, ruleNames);
RuleDependencyChecker.RuleRelations relations = ExtractRuleRelations(recognizerType);
StringBuilder errors = new StringBuilder();
foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)
{
if (!dependency.Item1.Recognizer.GetTypeInfo().IsAssignableFrom(recognizerType))
{
continue;
}
// this is the rule in the dependency set with the highest version number
int effectiveRule = dependency.Item1.Rule;
if (effectiveRule < 0 || effectiveRule >= ruleVersions.Length)
{
string message = string.Format("Rule dependency on unknown rule {0}@{1} in {2}", dependency.Item1.Rule, dependency.Item1.Version, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
continue;
}
Dependents dependents = Dependents.Self | dependency.Item1.Dependents;
ReportUnimplementedDependents(errors, dependency, dependents);
BitSet @checked = new BitSet();
int highestRequiredDependency = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, effectiveRule, null);
if ((dependents & Dependents.Parents) != 0)
{
BitSet parents = relations.parents[dependency.Item1.Rule];
for (int parent = parents.NextSetBit(0); parent >= 0; parent = parents.NextSetBit(parent + 1))
{
if (parent < 0 || parent >= ruleVersions.Length || @checked.Get(parent))
{
continue;
}
@checked.Set(parent);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, parent, "parent");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Children) != 0)
{
BitSet children = relations.children[dependency.Item1.Rule];
for (int child = children.NextSetBit(0); child >= 0; child = children.NextSetBit(child + 1))
{
if (child < 0 || child >= ruleVersions.Length || @checked.Get(child))
{
continue;
}
@checked.Set(child);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, child, "child");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Ancestors) != 0)
{
BitSet ancestors = relations.GetAncestors(dependency.Item1.Rule);
for (int ancestor = ancestors.NextSetBit(0); ancestor >= 0; ancestor = ancestors.NextSetBit(ancestor + 1))
{
if (ancestor < 0 || ancestor >= ruleVersions.Length || @checked.Get(ancestor))
{
continue;
}
@checked.Set(ancestor);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, ancestor, "ancestor");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Descendants) != 0)
{
BitSet descendants = relations.GetDescendants(dependency.Item1.Rule);
for (int descendant = descendants.NextSetBit(0); descendant >= 0; descendant = descendants.NextSetBit(descendant + 1))
{
if (descendant < 0 || descendant >= ruleVersions.Length || @checked.Get(descendant))
{
continue;
}
@checked.Set(descendant);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, descendant, "descendant");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
int declaredVersion = dependency.Item1.Version;
if (declaredVersion > highestRequiredDependency)
{
string message = string.Format("Rule dependency version mismatch: {0} has maximum dependency version {1} (expected {2}) in {3}", ruleNames[dependency.Item1.Rule], highestRequiredDependency, declaredVersion, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
}
}
if (errors.Length > 0)
{
throw new InvalidOperationException(errors.ToString());
}
}
private static readonly Dependents ImplementedDependents = Dependents.Self | Dependents.Parents | Dependents.Children | Dependents.Ancestors | Dependents.Descendants;
private static void ReportUnimplementedDependents(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, Dependents dependents)
{
Dependents unimplemented = dependents;
unimplemented &= ~ImplementedDependents;
if (unimplemented != Dependents.None)
{
string message = string.Format("Cannot validate the following dependents of rule {0}: {1}", dependency.Item1.Rule, unimplemented);
errors.AppendLine(message);
}
}
private static int CheckDependencyVersion(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, string[] ruleNames, int[] ruleVersions, int relatedRule, string relation)
{
string ruleName = ruleNames[dependency.Item1.Rule];
string path;
if (relation == null)
{
path = ruleName;
}
else
{
string mismatchedRuleName = ruleNames[relatedRule];
path = string.Format("rule {0} ({1} of {2})", mismatchedRuleName, relation, ruleName);
}
int declaredVersion = dependency.Item1.Version;
int actualVersion = ruleVersions[relatedRule];
if (actualVersion > declaredVersion)
{
string message = string.Format("Rule dependency version mismatch: {0} has version {1} (expected <= {2}) in {3}", path, actualVersion, declaredVersion, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
}
return actualVersion;
}
private static int[] GetRuleVersions(TypeInfo recognizerClass, string[] ruleNames)
{
int[] versions = new int[ruleNames.Length];
IEnumerable<FieldInfo> fields = recognizerClass.DeclaredFields;
foreach (FieldInfo field in fields)
{
bool isStatic = field.IsStatic;
bool isInteger = field.FieldType == typeof(int);
if (isStatic && isInteger && field.Name.StartsWith("RULE_"))
{
try
{
string name = field.Name.Substring("RULE_".Length);
if (name.Length == 0 || !System.Char.IsLower(name[0]))
{
continue;
}
int index = (int)field.GetValue(null);
if (index < 0 || index >= versions.Length)
{
object[] @params = new object[] { index, field.Name, recognizerClass.Name };
#if false
Logger.Log(Level.Warning, "Rule index {0} for rule ''{1}'' out of bounds for recognizer {2}.", @params);
#endif
continue;
}
MethodInfo ruleMethod = GetRuleMethod(recognizerClass, name);
if (ruleMethod == null)
{
object[] @params = new object[] { name, recognizerClass.Name };
#if false
Logger.Log(Level.Warning, "Could not find rule method for rule ''{0}'' in recognizer {1}.", @params);
#endif
continue;
}
RuleVersionAttribute ruleVersion = ruleMethod.GetCustomAttribute<RuleVersionAttribute>();
int version = ruleVersion != null ? ruleVersion.Version : 0;
versions[index] = version;
}
catch (ArgumentException)
{
#if false
Logger.Log(Level.Warning, null, ex);
#else
throw;
#endif
}
catch (MemberAccessException)
{
#if false
Logger.Log(Level.Warning, null, ex);
#else
throw;
#endif
}
}
}
return versions;
}
private static MethodInfo GetRuleMethod(TypeInfo recognizerClass, string name)
{
IEnumerable<MethodInfo> declaredMethods = recognizerClass.DeclaredMethods;
foreach (MethodInfo method in declaredMethods)
{
if (method.Name.Equals(name) && method.GetCustomAttribute<RuleVersionAttribute>() != null)
{
return method;
}
}
return null;
}
private static string[] GetRuleNames(TypeInfo recognizerClass)
{
FieldInfo ruleNames = recognizerClass.DeclaredFields.First(i => i.Name == "ruleNames");
return (string[])ruleNames.GetValue(null);
}
public static IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> GetDependencies(TypeInfo clazz)
{
IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
GetElementDependencies(AsCustomAttributeProvider(clazz), result);
foreach (ConstructorInfo ctor in clazz.DeclaredConstructors)
{
GetElementDependencies(AsCustomAttributeProvider(ctor), result);
foreach (ParameterInfo parameter in ctor.GetParameters())
GetElementDependencies(AsCustomAttributeProvider(parameter), result);
}
foreach (FieldInfo field in clazz.DeclaredFields)
{
GetElementDependencies(AsCustomAttributeProvider(field), result);
}
foreach (MethodInfo method in clazz.DeclaredMethods)
{
GetElementDependencies(AsCustomAttributeProvider(method), result);
#if COMPACT
if (method.ReturnTypeCustomAttributes != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnTypeCustomAttributes), result);
#else
if (method.ReturnParameter != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnParameter), result);
#endif
foreach (ParameterInfo parameter in method.GetParameters())
GetElementDependencies(AsCustomAttributeProvider(parameter), result);
}
return result;
}
private static void GetElementDependencies(ICustomAttributeProvider annotatedElement, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result)
{
foreach (RuleDependencyAttribute dependency in annotatedElement.GetCustomAttributes(typeof(RuleDependencyAttribute), true))
{
result.Add(Tuple.Create(dependency, annotatedElement));
}
}
private static RuleDependencyChecker.RuleRelations ExtractRuleRelations(TypeInfo recognizer)
{
string serializedATN = GetSerializedATN(recognizer);
if (serializedATN == null)
{
return null;
}
ATN atn = new ATNDeserializer().Deserialize(serializedATN.ToCharArray());
RuleDependencyChecker.RuleRelations relations = new RuleDependencyChecker.RuleRelations(atn.ruleToStartState.Length);
foreach (ATNState state in atn.states)
{
if (!state.epsilonOnlyTransitions)
{
continue;
}
foreach (Transition transition in state.transitions)
{
if (transition.TransitionType != TransitionType.Rule)
{
continue;
}
RuleTransition ruleTransition = (RuleTransition)transition;
relations.AddRuleInvocation(state.ruleIndex, ruleTransition.target.ruleIndex);
}
}
return relations;
}
private static string GetSerializedATN(TypeInfo recognizerClass)
{
FieldInfo serializedAtnField = recognizerClass.DeclaredFields.First(i => i.Name == "_serializedATN");
if (serializedAtnField != null)
return (string)serializedAtnField.GetValue(null);
if (recognizerClass.BaseType != null)
return GetSerializedATN(recognizerClass.BaseType.GetTypeInfo());
return null;
}
private sealed class RuleRelations
{
public readonly BitSet[] parents;
public readonly BitSet[] children;
public RuleRelations(int ruleCount)
{
parents = new BitSet[ruleCount];
for (int i = 0; i < ruleCount; i++)
{
parents[i] = new BitSet();
}
children = new BitSet[ruleCount];
for (int i_1 = 0; i_1 < ruleCount; i_1++)
{
children[i_1] = new BitSet();
}
}
public bool AddRuleInvocation(int caller, int callee)
{
if (caller < 0)
{
// tokens rule
return false;
}
if (children[caller].Get(callee))
{
// already added
return false;
}
children[caller].Set(callee);
parents[callee].Set(caller);
return true;
}
public BitSet GetAncestors(int rule)
{
BitSet ancestors = new BitSet();
ancestors.Or(parents[rule]);
while (true)
{
int cardinality = ancestors.Cardinality();
for (int i = ancestors.NextSetBit(0); i >= 0; i = ancestors.NextSetBit(i + 1))
{
ancestors.Or(parents[i]);
}
if (ancestors.Cardinality() == cardinality)
{
// nothing changed
break;
}
}
return ancestors;
}
public BitSet GetDescendants(int rule)
{
BitSet descendants = new BitSet();
descendants.Or(children[rule]);
while (true)
{
int cardinality = descendants.Cardinality();
for (int i = descendants.NextSetBit(0); i >= 0; i = descendants.NextSetBit(i + 1))
{
descendants.Or(children[i]);
}
if (descendants.Cardinality() == cardinality)
{
// nothing changed
break;
}
}
return descendants;
}
}
private RuleDependencyChecker()
{
}
#if PORTABLE
public interface ICustomAttributeProvider
{
object[] GetCustomAttributes(Type attributeType, bool inherit);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(TypeInfo type)
{
return new TypeCustomAttributeProvider(type);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(MethodBase method)
{
return new MethodBaseCustomAttributeProvider(method);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(ParameterInfo parameter)
{
return new ParameterInfoCustomAttributeProvider(parameter);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(FieldInfo field)
{
return new FieldInfoCustomAttributeProvider(field);
}
protected sealed class TypeCustomAttributeProvider : ICustomAttributeProvider
{
private readonly TypeInfo _provider;
public TypeCustomAttributeProvider(TypeInfo provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _provider.GetCustomAttributes(attributeType, inherit).ToArray();
}
}
protected sealed class MethodBaseCustomAttributeProvider : ICustomAttributeProvider
{
private readonly MethodBase _provider;
public MethodBaseCustomAttributeProvider(MethodBase provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _provider.GetCustomAttributes(attributeType, inherit).ToArray();
}
}
protected sealed class ParameterInfoCustomAttributeProvider : ICustomAttributeProvider
{
private readonly ParameterInfo _provider;
public ParameterInfoCustomAttributeProvider(ParameterInfo provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _provider.GetCustomAttributes(attributeType, inherit).ToArray();
}
}
protected sealed class FieldInfoCustomAttributeProvider : ICustomAttributeProvider
{
private readonly FieldInfo _provider;
public FieldInfoCustomAttributeProvider(FieldInfo provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _provider.GetCustomAttributes(attributeType, inherit).ToArray();
}
}
#else
protected static ICustomAttributeProvider AsCustomAttributeProvider(ICustomAttributeProvider obj)
{
return obj;
}
#endif
}
}
#else
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.Text;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
/// <author>Sam Harwell</author>
public class RuleDependencyChecker
{
#if false
private static readonly Logger Logger = Logger.GetLogger(typeof(Antlr4.Runtime.Misc.RuleDependencyChecker).FullName);
#endif
private const BindingFlags AllDeclaredStaticMembers = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
private const BindingFlags AllDeclaredMembers = AllDeclaredStaticMembers | BindingFlags.Instance;
private static readonly HashSet<string> checkedAssemblies = new HashSet<string>();
public static void CheckDependencies(Assembly assembly)
{
if (IsChecked(assembly))
{
return;
}
IList<Type> typesToCheck = GetTypesToCheck(assembly);
List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
foreach (Type clazz in typesToCheck)
{
dependencies.AddRange(GetDependencies(clazz));
}
if (dependencies.Count > 0)
{
IDictionary<Type, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> recognizerDependencies = new Dictionary<Type, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>>();
foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)
{
Type recognizerType = dependency.Item1.Recognizer;
IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> list;
if (!recognizerDependencies.TryGetValue(recognizerType, out list))
{
list = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
recognizerDependencies[recognizerType] = list;
}
list.Add(dependency);
}
foreach (KeyValuePair<Type, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>> entry in recognizerDependencies)
{
//processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, String.format("ANTLR 4: Validating {0} dependencies on rules in {1}.", entry.getValue().size(), entry.getKey().toString()));
CheckDependencies(entry.Value, entry.Key);
}
}
MarkChecked(assembly);
}
private static IList<Type> GetTypesToCheck(Assembly assembly)
{
return assembly.GetTypes();
}
private static bool IsChecked(Assembly assembly)
{
lock (checkedAssemblies)
{
return checkedAssemblies.Contains(assembly.FullName);
}
}
private static void MarkChecked(Assembly assembly)
{
lock (checkedAssemblies)
{
checkedAssemblies.Add(assembly.FullName);
}
}
private static void CheckDependencies(IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> dependencies, Type recognizerType)
{
string[] ruleNames = GetRuleNames(recognizerType);
int[] ruleVersions = GetRuleVersions(recognizerType, ruleNames);
RuleDependencyChecker.RuleRelations relations = ExtractRuleRelations(recognizerType);
StringBuilder errors = new StringBuilder();
foreach (Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency in dependencies)
{
if (!dependency.Item1.Recognizer.IsAssignableFrom(recognizerType))
{
continue;
}
// this is the rule in the dependency set with the highest version number
int effectiveRule = dependency.Item1.Rule;
if (effectiveRule < 0 || effectiveRule >= ruleVersions.Length)
{
string message = string.Format("Rule dependency on unknown rule {0}@{1} in {2}", dependency.Item1.Rule, dependency.Item1.Version, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
continue;
}
Dependents dependents = Dependents.Self | dependency.Item1.Dependents;
ReportUnimplementedDependents(errors, dependency, dependents);
BitSet @checked = new BitSet();
int highestRequiredDependency = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, effectiveRule, null);
if ((dependents & Dependents.Parents) != 0)
{
BitSet parents = relations.parents[dependency.Item1.Rule];
for (int parent = parents.NextSetBit(0); parent >= 0; parent = parents.NextSetBit(parent + 1))
{
if (parent < 0 || parent >= ruleVersions.Length || @checked.Get(parent))
{
continue;
}
@checked.Set(parent);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, parent, "parent");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Children) != 0)
{
BitSet children = relations.children[dependency.Item1.Rule];
for (int child = children.NextSetBit(0); child >= 0; child = children.NextSetBit(child + 1))
{
if (child < 0 || child >= ruleVersions.Length || @checked.Get(child))
{
continue;
}
@checked.Set(child);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, child, "child");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Ancestors) != 0)
{
BitSet ancestors = relations.GetAncestors(dependency.Item1.Rule);
for (int ancestor = ancestors.NextSetBit(0); ancestor >= 0; ancestor = ancestors.NextSetBit(ancestor + 1))
{
if (ancestor < 0 || ancestor >= ruleVersions.Length || @checked.Get(ancestor))
{
continue;
}
@checked.Set(ancestor);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, ancestor, "ancestor");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
if ((dependents & Dependents.Descendants) != 0)
{
BitSet descendants = relations.GetDescendants(dependency.Item1.Rule);
for (int descendant = descendants.NextSetBit(0); descendant >= 0; descendant = descendants.NextSetBit(descendant + 1))
{
if (descendant < 0 || descendant >= ruleVersions.Length || @checked.Get(descendant))
{
continue;
}
@checked.Set(descendant);
int required = CheckDependencyVersion(errors, dependency, ruleNames, ruleVersions, descendant, "descendant");
highestRequiredDependency = Math.Max(highestRequiredDependency, required);
}
}
int declaredVersion = dependency.Item1.Version;
if (declaredVersion > highestRequiredDependency)
{
string message = string.Format("Rule dependency version mismatch: {0} has maximum dependency version {1} (expected {2}) in {3}", ruleNames[dependency.Item1.Rule], highestRequiredDependency, declaredVersion, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
}
}
if (errors.Length > 0)
{
throw new InvalidOperationException(errors.ToString());
}
}
private static readonly Dependents ImplementedDependents = Dependents.Self | Dependents.Parents | Dependents.Children | Dependents.Ancestors | Dependents.Descendants;
private static void ReportUnimplementedDependents(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, Dependents dependents)
{
Dependents unimplemented = dependents;
unimplemented &= ~ImplementedDependents;
if (unimplemented != Dependents.None)
{
string message = string.Format("Cannot validate the following dependents of rule {0}: {1}", dependency.Item1.Rule, unimplemented);
errors.AppendLine(message);
}
}
private static int CheckDependencyVersion(StringBuilder errors, Tuple<RuleDependencyAttribute, ICustomAttributeProvider> dependency, string[] ruleNames, int[] ruleVersions, int relatedRule, string relation)
{
string ruleName = ruleNames[dependency.Item1.Rule];
string path;
if (relation == null)
{
path = ruleName;
}
else
{
string mismatchedRuleName = ruleNames[relatedRule];
path = string.Format("rule {0} ({1} of {2})", mismatchedRuleName, relation, ruleName);
}
int declaredVersion = dependency.Item1.Version;
int actualVersion = ruleVersions[relatedRule];
if (actualVersion > declaredVersion)
{
string message = string.Format("Rule dependency version mismatch: {0} has version {1} (expected <= {2}) in {3}", path, actualVersion, declaredVersion, dependency.Item1.Recognizer.ToString());
errors.AppendLine(dependency.Item2.ToString());
errors.AppendLine(message);
}
return actualVersion;
}
private static int[] GetRuleVersions(Type recognizerClass, string[] ruleNames)
{
int[] versions = new int[ruleNames.Length];
FieldInfo[] fields = recognizerClass.GetFields();
foreach (FieldInfo field in fields)
{
bool isStatic = field.IsStatic;
bool isInteger = field.FieldType == typeof(int);
if (isStatic && isInteger && field.Name.StartsWith("RULE_"))
{
try
{
string name = field.Name.Substring("RULE_".Length);
if (name.Length == 0 || !System.Char.IsLower(name[0]))
{
continue;
}
int index = (int)field.GetValue(null);
if (index < 0 || index >= versions.Length)
{
#if false
object[] @params = new object[] { index, field.Name, recognizerClass.Name };
Logger.Log(Level.Warning, "Rule index {0} for rule ''{1}'' out of bounds for recognizer {2}.", @params);
#endif
continue;
}
MethodInfo ruleMethod = GetRuleMethod(recognizerClass, name);
if (ruleMethod == null)
{
#if false
object[] @params = new object[] { name, recognizerClass.Name };
Logger.Log(Level.Warning, "Could not find rule method for rule ''{0}'' in recognizer {1}.", @params);
#endif
continue;
}
RuleVersionAttribute ruleVersion = (RuleVersionAttribute)Attribute.GetCustomAttribute(ruleMethod, typeof(RuleVersionAttribute));
int version = ruleVersion != null ? ruleVersion.Version : 0;
versions[index] = version;
}
catch (ArgumentException)
{
#if false
Logger.Log(Level.Warning, null, ex);
#else
throw;
#endif
}
catch (MemberAccessException)
{
#if false
Logger.Log(Level.Warning, null, ex);
#else
throw;
#endif
}
}
}
return versions;
}
private static MethodInfo GetRuleMethod(Type recognizerClass, string name)
{
MethodInfo[] declaredMethods = recognizerClass.GetMethods();
foreach (MethodInfo method in declaredMethods)
{
if (method.Name.Equals(name) && Attribute.IsDefined(method, typeof(RuleVersionAttribute)))
{
return method;
}
}
return null;
}
private static string[] GetRuleNames(Type recognizerClass)
{
FieldInfo ruleNames = recognizerClass.GetField("ruleNames");
return (string[])ruleNames.GetValue(null);
}
public static IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> GetDependencies(Type clazz)
{
IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result = new List<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>>();
GetElementDependencies(AsCustomAttributeProvider(clazz), result);
foreach (ConstructorInfo ctor in clazz.GetConstructors(AllDeclaredMembers))
{
GetElementDependencies(AsCustomAttributeProvider(ctor), result);
foreach (ParameterInfo parameter in ctor.GetParameters())
GetElementDependencies(AsCustomAttributeProvider(parameter), result);
}
foreach (FieldInfo field in clazz.GetFields(AllDeclaredMembers))
{
GetElementDependencies(AsCustomAttributeProvider(field), result);
}
foreach (MethodInfo method in clazz.GetMethods(AllDeclaredMembers))
{
GetElementDependencies(AsCustomAttributeProvider(method), result);
#if COMPACT
if (method.ReturnTypeCustomAttributes != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnTypeCustomAttributes), result);
#else
if (method.ReturnParameter != null)
GetElementDependencies(AsCustomAttributeProvider(method.ReturnParameter), result);
#endif
foreach (ParameterInfo parameter in method.GetParameters())
GetElementDependencies(AsCustomAttributeProvider(parameter), result);
}
return result;
}
private static void GetElementDependencies(ICustomAttributeProvider annotatedElement, IList<Tuple<RuleDependencyAttribute, ICustomAttributeProvider>> result)
{
foreach (RuleDependencyAttribute dependency in annotatedElement.GetCustomAttributes(typeof(RuleDependencyAttribute), true))
{
result.Add(Tuple.Create(dependency, annotatedElement));
}
}
private static RuleDependencyChecker.RuleRelations ExtractRuleRelations(Type recognizer)
{
string serializedATN = GetSerializedATN(recognizer);
if (serializedATN == null)
{
return null;
}
ATN atn = new ATNDeserializer().Deserialize(serializedATN.ToCharArray());
RuleDependencyChecker.RuleRelations relations = new RuleDependencyChecker.RuleRelations(atn.ruleToStartState.Length);
foreach (ATNState state in atn.states)
{
if (!state.epsilonOnlyTransitions)
{
continue;
}
foreach (Transition transition in state.transitions)
{
if (transition.TransitionType != TransitionType.Rule)
{
continue;
}
RuleTransition ruleTransition = (RuleTransition)transition;
relations.AddRuleInvocation(state.ruleIndex, ruleTransition.target.ruleIndex);
}
}
return relations;
}
private static string GetSerializedATN(Type recognizerClass)
{
FieldInfo serializedAtnField = recognizerClass.GetField("_serializedATN", AllDeclaredStaticMembers);
if (serializedAtnField != null)
return (string)serializedAtnField.GetValue(null);
if (recognizerClass.BaseType != null)
return GetSerializedATN(recognizerClass.BaseType);
return null;
}
private sealed class RuleRelations
{
public readonly BitSet[] parents;
public readonly BitSet[] children;
public RuleRelations(int ruleCount)
{
parents = new BitSet[ruleCount];
for (int i = 0; i < ruleCount; i++)
{
parents[i] = new BitSet();
}
children = new BitSet[ruleCount];
for (int i_1 = 0; i_1 < ruleCount; i_1++)
{
children[i_1] = new BitSet();
}
}
public bool AddRuleInvocation(int caller, int callee)
{
if (caller < 0)
{
// tokens rule
return false;
}
if (children[caller].Get(callee))
{
// already added
return false;
}
children[caller].Set(callee);
parents[callee].Set(caller);
return true;
}
public BitSet GetAncestors(int rule)
{
BitSet ancestors = new BitSet();
ancestors.Or(parents[rule]);
while (true)
{
int cardinality = ancestors.Cardinality();
for (int i = ancestors.NextSetBit(0); i >= 0; i = ancestors.NextSetBit(i + 1))
{
ancestors.Or(parents[i]);
}
if (ancestors.Cardinality() == cardinality)
{
// nothing changed
break;
}
}
return ancestors;
}
public BitSet GetDescendants(int rule)
{
BitSet descendants = new BitSet();
descendants.Or(children[rule]);
while (true)
{
int cardinality = descendants.Cardinality();
for (int i = descendants.NextSetBit(0); i >= 0; i = descendants.NextSetBit(i + 1))
{
descendants.Or(children[i]);
}
if (descendants.Cardinality() == cardinality)
{
// nothing changed
break;
}
}
return descendants;
}
}
private RuleDependencyChecker()
{
}
#if PORTABLE
public interface ICustomAttributeProvider
{
object[] GetCustomAttributes(Type attributeType, bool inherit);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(Type type)
{
return new TypeCustomAttributeProvider(type);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(MethodBase method)
{
return new MethodBaseCustomAttributeProvider(method);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(ParameterInfo parameter)
{
return new ParameterInfoCustomAttributeProvider(parameter);
}
protected static ICustomAttributeProvider AsCustomAttributeProvider(FieldInfo field)
{
return new FieldInfoCustomAttributeProvider(field);
}
protected sealed class TypeCustomAttributeProvider : ICustomAttributeProvider
{
private readonly Type _provider;
public TypeCustomAttributeProvider(Type provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
protected sealed class MethodBaseCustomAttributeProvider : ICustomAttributeProvider
{
private readonly MethodBase _provider;
public MethodBaseCustomAttributeProvider(MethodBase provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
protected sealed class ParameterInfoCustomAttributeProvider : ICustomAttributeProvider
{
private readonly ParameterInfo _provider;
public ParameterInfoCustomAttributeProvider(ParameterInfo provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
protected sealed class FieldInfoCustomAttributeProvider : ICustomAttributeProvider
{
private readonly FieldInfo _provider;
public FieldInfoCustomAttributeProvider(FieldInfo provider)
{
_provider = provider;
}
public object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return Attribute.GetCustomAttributes(_provider, attributeType, inherit);
}
}
#else
protected static ICustomAttributeProvider AsCustomAttributeProvider(ICustomAttributeProvider obj)
{
return obj;
}
#endif
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace ApiFox.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Online.Multiplayer;
using osu.Game.Online.Spectator;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osu.Game.Screens.Spectate;
namespace osu.Game.Screens.OnlinePlay.Multiplayer.Spectate
{
/// <summary>
/// A <see cref="SpectatorScreen"/> that spectates multiple users in a match.
/// </summary>
public class MultiSpectatorScreen : SpectatorScreen
{
// Isolates beatmap/ruleset to this screen.
public override bool DisallowExternalBeatmapRulesetChanges => true;
// We are managing our own adjustments. For now, this happens inside the Player instances themselves.
public override bool? AllowTrackAdjustments => false;
/// <summary>
/// Whether all spectating players have finished loading.
/// </summary>
public bool AllPlayersLoaded => instances.All(p => p?.PlayerLoaded == true);
[Resolved]
private OsuColour colours { get; set; }
[Resolved]
private SpectatorClient spectatorClient { get; set; }
[Resolved]
private MultiplayerClient multiplayerClient { get; set; }
private readonly PlayerArea[] instances;
private MasterGameplayClockContainer masterClockContainer;
private ISyncManager syncManager;
private PlayerGrid grid;
private MultiSpectatorLeaderboard leaderboard;
private PlayerArea currentAudioSource;
private bool canStartMasterClock;
private readonly MultiplayerRoomUser[] users;
/// <summary>
/// Creates a new <see cref="MultiSpectatorScreen"/>.
/// </summary>
/// <param name="users">The players to spectate.</param>
public MultiSpectatorScreen(MultiplayerRoomUser[] users)
: base(users.Select(u => u.UserID).ToArray())
{
this.users = users;
instances = new PlayerArea[Users.Count];
}
[BackgroundDependencyLoader]
private void load()
{
Container leaderboardContainer;
Container scoreDisplayContainer;
masterClockContainer = new MasterGameplayClockContainer(Beatmap.Value, 0);
InternalChildren = new[]
{
(Drawable)(syncManager = new CatchUpSyncManager(masterClockContainer)),
masterClockContainer.WithChild(new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize) },
Content = new[]
{
new Drawable[]
{
scoreDisplayContainer = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
},
},
new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize) },
Content = new[]
{
new Drawable[]
{
leaderboardContainer = new Container
{
RelativeSizeAxes = Axes.Y,
AutoSizeAxes = Axes.X
},
grid = new PlayerGrid { RelativeSizeAxes = Axes.Both }
}
}
}
}
}
})
};
for (int i = 0; i < Users.Count; i++)
{
grid.Add(instances[i] = new PlayerArea(Users[i], masterClockContainer.GameplayClock));
syncManager.AddPlayerClock(instances[i].GameplayClock);
}
// Todo: This is not quite correct - it should be per-user to adjust for other mod combinations.
var playableBeatmap = Beatmap.Value.GetPlayableBeatmap(Ruleset.Value);
var scoreProcessor = Ruleset.Value.CreateInstance().CreateScoreProcessor();
scoreProcessor.ApplyBeatmap(playableBeatmap);
LoadComponentAsync(leaderboard = new MultiSpectatorLeaderboard(scoreProcessor, users)
{
Expanded = { Value = true },
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
}, l =>
{
foreach (var instance in instances)
leaderboard.AddClock(instance.UserId, instance.GameplayClock);
leaderboardContainer.Add(leaderboard);
if (leaderboard.TeamScores.Count == 2)
{
LoadComponentAsync(new MatchScoreDisplay
{
Team1Score = { BindTarget = leaderboard.TeamScores.First().Value },
Team2Score = { BindTarget = leaderboard.TeamScores.Last().Value },
}, scoreDisplayContainer.Add);
}
});
}
protected override void LoadComplete()
{
base.LoadComplete();
masterClockContainer.Reset();
masterClockContainer.Stop();
syncManager.ReadyToStart += onReadyToStart;
syncManager.MasterState.BindValueChanged(onMasterStateChanged, true);
}
protected override void Update()
{
base.Update();
if (!isCandidateAudioSource(currentAudioSource?.GameplayClock))
{
currentAudioSource = instances.Where(i => isCandidateAudioSource(i.GameplayClock))
.OrderBy(i => Math.Abs(i.GameplayClock.CurrentTime - syncManager.MasterClock.CurrentTime))
.FirstOrDefault();
foreach (var instance in instances)
instance.Mute = instance != currentAudioSource;
}
}
private bool isCandidateAudioSource([CanBeNull] ISpectatorPlayerClock clock)
=> clock?.IsRunning == true && !clock.IsCatchingUp && !clock.WaitingOnFrames.Value;
private void onReadyToStart()
{
// Seek the master clock to the gameplay time.
// This is chosen as the first available frame in the players' replays, which matches the seek by each individual SpectatorPlayer.
var startTime = instances.Where(i => i.Score != null)
.SelectMany(i => i.Score.Replay.Frames)
.Select(f => f.Time)
.DefaultIfEmpty(0)
.Min();
masterClockContainer.Seek(startTime);
masterClockContainer.Start();
// Although the clock has been started, this flag is set to allow for later synchronisation state changes to also be able to start it.
canStartMasterClock = true;
}
private void onMasterStateChanged(ValueChangedEvent<MasterClockState> state)
{
switch (state.NewValue)
{
case MasterClockState.Synchronised:
if (canStartMasterClock)
masterClockContainer.Start();
break;
case MasterClockState.TooFarAhead:
masterClockContainer.Stop();
break;
}
}
protected override void OnUserStateChanged(int userId, SpectatorState spectatorState)
{
}
protected override void StartGameplay(int userId, SpectatorGameplayState spectatorGameplayState)
=> instances.Single(i => i.UserId == userId).LoadScore(spectatorGameplayState.Score);
protected override void EndGameplay(int userId)
{
RemoveUser(userId);
var instance = instances.Single(i => i.UserId == userId);
instance.FadeColour(colours.Gray4, 400, Easing.OutQuint);
syncManager.RemovePlayerClock(instance.GameplayClock);
leaderboard.RemoveClock(userId);
}
public override bool OnBackButton()
{
// On a manual exit, set the player state back to idle.
multiplayerClient.ChangeState(MultiplayerUserState.Idle);
return base.OnBackButton();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace /*<com>*/Finegamedesign.Utils
{
//
// Another option is an extension method.
// In-case someone else already made a different extension method,
// or the language has different syntax, I used static functions.
// For examples of divergent syntax:
// ActionScript: items.length
// C#: items.Count
// Python: len(items)
// Some of these use different method names or property names in different languages.
//
public sealed class DataUtil
{
// http://stackoverflow.com/questions/222598/how-do-i-clone-a-generic-list-in-c
public static List<T> CloneList<T>(List<T> original)
{
return new List<T>(original);
}
public static int Length<T>(List<T> data)
{
return data.Count;
}
public static int Length<T, U>(Dictionary<T, U> items)
{
return items.Count;
}
public static int Length(ArrayList elements)
{
return elements.Count;
}
public static int Length<T>(T[] elements)
{
return elements.Length;
}
public static int Length(string text)
{
return text.Length;
}
public static int IndexOf<T>(ArrayList elements, T target)
{
return elements.IndexOf(target);
}
public static int IndexOf<T>(List<T> elements, T target)
{
return elements.IndexOf(target);
}
public static int IndexOf<T>(T[] elements, T target)
{
return Array.IndexOf(elements, target);
}
public static int IndexOf(string text, string target)
{
return text.IndexOf(target);
}
public static int LastIndexOf<T>(ArrayList elements, T target)
{
return elements.LastIndexOf(target);
}
public static int LastIndexOf<T>(List<T> elements, T target)
{
return elements.LastIndexOf(target);
}
public static int LastIndexOf<T>(T[] elements, T target)
{
return Array.LastIndexOf(elements, target);
}
public static int LastIndexOf(string text, string target)
{
return text.LastIndexOf(target);
}
public static void Clear<T>(T[] items, int startIndex = 0)
{
Array.Clear(items, startIndex, items.Length);
}
public static void Clear(ArrayList items, int startIndex = 0)
{
if (0 == startIndex)
{
items.Clear();
}
else
{
items.RemoveRange(startIndex, items.Count - startIndex);
}
}
public static void Clear<T>(List<T> items, int startIndex = 0)
{
if (0 == startIndex)
{
items.Clear();
}
else
{
items.RemoveRange(startIndex, items.Count - startIndex);
}
}
/**
* Is integer or single floating point.
*/
public static bool IsNumber(string text)
{
float n;
return float.TryParse(text, out n);
}
/**
* Is data type flat or a class or collection?
*/
public static bool IsFlat(object value)
{
return (bool)((value is string) || (value is float)
|| (value is int) || (null == value));
}
public static ArrayList SplitToArrayList(string text, string delimiter)
{
return new ArrayList(Split(text, delimiter));
}
//
// I wish C# API were as simple as JavaScript and Python:
// http://stackoverflow.com/questions/1126915/how-do-i-split-a-string-by-a-multi-character-delimiter-in-c
//
public static List<string> Split(string text, string delimiter)
{
if ("" == delimiter) {
return SplitString(text);
}
else {
string[] delimiters = new string[] {delimiter};
string[] parts = text.Split(delimiters, StringSplitOptions.None);
List<string> list = new List<string>(parts);
return list;
}
}
//
// This was the most concise way I found to split a string without depending on a library.
// In ActionScript splitting a string is concise: s.split("");
// C# has characters, which would be more efficient, though less portable.
//
public static List<string> SplitString(string text)
{
List<string> letters = new List<string>();
char[] characters = text.ToCharArray();
for (int i = 0; i < characters.Length; i++) {
letters.Add(characters[i].ToString());
}
return letters;
}
// Without depending on LINQ or that each item is already a string.
public static string Join(ArrayList items, string delimiter)
{
string[] parts = new string[items.Count];
for (int index = 0; index < items.Count; index++) {
parts[index] = items[index].ToString();
}
string joined = string.Join(delimiter, parts);
return joined;
}
public static string Join(List<string> texts, string delimiter)
{
string[] parts = (string[]) texts.ToArray();
string joined = string.Join(delimiter, parts);
return joined;
}
public static string Join(List<int> numbers, string delimiter)
{
int length = numbers.Count;
string[] parts = new string[length];
for (int index = 0; index < length; index++)
{
parts[index] = numbers[index].ToString();
}
string joined = string.Join(delimiter, parts);
return joined;
}
public static string Trim(string text)
{
return text.Trim();
}
public static string Replace(string text, string from, string to)
{
return Join(Split(text, from), to);
}
public static string Join<T>(List<T> items, string delimiter)
{
string[] parts = new string[items.Count];
for (int i = 0; i < items.Count; i++) {
parts[i] = items[i].ToString();
}
string joined = string.Join(delimiter, parts);
return joined;
}
public static T Pop<T>(List<T> items)
{
T item = (T)items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return item;
}
public static object Pop(ArrayList items)
{
object item = items[items.Count - 1];
items.RemoveAt(items.Count - 1);
return item;
}
public static void RemoveAt<T>(List<T> items, int index)
{
items.RemoveAt(index);
}
public static void RemoveAt(ArrayList items, int index)
{
items.RemoveAt(index);
}
public static List<T> Slice<T>(List<T> items, int start, int end)
{
List<T> sliced = new List<T>();
for (int index = start; index < end; index++) {
sliced.Add(items[index]);
}
return sliced;
}
public static ArrayList Slice(ArrayList items, int start, int end)
{
ArrayList sliced = new ArrayList();
for (int index = start; index < end; index++) {
sliced.Add(items[index]);
}
return sliced;
}
public static T Shift<T>(List<T> items)
{
T item = (T)items[0];
items.RemoveAt(0);
return item;
}
public static object Shift(ArrayList items)
{
object item = items[0];
items.RemoveAt(0);
return item;
}
public static List<T> ToListItems<T>(T[] rest)
{
List<T> aList = new List<T>();
for (int i = 0; i < rest.Length; i++) {
aList.Add(rest[i]);
}
return aList;
}
public static List<T> ToList<T>(params T[] rest)
{
List<T> aList = new List<T>();
for (int i = 0; i < rest.Length; i++) {
aList.Add(rest[i]);
}
return aList;
}
public static List<T> ToListItems<T>(ArrayList elements)
{
List<T> aList = new List<T>();
for (int i = 0; i < elements.Count; i++) {
aList.Add((T)elements[i]);
}
return aList;
}
public static ArrayList ToArrayList<T>(List<T> aList)
{
ArrayList items = new ArrayList();
for (int i = 0; i < aList.Count; i++) {
aList.Add(aList[i]);
}
return items;
}
}
}
| |
// 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;
/// <summary>
/// Sign(System.Double)
/// </summary>
public class MathSign2
{
public static int Main(string[] args)
{
MathSign2 test = new MathSign2();
TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Sign(System.Double).");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
TestLibrary.TestFramework.LogInformation("[Negtive]");
retVal = NegTest1() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Double.MaxValue is a positive number.");
try
{
Double d = Double.MaxValue;
if (Math.Sign(d) != 1)
{
TestLibrary.TestFramework.LogError("P01.1", "Double.MaxValue is not a positive number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify Double.MinValue is a negative number.");
try
{
Double d = Double.MinValue;
if (Math.Sign(d) != -1)
{
TestLibrary.TestFramework.LogError("P02.1", "Double.MinValue is not a negative number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify Double.PositiveInfinity is a positive number.");
try
{
Double d = Double.PositiveInfinity;
if (Math.Sign(d) != 1)
{
TestLibrary.TestFramework.LogError("P03.1", "Double.PositiveInfinity is not a positive number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify Double.NegativeInfinity is a negative number.");
try
{
Double d = Double.NegativeInfinity;
if (Math.Sign(d) != -1)
{
TestLibrary.TestFramework.LogError("P04.1", "Double.NegativeInfinity is not a negative number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify Double.Epsilon is a positive number.");
try
{
Double d = Double.Epsilon;
if (Math.Sign(d) != 1)
{
TestLibrary.TestFramework.LogError("P05.1", "Double.Epsilon is not a positive number!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the return value should be 1 when the Double is positive.");
try
{
Double d = TestLibrary.Generator.GetDouble(-55);
while (d <= 0)
{
d = TestLibrary.Generator.GetDouble(-55);
}
if (Math.Sign(d) != 1)
{
TestLibrary.TestFramework.LogError("P06.1", "The return value is not 1 when the Double is positive!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the return value should be -1 when the Double is negative.");
try
{
Double d = TestLibrary.Generator.GetDouble(-55);
while (d <= 0)
{
d = TestLibrary.Generator.GetDouble(-55);
}
if (Math.Sign(-d) != -1)
{
TestLibrary.TestFramework.LogError("P07.1", "The return value is not -1 when the Double is negative!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest8: Verify the return value should be 0 when the Double is zero.");
try
{
Double d = 0.0d;
if (Math.Sign(d) != 0)
{
TestLibrary.TestFramework.LogError("P08.1", "The return value is not -1 when the Double is negative!");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("P08.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArithmeticException should be thrown when value is equal to NaN.");
try
{
Double d = Double.NaN;
Math.Sign(d);
TestLibrary.TestFramework.LogError("N01.1", "ArithmeticException is not thrown when value is equal to NaN!");
retVal = false;
}
catch (ArithmeticException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N01.2", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="ConversionActionServiceClient"/> instances.</summary>
public sealed partial class ConversionActionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ConversionActionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ConversionActionServiceSettings"/>.</returns>
public static ConversionActionServiceSettings GetDefault() => new ConversionActionServiceSettings();
/// <summary>
/// Constructs a new <see cref="ConversionActionServiceSettings"/> object with default settings.
/// </summary>
public ConversionActionServiceSettings()
{
}
private ConversionActionServiceSettings(ConversionActionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetConversionActionSettings = existing.GetConversionActionSettings;
MutateConversionActionsSettings = existing.MutateConversionActionsSettings;
OnCopy(existing);
}
partial void OnCopy(ConversionActionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionActionServiceClient.GetConversionAction</c> and
/// <c>ConversionActionServiceClient.GetConversionActionAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetConversionActionSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>ConversionActionServiceClient.MutateConversionActions</c> and
/// <c>ConversionActionServiceClient.MutateConversionActionsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateConversionActionsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ConversionActionServiceSettings"/> object.</returns>
public ConversionActionServiceSettings Clone() => new ConversionActionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="ConversionActionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class ConversionActionServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionActionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ConversionActionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ConversionActionServiceClientBuilder()
{
UseJwtAccessWithScopes = ConversionActionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ConversionActionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionActionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override ConversionActionServiceClient Build()
{
ConversionActionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ConversionActionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ConversionActionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ConversionActionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ConversionActionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<ConversionActionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ConversionActionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ConversionActionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionActionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionActionServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>ConversionActionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion actions.
/// </remarks>
public abstract partial class ConversionActionServiceClient
{
/// <summary>
/// The default endpoint for the ConversionActionService service, which is a host of "googleads.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default ConversionActionService scopes.</summary>
/// <remarks>
/// The default ConversionActionService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="ConversionActionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionActionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ConversionActionServiceClient"/>.</returns>
public static stt::Task<ConversionActionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ConversionActionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ConversionActionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="ConversionActionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ConversionActionServiceClient"/>.</returns>
public static ConversionActionServiceClient Create() => new ConversionActionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ConversionActionServiceClient"/> which uses the specified call invoker for remote
/// operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="ConversionActionServiceSettings"/>.</param>
/// <returns>The created <see cref="ConversionActionServiceClient"/>.</returns>
internal static ConversionActionServiceClient Create(grpccore::CallInvoker callInvoker, ConversionActionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
ConversionActionService.ConversionActionServiceClient grpcClient = new ConversionActionService.ConversionActionServiceClient(callInvoker);
return new ConversionActionServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC ConversionActionService client</summary>
public virtual ConversionActionService.ConversionActionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionAction GetConversionAction(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionAction> GetConversionActionAsync(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionAction> GetConversionActionAsync(GetConversionActionRequest request, st::CancellationToken cancellationToken) =>
GetConversionActionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionAction GetConversionAction(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionAction(new GetConversionActionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionAction> GetConversionActionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionActionAsync(new GetConversionActionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion action to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionAction> GetConversionActionAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetConversionActionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::ConversionAction GetConversionAction(gagvr::ConversionActionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionAction(new GetConversionActionRequest
{
ResourceNameAsConversionActionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion action to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionAction> GetConversionActionAsync(gagvr::ConversionActionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetConversionActionAsync(new GetConversionActionRequest
{
ResourceNameAsConversionActionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the conversion action to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::ConversionAction> GetConversionActionAsync(gagvr::ConversionActionName resourceName, st::CancellationToken cancellationToken) =>
GetConversionActionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateConversionActionsResponse MutateConversionActions(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, st::CancellationToken cancellationToken) =>
MutateConversionActionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion actions.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateConversionActionsResponse MutateConversionActions(string customerId, scg::IEnumerable<ConversionActionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionActions(new MutateConversionActionsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion actions.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionActionsResponse> MutateConversionActionsAsync(string customerId, scg::IEnumerable<ConversionActionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateConversionActionsAsync(new MutateConversionActionsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose conversion actions are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual conversion actions.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateConversionActionsResponse> MutateConversionActionsAsync(string customerId, scg::IEnumerable<ConversionActionOperation> operations, st::CancellationToken cancellationToken) =>
MutateConversionActionsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>ConversionActionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage conversion actions.
/// </remarks>
public sealed partial class ConversionActionServiceClientImpl : ConversionActionServiceClient
{
private readonly gaxgrpc::ApiCall<GetConversionActionRequest, gagvr::ConversionAction> _callGetConversionAction;
private readonly gaxgrpc::ApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse> _callMutateConversionActions;
/// <summary>
/// Constructs a client wrapper for the ConversionActionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="ConversionActionServiceSettings"/> used within this client.
/// </param>
public ConversionActionServiceClientImpl(ConversionActionService.ConversionActionServiceClient grpcClient, ConversionActionServiceSettings settings)
{
GrpcClient = grpcClient;
ConversionActionServiceSettings effectiveSettings = settings ?? ConversionActionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetConversionAction = clientHelper.BuildApiCall<GetConversionActionRequest, gagvr::ConversionAction>(grpcClient.GetConversionActionAsync, grpcClient.GetConversionAction, effectiveSettings.GetConversionActionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetConversionAction);
Modify_GetConversionActionApiCall(ref _callGetConversionAction);
_callMutateConversionActions = clientHelper.BuildApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse>(grpcClient.MutateConversionActionsAsync, grpcClient.MutateConversionActions, effectiveSettings.MutateConversionActionsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateConversionActions);
Modify_MutateConversionActionsApiCall(ref _callMutateConversionActions);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetConversionActionApiCall(ref gaxgrpc::ApiCall<GetConversionActionRequest, gagvr::ConversionAction> call);
partial void Modify_MutateConversionActionsApiCall(ref gaxgrpc::ApiCall<MutateConversionActionsRequest, MutateConversionActionsResponse> call);
partial void OnConstruction(ConversionActionService.ConversionActionServiceClient grpcClient, ConversionActionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC ConversionActionService client</summary>
public override ConversionActionService.ConversionActionServiceClient GrpcClient { get; }
partial void Modify_GetConversionActionRequest(ref GetConversionActionRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateConversionActionsRequest(ref MutateConversionActionsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::ConversionAction GetConversionAction(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetConversionActionRequest(ref request, ref callSettings);
return _callGetConversionAction.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested conversion action.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::ConversionAction> GetConversionActionAsync(GetConversionActionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetConversionActionRequest(ref request, ref callSettings);
return _callGetConversionAction.Async(request, callSettings);
}
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateConversionActionsResponse MutateConversionActions(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionActionsRequest(ref request, ref callSettings);
return _callMutateConversionActions.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates or removes conversion actions. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [ConversionActionError]()
/// [CurrencyCodeError]()
/// [DatabaseError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [StringLengthError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateConversionActionsResponse> MutateConversionActionsAsync(MutateConversionActionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateConversionActionsRequest(ref request, ref callSettings);
return _callMutateConversionActions.Async(request, callSettings);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Xunit;
public static unsafe class UriTests
{
// Bug 740420
[Fact]
public static void TestAppxName()
{
if (TestRunner.TestRunner.OnCoreCLR)
return;
bool ret = true;
try
{
Uri _uri = new Uri("ms-app://s-1-15-2-3682223341-1746277572-4098775175-2728279147-2871887747-149063373-1758401009/");
}
catch (Exception)
{
ret = false;
}
Assert.True(ret);
}
[Fact]
public static void TestCtor_String()
{
Uri uri = new Uri(@"http://foo/bar/baz#frag");
int i;
String s;
bool b;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://foo/bar/baz#frag");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/bar/baz");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://foo/bar/baz#frag");
s = uri.Authority;
Assert.Equal<String>(s, @"foo");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"foo");
s = uri.Fragment;
Assert.Equal<String>(s, @"#frag");
s = uri.Host;
Assert.Equal<String>(s, @"foo");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/bar/baz");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://foo/bar/baz#frag");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/bar/baz");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"bar/");
Assert.Equal<String>(ss[2], @"baz");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestCtor_Uri_String()
{
Uri uri;
uri = new Uri(@"http://www.contoso.com/");
uri = new Uri(uri, "catalog/shownew.htm?date=today");
int i;
String s;
bool b;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestCtor_String_UriKind()
{
Uri uri = new Uri("catalog/shownew.htm?date=today", UriKind.Relative);
String s;
bool b;
s = uri.ToString();
Assert.Equal(s, @"catalog/shownew.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsolutePath; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsoluteUri; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Authority; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.DnsSafeHost; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Fragment; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Host; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.HostNameType; });
Assert.False(uri.IsAbsoluteUri);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsDefaultPort; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsFile; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsLoopback; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsUnc; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.LocalPath; });
s = uri.OriginalString;
Assert.Equal<String>(s, @"catalog/shownew.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.PathAndQuery; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Port; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Query; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Scheme; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Segments; });
b = uri.UserEscaped;
Assert.False(b);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.UserInfo; });
}
[Fact]
public static void TestCtor_Uri_Uri()
{
Uri absoluteUri = new Uri("http://www.contoso.com/");
// Create a relative Uri from a string. allowRelative = true to allow for
// creating a relative Uri.
Uri relativeUri = new Uri("/catalog/shownew.htm?date=today", UriKind.Relative);
// Create a new Uri from an absolute Uri and a relative Uri.
Uri uri = new Uri(absoluteUri, relativeUri);
int i;
String s;
bool b;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestTryCreate_String_UriKind()
{
Uri uri;
bool b = Uri.TryCreate("http://www.contoso.com/catalog/shownew.htm?date=today", UriKind.Absolute, out uri);
Assert.True(b);
int i;
String s;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestTryCreate_Uri_String()
{
Uri uri;
Uri baseUri = new Uri("http://www.contoso.com/", UriKind.Absolute);
bool b = Uri.TryCreate(baseUri, "catalog/shownew.htm?date=today", out uri);
Assert.True(b);
int i;
String s;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestTryCreate_Uri_Uri()
{
Uri uri;
Uri baseUri = new Uri("http://www.contoso.com/", UriKind.Absolute);
Uri relativeUri = new Uri("catalog/shownew.htm?date=today", UriKind.Relative);
bool b = Uri.TryCreate(baseUri, relativeUri, out uri);
Assert.True(b);
int i;
String s;
UriHostNameType uriHostNameType;
String[] ss;
s = uri.ToString();
Assert.Equal(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.AbsolutePath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.AbsoluteUri;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.Authority;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.DnsSafeHost;
Assert.Equal<String>(s, @"www.contoso.com");
s = uri.Fragment;
Assert.Equal<String>(s, @"");
s = uri.Host;
Assert.Equal<String>(s, @"www.contoso.com");
uriHostNameType = uri.HostNameType;
Assert.Equal<UriHostNameType>(uriHostNameType, UriHostNameType.Dns);
b = uri.IsAbsoluteUri;
Assert.True(b);
b = uri.IsDefaultPort;
Assert.True(b);
b = uri.IsFile;
Assert.False(b);
b = uri.IsLoopback;
Assert.False(b);
b = uri.IsUnc;
Assert.False(b);
s = uri.LocalPath;
Assert.Equal<String>(s, @"/catalog/shownew.htm");
s = uri.OriginalString;
Assert.Equal<String>(s, @"http://www.contoso.com/catalog/shownew.htm?date=today");
s = uri.PathAndQuery;
Assert.Equal<String>(s, @"/catalog/shownew.htm?date=today");
i = uri.Port;
Assert.Equal<int>(i, 80);
s = uri.Query;
Assert.Equal<String>(s, @"?date=today");
s = uri.Scheme;
Assert.Equal<String>(s, @"http");
ss = uri.Segments;
Assert.Equal<int>(ss.Length, 3);
Assert.Equal<String>(ss[0], @"/");
Assert.Equal<String>(ss[1], @"catalog/");
Assert.Equal<String>(ss[2], @"shownew.htm");
b = uri.UserEscaped;
Assert.False(b);
s = uri.UserInfo;
Assert.Equal<String>(s, @"");
}
[Fact]
public static void TestMakeRelative()
{
// Create a base Uri.
Uri address1 = new Uri("http://www.contoso.com/");
// Create a new Uri from a string.
Uri address2 = new Uri("http://www.contoso.com/index.htm?date=today");
// Determine the relative Uri.
Uri uri = address1.MakeRelativeUri(address2);
String s;
bool b;
s = uri.ToString();
Assert.Equal(s, @"index.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsolutePath; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.AbsoluteUri; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Authority; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.DnsSafeHost; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Fragment; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Host; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.HostNameType; });
b = uri.IsAbsoluteUri;
Assert.False(b);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsDefaultPort; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsFile; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsLoopback; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.IsUnc; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.LocalPath; });
s = uri.OriginalString;
Assert.Equal<String>(s, @"index.htm?date=today");
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.PathAndQuery; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Port; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Query; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Scheme; });
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.Segments; });
b = uri.UserEscaped;
Assert.False(b);
Assert.Throws<System.InvalidOperationException>(() => { Object o = uri.UserInfo; });
}
[Fact]
public static void TestCheckHostName()
{
UriHostNameType u;
u = Uri.CheckHostName("www.contoso.com");
Assert.Equal(u, UriHostNameType.Dns);
u = Uri.CheckHostName("1.2.3.4");
Assert.Equal(u, UriHostNameType.IPv4);
u = Uri.CheckHostName(null);
Assert.Equal(u, UriHostNameType.Unknown);
u = Uri.CheckHostName("!@*(@#&*#$&*#");
Assert.Equal(u, UriHostNameType.Unknown);
}
[Fact]
public static void TestCheckSchemeName()
{
bool b;
b = Uri.CheckSchemeName("http");
Assert.True(b);
b = Uri.CheckSchemeName(null);
Assert.False(b);
b = Uri.CheckSchemeName("!");
Assert.False(b);
}
[Fact]
public static void TestIsBaseOf()
{
bool b;
Uri uri, uri2;
uri = new Uri("http://host/path/path/file?query");
uri2 = new Uri(@"http://host/path/path/file/");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/#fragment");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri("http://host/path/path/MoreDir/\"");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/OtherFile?Query");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path/file");
b = uri.IsBaseOf(uri2);
Assert.True(b);
uri2 = new Uri(@"http://host/path/path");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path?query");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path#Fragment");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path2/");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/path2/MoreDir");
b = uri.IsBaseOf(uri2);
Assert.False(b);
uri2 = new Uri(@"http://host/path/File");
b = uri.IsBaseOf(uri2);
Assert.False(b);
}
[Fact]
public static void TestIsWellFormedOriginalString()
{
Uri uri;
bool b;
uri = new Uri("http://www.contoso.com/path?name");
b = uri.IsWellFormedOriginalString();
Assert.True(b);
uri = new Uri("http://www.contoso.com/path???/file name");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
uri = new Uri(@"c:\\directory\filename");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
uri = new Uri(@"file://c:/directory/filename");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
uri = new Uri(@"http:\\host/path/file");
b = uri.IsWellFormedOriginalString();
Assert.False(b);
}
[Fact]
public static void TestIsWellFormedUriString()
{
bool b;
b = Uri.IsWellFormedUriString("http://www.contoso.com/path?name", UriKind.RelativeOrAbsolute);
Assert.True(b);
b = Uri.IsWellFormedUriString("http://www.contoso.com/path???/file name", UriKind.RelativeOrAbsolute);
Assert.False(b);
b = Uri.IsWellFormedUriString(@"c:\\directory\filename", UriKind.RelativeOrAbsolute);
Assert.False(b);
b = Uri.IsWellFormedUriString(@"file://c:/directory/filename", UriKind.RelativeOrAbsolute);
Assert.False(b);
b = Uri.IsWellFormedUriString(@"http:\\host/path/file", UriKind.RelativeOrAbsolute);
Assert.False(b);
}
[Fact]
public static void TestCompare()
{
Uri uri1 = new Uri("http://www.contoso.com/path?name#frag");
Uri uri2 = new Uri("http://www.contosooo.com/path?name#slag");
Uri uri2a = new Uri("http://www.contosooo.com/path?name#slag");
int i;
i = Uri.Compare(uri1, uri2, UriComponents.AbsoluteUri, UriFormat.UriEscaped, StringComparison.CurrentCulture);
Assert.Equal(i, -1);
i = Uri.Compare(uri1, uri2, UriComponents.Query, UriFormat.UriEscaped, StringComparison.CurrentCulture);
Assert.Equal(i, 0);
i = Uri.Compare(uri1, uri2, UriComponents.Query | UriComponents.Fragment, UriFormat.UriEscaped, StringComparison.CurrentCulture);
Assert.Equal(i, -1);
bool b;
b = uri1.Equals(uri2);
Assert.False(b);
b = uri1 == uri2;
Assert.False(b);
b = uri1 != uri2;
Assert.True(b);
b = uri2.Equals(uri2a);
Assert.True(b);
b = uri2 == uri2a;
Assert.True(b);
b = uri2 != uri2a;
Assert.False(b);
// Blocked: Globalization
/*
int h2 = uri2.GetHashCode();
int h2a = uri2a.GetHashCode();
Assert.AreEqual(h2, h2a);
*/
}
[Fact]
public static void TestEscapeDataString()
{
String s;
s = Uri.EscapeDataString("Hello");
Assert.Equal(s, "Hello");
s = Uri.EscapeDataString(@"He\l/lo");
Assert.Equal(s, "He%5Cl%2Flo");
}
[Fact]
public static void TestUnescapeDataString()
{
String s;
s = Uri.UnescapeDataString("Hello");
Assert.Equal(s, "Hello");
s = Uri.UnescapeDataString("He%5Cl%2Flo");
Assert.Equal(s, @"He\l/lo");
}
[Fact]
public static void TestEscapeUriString()
{
String s;
s = Uri.EscapeUriString("Hello");
Assert.Equal(s, "Hello");
s = Uri.EscapeUriString(@"He\l/lo");
Assert.Equal(s, @"He%5Cl/lo");
}
[Fact]
public static void TestGetComponentParts()
{
Uri uri = new Uri("http://www.contoso.com/path?name#frag");
String s;
s = uri.GetComponents(UriComponents.Fragment, UriFormat.UriEscaped);
Assert.Equal(s, "frag");
s = uri.GetComponents(UriComponents.Host, UriFormat.UriEscaped);
Assert.Equal(s, "www.contoso.com");
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using OLEDB.Test.ModuleCore;
using System.IO;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
[TestModule(Name = "XmlCharCheckingReader Test", Desc = "XmlCharCheckingReader Test")]
public partial class CharCheckingReaderTest : CGenericTestModule
{
public override int Init(object objParam)
{
int ret = base.Init(objParam);
string strFile = String.Empty;
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.XSLT_COPY);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.XMLSCHEMA);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVALID_DTD);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVALID_NAMESPACE);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVALID_SCHEMA);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.INVWELLFORMED_DTD);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.NONWELLFORMED_DTD);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.VALID_DTD);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.WELLFORMED_DTD);
TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.WHITESPACE_TEST);
ReaderFactory = new XmlCharCheckingReaderFactory();
return ret;
}
public override int Terminate(object objParam)
{
return base.Terminate(objParam);
}
}
////////////////////////////////////////////////////////////////
// CharCheckingReader factory
//
////////////////////////////////////////////////////////////////
internal class XmlCharCheckingReaderFactory : ReaderFactory
{
public override XmlReader Create(MyDict<string, object> options)
{
string tcDesc = (string)options[ReaderFactory.HT_CURDESC];
string tcVar = (string)options[ReaderFactory.HT_CURVAR];
CError.Compare(tcDesc == "charcheckingreader", "Invalid testcase");
XmlReaderSettings rs = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS];
Stream stream = (Stream)options[ReaderFactory.HT_STREAM];
string filename = (string)options[ReaderFactory.HT_FILENAME];
object readerType = options[ReaderFactory.HT_READERTYPE];
object vt = options[ReaderFactory.HT_VALIDATIONTYPE];
string fragment = (string)options[ReaderFactory.HT_FRAGMENT];
StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER];
if (rs == null)
rs = new XmlReaderSettings();
rs.DtdProcessing = DtdProcessing.Ignore;
rs.CheckCharacters = false;
XmlReaderSettings wrs = new XmlReaderSettings();
wrs.DtdProcessing = DtdProcessing.Ignore;
wrs.CheckCharacters = true;
wrs.ConformanceLevel = ConformanceLevel.Auto;
if (sr != null)
{
CError.WriteLine("CharCheckingReader String");
XmlReader r = ReaderHelper.Create(sr, rs, string.Empty);
XmlReader wr = ReaderHelper.Create(r, wrs);
return wr;
}
if (stream != null)
{
CError.WriteLine("CharCheckingReader Stream");
XmlReader r = ReaderHelper.Create(stream, rs, filename);
XmlReader wr = ReaderHelper.Create(r, wrs);
return wr;
}
if (fragment != null)
{
CError.WriteLine("CharCheckingReader Fragment");
rs.ConformanceLevel = ConformanceLevel.Fragment;
StringReader tr = new StringReader(fragment);
XmlReader r = ReaderHelper.Create(tr, rs, (string)null);
XmlReader wr = ReaderHelper.Create(r, wrs);
return wr;
}
if (filename != null)
{
CError.WriteLine("CharCheckingReader Filename");
Stream fs = FilePathUtil.getStream(filename);
XmlReader r = ReaderHelper.Create(fs, rs, filename);
XmlReader wr = ReaderHelper.Create(r, wrs);
return wr;
}
return null;
}
}
[TestCase(Name = "ErrorCondition", Desc = "CharCheckingReader")]
public class TCErrorConditionReader : TCErrorCondition
{
}
[TestCase(Name = "Depth", Desc = "CharCheckingReader")]
public class TCDepthReader : TCDepth
{
}
[TestCase(Name = "Namespace", Desc = "CharCheckingReader")]
public class TCNamespaceReader : TCNamespace
{
}
[TestCase(Name = "LookupNamespace", Desc = "CharCheckingReader")]
public class TCLookupNamespaceReader : TCLookupNamespace
{
}
[TestCase(Name = "IsEmptyElement", Desc = "CharCheckingReader")]
public class TCIsEmptyElementReader : TCIsEmptyElement
{
}
[TestCase(Name = "XmlSpace", Desc = "CharCheckingReader")]
public class TCXmlSpaceReader : TCXmlSpace
{
}
[TestCase(Name = "XmlLang", Desc = "CharCheckingReader")]
public class TCXmlLangReader : TCXmlLang
{
}
[TestCase(Name = "Skip", Desc = "CharCheckingReader")]
public class TCSkipReader : TCSkip
{
}
[TestCase(Name = "InvalidXML", Desc = "CharCheckingReader")]
public class TCInvalidXMLReader : TCInvalidXML
{
}
[TestCase(Name = "ReadOuterXml", Desc = "CharCheckingReader")]
public class TCReadOuterXmlReader : TCReadOuterXml
{
}
[TestCase(Name = "AttributeAccess", Desc = "CharCheckingReader")]
public class TCAttributeAccessReader : TCAttributeAccess
{
}
[TestCase(Name = "This(Name) and This(Name, Namespace)", Desc = "CharCheckingReader")]
public class TCThisNameReader : TCThisName
{
}
[TestCase(Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "CharCheckingReader")]
public class TCMoveToAttributeReader : TCMoveToAttribute
{
}
[TestCase(Name = "GetAttribute (Ordinal)", Desc = "CharCheckingReader")]
public class TCGetAttributeOrdinalReader : TCGetAttributeOrdinal
{
}
[TestCase(Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "CharCheckingReader")]
public class TCGetAttributeNameReader : TCGetAttributeName
{
}
[TestCase(Name = "This [Ordinal]", Desc = "CharCheckingReader")]
public class TCThisOrdinalReader : TCThisOrdinal
{
}
[TestCase(Name = "MoveToAttribute(Ordinal)", Desc = "CharCheckingReader")]
public class TCMoveToAttributeOrdinalReader : TCMoveToAttributeOrdinal
{
}
[TestCase(Name = "MoveToFirstAttribute()", Desc = "CharCheckingReader")]
public class TCMoveToFirstAttributeReader : TCMoveToFirstAttribute
{
}
[TestCase(Name = "MoveToNextAttribute()", Desc = "CharCheckingReader")]
public class TCMoveToNextAttributeReader : TCMoveToNextAttribute
{
}
[TestCase(Name = "Attribute Test when NodeType != Attributes", Desc = "CharCheckingReader")]
public class TCAttributeTestReader : TCAttributeTest
{
}
[TestCase(Name = "Attributes test on XmlDeclaration DCR52258", Desc = "CharCheckingReader")]
public class TCAttributeXmlDeclarationReader : TCAttributeXmlDeclaration
{
}
[TestCase(Name = "xmlns as local name DCR50345", Desc = "CharCheckingReader")]
public class TCXmlnsReader : TCXmlns
{
}
[TestCase(Name = "bounded namespace to xmlns prefix DCR50881", Desc = "CharCheckingReader")]
public class TCXmlnsPrefixReader : TCXmlnsPrefix
{
}
[TestCase(Name = "ReadInnerXml", Desc = "CharCheckingReader")]
public class TCReadInnerXmlReader : TCReadInnerXml
{
}
[TestCase(Name = "MoveToContent", Desc = "CharCheckingReader")]
public class TCMoveToContentReader : TCMoveToContent
{
}
[TestCase(Name = "IsStartElement", Desc = "CharCheckingReader")]
public class TCIsStartElementReader : TCIsStartElement
{
}
[TestCase(Name = "ReadStartElement", Desc = "CharCheckingReader")]
public class TCReadStartElementReader : TCReadStartElement
{
}
[TestCase(Name = "ReadEndElement", Desc = "CharCheckingReader")]
public class TCReadEndElementReader : TCReadEndElement
{
}
[TestCase(Name = "ResolveEntity and ReadAttributeValue", Desc = "CharCheckingReader")]
public class TCResolveEntityReader : TCResolveEntity
{
}
[TestCase(Name = "HasValue", Desc = "CharCheckingReader")]
public class TCHasValueReader : TCHasValue
{
}
[TestCase(Name = "ReadAttributeValue", Desc = "CharCheckingReader")]
public class TCReadAttributeValueReader : TCReadAttributeValue
{
}
[TestCase(Name = "Read", Desc = "CharCheckingReader")]
public class TCReadReader : TCRead2
{
}
[TestCase(Name = "MoveToElement", Desc = "CharCheckingReader")]
public class TCMoveToElementReader : TCMoveToElement
{
}
[TestCase(Name = "Dispose", Desc = "CharCheckingReader")]
public class TCDisposeReader : TCDispose
{
}
[TestCase(Name = "Buffer Boundaries", Desc = "CharCheckingReader")]
public class TCBufferBoundariesReader : TCBufferBoundaries
{
}
//[TestCase(Name = "BeforeRead", Desc = "BeforeRead")]
//[TestCase(Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse")]
//[TestCase(Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle")]
//[TestCase(Name = "AfterClose", Desc = "AfterClose")]
public class TCXmlNodeIntegrityTestFile : TCXMLIntegrityBase
{
}
[TestCase(Name = "Read Subtree", Desc = "CharCheckingReader")]
public class TCReadSubtreeReader : TCReadSubtree
{
}
[TestCase(Name = "ReadToDescendant", Desc = "CharCheckingReader")]
public class TCReadToDescendantReader : TCReadToDescendant
{
}
[TestCase(Name = "ReadToNextSibling", Desc = "CharCheckingReader")]
public class TCReadToNextSiblingReader : TCReadToNextSibling
{
}
[TestCase(Name = "ReadValue", Desc = "CharCheckingReader")]
public class TCReadValueReader : TCReadValue
{
}
[TestCase(Name = "ReadContentAsBase64", Desc = "CharCheckingReader")]
public class TCReadContentAsBase64Reader : TCReadContentAsBase64
{
}
[TestCase(Name = "ReadElementContentAsBase64", Desc = "CharCheckingReader")]
public class TCReadElementContentAsBase64Reader : TCReadElementContentAsBase64
{
}
[TestCase(Name = "ReadContentAsBinHex", Desc = "CharCheckingReader")]
public class TCReadContentAsBinHexReader : TCReadContentAsBinHex
{
}
[TestCase(Name = "ReadElementContentAsBinHex", Desc = "CharCheckingReader")]
public class TCReadElementContentAsBinHexReader : TCReadElementContentAsBinHex
{
}
[TestCase(Name = "ReadToFollowing", Desc = "CharCheckingReader")]
public class TCReadToFollowingReader : TCReadToFollowing
{
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace appveyortest.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);
}
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System.Diagnostics;
using SharpNeat.Core;
using SharpNeat.Phenomes;
namespace SharpNeat.Domains
{
/// <summary>
/// A black box evaluator for the XOR logic gate problem domain.
///
/// XOR (also known as Exclusive OR) is a type of logical disjunction on two operands that results in
/// a value of true if and only if exactly one of the operands has a value of 'true'. A simple way
/// to state this is 'one or the other but not both.'.
///
/// This evaulator therefore requires that the black box to be evaluated has has two inputs and one
/// output all using the range 0..1
///
/// In turn each of the four possible test cases are applied to the two inputs, the network is activated
/// and the output is evaulated. If a 'false' response is requried we expect an output of zero, for true
/// we expect a 1.0. Fitness for each test case is the difference between the output and the wrong output,
/// thus a maximum of 1 can be scored on each test case giving a maximum of 4. In addition each outputs is
/// compared against a threshold of 0.5, if all four outputs are on teh correct side of the threshold then
/// 10.0 is added to the total fitness. Therefore a black box that answers correctly but very close to the
/// threshold will score just above 10, and a black box that answers correctly with perfect 0.0 and 1.0
/// answers will score a maximum of 14.0.
///
/// The first type of evaulation punishes for difference from the required outputs and therefore represents
/// a smooth fitness space (we can evolve gradually towards better scores). The +10 score for 4 correct
/// responses is 'all or nothing', in other words it is a fitness space with a large step and no indication
/// of where the step is, which on it's own would be a poor fitness space as it required evolution to stumble
/// on the correct network by random rather than ascending a gradient in the fitness space. If however we do
/// stumble on a black box that answers correctly but close to the threshold, then we would like that box to
/// obtain a higher score than a network with, say, 3 strong correct responses and but wrong overall. We can
/// improve the correct box's output difference from threshold value gradually, while the box with 3 correct
/// responses may actually be in the wrong area of the fitness space alltogether - in the wrong 'ballpark'.
/// </summary>
public class XorBlackBoxEvaluator : IPhenomeEvaluator<IBlackBox>
{
const double StopFitness = 10.0;
ulong _evalCount;
bool _stopConditionSatisfied;
#region IPhenomeEvaluator<IBlackBox> Members
/// <summary>
/// Gets the total number of evaluations that have been performed.
/// </summary>
public ulong EvaluationCount
{
get { return _evalCount; }
}
/// <summary>
/// Gets a value indicating whether some goal fitness has been achieved and that
/// the the evolutionary algorithm/search should stop. This property's value can remain false
/// to allow the algorithm to run indefinitely.
/// </summary>
public bool StopConditionSatisfied
{
get { return _stopConditionSatisfied; }
}
/// <summary>
/// Evaluate the provided IBlackBox against the XOR problem domain and return its fitness score.
/// </summary>
public FitnessInfo Evaluate(IBlackBox box)
{
double fitness = 0;
double output;
double pass = 1.0;
ISignalArray inputArr = box.InputSignalArray;
ISignalArray outputArr = box.OutputSignalArray;
_evalCount++;
//----- Test 0,0
box.ResetState();
// Set the input values
inputArr[0] = 0.0;
inputArr[1] = 0.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
//fitness += 1.0 - output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-(output*output);
if(output > 0.5) {
pass = 0.0;
}
//----- Test 1,1
// Reset any black box state from the previous test case.
box.ResetState();
// Set the input values
inputArr[0] = 1.0;
inputArr[1] = 1.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
//fitness += 1.0 - output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-(output*output);
if(output > 0.5) {
pass = 0.0;
}
//----- Test 0,1
// Reset any black box state from the previous test case.
box.ResetState();
// Set the input values
inputArr[0] = 0.0;
inputArr[1] = 1.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
// fitness += output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-((1.0-output)*(1.0-output));
if(output <= 0.5) {
pass = 0.0;
}
//----- Test 1,0
// Reset any black box state from the previous test case.
box.ResetState();
// Set the input values
inputArr[0] = 1.0;
inputArr[1] = 0.0;
// Activate the black box.
box.Activate();
if(!box.IsStateValid)
{ // Any black box that gets itself into an invalid state is unlikely to be
// any good, so lets just bail out here.
return FitnessInfo.Zero;
}
// Read output signal.
output = outputArr[0];
Debug.Assert(output >= 0.0, "Unexpected negative output.");
// Calculate this test case's contribution to the overall fitness score.
// fitness += output; // Use this line to punish absolute error instead of squared error.
fitness += 1.0-((1.0-output)*(1.0-output));
if(output <= 0.5) {
pass = 0.0;
}
// If all four outputs were correct, that is, all four were on the correct side of the
// threshold level - then we add 10 to the fitness.
fitness += pass * 10.0;
if(fitness >= StopFitness) {
_stopConditionSatisfied = true;
}
return new FitnessInfo(fitness, fitness);
}
/// <summary>
/// Reset the internal state of the evaluation scheme if any exists.
/// Note. The XOR problem domain has no internal state. This method does nothing.
/// </summary>
public void Reset()
{
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Osu.Difficulty
{
public class OsuPerformanceCalculator : PerformanceCalculator
{
public new OsuDifficultyAttributes Attributes => (OsuDifficultyAttributes)base.Attributes;
private Mod[] mods;
private double accuracy;
private int scoreMaxCombo;
private int countGreat;
private int countOk;
private int countMeh;
private int countMiss;
private double effectiveMissCount;
public OsuPerformanceCalculator(Ruleset ruleset, DifficultyAttributes attributes, ScoreInfo score)
: base(ruleset, attributes, score)
{
}
public override PerformanceAttributes Calculate()
{
mods = Score.Mods;
accuracy = Score.Accuracy;
scoreMaxCombo = Score.MaxCombo;
countGreat = Score.Statistics.GetValueOrDefault(HitResult.Great);
countOk = Score.Statistics.GetValueOrDefault(HitResult.Ok);
countMeh = Score.Statistics.GetValueOrDefault(HitResult.Meh);
countMiss = Score.Statistics.GetValueOrDefault(HitResult.Miss);
effectiveMissCount = calculateEffectiveMissCount();
double multiplier = 1.12; // This is being adjusted to keep the final pp value scaled around what it used to be when changing things.
if (mods.Any(m => m is OsuModNoFail))
multiplier *= Math.Max(0.90, 1.0 - 0.02 * effectiveMissCount);
if (mods.Any(m => m is OsuModSpunOut) && totalHits > 0)
multiplier *= 1.0 - Math.Pow((double)Attributes.SpinnerCount / totalHits, 0.85);
if (mods.Any(h => h is OsuModRelax))
{
// As we're adding Oks and Mehs to an approximated number of combo breaks the result can be higher than total hits in specific scenarios (which breaks some calculations) so we need to clamp it.
effectiveMissCount = Math.Min(effectiveMissCount + countOk + countMeh, totalHits);
multiplier *= 0.6;
}
double aimValue = computeAimValue();
double speedValue = computeSpeedValue();
double accuracyValue = computeAccuracyValue();
double flashlightValue = computeFlashlightValue();
double totalValue =
Math.Pow(
Math.Pow(aimValue, 1.1) +
Math.Pow(speedValue, 1.1) +
Math.Pow(accuracyValue, 1.1) +
Math.Pow(flashlightValue, 1.1), 1.0 / 1.1
) * multiplier;
return new OsuPerformanceAttributes
{
Aim = aimValue,
Speed = speedValue,
Accuracy = accuracyValue,
Flashlight = flashlightValue,
EffectiveMissCount = effectiveMissCount,
Total = totalValue
};
}
private double computeAimValue()
{
double rawAim = Attributes.AimDifficulty;
if (mods.Any(m => m is OsuModTouchDevice))
rawAim = Math.Pow(rawAim, 0.8);
double aimValue = Math.Pow(5.0 * Math.Max(1.0, rawAim / 0.0675) - 4.0, 3.0) / 100000.0;
double lengthBonus = 0.95 + 0.4 * Math.Min(1.0, totalHits / 2000.0) +
(totalHits > 2000 ? Math.Log10(totalHits / 2000.0) * 0.5 : 0.0);
aimValue *= lengthBonus;
// Penalize misses by assessing # of misses relative to the total # of objects. Default a 3% reduction for any # of misses.
if (effectiveMissCount > 0)
aimValue *= 0.97 * Math.Pow(1 - Math.Pow(effectiveMissCount / totalHits, 0.775), effectiveMissCount);
aimValue *= getComboScalingFactor();
double approachRateFactor = 0.0;
if (Attributes.ApproachRate > 10.33)
approachRateFactor = 0.3 * (Attributes.ApproachRate - 10.33);
else if (Attributes.ApproachRate < 8.0)
approachRateFactor = 0.1 * (8.0 - Attributes.ApproachRate);
aimValue *= 1.0 + approachRateFactor * lengthBonus; // Buff for longer maps with high AR.
if (mods.Any(m => m is OsuModBlinds))
aimValue *= 1.3 + (totalHits * (0.0016 / (1 + 2 * effectiveMissCount)) * Math.Pow(accuracy, 16)) * (1 - 0.003 * Attributes.DrainRate * Attributes.DrainRate);
else if (mods.Any(h => h is OsuModHidden))
{
// We want to give more reward for lower AR when it comes to aim and HD. This nerfs high AR and buffs lower AR.
aimValue *= 1.0 + 0.04 * (12.0 - Attributes.ApproachRate);
}
// We assume 15% of sliders in a map are difficult since there's no way to tell from the performance calculator.
double estimateDifficultSliders = Attributes.SliderCount * 0.15;
if (Attributes.SliderCount > 0)
{
double estimateSliderEndsDropped = Math.Clamp(Math.Min(countOk + countMeh + countMiss, Attributes.MaxCombo - scoreMaxCombo), 0, estimateDifficultSliders);
double sliderNerfFactor = (1 - Attributes.SliderFactor) * Math.Pow(1 - estimateSliderEndsDropped / estimateDifficultSliders, 3) + Attributes.SliderFactor;
aimValue *= sliderNerfFactor;
}
aimValue *= accuracy;
// It is important to consider accuracy difficulty when scaling with accuracy.
aimValue *= 0.98 + Math.Pow(Attributes.OverallDifficulty, 2) / 2500;
return aimValue;
}
private double computeSpeedValue()
{
double speedValue = Math.Pow(5.0 * Math.Max(1.0, Attributes.SpeedDifficulty / 0.0675) - 4.0, 3.0) / 100000.0;
double lengthBonus = 0.95 + 0.4 * Math.Min(1.0, totalHits / 2000.0) +
(totalHits > 2000 ? Math.Log10(totalHits / 2000.0) * 0.5 : 0.0);
speedValue *= lengthBonus;
// Penalize misses by assessing # of misses relative to the total # of objects. Default a 3% reduction for any # of misses.
if (effectiveMissCount > 0)
speedValue *= 0.97 * Math.Pow(1 - Math.Pow(effectiveMissCount / totalHits, 0.775), Math.Pow(effectiveMissCount, .875));
speedValue *= getComboScalingFactor();
double approachRateFactor = 0.0;
if (Attributes.ApproachRate > 10.33)
approachRateFactor = 0.3 * (Attributes.ApproachRate - 10.33);
speedValue *= 1.0 + approachRateFactor * lengthBonus; // Buff for longer maps with high AR.
if (mods.Any(m => m is OsuModBlinds))
{
// Increasing the speed value by object count for Blinds isn't ideal, so the minimum buff is given.
speedValue *= 1.12;
}
else if (mods.Any(m => m is OsuModHidden))
{
// We want to give more reward for lower AR when it comes to aim and HD. This nerfs high AR and buffs lower AR.
speedValue *= 1.0 + 0.04 * (12.0 - Attributes.ApproachRate);
}
// Scale the speed value with accuracy and OD.
speedValue *= (0.95 + Math.Pow(Attributes.OverallDifficulty, 2) / 750) * Math.Pow(accuracy, (14.5 - Math.Max(Attributes.OverallDifficulty, 8)) / 2);
// Scale the speed value with # of 50s to punish doubletapping.
speedValue *= Math.Pow(0.98, countMeh < totalHits / 500.0 ? 0 : countMeh - totalHits / 500.0);
return speedValue;
}
private double computeAccuracyValue()
{
if (mods.Any(h => h is OsuModRelax))
return 0.0;
// This percentage only considers HitCircles of any value - in this part of the calculation we focus on hitting the timing hit window.
double betterAccuracyPercentage;
int amountHitObjectsWithAccuracy = Attributes.HitCircleCount;
if (amountHitObjectsWithAccuracy > 0)
betterAccuracyPercentage = ((countGreat - (totalHits - amountHitObjectsWithAccuracy)) * 6 + countOk * 2 + countMeh) / (double)(amountHitObjectsWithAccuracy * 6);
else
betterAccuracyPercentage = 0;
// It is possible to reach a negative accuracy with this formula. Cap it at zero - zero points.
if (betterAccuracyPercentage < 0)
betterAccuracyPercentage = 0;
// Lots of arbitrary values from testing.
// Considering to use derivation from perfect accuracy in a probabilistic manner - assume normal distribution.
double accuracyValue = Math.Pow(1.52163, Attributes.OverallDifficulty) * Math.Pow(betterAccuracyPercentage, 24) * 2.83;
// Bonus for many hitcircles - it's harder to keep good accuracy up for longer.
accuracyValue *= Math.Min(1.15, Math.Pow(amountHitObjectsWithAccuracy / 1000.0, 0.3));
// Increasing the accuracy value by object count for Blinds isn't ideal, so the minimum buff is given.
if (mods.Any(m => m is OsuModBlinds))
accuracyValue *= 1.14;
else if (mods.Any(m => m is OsuModHidden))
accuracyValue *= 1.08;
if (mods.Any(m => m is OsuModFlashlight))
accuracyValue *= 1.02;
return accuracyValue;
}
private double computeFlashlightValue()
{
if (!mods.Any(h => h is OsuModFlashlight))
return 0.0;
double rawFlashlight = Attributes.FlashlightDifficulty;
if (mods.Any(m => m is OsuModTouchDevice))
rawFlashlight = Math.Pow(rawFlashlight, 0.8);
double flashlightValue = Math.Pow(rawFlashlight, 2.0) * 25.0;
if (mods.Any(h => h is OsuModHidden))
flashlightValue *= 1.3;
// Penalize misses by assessing # of misses relative to the total # of objects. Default a 3% reduction for any # of misses.
if (effectiveMissCount > 0)
flashlightValue *= 0.97 * Math.Pow(1 - Math.Pow(effectiveMissCount / totalHits, 0.775), Math.Pow(effectiveMissCount, .875));
flashlightValue *= getComboScalingFactor();
// Account for shorter maps having a higher ratio of 0 combo/100 combo flashlight radius.
flashlightValue *= 0.7 + 0.1 * Math.Min(1.0, totalHits / 200.0) +
(totalHits > 200 ? 0.2 * Math.Min(1.0, (totalHits - 200) / 200.0) : 0.0);
// Scale the flashlight value with accuracy _slightly_.
flashlightValue *= 0.5 + accuracy / 2.0;
// It is important to also consider accuracy difficulty when doing that.
flashlightValue *= 0.98 + Math.Pow(Attributes.OverallDifficulty, 2) / 2500;
return flashlightValue;
}
private double calculateEffectiveMissCount()
{
// Guess the number of misses + slider breaks from combo
double comboBasedMissCount = 0.0;
if (Attributes.SliderCount > 0)
{
double fullComboThreshold = Attributes.MaxCombo - 0.1 * Attributes.SliderCount;
if (scoreMaxCombo < fullComboThreshold)
comboBasedMissCount = fullComboThreshold / Math.Max(1.0, scoreMaxCombo);
}
// Clamp miss count since it's derived from combo and can be higher than total hits and that breaks some calculations
comboBasedMissCount = Math.Min(comboBasedMissCount, totalHits);
return Math.Max(countMiss, comboBasedMissCount);
}
private double getComboScalingFactor() => Attributes.MaxCombo <= 0 ? 1.0 : Math.Min(Math.Pow(scoreMaxCombo, 0.8) / Math.Pow(Attributes.MaxCombo, 0.8), 1.0);
private int totalHits => countGreat + countOk + countMeh + countMiss;
private int totalSuccessfulHits => countGreat + countOk + countMeh;
}
}
| |
// 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.Diagnostics;
using Microsoft.CodeAnalysis.UnitTests;
using Xunit;
namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests
{
public class PropertiesShouldNotBeWriteOnlyTests : DiagnosticAnalyzerTestBase
{
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new PropertiesShouldNotBeWriteOnlyAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new PropertiesShouldNotBeWriteOnlyAnalyzer();
}
// Valid C# Tests that should not be flagged based on CA1044 (good tests)
[Fact]
public void CS_CA1044Good_Read_Write()
{
var code = @"
using System;
namespace DesignLibrary
{
public class CS_GoodClassWithReadWriteProperty
{
string CS_someName;
public string CS_Name
{
get { return CS_someName; }
set { CS_someName = CS_value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_Read_Write1()
{ var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests1
{
public class CS_ClassWithReadableProperty1
{
protected string CS_field;
public virtual string CS_ReadableProperty1
{
get { return CS_field; }
set { CS_field = CS_value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_public_Read_private_Write()
{
var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests2
{
public class CS_ClassWithReadableProperty2
{
protected string CS_field;
public string CS_AccessibleProperty2
{
get { return CS_field; }
private set { CS_field = CS_value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_protected_Read_private_Write()
{
var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests3
{
public class CS_ClassWithReadableProperty3
{
protected string CS_field;
protected string CS_AccessibleProperty3
{
get { return CS_field; }
private set { CS_field = CS_value; }
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_internal_Read_private_Write()
{
var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests4
{
public class CS_GoodClassWithReadWriteProperty4
{
protected string CS_field;
internal string CS_AccessibleProperty4
{
get { return CS_field; }
private set { CS_field = CS_value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_protected_internal_Read_internal_Write()
{
var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests5
{
public class CS_GoodClassWithReadWriteProperty5
{
protected string CS_field;
protected internal string AccessibleProperty5
{
get { return field; }
internal set { field = value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_public_Read_internal_Write()
{
var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests6
{
public class CS_GoodClassWithReadWriteProperty6
{
protected string CS_field;
public string CS_AccessibleProperty6
{
get { return CS_field; }
internal set { CS_field = CS_value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_public_Read_protected_Write()
{
var code = @"
using System;
namespace DesignLibrary
{
public class CS_GoodClassWithReadWriteProperty7
{
protected string CS_field;
public string CS_AccessibleProperty7
{
get { return CS_field; }
protected set { CS_field = CS_value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Good_public_override_Write()
{
var code = @"
using System;
namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests8
{
protected string CS_field;
public class CS_DerivedClassWithReadableProperty : CS_ClassWithReadableProperty
{
public override string CS_ReadableProperty8
{
set { CS_field = CS_value; }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Interface_Write()
{
var code = @"
using System;
namespace GoodPropertiesShouldNotBeWriteOnlyTests9
{
public class Class1 : IInterface9
{
string IInterface.InterfaceProperty
{
set { }
}
}
}";
VerifyCSharp(code);
}
[Fact]
public void CS_CA1044Base_Write1()
{
var code = @"
using System;
namespace GoodPropertiesShouldNotBeWriteOnlyTests10
{
public class Derived : Base10
{
public override string BaseProperty10
{
set { base.BaseProperty = value; }
}
}
}";
VerifyCSharp(code);
}
// Valid VB Tests that should not be flagged based on CA1044 (good tests)
[Fact]
public void VB_CA1044Good_Read_Write()
{
var code = @"
Imports System
Namespace DesignLibrary
Public Class VB_GoodClassWithReadWriteProperty
Private VB_someName As String
Public Property VB_Name() As String
Get
Return VB_someName
End Get
Set(ByVal value As String)
VB_someName = VB_value
End Set
End Property
End Class
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_Read_Write1()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests1
Public Class VB_GoodClassWithReadWriteProperty1
Protected VB_field As String
Public Overridable Property VB_ReadableProperty1() As String
Get
Return VB_field
End Get
Set(ByVal value As String)
VB_field = VB_value
End Set
End Property
End Class
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_public_Read_private_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests2
Public class VB_ClassWithReadableProperty2
Protected VB_field As String
Public Property VB_AccessibleProperty2() As String
Get
Return VB_field
End Get
Private Set(ByVal value As String)
VB_field = VB_value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_protected_Read_private_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests3
Public class VB_ClassWithReadableProperty3
Protected VB_field As String
Protected Property VB_AccessibleProperty3() As String
Get
Return VB_field
End Get
Private Set(ByVal value As String)
VB_field = VB_value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_internal_Read_private_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests4
Public VB_class ClassWithReadableProperty4
Protected VB_field As String
Friend Property VB_AccessibleProperty4() As String
Get
Return VB_field
End Get
Private Set(ByVal value As String)
VB_field = VB_value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_protected_internal_Read_internal_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests5
Public class VB_ClassWithReadableProperty5
Protected VB_field As String
Protected Friend Property AccessibleProperty5() As String
Get
Return field
End Get
Friend Set(ByVal value As String)
field = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_public_Read_internal_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests6
Public class VB_ClassWithReadableProperty6
Protected VB_field As String
Public Property VB_AccessibleProperty6() As String
Get
Return VB_field
End Get
Friend Set(ByVal value As String)
VB_field = VB_value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_public_Read_protected_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests7
Public class VB_ClassWithReadableProperty7
Protected VB_field As String
Public Property VB_AccessibleProperty7() As String
Get
Return VB_field
End Get
Protected Set(ByVal value As String)
VB_field = VB_value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Good_ClassWithReadableProperty()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests8
Protected VB_field As String
Public Class VB_DerivedClassWithReadableProperty
Inherits VB_ClassWithReadableProperty
Public Overrides WriteOnly Property VB_ReadableProperty8() As String
Set(ByVal value As String)
VB_field = VB_value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Interface_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests9
Public Class Class1
Implements IInterface9
Private WriteOnly Property IInterface_InterfaceProperty() As String Implements IInterface.InterfaceProperty
Set(ByVal value As String)
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
[Fact]
public void VB_CA1044Base_Write()
{
var code = @"
Imports System
Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests10
Public Class Derived
Inherits Base10
Public Overrides WriteOnly Property BaseProperty10() As String
Set(ByVal value As String)
MyBase.BaseProperty = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code);
}
// C# Tests that should be flagged with CA1044 Addgetter
[Fact]
public void CS_CA1044Bad_Write_with_NoRead()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests
{
public class CS_BadClassWithWriteOnlyProperty
{
protected string CS_someName;
public string CS_WriteOnlyProperty
{
set { CS_someName = value; }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(8, 23, CA1044MessageAddGetter, "CS_WriteOnlyProperty"));
}
[Fact]
public void CS_CA1044Bad_Write_with_NoRead1()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests1
{
public class CS_BadClassWithWriteOnlyProperty1
{
protected string CS_someName;
protected public string CS_WriteOnlyProperty1
{
set { CS_someName = value; }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(8, 33, CA1044MessageAddGetter, "CS_WriteOnlyProperty1"));
}
[Fact]
public void CS_CA1044Bad_Write_with_NoRead2()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests2
{
public class CS_BadClassWithWriteOnlyProperty2
{
protected string CS_someName;
protected internal string CS_WriteOnlyProperty2
{
set { CS_someName = value; }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(8, 35, CA1044MessageAddGetter, "CS_WriteOnlyProperty2"));
}
[Fact]
public void CS_CA1044bad_Base_Write()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests3
{
public class CS_Base3
{
public virtual string CS_BaseProperty3
{
set { }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(7, 31, CA1044MessageAddGetter, "CS_BaseProperty3"));
}
[Fact]
public void CS_CA1044bad_Interface_Write()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests4
{
public interface CS_IInterface4
{
string CS_InterfaceProperty4
{
set;
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(7, 16, CA1044MessageAddGetter, "CS_InterfaceProperty4"));
}
// C# Tests that should be flagged with CA1044 MakeMoreAccessible
[Fact]
public void CS_CA1044Bad_InaccessibleRead()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests5
{
public class CS_BadClassWithWriteOnlyProperty5
{
public string CS_InaccessibleProperty5
{
private get { return field; }
set { field = value; }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(7, 24, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty5"));
}
[Fact]
public void CS_CA1044Bad_InaccessibleRead1()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests6
{
public class CS_BadClassWithWriteOnlyProperty6
{
string field;
protected string CS_InaccessibleProperty6
{
private get { return field; }
set { field = value; }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(8, 26, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty6"));
}
[Fact]
public void CS_CA1044Bad_InaccessibleRead2()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests7
{
public class CS_BadClassWithWriteOnlyProperty7
{
protected internal string CS_InaccessibleProperty7
{
internal get { return field; }
set { field = value; }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(7, 35, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty7"));
}
[Fact]
public void CS_CA1044Bad_InaccessibleRead3()
{
var code = @"
using System;
namespace CS_BadPropertiesShouldNotBeWriteOnlyTests8
{
public class CS_BadClassWithWriteOnlyProperty8
{
public string CS_InaccessibleProperty8
{
internal get { return field; }
set { field = value; }
}
}
}";
VerifyCSharp(code, GetCA1044CSharpResultAt(7, 23, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty8"));
}
// VB Tests that should be flagged with CA1044 Addgetter
[Fact]
public void VB_CA1044Bad_Write_with_NoRead()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests
Public Class VB_BadClassWithWriteOnlyProperty
Protected VB_someName As String
Public WriteOnly Property VB_WriteOnlyProperty() As String
Set(ByVal value As String)
VB_someName = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(6, 29, CA1044MessageAddGetter, "VB_WriteOnlyProperty"));
}
[Fact]
public void VB_CA1044Bad_Write_with_NoRead1()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests1
Public Class VB_BadClassWithWriteOnlyProperty1
Protected VB_someName As String
Protected Public WriteOnly Property VB_WriteOnlyProperty1() As String
Set(ByVal value As String)
VB_someName = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(6, 39, CA1044MessageAddGetter, "VB_WriteOnlyProperty1"));
}
[Fact]
public void VB_CA1044Bad_Base_NoRead()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests2
Public Class VB_BadClassWithWriteOnlyProperty2
Protected VB_someName As String
Protected Friend WriteOnly Property VB_WriteOnlyProperty2() As String
Set(ByVal value As String)
VB_someName = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(6, 39, CA1044MessageAddGetter, "VB_WriteOnlyProperty2"));
}
[Fact]
public void VB_CA1044Bad_Base_Write()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests3
Public Class VB_Base3
Public Overridable WriteOnly Property VB_BaseProperty3() As String
Set(ByVal value As String)
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(5, 41, CA1044MessageAddGetter, "VB_BaseProperty3"));
}
[Fact]
public void VB_CA1044Bad_Interface_Write()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests4
Public Interface VB_IInterface4
WriteOnly Property VB_InterfaceProperty4() As String
End Interface
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(5, 22, CA1044MessageAddGetter, "VB_InterfaceProperty4"));
}
[Fact]
public void VB_CA1044Bad_InaccessibleRead()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests5
Public Class VB_BadClassWithWriteOnlyProperty5
Public Property VB_InaccessibleProperty5() As String
Private Get
Return field
End Get
Set(ByVal value As String)
field = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(5, 20, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty5"));
}
[Fact]
public void VB_CA1044Bad_InaccessibleRead1()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests6
Public Class VB_BadClassWithWriteOnlyProperty6
Private field As String
Protected Property VB_InaccessibleProperty6() As String
Private Get
Return field
End Get
Set(ByVal value As String)
field = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(6, 22, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty6"));
}
[Fact]
public void VB_CA1044Bad_InaccessibleRead2()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests7
Public Class VB_BadClassWithWriteOnlyProperty7
Protected Friend Property VB_InaccessibleProperty7() As String
Friend Get
Return field
End Get
Set(ByVal value As String)
field = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(5, 29, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty7"));
}
[Fact]
public void VB_CA1044Bad_InaccessibleRead3()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests8
Public Class VB_BadClassWithWriteOnlyProperty8
Public Property VB_InaccessibleProperty8() As String
Friend Get
Return field
End Get
Set(ByVal value As String)
field = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(5, 22, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty8"));
}
[Fact]
public void VB_CA1044Bad_ClassWithWriteOnlyProperty()
{
var code = @"
Import System
Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests8
Public Class VB_BadClassWithWriteOnlyProperty8
Public Property VB_InaccessibleProperty8() As String
Friend Get
Return field
End Get
Set(ByVal value As String)
field = value
End Set
End Property
End Class
End NameSpace
";
VerifyBasic(code, GetCA1044BasicResultAt(5, 22, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty8"));
}
private static readonly string CA1044MessageAddGetter = MicrosoftApiDesignGuidelinesAnalyzersResources.PropertiesShouldNotBeWriteOnlyMessageAddGetter;
private static readonly string CA1044MessageMakeMoreAccessible = MicrosoftApiDesignGuidelinesAnalyzersResources.PropertiesShouldNotBeWriteOnlyMessageMakeMoreAccessible;
private static DiagnosticResult GetCA1044CSharpResultAt(int line, int column, string CA1044Message, string objectName)
{
return GetCSharpResultAt(line, column, PropertiesShouldNotBeWriteOnlyAnalyzer.RuleId, string.Format(CA1044Message, objectName));
}
private static DiagnosticResult GetCA1044BasicResultAt(int line, int column, string CA1044Message, string objectName)
{
return GetBasicResultAt(line, column, PropertiesShouldNotBeWriteOnlyAnalyzer.RuleId, string.Format(CA1044Message, objectName));
}
}
}
| |
#region license
// Copyright (c) 2009 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
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class CallableDefinition : TypeMember, INodeWithParameters, INodeWithGenericParameters
{
protected ParameterDeclarationCollection _parameters;
protected GenericParameterDeclarationCollection _genericParameters;
protected TypeReference _returnType;
protected AttributeCollection _returnTypeAttributes;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public CallableDefinition CloneNode()
{
return (CallableDefinition)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public CallableDefinition CleanClone()
{
return (CallableDefinition)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.CallableDefinition; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnCallableDefinition(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( CallableDefinition)node;
if (_modifiers != other._modifiers) return NoMatch("CallableDefinition._modifiers");
if (_name != other._name) return NoMatch("CallableDefinition._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("CallableDefinition._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("CallableDefinition._parameters");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("CallableDefinition._genericParameters");
if (!Node.Matches(_returnType, other._returnType)) return NoMatch("CallableDefinition._returnType");
if (!Node.AllMatch(_returnTypeAttributes, other._returnTypeAttributes)) return NoMatch("CallableDefinition._returnTypeAttributes");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
if (_returnType == existing)
{
this.ReturnType = (TypeReference)newNode;
return true;
}
if (_returnTypeAttributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_returnTypeAttributes.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
CallableDefinition clone = (CallableDefinition)FormatterServices.GetUninitializedObject(typeof(CallableDefinition));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
if (null != _returnType)
{
clone._returnType = _returnType.Clone() as TypeReference;
clone._returnType.InitializeParent(clone);
}
if (null != _returnTypeAttributes)
{
clone._returnTypeAttributes = _returnTypeAttributes.Clone() as AttributeCollection;
clone._returnTypeAttributes.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
if (null != _returnType)
{
_returnType.ClearTypeSystemBindings();
}
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(ParameterDeclaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ParameterDeclarationCollection Parameters
{
get { return _parameters ?? (_parameters = new ParameterDeclarationCollection(this)); }
set
{
if (_parameters != value)
{
_parameters = value;
if (null != _parameters)
{
_parameters.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(GenericParameterDeclaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public GenericParameterDeclarationCollection GenericParameters
{
get { return _genericParameters ?? (_genericParameters = new GenericParameterDeclarationCollection(this)); }
set
{
if (_genericParameters != value)
{
_genericParameters = value;
if (null != _genericParameters)
{
_genericParameters.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public TypeReference ReturnType
{
get { return _returnType; }
set
{
if (_returnType != value)
{
_returnType = value;
if (null != _returnType)
{
_returnType.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Attribute))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public AttributeCollection ReturnTypeAttributes
{
get { return _returnTypeAttributes ?? (_returnTypeAttributes = new AttributeCollection(this)); }
set
{
if (_returnTypeAttributes != value)
{
_returnTypeAttributes = value;
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.InitializeParent(this);
}
}
}
}
}
}
| |
using FontBuddyLib;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using ResolutionBuddy;
using System;
using System.Threading.Tasks;
namespace MenuBuddy
{
/// <summary>
/// Helper class represents a single entry in a MenuScreen. By default this
/// just draws the entry text string, but it can be customized to display menu
/// entries in different ways. This also provides an event that will be raised
/// when the menu entry is selected.
/// </summary>
public class MenuEntry : RelativeLayoutButton, ILabel, IDisposable
{
#region Fields
private string _text;
#endregion //Fields
#region Properties
public Label Label { get; protected set; }
public string Text
{
get
{
return _text;
}
set
{
_text = value;
if (null != Label)
{
Label.Text = value;
}
}
}
public bool IsPassword
{
get
{
return null != Label ? Label.IsPassword : false;
}
set
{
if (null != Label)
{
Label.IsPassword = value;
}
}
}
public FontSize FontSize
{
get
{
return Label.FontSize;
}
}
public Color? ShadowColor
{
get
{
return Label.ShadowColor;
}
set
{
Label.ShadowColor = value;
}
}
public Color? TextColor
{
get
{
return Label.TextColor;
}
set
{
Label.TextColor = value;
}
}
public IFontBuddy Font
{
get
{
return Label.Font;
}
set
{
Label.Font = value;
}
}
public override float Scale
{
get
{
return base.Scale;
}
set
{
base.Scale = value;
Label.Scale = Scale;
}
}
#endregion //Properties
#region Initialization
/// <summary>
/// Constructs a new menu entry with the specified text.
/// </summary>
public MenuEntry(string text, ContentManager content)
{
_text = text;
Horizontal = HorizontalAlignment.Center;
Vertical = VerticalAlignment.Top;
Label = CreateLabel(content);
Init();
}
/// <summary>
/// Constructs a new menu entry with the specified text.
/// </summary>
public MenuEntry(string text, IFontBuddy font, IFontBuddy highlightedFont = null)
{
_text = text;
Horizontal = HorizontalAlignment.Center;
Vertical = VerticalAlignment.Top;
Label = CreateLabel(font, highlightedFont);
Init();
}
public MenuEntry(MenuEntry inst) : base(inst)
{
_text = inst._text;
Label = CreateLabel(inst.Label);
Init();
}
public virtual Label CreateLabel(ContentManager content)
{
return new Label(Text, content, FontSize.Medium)
{
Vertical = VerticalAlignment.Center,
Horizontal = HorizontalAlignment.Center
};
}
public virtual Label CreateLabel(IFontBuddy font, IFontBuddy highlightedFont = null)
{
return new Label(Text, font, highlightedFont)
{
Vertical = VerticalAlignment.Center,
Horizontal = HorizontalAlignment.Center
};
}
public virtual Label CreateLabel(Label inst)
{
return new Label(inst);
}
private void Init()
{
//get the label height from the font being used
var labelHeight = Label.Rect.Height;
var labelWidth = Resolution.TitleSafeArea.Width;
var shim = new Shim(labelWidth, labelHeight * 0.7f)
{
Horizontal = HorizontalAlignment.Center,
Vertical = VerticalAlignment.Bottom,
HasBackground = this.HasBackground,
};
Size = new Vector2(labelWidth, labelHeight + shim.Rect.Height);
AddItem(shim);
AddItem(Label);
}
public override IScreenItem DeepCopy()
{
return new MenuEntry(this);
}
public override void UnloadContent()
{
base.UnloadContent();
Label?.UnloadContent();
Label = null;
}
#endregion //Initialization
#region Methods
public override string ToString()
{
return Text;
}
public void ScaleToFit(int rowWidth)
{
Label.ScaleToFit(rowWidth);
}
public void ShrinkToFit(int rowWidth)
{
Label.ShrinkToFit(rowWidth);
}
#endregion //Methods
}
}
| |
using System;
class MyTestClass
{
public MyTestClass()
{
this.m_value = false;
}
public MyTestClass(bool value)
{
this.m_value = value;
}
bool m_value;
};
public class BooleanIConvertibleToType
{
public static int Main()
{
BooleanIConvertibleToType testCase = new BooleanIConvertibleToType();
TestLibrary.TestFramework.BeginTestCase("Boolean.IConvertible.ToType");
if (testCase.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive test cases
/// <summary>
/// convert to int
/// </summary>
/// <returns></returns>
public bool PosTest1()
{
bool retVal = true;
try
{
if ( (int)(true as IConvertible).ToType(typeof(int), null) != 1 )
{
TestLibrary.TestFramework.LogError("001", "expect (int)(true as IConvertible).ToType(typeof(int), null) == 1");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to uint
/// </summary>
/// <returns></returns>
public bool PosTest2()
{
bool retVal = true;
try
{
if ((uint)(true as IConvertible).ToType(typeof(uint), null) != 1)
{
TestLibrary.TestFramework.LogError("002", "expect (uint)(true as IConvertible).ToType(typeof(uint), null) == 1");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to long
/// </summary>
/// <returns></returns>
public bool PosTest3()
{
bool retVal = true;
try
{
if ((long)(false as IConvertible).ToType(typeof(long), null) != (long)0)
{
TestLibrary.TestFramework.LogError("003", "expect (long)(false as IConvertible).ToType(typeof(long), null) == (long)0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to ulong
/// </summary>
/// <returns></returns>
public bool PosTest4()
{
bool retVal = true;
try
{
if ((ulong)(false as IConvertible).ToType(typeof(ulong), null) != (ulong)0)
{
TestLibrary.TestFramework.LogError("004", "expect (ulong)(false as IConvertible).ToType(typeof(ulong), null) == (ulong)0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to short
/// </summary>
/// <returns></returns>
public bool PosTest5()
{
bool retVal = true;
try
{
if ((short)(true as IConvertible).ToType(typeof(short), null) != (short)1)
{
TestLibrary.TestFramework.LogError("005", "expect (short)(true as IConvertible).ToType(typeof(short), null) == (short)1");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to ushort
/// </summary>
/// <returns></returns>
public bool PosTest6()
{
bool retVal = true;
try
{
if ((ushort)(false as IConvertible).ToType(typeof(ushort), null) != (ushort)0)
{
TestLibrary.TestFramework.LogError("006", "expect (ushort)(false as IConvertible).ToType(typeof(ushort), null) == (ushort)0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to byte
/// </summary>
/// <returns></returns>
public bool PosTest7()
{
bool retVal = true;
try
{
if ((byte)(true as IConvertible).ToType(typeof(byte), null) != (byte)1)
{
TestLibrary.TestFramework.LogError("007", "expect (byte)(true as IConvertible).ToType(typeof(byte), null) == (byte)1");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to sbyte
/// </summary>
/// <returns></returns>
public bool PosTest8()
{
bool retVal = true;
try
{
if ((sbyte)(true as IConvertible).ToType(typeof(sbyte), null) != (sbyte)1)
{
TestLibrary.TestFramework.LogError("008", "expect (sbyte)(true as IConvertible).ToType(typeof(sbyte), null) == (sbyte)1");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to bool
/// </summary>
/// <returns></returns>
public bool PosTest9()
{
bool retVal = true;
try
{
if ((bool)(true as IConvertible).ToType(typeof(Boolean), null) != true)
{
TestLibrary.TestFramework.LogError("009", "expect (bool)(true as IConvertible).ToType(typeof(Boolean), null) == true");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to Object
/// </summary>
/// <returns></returns>
public bool PosTest10()
{
bool retVal = true;
try
{
object v = (true as IConvertible).ToType(typeof(Object), null);
if ( v.GetType() != typeof(Boolean) )
{
TestLibrary.TestFramework.LogError("010.1", "expect (true as IConvertible).ToType(typeof(Object), null).GetType() == typeof(Boolean)");
retVal = false;
}
if ((bool)v != true)
{
TestLibrary.TestFramework.LogError("0010.2", "expect (bool)(true as IConvertible).ToType(typeof(Object), null) == true");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to float
/// </summary>
/// <returns></returns>
public bool PosTest11()
{
bool retVal = true;
try
{
if ((float)(true as IConvertible).ToType(typeof(float), null) != 1.0f)
{
TestLibrary.TestFramework.LogError("011.1", "expect (float)(true as IConvertible).ToType(typeof(float), null) == 1.0f");
retVal = false;
}
if ((float)(false as IConvertible).ToType(typeof(float), null) != 0.0f)
{
TestLibrary.TestFramework.LogError("011.1", "expect (float)(false as IConvertible).ToType(typeof(float), null) == 0.0f");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to double
/// </summary>
/// <returns></returns>
public bool PosTest12()
{
bool retVal = true;
try
{
if ((double)(true as IConvertible).ToType(typeof(double), null) != 1.0)
{
TestLibrary.TestFramework.LogError("012.1", "expect (double)(true as IConvertible).ToType(typeof(double), null) == 1.0");
retVal = false;
}
if ((double)(false as IConvertible).ToType(typeof(double), null) != 0.0)
{
TestLibrary.TestFramework.LogError("012.1", "expect (double)(false as IConvertible).ToType(typeof(double), null) == 0.0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to decimal
/// </summary>
/// <returns></returns>
public bool PosTest13()
{
bool retVal = true;
try
{
if ((decimal)(true as IConvertible).ToType(typeof(decimal), null) != (decimal)1.0)
{
TestLibrary.TestFramework.LogError("013.1", "expect (decimal)(true as IConvertible).ToType(typeof(decimal), null) == (decimal)1.0");
retVal = false;
}
if ((decimal)(false as IConvertible).ToType(typeof(decimal), null) != (decimal)0.0)
{
TestLibrary.TestFramework.LogError("013.1", "expect (decimal)(false as IConvertible).ToType(typeof(decimal), null) == (decimal)0.0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Negative test cases
/// <summary>
/// convert to char and expcet InvalidCastException
/// </summary>
/// <returns></returns>
public bool NegTest1()
{
bool retVal = true;
try
{
char v = (char)(true as IConvertible).ToType(typeof(Char), null);
TestLibrary.TestFramework.LogError("001",
String.Format("expected a InvalidCastException on (true as IConvertible).ToType(typeof(Char), null) but got {0}", v));
retVal = false;
}
catch (InvalidCastException)
{
retVal = true;
return retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to DateTime and expcet InvalidCastException
/// </summary>
/// <returns></returns>
public bool NegTest2()
{
bool retVal = true;
try
{
DateTime v = (DateTime)(true as IConvertible).ToType(typeof(DateTime), null);
TestLibrary.TestFramework.LogError("002",
String.Format("expected a InvalidCastException on (true as IConvertible).ToType(typeof(DateTime), null) but got {0}", v));
retVal = false;
}
catch (InvalidCastException)
{
retVal = true;
return retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
/// <summary>
/// convert to MyTestClass and expcet InvalidCastException
/// </summary>
/// <returns></returns>
public bool NegTest3()
{
bool retVal = true;
try
{
MyTestClass v = (MyTestClass)(true as IConvertible).ToType(typeof(MyTestClass), null);
TestLibrary.TestFramework.LogError("003",
String.Format("expected a InvalidCastException on (true as IConvertible).ToType(typeof(MyTestClass), null) but got {0}", v));
retVal = false;
}
catch (InvalidCastException)
{
retVal = true;
return retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using OpenIddict.Abstractions;
using OrchardCore.OpenId.Abstractions.Stores;
using OrchardCore.OpenId.YesSql.Indexes;
using OrchardCore.OpenId.YesSql.Models;
using YesSql;
namespace OrchardCore.OpenId.YesSql.Stores
{
public class OpenIdApplicationStore<TApplication> : IOpenIdApplicationStore<TApplication>
where TApplication : OpenIdApplication, new()
{
private readonly ISession _session;
public OpenIdApplicationStore(ISession session)
{
_session = session;
}
/// <summary>
/// Determines the number of applications that exist in the database.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the number of applications in the database.
/// </returns>
public virtual async Task<long> CountAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return await _session.Query<TApplication>().CountAsync();
}
/// <summary>
/// Determines the number of applications that match the specified query.
/// </summary>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="query">The query to execute.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the number of applications that match the specified query.
/// </returns>
public virtual Task<long> CountAsync<TResult>(Func<IQueryable<TApplication>, IQueryable<TResult>> query, CancellationToken cancellationToken)
=> throw new NotSupportedException();
/// <summary>
/// Creates a new application.
/// </summary>
/// <param name="application">The application to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task CreateAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
cancellationToken.ThrowIfCancellationRequested();
_session.Save(application);
return _session.CommitAsync();
}
/// <summary>
/// Removes an existing application.
/// </summary>
/// <param name="application">The application to delete.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task DeleteAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
cancellationToken.ThrowIfCancellationRequested();
_session.Delete(application);
return _session.CommitAsync();
}
/// <summary>
/// Retrieves an application using its unique identifier.
/// </summary>
/// <param name="identifier">The unique identifier associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the client application corresponding to the identifier.
/// </returns>
public virtual Task<TApplication> FindByIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier));
}
cancellationToken.ThrowIfCancellationRequested();
return _session.Query<TApplication, OpenIdApplicationIndex>(index => index.ApplicationId == identifier).FirstOrDefaultAsync();
}
/// <summary>
/// Retrieves an application using its client identifier.
/// </summary>
/// <param name="identifier">The client identifier associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the client application corresponding to the identifier.
/// </returns>
public virtual Task<TApplication> FindByClientIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier));
}
cancellationToken.ThrowIfCancellationRequested();
return _session.Query<TApplication, OpenIdApplicationIndex>(index => index.ClientId == identifier).FirstOrDefaultAsync();
}
/// <summary>
/// Retrieves an application using its physical identifier.
/// </summary>
/// <param name="identifier">The unique identifier associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the client application corresponding to the identifier.
/// </returns>
public virtual Task<TApplication> FindByPhysicalIdAsync(string identifier, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(identifier))
{
throw new ArgumentException("The identifier cannot be null or empty.", nameof(identifier));
}
cancellationToken.ThrowIfCancellationRequested();
return _session.GetAsync<TApplication>(int.Parse(identifier, CultureInfo.InvariantCulture));
}
/// <summary>
/// Retrieves all the applications associated with the specified post_logout_redirect_uri.
/// </summary>
/// <param name="address">The post_logout_redirect_uri associated with the applications.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation, whose result
/// returns the client applications corresponding to the specified post_logout_redirect_uri.
/// </returns>
public virtual async Task<ImmutableArray<TApplication>> FindByPostLogoutRedirectUriAsync(string address, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(address))
{
throw new ArgumentException("The address cannot be null or empty.", nameof(address));
}
cancellationToken.ThrowIfCancellationRequested();
return ImmutableArray.CreateRange(
await _session.Query<TApplication, OpenIdAppByLogoutUriIndex>(
index => index.LogoutRedirectUri == address).ListAsync());
}
/// <summary>
/// Retrieves all the applications associated with the specified redirect_uri.
/// </summary>
/// <param name="address">The redirect_uri associated with the applications.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation, whose result
/// returns the client applications corresponding to the specified redirect_uri.
/// </returns>
public virtual async Task<ImmutableArray<TApplication>> FindByRedirectUriAsync(string address, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(address))
{
throw new ArgumentException("The address cannot be null or empty.", nameof(address));
}
cancellationToken.ThrowIfCancellationRequested();
return ImmutableArray.CreateRange(
await _session.Query<TApplication, OpenIdAppByRedirectUriIndex>(
index => index.RedirectUri == address).ListAsync());
}
/// <summary>
/// Executes the specified query and returns the first element.
/// </summary>
/// <typeparam name="TState">The state type.</typeparam>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="query">The query to execute.</param>
/// <param name="state">The optional state.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns the first element returned when executing the query.
/// </returns>
public virtual Task<TResult> GetAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query,
TState state, CancellationToken cancellationToken)
=> throw new NotSupportedException();
/// <summary>
/// Retrieves the client identifier associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the client identifier associated with the application.
/// </returns>
public virtual ValueTask<string> GetClientIdAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string>(application.ClientId);
}
/// <summary>
/// Retrieves the client secret associated with an application.
/// Note: depending on the manager used to create the application,
/// the client secret may be hashed for security reasons.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the client secret associated with the application.
/// </returns>
public virtual ValueTask<string> GetClientSecretAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string>(application.ClientSecret);
}
/// <summary>
/// Retrieves the client type associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the client type of the application (by default, "public").
/// </returns>
public virtual ValueTask<string> GetClientTypeAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string>(application.Type);
}
/// <summary>
/// Retrieves the consent type associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the consent type of the application (by default, "explicit").
/// </returns>
public virtual ValueTask<string> GetConsentTypeAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string>(application.ConsentType);
}
/// <summary>
/// Retrieves the display name associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the display name associated with the application.
/// </returns>
public virtual ValueTask<string> GetDisplayNameAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string>(application.DisplayName);
}
/// <summary>
/// Retrieves the unique identifier associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the unique identifier associated with the application.
/// </returns>
public virtual ValueTask<string> GetIdAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string>(application.ApplicationId);
}
/// <summary>
/// Retrieves the permissions associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the permissions associated with the application.
/// </returns>
public virtual ValueTask<ImmutableArray<string>> GetPermissionsAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<ImmutableArray<string>>(application.Permissions);
}
/// <summary>
/// Retrieves the physical identifier associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the physical identifier associated with the application.
/// </returns>
public virtual ValueTask<string> GetPhysicalIdAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<string>(application.Id.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Retrieves the logout callback addresses associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the post_logout_redirect_uri associated with the application.
/// </returns>
public virtual ValueTask<ImmutableArray<string>> GetPostLogoutRedirectUrisAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<ImmutableArray<string>>(application.PostLogoutRedirectUris);
}
/// <summary>
/// Retrieves the additional properties associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the additional properties associated with the application.
/// </returns>
public virtual ValueTask<JObject> GetPropertiesAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<JObject>(application.Properties ?? new JObject());
}
/// <summary>
/// Retrieves the callback addresses associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the redirect_uri associated with the application.
/// </returns>
public virtual ValueTask<ImmutableArray<string>> GetRedirectUrisAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<ImmutableArray<string>>(application.RedirectUris);
}
/// <summary>
/// Instantiates a new application.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> that can be used to monitor the asynchronous operation,
/// whose result returns the instantiated application, that can be persisted in the database.
/// </returns>
public virtual ValueTask<TApplication> InstantiateAsync(CancellationToken cancellationToken)
=> new ValueTask<TApplication>(new TApplication { ApplicationId = Guid.NewGuid().ToString("n") });
/// <summary>
/// Executes the specified query and returns all the corresponding elements.
/// </summary>
/// <param name="count">The number of results to return.</param>
/// <param name="offset">The number of results to skip.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the elements returned when executing the specified query.
/// </returns>
public virtual async Task<ImmutableArray<TApplication>> ListAsync(int? count, int? offset, CancellationToken cancellationToken)
{
var query = _session.Query<TApplication>();
if (offset.HasValue)
{
query = query.Skip(offset.Value);
}
if (count.HasValue)
{
query = query.Take(count.Value);
}
return ImmutableArray.CreateRange(await query.ListAsync());
}
/// <summary>
/// Executes the specified query and returns all the corresponding elements.
/// </summary>
/// <typeparam name="TState">The state type.</typeparam>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="query">The query to execute.</param>
/// <param name="state">The optional state.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation,
/// whose result returns all the elements returned when executing the specified query.
/// </returns>
public virtual Task<ImmutableArray<TResult>> ListAsync<TState, TResult>(
Func<IQueryable<TApplication>, TState, IQueryable<TResult>> query,
TState state, CancellationToken cancellationToken)
=> throw new NotSupportedException();
/// <summary>
/// Sets the client identifier associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="identifier">The client identifier associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetClientIdAsync(TApplication application,
string identifier, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientId = identifier;
return Task.CompletedTask;
}
/// <summary>
/// Sets the client secret associated with an application.
/// Note: depending on the manager used to create the application,
/// the client secret may be hashed for security reasons.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="secret">The client secret associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetClientSecretAsync(TApplication application, string secret, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.ClientSecret = secret;
return Task.CompletedTask;
}
/// <summary>
/// Sets the client type associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="type">The client type associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetClientTypeAsync(TApplication application, string type, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.Type = type;
return Task.CompletedTask;
}
/// <summary>
/// Sets the consent type associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="type">The consent type associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetConsentTypeAsync(TApplication application, string type, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.ConsentType = type;
return Task.CompletedTask;
}
/// <summary>
/// Sets the display name associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="name">The display name associated with the application.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetDisplayNameAsync(TApplication application, string name, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.DisplayName = name;
return Task.CompletedTask;
}
/// <summary>
/// Sets the permissions associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="permissions">The permissions associated with the application </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetPermissionsAsync(TApplication application, ImmutableArray<string> permissions, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.Permissions = permissions;
return Task.CompletedTask;
}
/// <summary>
/// Sets the logout callback addresses associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="addresses">The logout callback addresses associated with the application </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetPostLogoutRedirectUrisAsync(TApplication application,
ImmutableArray<string> addresses, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.PostLogoutRedirectUris = addresses;
return Task.CompletedTask;
}
/// <summary>
/// Sets the additional properties associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="properties">The additional properties associated with the application </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetPropertiesAsync(TApplication application, JObject properties, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.Properties = properties;
return Task.CompletedTask;
}
/// <summary>
/// Sets the callback addresses associated with an application.
/// </summary>
/// <param name="application">The application.</param>
/// <param name="addresses">The callback addresses associated with the application </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual Task SetRedirectUrisAsync(TApplication application,
ImmutableArray<string> addresses, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.RedirectUris = addresses;
return Task.CompletedTask;
}
/// <summary>
/// Updates an existing application.
/// </summary>
/// <param name="application">The application to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
/// </returns>
public virtual async Task UpdateAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
cancellationToken.ThrowIfCancellationRequested();
_session.Save(application, checkConcurrency: true);
try
{
await _session.CommitAsync();
}
catch (ConcurrencyException exception)
{
throw new OpenIddictExceptions.ConcurrencyException(new StringBuilder()
.AppendLine("The application was concurrently updated and cannot be persisted in its current state.")
.Append("Reload the application from the database and retry the operation.")
.ToString(), exception);
}
}
public virtual ValueTask<ImmutableArray<string>> GetRolesAsync(TApplication application, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
return new ValueTask<ImmutableArray<string>>(application.Roles);
}
public virtual async Task<ImmutableArray<TApplication>> ListInRoleAsync(string role, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(role))
{
throw new ArgumentException("The role name cannot be null or empty.", nameof(role));
}
return ImmutableArray.CreateRange(await _session.Query<TApplication, OpenIdAppByRoleNameIndex>(index => index.RoleName == role).ListAsync());
}
public virtual Task SetRolesAsync(TApplication application, ImmutableArray<string> roles, CancellationToken cancellationToken)
{
if (application == null)
{
throw new ArgumentNullException(nameof(application));
}
application.Roles = roles;
return Task.CompletedTask;
}
}
}
| |
/***************************************************************************
* MtpDevice.cs
*
* Copyright (C) 2006-2007 Alan McGovern
* Authors:
* Alan McGovern (alan.mcgovern@gmail.com)
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Mtp
{
public delegate int ProgressFunction(ulong sent, ulong total, IntPtr data);
public class MtpDevice : IDisposable
{
internal static IntPtr Offset (IntPtr ptr, int offset)
{
if (IntPtr.Size == 8) {
return (IntPtr) (ptr.ToInt64 () + offset);
} else {
return (IntPtr) (ptr.ToInt32 () + offset);
}
}
internal MtpDeviceHandle Handle;
private MtpDeviceStruct device;
private string name;
private Folder albumFolder;
private Folder musicFolder;
private Folder organizerFolder;
private Folder pictureFolder;
private Folder playlistFolder;
private Folder podcastFolder;
private Folder textFolder;
private Folder videoFolder;
static MtpDevice() {
LIBMTP_Init ();
}
public int BatteryLevel {
get {
ushort level, maxLevel;
GetBatteryLevel (Handle, out maxLevel, out level);
return (int)((level * 100.0) / maxLevel);
}
}
public string SerialNumber {
get { return GetSerialnumber (Handle); }
}
public string Version {
get { return GetDeviceversion (Handle); }
}
public string ModelName {
get; private set;
}
public string Name {
get { return name; }
set {
if (SetFriendlyName (Handle, value)) {
name = value;
}
}
}
public Folder AlbumFolder {
get { return albumFolder; }
}
public Folder MusicFolder {
get { return musicFolder; }
}
public Folder OrganizerFolder {
get { return organizerFolder; }
}
public Folder PictureFolder {
get { return pictureFolder; }
}
public Folder PlaylistFolder {
get { return playlistFolder; }
}
public Folder PodcastFolder {
get { return podcastFolder; }
}
public Folder TextFolder {
get { return textFolder; }
}
public Folder VideoFolder {
get { return videoFolder; }
}
internal MtpDevice (MtpDeviceHandle handle, MtpDeviceStruct device)
{
this.device = device;
this.Handle = handle;
this.name = GetFriendlyName(Handle);
this.ModelName = GetModelName (Handle);
SetDefaultFolders ();
}
internal MtpDevice(IntPtr handle, bool ownsHandle, MtpDeviceStruct device)
: this(new MtpDeviceHandle(handle, ownsHandle), device)
{
}
/// <summary>
/// This function scans the top level directories and stores the relevant ones so they are readily
/// accessible
/// </summary>
private void SetDefaultFolders ()
{
List<Folder> folders = GetRootFolders();
foreach (Folder f in folders)
{
if (f.FolderId == this.device.default_album_folder)
albumFolder = f;
else if (f.FolderId == device.default_music_folder) {
musicFolder = f;
}
else if (f.FolderId == device.default_organizer_folder)
organizerFolder = f;
else if (f.FolderId == device.default_picture_folder)
pictureFolder = f;
else if (f.FolderId == device.default_playlist_folder)
playlistFolder = f;
else if (f.FolderId == device.default_text_folder)
textFolder = f;
else if (f.FolderId == device.default_video_folder)
videoFolder = f;
else if (f.FolderId == device.default_zencast_folder)
podcastFolder = f;
}
// Fix for devices that don't have an explicit playlist folder (see BGO #590342 and #733883)
if (playlistFolder == null && musicFolder != null) {
playlistFolder = musicFolder;
}
}
public void Dispose ()
{
if (!Handle.IsClosed)
Handle.Close();
}
public List<Folder> GetRootFolders()
{
return Folder.GetRootFolders(this);
}
public List<Track> GetAllTracks()
{
return GetAllTracks(null);
}
public List<Track> GetAllTracks(ProgressFunction callback)
{
IntPtr ptr = Track.GetTrackListing(Handle, callback, IntPtr.Zero);
List<Track> tracks = new List<Track>();
while (ptr != IntPtr.Zero) {
// Destroy the struct after we use it to avoid potential referencing of freed memory.
TrackStruct track = (TrackStruct)Marshal.PtrToStructure(ptr, typeof(TrackStruct));
tracks.Add (new Track (track, this));
Track.DestroyTrack (ptr);
ptr = track.next;
}
return tracks;
}
public List<Playlist> GetPlaylists ()
{
return Playlist.GetPlaylists (this);
}
public List<Album> GetAlbums ()
{
return Album.GetAlbums (this);
}
public List<DeviceStorage> GetStorage ()
{
List<DeviceStorage> storages = new List<DeviceStorage>();
IntPtr ptr = device.storage;
while (ptr != IntPtr.Zero) {
DeviceStorage storage = (DeviceStorage)Marshal.PtrToStructure(ptr, typeof(DeviceStorage));
storages.Add (storage);
ptr = storage.Next;
}
return storages;
}
public void Remove (Track track)
{
DeleteObject(Handle, track.FileId);
}
public void UploadTrack (string path, Track track, Folder folder)
{
UploadTrack (path, track, folder, null);
}
public void UploadTrack (string path, Track track, Folder folder, ProgressFunction callback)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (track == null)
throw new ArgumentNullException("track");
folder = folder ?? MusicFolder;
if (folder != null) {
track.trackStruct.parent_id = folder.FolderId;
}
// We send the trackstruct by ref so that when the file_id gets filled in, our copy is updated
Track.SendTrack (Handle, path, ref track.trackStruct, callback, IntPtr.Zero);
// LibMtp.GetStorage (Handle, 0);
}
public FileType [] GetFileTypes ()
{
Int16 [] ints = GetFileTypes (Handle);
FileType [] file_types = new FileType [ints.Length];
for (int i = 0; i < ints.Length; i++) {
file_types[i] = (FileType) ints[i];
}
return file_types;
}
public static MtpDevice Connect (RawMtpDevice rawDevice)
{
var raw = rawDevice.RawDevice;
IntPtr device = LIBMTP_Open_Raw_Device (ref raw);
if (device == IntPtr.Zero)
return null;
return new MtpDevice (new MtpDeviceHandle (device, true), (MtpDeviceStruct) Marshal.PtrToStructure (device, typeof (MtpDeviceStruct)));
}
public static List<RawMtpDevice> Detect ()
{
int count = 0;
IntPtr ptr = IntPtr.Zero;
LIBMTP_Detect_Raw_Devices (ref ptr, ref count);
List<RawMtpDevice> devices = new List<RawMtpDevice>();
for (int i = 0; i < count; i++) {
IntPtr offset = Offset (ptr, i * Marshal.SizeOf (typeof (RawDeviceStruct)));
RawDeviceStruct d = (RawDeviceStruct)Marshal.PtrToStructure (offset, typeof(RawDeviceStruct));
devices.Add(new RawMtpDevice (d));
}
return devices;
}
internal static void ClearErrorStack(MtpDeviceHandle handle)
{
LIBMTP_Clear_Errorstack (handle);
}
internal static void DeleteObject(MtpDeviceHandle handle, uint object_id)
{
if (LIBMTP_Delete_Object(handle, object_id) != 0)
{
LibMtpException.CheckErrorStack(handle);
throw new LibMtpException(ErrorCode.General, "Could not delete the track");
}
}
internal static void GetBatteryLevel (MtpDeviceHandle handle, out ushort maxLevel, out ushort currentLevel)
{
int result = LIBMTP_Get_Batterylevel (handle, out maxLevel, out currentLevel);
if (result != 0) {
LibMtpException.CheckErrorStack (handle);
throw new LibMtpException (ErrorCode.General, "Could not retrieve battery stats");
}
}
internal static void GetConnectedDevices (out IntPtr list)
{
Error.CheckError (LIBMTP_Get_Connected_Devices (out list));
}
internal static IntPtr GetErrorStack (MtpDeviceHandle handle)
{
return LIBMTP_Get_Errorstack(handle);
}
internal static string GetDeviceversion(MtpDeviceHandle handle)
{
IntPtr ptr = LIBMTP_Get_Deviceversion(handle);
if (ptr == IntPtr.Zero)
return null;
return StringFromIntPtr (ptr);
}
internal static string GetFriendlyName(MtpDeviceHandle handle)
{
IntPtr ptr = LIBMTP_Get_Friendlyname(handle);
if (ptr == IntPtr.Zero)
return null;
return StringFromIntPtr (ptr);
}
internal static bool SetFriendlyName(MtpDeviceHandle handle, string name)
{
bool success = LIBMTP_Set_Friendlyname (handle, name) == 0;
return success;
}
internal static string GetModelName(MtpDeviceHandle handle)
{
IntPtr ptr = LIBMTP_Get_Modelname (handle);
if (ptr == IntPtr.Zero)
return null;
return StringFromIntPtr (ptr);
}
internal static string GetSerialnumber(MtpDeviceHandle handle)
{
IntPtr ptr = LIBMTP_Get_Serialnumber(handle);
if (ptr == IntPtr.Zero)
return null;
return StringFromIntPtr (ptr);
}
internal static void GetStorage (MtpDeviceHandle handle, int sortMode)
{
LIBMTP_Get_Storage (handle, sortMode);
}
internal static Int16 [] GetFileTypes (MtpDeviceHandle handle)
{
IntPtr types = IntPtr.Zero;
ushort count = 0;
if (LIBMTP_Get_Supported_Filetypes (handle, ref types, ref count) == 0) {
Int16 [] type_ary = new Int16 [count];
Marshal.Copy (types, type_ary, 0, (int)count);
Marshal.FreeHGlobal (types);
return type_ary;
}
return new Int16[0];
}
internal static void ReleaseDevice (IntPtr handle)
{
LIBMTP_Release_Device(handle);
}
private static string StringFromIntPtr (IntPtr ptr)
{
int i = 0;
while (Marshal.ReadByte (ptr, i) != (byte) 0) ++i;
byte[] s_buf = new byte [i];
Marshal.Copy (ptr, s_buf, 0, s_buf.Length);
string s = System.Text.Encoding.UTF8.GetString (s_buf);
Marshal.FreeCoTaskMem(ptr);
return s;
}
internal const string LibMtpLibrary = "libmtp.dll";
// Device Management
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void LIBMTP_Init ();
// Clears out the error stack and frees any allocated memory.
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void LIBMTP_Clear_Errorstack (MtpDeviceHandle handle);
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
internal static extern int LIBMTP_Delete_Object (MtpDeviceHandle handle, uint object_id);
// Gets the first connected device:
//[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
//private static extern IntPtr LIBMTP_Get_First_Device (); // LIBMTP_mtpdevice_t *
// Gets the storage information
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern int LIBMTP_Get_Storage (MtpDeviceHandle handle, int sortMode);
// Formats the supplied storage device attached to the device
//[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
//private static extern int LIBMTP_Format_Storage (MtpDeviceHandle handle, ref DeviceStorage storage);
// Counts the devices in the list
//[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
//private static extern uint LIBMTP_Number_Devices_In_List (MtpDeviceHandle handle);
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern ErrorCode LIBMTP_Get_Connected_Devices (out IntPtr list); //LIBMTP_mtpdevice_t **
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern ErrorCode LIBMTP_Detect_Raw_Devices (ref IntPtr list, ref int count); //LIBMTP_raw_device_t
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr LIBMTP_Open_Raw_Device (ref RawDeviceStruct rawdevice);
// Deallocates the memory for the device
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void LIBMTP_Release_Device (IntPtr device);
//[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
//private static extern int LIBMTP_Reset_Device (MtpDeviceHandle handle);
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern int LIBMTP_Get_Batterylevel (MtpDeviceHandle handle, out ushort maxLevel, out ushort currentLevel);
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr LIBMTP_Get_Modelname (MtpDeviceHandle handle); // char *
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr LIBMTP_Get_Serialnumber (MtpDeviceHandle handle); // char *
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr LIBMTP_Get_Deviceversion (MtpDeviceHandle handle); // char *
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr LIBMTP_Get_Friendlyname (MtpDeviceHandle handle); // char *
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern int LIBMTP_Set_Friendlyname (MtpDeviceHandle handle, string name);
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr LIBMTP_Get_Errorstack (MtpDeviceHandle handle); // LIBMTP_error_t *
[DllImport (LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern int LIBMTP_Get_Supported_Filetypes (MtpDeviceHandle handle, ref IntPtr types, ref ushort count); // uint16_t **const
// void LIBMTP_Release_Device_List (LIBMTP_mtpdevice_t *)
// int LIBMTP_Detect_Descriptor (uint16_t *, uint16_t *);
/*
void LIBMTP_Dump_Device_Info (LIBMTP_mtpdevice_t *)
char * LIBMTP_Get_Syncpartner (LIBMTP_mtpdevice_t *)
int LIBMTP_Set_Syncpartner (LIBMTP_mtpdevice_t *, char const *const)
int LIBMTP_Get_Secure_Time (LIBMTP_mtpdevice_t *, char **const)
int LIBMTP_Get_Device_Certificate (LIBMTP_mtpdevice_t *, char **const)
*/
public static string GetMimeTypeFor (FileType type)
{
switch (type) {
case FileType.MP3: return "audio/mpeg";
case FileType.OGG: return "audio/ogg";
case FileType.WMA: return "audio/x-ms-wma";
case FileType.WMV: return "video/x-ms-wmv";
case FileType.ASF: return "video/x-ms-asf";
case FileType.AAC: return "audio/x-aac";
case FileType.MP4: return "video/mp4";
case FileType.AVI: return "video/avi";
case FileType.WAV: return "audio/x-wav";
case FileType.MPEG: return "video/mpeg";
case FileType.FLAC: return "audio/flac";
case FileType.QT: return "video/quicktime";
case FileType.M4A: return "audio/mp4";
}
return null;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct DeviceEntry
{
[MarshalAs(UnmanagedType.LPStr)] public string vendor;
public ushort vendor_id;
[MarshalAs(UnmanagedType.LPStr)] public string product;
public ushort product_id;
public uint device_flags;
}
[StructLayout(LayoutKind.Sequential)]
public struct DeviceStorage
{
public uint Id;
public ushort StorageType;
public ushort FileSystemType;
public ushort AccessCapability;
public ulong MaxCapacity;
public ulong FreeSpaceInBytes;
public ulong FreeSpaceInObjects;
[MarshalAs(UnmanagedType.LPStr)] public string StorageDescription;
[MarshalAs(UnmanagedType.LPStr)] public string VolumeIdentifier;
public IntPtr Next; // LIBMTP_devicestorage_t*
public IntPtr Prev; // LIBMTP_devicestorage_t*
}
internal class MtpDeviceHandle : SafeHandle
{
private MtpDeviceHandle()
: base(IntPtr.Zero, true)
{
}
internal MtpDeviceHandle(IntPtr ptr, bool ownsHandle)
: base (IntPtr.Zero, ownsHandle)
{
SetHandle (ptr);
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle ()
{
MtpDevice.ReleaseDevice(handle);
return true;
}
}
internal struct MtpDeviceStruct
{
public byte object_bitsize;
public IntPtr parameters; // void*
public IntPtr usbinfo; // void*
public IntPtr storage; // LIBMTP_devicestorage_t*
public IntPtr errorstack; // LIBMTP_error_t*
public byte maximum_battery_level;
public uint default_music_folder;
public uint default_playlist_folder;
public uint default_picture_folder;
public uint default_video_folder;
public uint default_organizer_folder;
public uint default_zencast_folder;
public uint default_album_folder;
public uint default_text_folder;
public IntPtr cd; // void*
public IntPtr next; // LIBMTP_mtpdevice_t*
}
[StructLayout (LayoutKind.Sequential)]
internal struct RawDeviceStruct {
public DeviceEntry device_entry; /**< The device entry for this raw device */
public uint bus_location; /**< Location of the bus, if device available */
public byte devnum; /**< Device number on the bus, if device available */
}
public class RawMtpDevice {
public uint BusNumber {
get { return RawDevice.bus_location; }
}
public int DeviceNumber {
get { return RawDevice.devnum; }
}
internal RawDeviceStruct RawDevice {
get; private set;
}
internal RawMtpDevice (RawDeviceStruct device)
{
RawDevice = device;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Data.Common
{
[Serializable]
internal sealed class DBConnectionString
{
// instances of this class are intended to be immutable, i.e readonly
// used by permission classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
private static class KEY
{
internal const string Password = "password";
internal const string PersistSecurityInfo = "persist security info";
internal const string Pwd = "pwd";
};
// this class is serializable with Everett, so ugly field names can't be changed
readonly private string _encryptedUsersConnectionString;
// hash of unique keys to values
readonly private Hashtable _parsetable;
// a linked list of key/value and their length in _encryptedUsersConnectionString
readonly private NameValuePair _keychain;
// track the existance of "password" or "pwd" in the connection string
// not used for anything anymore but must keep it set correct for V1.1 serialization
readonly private bool _hasPassword;
readonly private string[] _restrictionValues;
readonly private string _restrictions;
readonly private KeyRestrictionBehavior _behavior;
#pragma warning disable 169
// this field is no longer used, hence the warning was disabled
// however, it can not be removed or it will break serialization with V1.1
readonly private string _encryptedActualConnectionString;
#pragma warning restore 169
internal DBConnectionString(string value, string restrictions, KeyRestrictionBehavior behavior, Hashtable synonyms, bool useOdbcRules)
: this(new DbConnectionOptions(value, synonyms, useOdbcRules), restrictions, behavior, synonyms, false)
{
// useOdbcRules is only used to parse the connection string, not to parse restrictions because values don't apply there
// the hashtable doesn't need clone since it isn't shared with anything else
}
private DBConnectionString(DbConnectionOptions connectionOptions, string restrictions, KeyRestrictionBehavior behavior, Hashtable synonyms, bool mustCloneDictionary)
{
Debug.Assert(null != connectionOptions, "null connectionOptions");
switch (behavior)
{
case KeyRestrictionBehavior.PreventUsage:
case KeyRestrictionBehavior.AllowOnly:
_behavior = behavior;
break;
default:
throw ADP.InvalidKeyRestrictionBehavior(behavior);
}
// grab all the parsed details from DbConnectionOptions
_encryptedUsersConnectionString = connectionOptions.UsersConnectionString(false);
_hasPassword = connectionOptions._hasPasswordKeyword;
_parsetable = connectionOptions.Parsetable;
_keychain = connectionOptions._keyChain;
// we do not want to serialize out user password unless directed so by "persist security info=true"
// otherwise all instances of user's password will be replaced with "*"
if (_hasPassword && !connectionOptions.HasPersistablePassword)
{
if (mustCloneDictionary)
{
// clone the hashtable to replace user's password/pwd value with "*"
// we only need to clone if coming from DbConnectionOptions and password exists
_parsetable = (Hashtable)_parsetable.Clone();
}
// different than Everett in that instead of removing password/pwd from
// the hashtable, we replace the value with '*'. This is okay since we
// serialize out with '*' so already knows what we do. Better this way
// than to treat password specially later on which causes problems.
const string star = "*";
if (_parsetable.ContainsKey(KEY.Password))
{
_parsetable[KEY.Password] = star;
}
if (_parsetable.ContainsKey(KEY.Pwd))
{
_parsetable[KEY.Pwd] = star;
}
// replace user's password/pwd value with "*" in the linked list and build a new string
_keychain = connectionOptions.ReplacePasswordPwd(out _encryptedUsersConnectionString, true);
}
if (!string.IsNullOrEmpty(restrictions))
{
_restrictionValues = ParseRestrictions(restrictions, synonyms);
_restrictions = restrictions;
}
}
private DBConnectionString(DBConnectionString connectionString, string[] restrictionValues, KeyRestrictionBehavior behavior)
{
// used by intersect for two equal connection strings with different restrictions
_encryptedUsersConnectionString = connectionString._encryptedUsersConnectionString;
_parsetable = connectionString._parsetable;
_keychain = connectionString._keychain;
_hasPassword = connectionString._hasPassword;
_restrictionValues = restrictionValues;
_restrictions = null;
_behavior = behavior;
Verify(restrictionValues);
}
internal KeyRestrictionBehavior Behavior
{
get { return _behavior; }
}
internal string ConnectionString
{
get { return _encryptedUsersConnectionString; }
}
internal bool IsEmpty
{
get { return (null == _keychain); }
}
internal NameValuePair KeyChain
{
get { return _keychain; }
}
internal string Restrictions
{
get
{
string restrictions = _restrictions;
if (null == restrictions)
{
string[] restrictionValues = _restrictionValues;
if ((null != restrictionValues) && (0 < restrictionValues.Length))
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < restrictionValues.Length; ++i)
{
if (!string.IsNullOrEmpty(restrictionValues[i]))
{
builder.Append(restrictionValues[i]);
builder.Append("=;");
}
#if DEBUG
else
{
Debug.Assert(false, "empty restriction");
}
#endif
}
restrictions = builder.ToString();
}
}
return ((null != restrictions) ? restrictions : "");
}
}
internal string this[string keyword]
{
get { return (string)_parsetable[keyword]; }
}
internal bool ContainsKey(string keyword)
{
return _parsetable.ContainsKey(keyword);
}
internal DBConnectionString Intersect(DBConnectionString entry)
{
KeyRestrictionBehavior behavior = _behavior;
string[] restrictionValues = null;
if (null == entry)
{
behavior = KeyRestrictionBehavior.AllowOnly;
}
else if (_behavior != entry._behavior)
{
// subset of the AllowOnly array
behavior = KeyRestrictionBehavior.AllowOnly;
if (KeyRestrictionBehavior.AllowOnly == entry._behavior)
{
// this PreventUsage and entry AllowOnly
if (!ADP.IsEmptyArray(_restrictionValues))
{
if (!ADP.IsEmptyArray(entry._restrictionValues))
{
restrictionValues = NewRestrictionAllowOnly(entry._restrictionValues, _restrictionValues);
}
}
else
{
restrictionValues = entry._restrictionValues;
}
}
else if (!ADP.IsEmptyArray(_restrictionValues))
{
// this AllowOnly and entry PreventUsage
if (!ADP.IsEmptyArray(entry._restrictionValues))
{
restrictionValues = NewRestrictionAllowOnly(_restrictionValues, entry._restrictionValues);
}
else
{
restrictionValues = _restrictionValues;
}
}
}
else if (KeyRestrictionBehavior.PreventUsage == _behavior)
{
// both PreventUsage
if (ADP.IsEmptyArray(_restrictionValues))
{
restrictionValues = entry._restrictionValues;
}
else if (ADP.IsEmptyArray(entry._restrictionValues))
{
restrictionValues = _restrictionValues;
}
else
{
restrictionValues = NoDuplicateUnion(_restrictionValues, entry._restrictionValues);
}
}
else if (!ADP.IsEmptyArray(_restrictionValues) && !ADP.IsEmptyArray(entry._restrictionValues))
{
// both AllowOnly with restrictions
if (_restrictionValues.Length <= entry._restrictionValues.Length)
{
restrictionValues = NewRestrictionIntersect(_restrictionValues, entry._restrictionValues);
}
else
{
restrictionValues = NewRestrictionIntersect(entry._restrictionValues, _restrictionValues);
}
}
// verify _hasPassword & _parsetable are in sync between Everett/Whidbey
Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this");
Debug.Assert(null == entry || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry");
DBConnectionString value = new DBConnectionString(this, restrictionValues, behavior);
ValidateCombinedSet(this, value);
ValidateCombinedSet(entry, value);
return value;
}
[Conditional("DEBUG")]
private void ValidateCombinedSet(DBConnectionString componentSet, DBConnectionString combinedSet)
{
Debug.Assert(combinedSet != null, "The combined connection string should not be null");
if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null))
{
if (componentSet._behavior == KeyRestrictionBehavior.AllowOnly)
{
if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly)
{
// Component==Allow, Combined==Allow
// All values in the Combined Set should also be in the Component Set
// Combined - Component == null
Debug.Assert(combinedSet._restrictionValues.Except(componentSet._restrictionValues).Count() == 0, "Combined set allows values not allowed by component set");
}
else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage)
{
// Component==Allow, Combined==PreventUsage
// Preventions override allows, so there is nothing to check here
}
else
{
Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
}
}
else if (componentSet._behavior == KeyRestrictionBehavior.PreventUsage)
{
if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly)
{
// Component==PreventUsage, Combined==Allow
// There shouldn't be any of the values from the Component Set in the Combined Set
// Intersect(Component, Combined) == null
Debug.Assert(combinedSet._restrictionValues.Intersect(componentSet._restrictionValues).Count() == 0, "Combined values allows values prevented by component set");
}
else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage)
{
// Component==PreventUsage, Combined==PreventUsage
// All values in the Component Set should also be in the Combined Set
// Component - Combined == null
Debug.Assert(componentSet._restrictionValues.Except(combinedSet._restrictionValues).Count() == 0, "Combined values does not prevent all of the values prevented by the component set");
}
else
{
Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
}
}
else
{
Debug.Assert(false, string.Format("Unknown behavior for component set: {0}", componentSet._behavior));
}
}
}
private bool IsRestrictedKeyword(string key)
{
// restricted if not found
return ((null == _restrictionValues) || (0 > Array.BinarySearch(_restrictionValues, key, StringComparer.Ordinal)));
}
internal bool IsSupersetOf(DBConnectionString entry)
{
Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this");
Debug.Assert(!entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry");
switch (_behavior)
{
case KeyRestrictionBehavior.AllowOnly:
// every key must either be in the resticted connection string or in the allowed keywords
// keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys
for (NameValuePair current = entry.KeyChain; null != current; current = current.Next)
{
if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name))
{
return false;
}
}
break;
case KeyRestrictionBehavior.PreventUsage:
// every key can not be in the restricted keywords (even if in the restricted connection string)
if (null != _restrictionValues)
{
foreach (string restriction in _restrictionValues)
{
if (entry.ContainsKey(restriction))
{
return false;
}
}
}
break;
default:
Debug.Assert(false, "invalid KeyRestrictionBehavior");
throw ADP.InvalidKeyRestrictionBehavior(_behavior);
}
return true;
}
private static string[] NewRestrictionAllowOnly(string[] allowonly, string[] preventusage)
{
List<string> newlist = null;
for (int i = 0; i < allowonly.Length; ++i)
{
if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal))
{
if (null == newlist)
{
newlist = new List<string>();
}
newlist.Add(allowonly[i]);
}
}
string[] restrictionValues = null;
if (null != newlist)
{
restrictionValues = newlist.ToArray();
}
Verify(restrictionValues);
return restrictionValues;
}
private static string[] NewRestrictionIntersect(string[] a, string[] b)
{
List<string> newlist = null;
for (int i = 0; i < a.Length; ++i)
{
if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal))
{
if (null == newlist)
{
newlist = new List<string>();
}
newlist.Add(a[i]);
}
}
string[] restrictionValues = null;
if (newlist != null)
{
restrictionValues = newlist.ToArray();
}
Verify(restrictionValues);
return restrictionValues;
}
private static string[] NoDuplicateUnion(string[] a, string[] b)
{
#if DEBUG
Debug.Assert(null != a && 0 < a.Length, "empty a");
Debug.Assert(null != b && 0 < b.Length, "empty b");
Verify(a);
Verify(b);
#endif
List<string> newlist = new List<string>(a.Length + b.Length);
for (int i = 0; i < a.Length; ++i)
{
newlist.Add(a[i]);
}
for (int i = 0; i < b.Length; ++i)
{ // find duplicates
if (0 > Array.BinarySearch(a, b[i], StringComparer.Ordinal))
{
newlist.Add(b[i]);
}
}
string[] restrictionValues = newlist.ToArray();
Array.Sort(restrictionValues, StringComparer.Ordinal);
Verify(restrictionValues);
return restrictionValues;
}
private static string[] ParseRestrictions(string restrictions, Hashtable synonyms)
{
#if DEBUG
DataCommonEventSource.Log.Trace("<comm.DBConnectionString|INFO|ADV> Restrictions='{0}'", restrictions);
#endif
List<string> restrictionValues = new List<string>();
StringBuilder buffer = new StringBuilder(restrictions.Length);
int nextStartPosition = 0;
int endPosition = restrictions.Length;
while (nextStartPosition < endPosition)
{
int startPosition = nextStartPosition;
string keyname, keyvalue; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules
nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out keyvalue);
if (!string.IsNullOrEmpty(keyname))
{
#if DEBUG
DataCommonEventSource.Log.Trace("<comm.DBConnectionString|INFO|ADV> KeyName='{0}'", keyname);
#endif
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
if (string.IsNullOrEmpty(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
restrictionValues.Add(realkeyname);
}
}
return RemoveDuplicates(restrictionValues.ToArray());
}
internal static string[] RemoveDuplicates(string[] restrictions)
{
int count = restrictions.Length;
if (0 < count)
{
Array.Sort(restrictions, StringComparer.Ordinal);
for (int i = 1; i < restrictions.Length; ++i)
{
string prev = restrictions[i - 1];
if ((0 == prev.Length) || (prev == restrictions[i]))
{
restrictions[i - 1] = null;
count--;
}
}
if (0 == restrictions[restrictions.Length - 1].Length)
{
restrictions[restrictions.Length - 1] = null;
count--;
}
if (count != restrictions.Length)
{
string[] tmp = new string[count];
count = 0;
for (int i = 0; i < restrictions.Length; ++i)
{
if (null != restrictions[i])
{
tmp[count++] = restrictions[i];
}
}
restrictions = tmp;
}
}
Verify(restrictions);
return restrictions;
}
[ConditionalAttribute("DEBUG")]
private static void Verify(string[] restrictionValues)
{
if (null != restrictionValues)
{
for (int i = 1; i < restrictionValues.Length; ++i)
{
Debug.Assert(!string.IsNullOrEmpty(restrictionValues[i - 1]), "empty restriction");
Debug.Assert(!string.IsNullOrEmpty(restrictionValues[i]), "empty restriction");
Debug.Assert(0 >= StringComparer.Ordinal.Compare(restrictionValues[i - 1], restrictionValues[i]));
}
}
}
}
}
| |
using System.Linq;
using System.Reflection;
using Glass.Mapper.Configuration;
using Glass.Mapper.Configuration.Attributes;
using Sitecore.Data;
namespace Glass.Mapper.Sc.Configuration.Attributes
{
/// <summary>
/// Class SitecoreFieldAttribute
/// </summary>
public class SitecoreFieldAttribute : FieldAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="SitecoreFieldAttribute"/> class.
/// </summary>
public SitecoreFieldAttribute()
{
Setting = SitecoreFieldSettings.Default;
}
/// <summary>
/// Initializes a new instance of the <see cref="SitecoreFieldAttribute"/> class.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
public SitecoreFieldAttribute(string fieldName) : this()
{
FieldName = fieldName;
FieldSortOrder = -1;
SectionSortOrder = -1;
}
/// <summary>
/// Initializes a new instance of the <see cref="SitecoreFieldAttribute"/> class.
/// </summary>
/// <param name="fieldId">The field id.</param>
/// <param name="fieldType">Type of the field.</param>
/// <param name="sectionName">Name of the section.</param>
/// <param name="codeFirst">if set to <c>true</c> [code first].</param>
public SitecoreFieldAttribute(string fieldId, SitecoreFieldType fieldType, string sectionName = "Data", bool codeFirst = true)
{
FieldId = fieldId;
SectionName = sectionName;
CodeFirst = codeFirst;
FieldType = fieldType;
FieldSortOrder = -1;
SectionSortOrder = 100;
}
/// <summary>
/// Use with the Glass.Mapper.Sc.Fields.Link type
/// </summary>
/// <value>The URL options.</value>
public SitecoreInfoUrlOptions UrlOptions { get; set; }
/// <summary>
/// The name of the field to use if it is different to the property name
/// </summary>
/// <value>The name of the field.</value>
public string FieldName { get; set; }
/// <summary>
/// The ID of the field when used in a code first scenario
/// </summary>
/// <value>The field id.</value>
public string FieldId { get; set; }
/// <summary>
/// Options to override the behaviour of certain fields.
/// </summary>
/// <value>The setting.</value>
public SitecoreFieldSettings Setting { get; set; }
public SitecoreMediaUrlOptions MediaUrlOptions { get; set; }
#region Code First Properties
/// <summary>
/// Indicates the field should be used as part of a code first template
/// </summary>
/// <value><c>true</c> if [code first]; otherwise, <c>false</c>.</value>
public bool CodeFirst { get; set; }
/// <summary>
/// The type of field to create when using Code First
/// </summary>
/// <value>The type of the field.</value>
public SitecoreFieldType FieldType { get; set; }
/// <summary>
/// The name of the section this field will appear in when using code first.
/// </summary>
/// <value>The name of the section.</value>
public string SectionName { get; set; }
/// <summary>
/// The title for the field if using Code First
/// </summary>
/// <value>The field title.</value>
public string FieldTitle { get; set; }
/// <summary>
/// The source for the field if using Code First
/// </summary>
/// <value>The field source.</value>
public string FieldSource { get; set; }
/// <summary>
/// Sets the field as shared if using Code First
/// </summary>
/// <value><c>true</c> if this instance is shared; otherwise, <c>false</c>.</value>
public bool IsShared { get; set; }
/// <summary>
/// Sets the field as unversioned if using Code First
/// </summary>
/// <value><c>true</c> if this instance is unversioned; otherwise, <c>false</c>.</value>
public bool IsUnversioned { get; set; }
/// <summary>
/// Overrides the field sort order if using Code First
/// </summary>
/// <value>The field sort order.</value>
public int FieldSortOrder { get; set; }
/// <summary>
/// Overrides the section sort order if using Code First
/// </summary>
/// <value>The section sort order.</value>
public int SectionSortOrder { get; set; }
/// <summary>
/// Overrides the field validation regular expression if using Code First
/// </summary>
/// <value>The validation regular expression.</value>
public string ValidationRegularExpression { get; set; }
/// <summary>
/// Overrides the field validation error text if using Code First
/// </summary>
/// <value>The validation error text.</value>
public string ValidationErrorText { get; set; }
/// <summary>
/// Sets the field as required if using Code First
/// </summary>
/// <value><c>true</c> if this instance is required; otherwise, <c>false</c>.</value>
public bool IsRequired { get; set; }
/// <summary>
/// Allows for custom types of field to create when using Code First
/// </summary>
/// <value>The type of the field.</value>
public string CustomFieldType { get; set; }
#endregion
/// <summary>
/// Configures the specified property info.
/// </summary>
/// <param name="propertyInfo">The property info.</param>
/// <returns>AbstractPropertyConfiguration.</returns>
public override AbstractPropertyConfiguration Configure(PropertyInfo propertyInfo)
{
var config = new SitecoreFieldConfiguration();
Configure(propertyInfo, config);
return config;
}
/// <summary>
/// Configures the specified property info.
/// </summary>
/// <param name="propertyInfo">The property info.</param>
/// <param name="config">The config.</param>
public void Configure(PropertyInfo propertyInfo, SitecoreFieldConfiguration config)
{
config.FieldName = this.FieldName;
if (config.FieldName.IsNullOrEmpty())
config.FieldName = propertyInfo.Name;
if(FieldId.HasValue())
config.FieldId = new ID(this.FieldId);
config.Setting = this.Setting;
config.MediaUrlOptions = MediaUrlOptions;
config.UrlOptions = UrlOptions;
//code first configuration
var fieldFieldValues = propertyInfo.GetCustomAttributes(typeof(SitecoreFieldFieldValueAttribute), true).Cast<SitecoreFieldFieldValueAttribute>();
////fix: fieldfieldvalues are not passed
var interfaceFromProperty = propertyInfo.DeclaringType.GetInterfaces().FirstOrDefault(inter => inter.GetProperty(propertyInfo.Name) != null);
if (interfaceFromProperty != null)
{
fieldFieldValues = interfaceFromProperty.GetProperty(propertyInfo.Name).GetCustomAttributes(typeof(SitecoreFieldFieldValueAttribute), true).Cast<SitecoreFieldFieldValueAttribute>(); ;
}
base.Configure(propertyInfo, config);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
using UnityEngine.VR.WSA.Input;
namespace PosterAlignment.InputUtilities
{
public class GestureStateManager : StateManager
{
public enum Mode
{
Navigation,
Manipulation
}
public ushort ClickCount { get; private set; }
public override bool IsPressed(UnityEngine.EventSystems.PointerEventData.InputButton button)
{
return this.ClickCount > 0;
}
public override bool IsReleased(UnityEngine.EventSystems.PointerEventData.InputButton button)
{
return this.isReleased;
}
private bool isReleased;
public bool IsCancelled { get; private set; }
public bool IsCapturingGestures
{
get { return (this.activeRecognizer != null) ? this.activeRecognizer.IsCapturingGestures() : false; }
}
public Mode GestureMode
{
get { return this.recognizerType; }
set { this.ResetGestureRecognizer(value); }
}
public Mode recognizerType = Mode.Manipulation;
private GestureRecognizer activeRecognizer = null;
private GestureRecognizer navigationRecognizer = null;
private Vector3 navigationPosition = Vector3.zero;
private GestureRecognizer manipulationRecognizer = null;
private Vector3 manipulationPosition = Vector3.zero;
private Vector3 manipulationPrevious = Vector3.zero;
public override Vector2 ScreenPosition { get { return this.screenPosition; } }
private Vector2 screenPosition;
public override Vector3 WorldScreenPosition { get { return this.worldScreenPosition; } }
private Vector3 worldScreenPosition;
public override Vector2 ScreenDelta { get { return this.screenDelta; } }
private Vector2 screenDelta;
public override Vector3 WorldDelta { get { return this.worldDelta; } }
private Vector3 worldDelta;
private void Awake()
{
// Instantiate the Navigation recognizer
this.navigationRecognizer = new GestureRecognizer();
this.navigationRecognizer.SetRecognizableGestures(
GestureSettings.Tap |
GestureSettings.DoubleTap |
GestureSettings.NavigationX | GestureSettings.NavigationY | GestureSettings.NavigationZ);
this.navigationRecognizer.TappedEvent += this.Recognizer_TappedEvent;
this.navigationRecognizer.NavigationStartedEvent += this.NavigationRecognizer_NavigationStartedEvent;
this.navigationRecognizer.NavigationUpdatedEvent += this.NavigationRecognizer_NavigationUpdatedEvent;
this.navigationRecognizer.NavigationCompletedEvent += this.NavigationRecognizer_NavigationCompletedEvent;
this.navigationRecognizer.NavigationCanceledEvent += this.NavigationRecognizer_NavigationCanceledEvent;
// Instantiate the Manipulation Recognizer.
this.manipulationRecognizer = new GestureRecognizer();
this.manipulationRecognizer.SetRecognizableGestures(
GestureSettings.Tap |
GestureSettings.DoubleTap |
GestureSettings.ManipulationTranslate);
this.manipulationRecognizer.TappedEvent += this.Recognizer_TappedEvent;
this.manipulationRecognizer.ManipulationStartedEvent += this.ManipulationRecognizer_ManipulationStartedEvent;
this.manipulationRecognizer.ManipulationUpdatedEvent += this.ManipulationRecognizer_ManipulationUpdatedEvent;
this.manipulationRecognizer.ManipulationCompletedEvent += this.ManipulationRecognizer_ManipulationCompletedEvent;
this.manipulationRecognizer.ManipulationCanceledEvent += this.ManipulationRecognizer_ManipulationCanceledEvent;
// interaction manager state handling
InteractionManager.SourcePressed += InteractionManager_SourcePressed;
InteractionManager.SourceReleased += InteractionManager_SourceReleased;
}
private void OnDestroy()
{
if (this.navigationRecognizer != null)
{
this.navigationRecognizer.TappedEvent -= this.Recognizer_TappedEvent;
this.navigationRecognizer.NavigationStartedEvent -= this.NavigationRecognizer_NavigationStartedEvent;
this.navigationRecognizer.NavigationUpdatedEvent -= this.NavigationRecognizer_NavigationUpdatedEvent;
this.navigationRecognizer.NavigationCompletedEvent -= this.NavigationRecognizer_NavigationCompletedEvent;
this.navigationRecognizer.NavigationCanceledEvent -= this.NavigationRecognizer_NavigationCanceledEvent;
}
if (this.manipulationRecognizer != null)
{
this.manipulationRecognizer.TappedEvent -= this.Recognizer_TappedEvent;
this.manipulationRecognizer.ManipulationStartedEvent -= this.ManipulationRecognizer_ManipulationStartedEvent;
this.manipulationRecognizer.ManipulationUpdatedEvent -= this.ManipulationRecognizer_ManipulationUpdatedEvent;
this.manipulationRecognizer.ManipulationCompletedEvent -=
this.ManipulationRecognizer_ManipulationCompletedEvent;
this.manipulationRecognizer.ManipulationCanceledEvent -=
this.ManipulationRecognizer_ManipulationCanceledEvent;
}
// interaction manager state handling
InteractionManager.SourcePressed -= InteractionManager_SourcePressed;
InteractionManager.SourceReleased -= InteractionManager_SourceReleased;
}
private void OnEnable()
{
this.ResetGestureRecognizer(this.GestureMode);
}
private void OnDisable()
{
this.Transition(null);
}
private void ResetGestureRecognizer(Mode type)
{
switch (type)
{
case Mode.Navigation:
this.Transition(this.navigationRecognizer);
break;
case Mode.Manipulation:
this.Transition(this.manipulationRecognizer);
break;
}
this.recognizerType = type;
}
private void Transition(GestureRecognizer newRecognizer)
{
if (newRecognizer != null && this.activeRecognizer == newRecognizer && this.IsCapturingGestures)
{
return;
}
if (this.activeRecognizer != null)
{
if (this.activeRecognizer == newRecognizer)
{
return;
}
this.activeRecognizer.CancelGestures();
this.activeRecognizer.StopCapturingGestures();
}
if (newRecognizer != null)
{
newRecognizer.StartCapturingGestures();
}
this.activeRecognizer = newRecognizer;
}
// only used when called via Unity UI
// use ResetGestureRecognizer
public void SetGestureMode(int type)
{
this.GestureMode = (Mode)Enum.ToObject(typeof(Mode), type);
}
private void Recognizer_TappedEvent(InteractionSourceKind source, int tapCount, Ray headRay)
{
this.ClickCount = (ushort)tapCount;
this.isReleased = true;
}
private void NavigationRecognizer_NavigationStartedEvent(InteractionSourceKind source, Vector3 relativePosition,
Ray ray)
{
this.ClickCount = 1;
this.isReleased = false;
this.navigationPosition = relativePosition;
}
private void NavigationRecognizer_NavigationUpdatedEvent(InteractionSourceKind source, Vector3 relativePosition,
Ray ray)
{
this.ClickCount = 0;
this.isReleased = false;
this.navigationPosition = relativePosition;
}
private void NavigationRecognizer_NavigationCompletedEvent(InteractionSourceKind source, Vector3 relativePosition,
Ray ray)
{
this.ClickCount = 0;
this.isReleased = true;
this.IsCancelled = false;
this.navigationPosition = relativePosition;
}
private void NavigationRecognizer_NavigationCanceledEvent(InteractionSourceKind source, Vector3 relativePosition,
Ray ray)
{
this.ClickCount = 0;
this.isReleased = true;
this.IsCancelled = true;
this.navigationPosition = Vector3.zero;
}
private void ManipulationRecognizer_ManipulationStartedEvent(InteractionSourceKind source, Vector3 position, Ray ray)
{
this.ClickCount = 1;
this.isReleased = false;
this.manipulationPosition = position;
this.manipulationPrevious = position;
}
private void ManipulationRecognizer_ManipulationUpdatedEvent(InteractionSourceKind source, Vector3 position, Ray ray)
{
this.ClickCount = 0;
this.isReleased = false;
this.manipulationPrevious = this.manipulationPosition;
this.manipulationPosition = position;
}
private void ManipulationRecognizer_ManipulationCompletedEvent(InteractionSourceKind source, Vector3 position,
Ray ray)
{
this.ClickCount = 0;
this.isReleased = true;
this.IsCancelled = false;
this.manipulationPrevious = this.manipulationPosition;
this.manipulationPosition = position;
}
private void ManipulationRecognizer_ManipulationCanceledEvent(InteractionSourceKind source, Vector3 position,
Ray ray)
{
this.ClickCount = 0;
this.isReleased = true;
this.IsCancelled = true;
this.manipulationPrevious = Vector3.zero;
this.manipulationPosition = Vector3.zero;
}
private void InteractionManager_SourcePressed(InteractionSourceState state)
{
this.ClickCount = 1;
}
private void InteractionManager_SourceReleased(InteractionSourceState state)
{
this.isReleased = true;
}
// IModuleManager
public override bool IsSupported()
{
return (this.activeRecognizer != null);
}
public override bool ShouldActivate()
{
bool shouldActivate = false;
if(this.IsCapturingGestures)
{
shouldActivate |= this.IsPressed(UnityEngine.EventSystems.PointerEventData.InputButton.Left); // did we click
shouldActivate |= !this.IsReleased(UnityEngine.EventSystems.PointerEventData.InputButton.Left); // did not release
shouldActivate |= this.IsCancelled; // did we cancel
}
return shouldActivate;
}
public override bool ShouldSubmit()
{
// TODO: support a voice command for submit
return false;
}
public override bool ShouldCancel()
{
return this.IsCancelled;
}
public override bool ShouldMove(out Vector2 movement)
{
// TODO: support a voice command for next previous / up/down actions
movement = Vector3.zero;
return false;
}
public override void ResetButtonState(UnityEngine.EventSystems.PointerEventData.InputButton button)
{
if (this.isReleased == true && this.ClickCount > 0)
{
this.ClickCount = 0;
}
this.IsCancelled = false;
this.isReleased = false;
}
public override void ActivateModule()
{
}
public override void DeactivateModule()
{
}
public override void UpdateModule()
{
this.screenPosition = StateManager.ScreenCenter;
this.worldScreenPosition = StateManager.WorldScreenCenter;
Vector3 delta = Vector3.zero;
if (this.IsCapturingGestures)
{
if (this.GestureMode == Mode.Navigation)
{
delta = this.navigationPosition;
}
else
{
delta = this.manipulationPosition - this.manipulationPrevious;
}
}
this.worldDelta = delta;
this.screenDelta = Camera.main.WorldToScreenPoint(this.worldDelta);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NServiceKit.Common.Extensions;
using NServiceKit.ServiceHost;
using NServiceKit.WebHost.Endpoints.Tests.Support.Host;
using NServiceKit.WebHost.Endpoints.Tests.Support.Services;
namespace NServiceKit.WebHost.Endpoints.Tests
{
/// <summary>An endpoint restriction tests.</summary>
[TestFixture]
public class EndpointRestrictionTests
: ServiceHostTestBase
{
//Localhost and LocalSubnet is always included with the Internal flag
private const int EndpointAttributeCount = 17;
private static readonly List<EndpointAttributes> AllAttributes = (EndpointAttributeCount).Times().ConvertAll<EndpointAttributes>(x => (EndpointAttributes)(1 << (int)x));
TestAppHost appHost;
/// <summary>Tests fixture set up.</summary>
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
appHost = CreateAppHost();
}
/// <summary>Should allow access when.</summary>
///
/// <typeparam name="TRequestDto">Type of the request dto.</typeparam>
/// <param name="withScenario">The with scenario.</param>
public void ShouldAllowAccessWhen<TRequestDto>(EndpointAttributes withScenario)
where TRequestDto : new()
{
ShouldNotThrow<UnauthorizedAccessException>(() => appHost.ExecuteService(new TRequestDto(), withScenario));
}
/// <summary>Should deny access when.</summary>
///
/// <typeparam name="TRequestDto">Type of the request dto.</typeparam>
/// <param name="withScenario">The with scenario.</param>
public void ShouldDenyAccessWhen<TRequestDto>(EndpointAttributes withScenario)
where TRequestDto : new()
{
ShouldThrow<UnauthorizedAccessException>(() => appHost.ExecuteService(new TRequestDto(), withScenario));
}
/// <summary>Should deny access for all other scenarios.</summary>
///
/// <typeparam name="TRequestDto">Type of the request dto.</typeparam>
/// <param name="notIncluding">A variable-length parameters list containing not including.</param>
public void ShouldDenyAccessForAllOtherScenarios<TRequestDto>(params EndpointAttributes[] notIncluding)
where TRequestDto : new()
{
ShouldDenyAccessForOtherScenarios<TRequestDto>(AllAttributes.Where(x => !notIncluding.Contains(x)).ToList());
}
/// <summary>Should deny access for other network access scenarios.</summary>
///
/// <typeparam name="TRequestDto">Type of the request dto.</typeparam>
/// <param name="notIncluding">A variable-length parameters list containing not including.</param>
public void ShouldDenyAccessForOtherNetworkAccessScenarios<TRequestDto>(params EndpointAttributes[] notIncluding)
where TRequestDto : new()
{
var scenarios = new List<EndpointAttributes> { EndpointAttributes.Localhost, EndpointAttributes.LocalSubnet, EndpointAttributes.External };
ShouldDenyAccessForOtherScenarios<TRequestDto>(scenarios.Where(x => !notIncluding.Contains(x)).ToList());
}
/// <summary>Should deny access for other HTTP request types scenarios.</summary>
///
/// <typeparam name="TRequestDto">Type of the request dto.</typeparam>
/// <param name="notIncluding">A variable-length parameters list containing not including.</param>
public void ShouldDenyAccessForOtherHttpRequestTypesScenarios<TRequestDto>(params EndpointAttributes[] notIncluding)
where TRequestDto : new()
{
var scenarios = new List<EndpointAttributes> { EndpointAttributes.HttpHead, EndpointAttributes.HttpGet,
EndpointAttributes.HttpPost, EndpointAttributes.HttpPut, EndpointAttributes.HttpDelete };
ShouldDenyAccessForOtherScenarios<TRequestDto>(scenarios.Where(x => !notIncluding.Contains(x)).ToList());
}
private void ShouldDenyAccessForOtherScenarios<TRequestDto>(IEnumerable<EndpointAttributes> otherScenarios)
where TRequestDto : new()
{
var requestDto = new TRequestDto();
foreach (var otherScenario in otherScenarios)
{
try
{
ShouldThrow<UnauthorizedAccessException>(() => appHost.ExecuteService(requestDto, otherScenario));
}
catch (Exception ex)
{
throw new Exception("Failed to throw on: " + otherScenario, ex);
}
}
}
/// <summary>Internal restriction allows calls from localhost or local subnet.</summary>
[Test]
public void InternalRestriction_allows_calls_from_Localhost_or_LocalSubnet()
{
ShouldAllowAccessWhen<InternalRestriction>(EndpointAttributes.Localhost);
ShouldAllowAccessWhen<InternalRestriction>(EndpointAttributes.LocalSubnet);
ShouldDenyAccessForOtherNetworkAccessScenarios<InternalRestriction>(EndpointAttributes.Localhost, EndpointAttributes.LocalSubnet);
}
/// <summary>Localhost restriction allows calls from localhost.</summary>
[Test]
public void LocalhostRestriction_allows_calls_from_localhost()
{
ShouldAllowAccessWhen<LocalhostRestriction>(EndpointAttributes.Localhost);
ShouldDenyAccessForOtherNetworkAccessScenarios<LocalhostRestriction>(EndpointAttributes.Localhost);
}
/// <summary>Local subnet restriction allows calls from local subnet.</summary>
[Test]
public void LocalSubnetRestriction_allows_calls_from_LocalSubnet()
{
ShouldAllowAccessWhen<LocalSubnetRestriction>(EndpointAttributes.LocalSubnet);
ShouldDenyAccessForOtherNetworkAccessScenarios<LocalSubnetRestriction>(EndpointAttributes.LocalSubnet);
}
/// <summary>Local subnet restriction does not allow calls from localhost.</summary>
[Test]
public void LocalSubnetRestriction_does_not_allow_calls_from_Localhost()
{
ShouldDenyAccessWhen<LocalSubnetRestriction>(EndpointAttributes.Localhost);
ShouldDenyAccessWhen<LocalSubnetRestriction>(EndpointAttributes.External);
}
/// <summary>Internal restriction allows calls from localhost and local subnet.</summary>
[Test]
public void InternalRestriction_allows_calls_from_Localhost_and_LocalSubnet()
{
ShouldAllowAccessWhen<InternalRestriction>(EndpointAttributes.Localhost);
ShouldAllowAccessWhen<InternalRestriction>(EndpointAttributes.LocalSubnet);
ShouldDenyAccessWhen<LocalSubnetRestriction>(EndpointAttributes.External);
}
/// <summary>Secure local subnet restriction does not allow partial success.</summary>
[Test]
public void SecureLocalSubnetRestriction_does_not_allow_partial_success()
{
ShouldDenyAccessWhen<SecureLocalSubnetRestriction>(EndpointAttributes.Localhost);
ShouldDenyAccessWhen<SecureLocalSubnetRestriction>(EndpointAttributes.InSecure | EndpointAttributes.LocalSubnet);
ShouldDenyAccessWhen<SecureLocalSubnetRestriction>(EndpointAttributes.InSecure);
ShouldDenyAccessWhen<SecureLocalSubnetRestriction>(EndpointAttributes.Secure | EndpointAttributes.Localhost);
ShouldAllowAccessWhen<SecureLocalSubnetRestriction>(EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
ShouldDenyAccessWhen<SecureLocalSubnetRestriction>(EndpointAttributes.Secure | EndpointAttributes.InternalNetworkAccess);
ShouldDenyAccessForOtherNetworkAccessScenarios<SecureLocalSubnetRestriction>(EndpointAttributes.LocalSubnet);
}
/// <summary>HTTP post XML and secure local subnet restriction does not allow partial success.</summary>
[Test]
public void HttpPostXmlAndSecureLocalSubnetRestriction_does_not_allow_partial_success()
{
ShouldDenyAccessForOtherNetworkAccessScenarios<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.LocalSubnet);
ShouldDenyAccessForOtherHttpRequestTypesScenarios<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost);
ShouldDenyAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.Localhost);
ShouldDenyAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Json | EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
ShouldDenyAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Xml | EndpointAttributes.Secure | EndpointAttributes.Localhost);
ShouldDenyAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.LocalSubnet | EndpointAttributes.Secure | EndpointAttributes.HttpHead);
ShouldDenyAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Xml | EndpointAttributes.InSecure );
ShouldDenyAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Json | EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
ShouldDenyAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Xml | EndpointAttributes.Secure | EndpointAttributes.Localhost);
ShouldAllowAccessWhen<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Xml | EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
}
/// <summary>HTTP post XML or secure local subnet restriction does allow partial success.</summary>
[Test]
public void HttpPostXmlOrSecureLocalSubnetRestriction_does_allow_partial_success()
{
ShouldDenyAccessForOtherNetworkAccessScenarios<HttpPostXmlAndSecureLocalSubnetRestriction>(EndpointAttributes.LocalSubnet);
ShouldDenyAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.Localhost | EndpointAttributes.HttpPut);
ShouldAllowAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
ShouldDenyAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Json | EndpointAttributes.Secure | EndpointAttributes.Localhost);
ShouldAllowAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
ShouldAllowAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Xml);
ShouldAllowAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Json | EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
ShouldAllowAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Xml | EndpointAttributes.Secure | EndpointAttributes.Localhost);
ShouldAllowAccessWhen<HttpPostXmlOrSecureLocalSubnetRestriction>(EndpointAttributes.HttpPost | EndpointAttributes.Xml | EndpointAttributes.Secure | EndpointAttributes.LocalSubnet);
}
/// <summary>Can access from insecure development environment.</summary>
[Test]
public void Can_access_from_insecure_dev_environment()
{
ShouldAllowAccessWhen<InSecureDevEnvironmentRestriction>(EndpointAttributes.Localhost | EndpointAttributes.InSecure | EndpointAttributes.HttpPost);
ShouldAllowAccessWhen<InSecureDevEnvironmentRestriction>(EndpointAttributes.LocalSubnet | EndpointAttributes.InSecure | EndpointAttributes.HttpPost);
ShouldAllowAccessWhen<InSecureDevEnvironmentRestriction>(EndpointAttributes.LocalSubnet | EndpointAttributes.InSecure | EndpointAttributes.HttpPost | EndpointAttributes.Reply);
ShouldAllowAccessWhen<InSecureDevEnvironmentRestriction>(EndpointAttributes.LocalSubnet | EndpointAttributes.InSecure | EndpointAttributes.HttpPost | EndpointAttributes.OneWay);
}
/// <summary>Can access from secure development environment.</summary>
[Test]
public void Can_access_from_secure_dev_environment()
{
ShouldAllowAccessWhen<SecureDevEnvironmentRestriction>(EndpointAttributes.Localhost | EndpointAttributes.Secure | EndpointAttributes.HttpPost);
ShouldAllowAccessWhen<SecureDevEnvironmentRestriction>(EndpointAttributes.LocalSubnet | EndpointAttributes.Secure | EndpointAttributes.HttpPost);
ShouldAllowAccessWhen<SecureDevEnvironmentRestriction>(EndpointAttributes.LocalSubnet | EndpointAttributes.Secure | EndpointAttributes.HttpPost | EndpointAttributes.Reply);
ShouldAllowAccessWhen<SecureDevEnvironmentRestriction>(EndpointAttributes.LocalSubnet | EndpointAttributes.Secure | EndpointAttributes.HttpPost | EndpointAttributes.OneWay);
}
/// <summary>Can access from insecure live environment.</summary>
[Test]
public void Can_access_from_insecure_live_environment()
{
ShouldAllowAccessWhen<InSecureLiveEnvironmentRestriction>(EndpointAttributes.External | EndpointAttributes.InSecure | EndpointAttributes.HttpPost);
ShouldAllowAccessWhen<InSecureLiveEnvironmentRestriction>(EndpointAttributes.External | EndpointAttributes.InSecure | EndpointAttributes.HttpPost | EndpointAttributes.Reply);
ShouldAllowAccessWhen<InSecureLiveEnvironmentRestriction>(EndpointAttributes.External | EndpointAttributes.InSecure | EndpointAttributes.HttpPost | EndpointAttributes.OneWay);
}
/// <summary>Can access from secure live environment.</summary>
[Test]
public void Can_access_from_secure_live_environment()
{
ShouldAllowAccessWhen<SecureLiveEnvironmentRestriction>(EndpointAttributes.External | EndpointAttributes.Secure | EndpointAttributes.HttpPost);
ShouldAllowAccessWhen<SecureLiveEnvironmentRestriction>(EndpointAttributes.External | EndpointAttributes.Secure | EndpointAttributes.HttpPost | EndpointAttributes.Reply);
ShouldAllowAccessWhen<SecureLiveEnvironmentRestriction>(EndpointAttributes.External | EndpointAttributes.Secure | EndpointAttributes.HttpPost | EndpointAttributes.OneWay);
}
/// <summary>Print enum results.</summary>
[Ignore]
[Test]
public void Print_enum_results()
{
PrintEnumResult(EndpointAttributes.InternalNetworkAccess, EndpointAttributes.Secure);
PrintEnumResult(EndpointAttributes.InternalNetworkAccess, EndpointAttributes.Secure | EndpointAttributes.External);
PrintEnumResult(EndpointAttributes.InternalNetworkAccess, EndpointAttributes.Secure | EndpointAttributes.Localhost);
PrintEnumResult(EndpointAttributes.InternalNetworkAccess, EndpointAttributes.Localhost);
PrintEnumResult(EndpointAttributes.Localhost, EndpointAttributes.Secure | EndpointAttributes.External);
PrintEnumResult(EndpointAttributes.Localhost, EndpointAttributes.Secure | EndpointAttributes.InternalNetworkAccess);
PrintEnumResult(EndpointAttributes.Localhost, EndpointAttributes.LocalSubnet);
PrintEnumResult(EndpointAttributes.Localhost, EndpointAttributes.Secure);
}
/// <summary>Print enum result.</summary>
///
/// <param name="actual"> The actual.</param>
/// <param name="required">The required.</param>
public void PrintEnumResult(EndpointAttributes actual, EndpointAttributes required)
{
Console.WriteLine(string.Format("({0} | {1}): {2}", actual, required, (actual | required)));
Console.WriteLine(string.Format("({0} & {1}): {2}", actual, required, (actual & required)));
Console.WriteLine(string.Format("({0} ^ {1}): {2}", actual, required, (actual ^ required)));
Console.WriteLine();
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
/// </summary>
public class BsonReader : JsonReader
{
private const int MaxCharBytesSize = 128;
private static readonly byte[] _seqRange1 = new byte[] { 0, 127 }; // range of 1-byte sequence
private static readonly byte[] _seqRange2 = new byte[] { 194, 223 }; // range of 2-byte sequence
private static readonly byte[] _seqRange3 = new byte[] { 224, 239 }; // range of 3-byte sequence
private static readonly byte[] _seqRange4 = new byte[] { 240, 244 }; // range of 4-byte sequence
private readonly BinaryReader _reader;
private readonly List<ContainerContext> _stack;
private byte[] _byteBuffer;
private char[] _charBuffer;
private BsonType _currentElementType;
private BsonReaderState _bsonReaderState;
private ContainerContext _currentContext;
private bool _readRootValueAsArray;
private bool _jsonNet35BinaryCompatibility;
private DateTimeKind _dateTimeKindHandling;
private enum BsonReaderState
{
Normal,
ReferenceStart,
ReferenceRef,
ReferenceId,
CodeWScopeStart,
CodeWScopeCode,
CodeWScopeScope,
CodeWScopeScopeObject,
CodeWScopeScopeEnd
}
private class ContainerContext
{
public readonly BsonType Type;
public int Length;
public int Position;
public ContainerContext(BsonType type)
{
Type = type;
}
}
/// <summary>
/// Gets or sets a value indicating whether binary data reading should compatible with incorrect Json.NET 3.5 written binary.
/// </summary>
/// <value>
/// <c>true</c> if binary data reading will be compatible with incorrect Json.NET 3.5 written binary; otherwise, <c>false</c>.
/// </value>
public bool JsonNet35BinaryCompatibility
{
get { return _jsonNet35BinaryCompatibility; }
set { _jsonNet35BinaryCompatibility = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the root object will be read as a JSON array.
/// </summary>
/// <value>
/// <c>true</c> if the root object will be read as a JSON array; otherwise, <c>false</c>.
/// </value>
public bool ReadRootValueAsArray
{
get { return _readRootValueAsArray; }
set { _readRootValueAsArray = value; }
}
/// <summary>
/// Gets or sets the <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.
/// </summary>
/// <value>The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</value>
public DateTimeKind DateTimeKindHandling
{
get { return _dateTimeKindHandling; }
set { _dateTimeKindHandling = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
public BsonReader(Stream stream)
: this(stream, false, DateTimeKind.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="readRootValueAsArray">if set to <c>true</c> the root object will be read as a JSON array.</param>
/// <param name="dateTimeKindHandling">The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</param>
public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(stream, "stream");
_reader = new BinaryReader(stream);
_stack = new List<ContainerContext>();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
private string ReadElement()
{
_currentElementType = ReadType();
string elementName = ReadString();
return elementName;
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>.
/// </summary>
/// <returns>
/// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null.
/// </returns>
public override byte[] ReadAsBytes()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Bytes)
return (byte[])Value;
throw new JsonReaderException("Error reading bytes. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>.
/// </summary>
/// <returns>A <see cref="Nullable{Decimal}"/>.</returns>
public override decimal? ReadAsDecimal()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Integer || TokenType == JsonToken.Float)
{
SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture));
return (decimal)Value;
}
throw new JsonReaderException("Error reading decimal. Expected a number but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>.
/// </summary>
/// <returns>
/// A <see cref="Nullable{DateTimeOffset}"/>.
/// </returns>
public override DateTimeOffset? ReadAsDateTimeOffset()
{
Read();
if (TokenType == JsonToken.Null)
return null;
if (TokenType == JsonToken.Date)
{
SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value));
return (DateTimeOffset)Value;
}
throw new JsonReaderException("Error reading date. Expected bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
/// <summary>
/// Reads the next JSON token from the stream.
/// </summary>
/// <returns>
/// true if the next token was read successfully; false if there are no more tokens to read.
/// </returns>
public override bool Read()
{
try
{
switch (_bsonReaderState)
{
case BsonReaderState.Normal:
return ReadNormal();
case BsonReaderState.ReferenceStart:
case BsonReaderState.ReferenceRef:
case BsonReaderState.ReferenceId:
return ReadReference();
case BsonReaderState.CodeWScopeStart:
case BsonReaderState.CodeWScopeCode:
case BsonReaderState.CodeWScopeScope:
case BsonReaderState.CodeWScopeScopeObject:
case BsonReaderState.CodeWScopeScopeEnd:
return ReadCodeWScope();
default:
throw new JsonReaderException("Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
}
}
catch (EndOfStreamException)
{
return false;
}
}
/// <summary>
/// Changes the <see cref="JsonReader.State"/> to Closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput && _reader != null)
_reader.Close();
}
private bool ReadCodeWScope()
{
switch (_bsonReaderState)
{
case BsonReaderState.CodeWScopeStart:
SetToken(JsonToken.PropertyName, "$code");
_bsonReaderState = BsonReaderState.CodeWScopeCode;
return true;
case BsonReaderState.CodeWScopeCode:
// total CodeWScope size - not used
ReadInt32();
SetToken(JsonToken.String, ReadLengthString());
_bsonReaderState = BsonReaderState.CodeWScopeScope;
return true;
case BsonReaderState.CodeWScopeScope:
if (CurrentState == State.PostValue)
{
SetToken(JsonToken.PropertyName, "$scope");
return true;
}
else
{
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeScopeObject;
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case BsonReaderState.CodeWScopeScopeObject:
bool result = ReadNormal();
if (result && TokenType == JsonToken.EndObject)
_bsonReaderState = BsonReaderState.CodeWScopeScopeEnd;
return result;
case BsonReaderState.CodeWScopeScopeEnd:
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
private bool ReadReference()
{
switch (CurrentState)
{
case State.ObjectStart:
{
SetToken(JsonToken.PropertyName, "$ref");
_bsonReaderState = BsonReaderState.ReferenceRef;
return true;
}
case State.Property:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.String, ReadLengthString());
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.Bytes, ReadBytes(12));
return true;
}
else
{
throw new JsonReaderException("Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
case State.PostValue:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.PropertyName, "$id");
_bsonReaderState = BsonReaderState.ReferenceId;
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
}
else
{
throw new JsonReaderException("Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
default:
throw new JsonReaderException("Unexpected state when reading BSON reference: " + CurrentState);
}
}
private bool ReadNormal()
{
switch (CurrentState)
{
case State.Start:
{
JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray;
BsonType type = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array;
SetToken(token);
ContainerContext newContext = new ContainerContext(type);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case State.Complete:
case State.Closed:
return false;
case State.Property:
{
ReadType(_currentElementType);
return true;
}
case State.ObjectStart:
case State.ArrayStart:
case State.PostValue:
ContainerContext context = _currentContext;
if (context == null)
return false;
int lengthMinusEnd = context.Length - 1;
if (context.Position < lengthMinusEnd)
{
if (context.Type == BsonType.Array)
{
ReadElement();
ReadType(_currentElementType);
return true;
}
else
{
SetToken(JsonToken.PropertyName, ReadElement());
return true;
}
}
else if (context.Position == lengthMinusEnd)
{
if (ReadByte() != 0)
throw new JsonReaderException("Unexpected end of object byte value.");
PopContext();
if (_currentContext != null)
MovePosition(context.Length);
JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray;
SetToken(endToken);
return true;
}
else
{
throw new JsonReaderException("Read past end of current container context.");
}
case State.ConstructorStart:
break;
case State.Constructor:
break;
case State.Error:
break;
case State.Finished:
break;
default:
throw new ArgumentOutOfRangeException();
}
return false;
}
private void PopContext()
{
_stack.RemoveAt(_stack.Count - 1);
if (_stack.Count == 0)
_currentContext = null;
else
_currentContext = _stack[_stack.Count - 1];
}
private void PushContext(ContainerContext newContext)
{
_stack.Add(newContext);
_currentContext = newContext;
}
private byte ReadByte()
{
MovePosition(1);
return _reader.ReadByte();
}
private void ReadType(BsonType type)
{
switch (type)
{
case BsonType.Number:
SetToken(JsonToken.Float, ReadDouble());
break;
case BsonType.String:
case BsonType.Symbol:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.Object:
{
SetToken(JsonToken.StartObject);
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Array:
{
SetToken(JsonToken.StartArray);
ContainerContext newContext = new ContainerContext(BsonType.Array);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Binary:
SetToken(JsonToken.Bytes, ReadBinary());
break;
case BsonType.Undefined:
SetToken(JsonToken.Undefined);
break;
case BsonType.Oid:
byte[] oid = ReadBytes(12);
SetToken(JsonToken.Bytes, oid);
break;
case BsonType.Boolean:
bool b = Convert.ToBoolean(ReadByte());
SetToken(JsonToken.Boolean, b);
break;
case BsonType.Date:
long ticks = ReadInt64();
DateTime utcDateTime = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks);
DateTime dateTime;
switch (DateTimeKindHandling)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
SetToken(JsonToken.Date, dateTime);
break;
case BsonType.Null:
SetToken(JsonToken.Null);
break;
case BsonType.Regex:
string expression = ReadString();
string modifiers = ReadString();
string regex = @"/" + expression + @"/" + modifiers;
SetToken(JsonToken.String, regex);
break;
case BsonType.Reference:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.ReferenceStart;
break;
case BsonType.Code:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.CodeWScope:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeStart;
break;
case BsonType.Integer:
SetToken(JsonToken.Integer, (long)ReadInt32());
break;
case BsonType.TimeStamp:
case BsonType.Long:
SetToken(JsonToken.Integer, ReadInt64());
break;
default:
throw new ArgumentOutOfRangeException("type", "Unexpected BsonType value: " + type);
}
}
private byte[] ReadBinary()
{
int dataLength = ReadInt32();
BsonBinaryType binaryType = (BsonBinaryType)ReadByte();
#pragma warning disable 612,618
// the old binary type has the data length repeated in the data for some reason
if (binaryType == BsonBinaryType.Data && !_jsonNet35BinaryCompatibility)
{
dataLength = ReadInt32();
}
#pragma warning restore 612,618
return ReadBytes(dataLength);
}
private string ReadString()
{
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = offset;
byte b;
while (count < MaxCharBytesSize && (b = _reader.ReadByte()) > 0)
{
_byteBuffer[count++] = b;
}
int byteCount = count - offset;
totalBytesRead += byteCount;
if (count < MaxCharBytesSize && builder == null)
{
// pref optimization to avoid reading into a string builder
// if string is smaller than the buffer then return it directly
int length = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
MovePosition(totalBytesRead + 1);
return new string(_charBuffer, 0, length);
}
else
{
// calculate the index of the end of the last full character in the buffer
int lastFullCharStop = GetLastFullCharStop(count - 1);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
if (builder == null)
builder = new StringBuilder(MaxCharBytesSize * 2);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
// reached end of string
if (count < MaxCharBytesSize)
{
MovePosition(totalBytesRead + 1);
return builder.ToString();
}
offset = 0;
}
}
}
while (true);
}
private string ReadLengthString()
{
int length = ReadInt32();
MovePosition(length);
string s = GetString(length - 1);
_reader.ReadByte();
return s;
}
private string GetString(int length)
{
if (length == 0)
return string.Empty;
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = ((length - totalBytesRead) > MaxCharBytesSize - offset)
? MaxCharBytesSize - offset
: length - totalBytesRead;
int byteCount = _reader.BaseStream.Read(_byteBuffer, offset, count);
if (byteCount == 0)
throw new EndOfStreamException("Unable to read beyond the end of the stream.");
totalBytesRead += byteCount;
// Above, byteCount is how many bytes we read this time.
// Below, byteCount is how many bytes are in the _byteBuffer.
byteCount += offset;
if (byteCount == length)
{
// pref optimization to avoid reading into a string builder
// first iteration and all bytes read then return string directly
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
return new string(_charBuffer, 0, charCount);
}
else
{
int lastFullCharStop = GetLastFullCharStop(byteCount - 1);
if (builder == null)
builder = new StringBuilder(length);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
offset = 0;
}
}
}
while (totalBytesRead < length);
return builder.ToString();
}
private int GetLastFullCharStop(int start)
{
int lookbackPos = start;
int bis = 0;
while (lookbackPos >= 0)
{
bis = BytesInSequence(_byteBuffer[lookbackPos]);
if (bis == 0)
{
lookbackPos--;
continue;
}
else if (bis == 1)
{
break;
}
else
{
lookbackPos--;
break;
}
}
if (bis == start - lookbackPos)
{
//Full character.
return start;
}
else
{
return lookbackPos;
}
}
private int BytesInSequence(byte b)
{
if (b <= _seqRange1[1]) return 1;
if (b >= _seqRange2[0] && b <= _seqRange2[1]) return 2;
if (b >= _seqRange3[0] && b <= _seqRange3[1]) return 3;
if (b >= _seqRange4[0] && b <= _seqRange4[1]) return 4;
return 0;
}
private void EnsureBuffers()
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
int charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize);
_charBuffer = new char[charBufferSize];
}
}
private double ReadDouble()
{
MovePosition(8);
return _reader.ReadDouble();
}
private int ReadInt32()
{
MovePosition(4);
return _reader.ReadInt32();
}
private long ReadInt64()
{
MovePosition(8);
return _reader.ReadInt64();
}
private BsonType ReadType()
{
MovePosition(1);
return (BsonType)_reader.ReadSByte();
}
private void MovePosition(int count)
{
_currentContext.Position += count;
}
private byte[] ReadBytes(int count)
{
MovePosition(count);
return _reader.ReadBytes(count);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
namespace EmergeTk.Model
{
public class Setting : AbstractRecord
{
string dataKey;
string dataValue;
DateTime created = DateTime.UtcNow;
public virtual string DataValue {
get {
return dataValue;
}
set {
dataValue = value;
}
}
public virtual string DataKey {
get {
return dataKey;
}
set {
dataKey = value;
}
}
public virtual System.DateTime Created {
get {
return created;
}
set {
created = value;
}
}
static public T GetValueT<T>(String name)
{
Setting s = Get(name);
if( s!= null && ! string.IsNullOrEmpty( s.DataValue ) )
return (T)PropertyConverter.Convert(s.DataValue, typeof(T));
else
return default(T);
}
static public T GetConfigT<T>(String name)
{
Setting s = Get(name, null, true);
if( s!= null && ! string.IsNullOrEmpty( s.DataValue ) )
return (T)PropertyConverter.Convert(s.DataValue, typeof(T));
else
return default(T);
}
static public T GetConfigT<T>(String name, T defaultValue)
{
Setting s = Get(name, null, true);
if (s != null && !String.IsNullOrEmpty(s.DataValue))
{
return (T)PropertyConverter.Convert(s.DataValue, typeof(T));
}
else
{
return defaultValue;
}
}
static public T GetValueT<T>(String name, T defaultValue)
{
Setting s = Get(name);
if (s != null && !String.IsNullOrEmpty(s.DataValue))
{
return (T)PropertyConverter.Convert(s.DataValue, typeof(T));
}
else
{
return defaultValue;
}
}
public Setting()
{
}
static Dictionary<string,string> settings = new Dictionary<string, string>();
static Setting()
{
Setup ();
}
static bool setup = false;
public static void Setup ()
{
if (!setup)
{
//let's load all the app config settings, if possible.
foreach( string k in ConfigurationManager.AppSettings.Keys )
{
settings[k] = ConfigurationManager.AppSettings[k];
log.Debug("config key: ", k, settings[k] );
}
setup = true;
}
}
public static void AddApplicationSetting(string key, string value)
{
settings[key] = value;
}
public static Setting Get(string key)
{
return Get(key, null, false);
}
public static Setting GetConfig (string key)
{
return Get (key, null, true);
}
static Dictionary<string,Setting> settingsCache = new Dictionary<string, Setting>();
public static Setting Get(string key, string defaultValue, bool configOnly )
{
if( settingsCache.ContainsKey(key) )
return settingsCache[key];
Setting s = null;
try
{
string v = settings.ContainsKey( key ) ? settings[key] : null;
if( v != null )
{
s = new Setting();
s.dataKey = key;
s.DataValue = v;
}
else if ( ! configOnly && ! DataProvider.DisableDataProvider)
{
s = Setting.Load<Setting>("DataKey", key);
}
}
catch (Exception e)
{
log.Error("Error getting setting",e);
}
if (s == null)
{
string v = System.Environment.GetEnvironmentVariable(key);
if ( v != null )
{
s = new Setting();
s.dataKey = key;
s.DataValue = v;
}
}
if (s == null && defaultValue != null)
{
s = new Setting();
s.dataKey = key;
s.dataValue = defaultValue;
}
settingsCache[key] = s;
return s;
}
//// <value>
/// Use VirtualRoot when you need to discover the subfolder the application is running in a webserver.
/// Manually configured via the 'virtualRoot' appSetting.
/// VirtualRoot is a static config file accessor because it is required by the system at a point
/// prior to DataProvider functionality.
/// </value>
public static string VirtualRoot
{
get
{
return ConfigurationManager.AppSettings["virtualRoot"] ?? "";
}
}
//// <value>
/// DefaultContext instructs EmergeTk to load a context of this type in the event a context type is
/// not recognized, such as when the root directory is accessed in the browser.
/// DefaultContext is a static config file accessor because it is required by the system at a point
/// prior to DataProvider functionality.
/// </value>
public static string DefaultContext
{
get
{
return ConfigurationManager.AppSettings["defaultContext"];
}
}
}
}
| |
// 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 ga = Google.Api;
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
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.Monitoring.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedMetricServiceClientTest
{
[xunit::FactAttribute]
public void GetMonitoredResourceDescriptorRequestObject()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMonitoredResourceDescriptorRequestObjectAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMonitoredResourceDescriptor()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMonitoredResourceDescriptorAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMonitoredResourceDescriptorResourceNames1()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request.MonitoredResourceDescriptorName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMonitoredResourceDescriptorResourceNames1Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request.MonitoredResourceDescriptorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request.MonitoredResourceDescriptorName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMonitoredResourceDescriptorResourceNames2()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor response = client.GetMonitoredResourceDescriptor(request.ResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMonitoredResourceDescriptorResourceNames2Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = MonitoredResourceDescriptorName.FromProjectMonitoredResourceDescriptor("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
ga::MonitoredResourceDescriptor expectedResponse = new ga::MonitoredResourceDescriptor
{
Type = "typee2cc9d59",
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
Labels =
{
new ga::LabelDescriptor(),
},
Name = "name1c9368b0",
LaunchStage = ga::LaunchStage.Unspecified,
};
mockGrpcClient.Setup(x => x.GetMonitoredResourceDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MonitoredResourceDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MonitoredResourceDescriptor responseCallSettings = await client.GetMonitoredResourceDescriptorAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MonitoredResourceDescriptor responseCancellationToken = await client.GetMonitoredResourceDescriptorAsync(request.ResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMetricDescriptorRequestObject()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.GetMetricDescriptor(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMetricDescriptorRequestObjectAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMetricDescriptor()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.GetMetricDescriptor(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMetricDescriptorAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMetricDescriptorResourceNames1()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.GetMetricDescriptor(request.MetricDescriptorName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMetricDescriptorResourceNames1Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request.MetricDescriptorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request.MetricDescriptorName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetMetricDescriptorResourceNames2()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.GetMetricDescriptor(request.ResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetMetricDescriptorResourceNames2Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.GetMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.GetMetricDescriptorAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.GetMetricDescriptorAsync(request.ResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateMetricDescriptorRequestObject()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.CreateMetricDescriptor(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateMetricDescriptorRequestObjectAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateMetricDescriptor()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.CreateMetricDescriptor(request.Name, request.MetricDescriptor);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateMetricDescriptorAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.Name, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.Name, request.MetricDescriptor, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateMetricDescriptorResourceNames1()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.CreateMetricDescriptor(request.ProjectName, request.MetricDescriptor);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateMetricDescriptorResourceNames1Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.ProjectName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.ProjectName, request.MetricDescriptor, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateMetricDescriptorResourceNames2()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.CreateMetricDescriptor(request.OrganizationName, request.MetricDescriptor);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateMetricDescriptorResourceNames2Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.OrganizationName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.OrganizationName, request.MetricDescriptor, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateMetricDescriptorResourceNames3()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.CreateMetricDescriptor(request.FolderName, request.MetricDescriptor);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateMetricDescriptorResourceNames3Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.FolderName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.FolderName, request.MetricDescriptor, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateMetricDescriptorResourceNames4()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor response = client.CreateMetricDescriptor(request.ResourceName, request.MetricDescriptor);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateMetricDescriptorResourceNames4Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
MetricDescriptor = new ga::MetricDescriptor(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
ga::MetricDescriptor expectedResponse = new ga::MetricDescriptor
{
Name = "name1c9368b0",
Labels =
{
new ga::LabelDescriptor(),
},
MetricKind = ga::MetricDescriptor.Types.MetricKind.Gauge,
ValueType = ga::MetricDescriptor.Types.ValueType.Money,
Unit = "unitebbd343e",
Description = "description2cf9da67",
DisplayName = "display_name137f65c2",
Type = "typee2cc9d59",
Metadata = new ga::MetricDescriptor.Types.MetricDescriptorMetadata(),
LaunchStage = ga::LaunchStage.Unspecified,
MonitoredResourceTypes =
{
"monitored_resource_typesc49bdc0a",
},
};
mockGrpcClient.Setup(x => x.CreateMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::MetricDescriptor>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
ga::MetricDescriptor responseCallSettings = await client.CreateMetricDescriptorAsync(request.ResourceName, request.MetricDescriptor, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ga::MetricDescriptor responseCancellationToken = await client.CreateMetricDescriptorAsync(request.ResourceName, request.MetricDescriptor, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteMetricDescriptorRequestObject()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteMetricDescriptor(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteMetricDescriptorRequestObjectAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteMetricDescriptorAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteMetricDescriptorAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteMetricDescriptor()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteMetricDescriptor(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteMetricDescriptorAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteMetricDescriptorAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteMetricDescriptorAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteMetricDescriptorResourceNames1()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteMetricDescriptor(request.MetricDescriptorName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteMetricDescriptorResourceNames1Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteMetricDescriptorAsync(request.MetricDescriptorName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteMetricDescriptorAsync(request.MetricDescriptorName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteMetricDescriptorResourceNames2()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptor(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteMetricDescriptor(request.ResourceName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteMetricDescriptorResourceNames2Async()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = MetricDescriptorName.FromProjectMetricDescriptor("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteMetricDescriptorAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteMetricDescriptorAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteMetricDescriptorAsync(request.ResourceName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTimeSeriesRequestObject()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.CreateTimeSeries(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTimeSeriesRequestObjectAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.CreateTimeSeriesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CreateTimeSeriesAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTimeSeries()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.CreateTimeSeries(request.Name, request.TimeSeries);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTimeSeriesAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.CreateTimeSeriesAsync(request.Name, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CreateTimeSeriesAsync(request.Name, request.TimeSeries, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTimeSeriesResourceNames()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.CreateTimeSeries(request.ProjectName, request.TimeSeries);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTimeSeriesResourceNamesAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.CreateTimeSeriesAsync(request.ProjectName, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CreateTimeSeriesAsync(request.ProjectName, request.TimeSeries, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateServiceTimeSeriesRequestObject()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateServiceTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.CreateServiceTimeSeries(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateServiceTimeSeriesRequestObjectAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateServiceTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.CreateServiceTimeSeriesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CreateServiceTimeSeriesAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateServiceTimeSeries()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateServiceTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.CreateServiceTimeSeries(request.Name, request.TimeSeries);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateServiceTimeSeriesAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateServiceTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.CreateServiceTimeSeriesAsync(request.Name, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CreateServiceTimeSeriesAsync(request.Name, request.TimeSeries, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateServiceTimeSeriesResourceNames()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateServiceTimeSeries(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
client.CreateServiceTimeSeries(request.ProjectName, request.TimeSeries);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateServiceTimeSeriesResourceNamesAsync()
{
moq::Mock<MetricService.MetricServiceClient> mockGrpcClient = new moq::Mock<MetricService.MetricServiceClient>(moq::MockBehavior.Strict);
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
TimeSeries = { new TimeSeries(), },
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.CreateServiceTimeSeriesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
MetricServiceClient client = new MetricServiceClientImpl(mockGrpcClient.Object, null);
await client.CreateServiceTimeSeriesAsync(request.ProjectName, request.TimeSeries, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.CreateServiceTimeSeriesAsync(request.ProjectName, request.TimeSeries, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
namespace DrawingEx.Drawing3D
{
public struct Vector3
{
public static readonly Vector3 Empty=new Vector3();
#region variables
private double _x, _y, _z, _w;
#endregion
#region ctor
/// <summary>
/// constructs a new vector from the given coordinates divided by w
/// </summary>
public Vector3(double x,double y,double z,double w)
{
// if(w==0.0)
// throw new ArgumentOutOfRangeException("w");
_x=x/w;
_y=y/w;
_z=z/w;
_w=1.0;
}
/// <summary>
/// constructs a new vector from the given coordinates
/// </summary>
public Vector3(double x,double y,double z)
{
_x=x;
_y=y;
_z=z;
_w=1.0;
}
#endregion
#region static functions
/// <summary>
/// returns a new vector that keeps the direction of the old one,
/// but its length restricted to 1 (0 respectively)
/// </summary>
public static Vector3 GetNormalizedVector(Vector3 value)
{
double length=value.GetLength();
if (length==0.0){return Vector3.Empty;}
return value/length;
}
/// <summary>
/// calculates the angle between two vectors
/// </summary>
public static Angle GetAngleBetween(Vector3 a, Vector3 b)
{
double divisor=a.GetLength()*b.GetLength();
if(divisor==0.0) return Angle.Empty;
return Angle.FromRadiants(Math.Acos(
(a._x*b._x+a._y*b._y+a._z*b._z)/divisor));
}
/// <summary>
/// cross-multiplicates two vectors
/// </summary>
public static Vector3 Cross(Vector3 a, Vector3 b)
{
return new Vector3(
a._y*b._z-a._z*b._y,
a._z*b._x-a._x*b._z,
a._x*b._y-a._y*b._x);
}
/// <summary>
/// gets a normal from a plane that is constructed by three points
/// </summary>
public static Vector3 GetNormalFromPoints(Vector3 a, Vector3 b, Vector3 c)
{
return Vector3.GetNormalizedVector(Vector3.Cross(a-b,b-c));
}
/// <summary>
/// gets a point that is element of the line constructed by a and b,
/// scalar representing the distance from point a
/// </summary>
public static Vector3 GetPointOnLine(Vector3 a, Vector3 b, float scalar)
{
return new Vector3(
a._x+scalar*(b._x-a._x),
a._y+scalar*(b._y-a._y),
a._z+scalar*(b._z-a._z));
}
#endregion
#region operators
//calculations
public static Vector3 operator+(Vector3 a, Vector3 b)
{
return new Vector3(
a._x+b._x,
a._y+b._y,
a._z+b._z);
}
public static Vector3 operator-(Vector3 a, Vector3 b)
{
return new Vector3(
a._x-b._x,
a._y-b._y,
a._z-b._z);
}
public static Vector3 operator*(Vector3 a, Vector3 b)
{
return new Vector3(
a._x*b._x,
a._y*b._y,
a._z*b._z);
}
public static Vector3 operator*(Vector3 value, Matrix3 mat)
{
return new Vector3(value._x*mat[0,0]+value._y*mat[0,1]+value._z*mat[0,2]+value._w*mat[0,3],
value._x*mat[1,0]+value._y*mat[1,1]+value._z*mat[1,2]+value._w*mat[1,3],
value._x*mat[2,0]+value._y*mat[2,1]+value._z*mat[2,2]+value._w*mat[2,3],
value._x*mat[3,0]+value._y*mat[3,1]+value._z*mat[3,2]+value._w*mat[3,3]);
}
public static Vector3 operator*(Vector3 value, double scalar)
{
return new Vector3(
value._x*scalar,
value._x*scalar,
value._z*scalar);
}
public static Vector3 operator/(Vector3 value, double scalar)
{
return new Vector3(
value._x/scalar,
value._x/scalar,
value._z/scalar);
}
//equality
public static bool operator==(Vector3 a, Vector3 b)
{
return a._x==b._x &&
a._y==b._y &&
a._z==b._z &&
a._w==b._w;
}
public static bool operator!=(Vector3 a, Vector3 b)
{
return !(a==b);
}
public override bool Equals(object obj)
{
if(obj is Vector3)
{
Vector3 vct=(Vector3)obj;
return vct==this;
}
return false;
}
public override int GetHashCode()
{
string representation=
_x.ToString()+":"+
_y.ToString()+":"+
_z.ToString()+":"+
_w.ToString();
return representation.GetHashCode();
}
#endregion
#region members
/// <summary>
/// gets the length of the vector
/// </summary>
public double GetLength()
{
return Math.Sqrt(
_x*_x+
_y*_y+
_z*_z);
}
/// <summary>
/// rounds the x and y coordinates tho the next integer value
/// </summary>
public void RoundXYInPlace()
{
_x=Math.Round(_x);
_y=Math.Round(_y);
}
#endregion
#region conversion
/// <summary>
/// represents the vector in human readable appearance
/// </summary>
public override string ToString()
{
return string.Format("Vector[\nX={0};\tY={1};\tZ={2};\tW={3}\n]",
_x,_y,_z,_w);
}
/// <summary>
/// returns a point by clamping z and w values
/// </summary>
public PointF ToPoint()
{
return new PointF(
(float)_x,
(float)_y);
}
/// <summary>
/// converts an array of vectors to 2d points
/// </summary>
public static PointF[] ToPointArray(Vector3[] ptarray)
{
if (ptarray==null || ptarray.Length<1)
throw new ArgumentNullException("ptarray");
//copy points
PointF[] ret=new PointF[ptarray.Length];
for (int i=0; i<ptarray.Length; i++)
{
ret[i]=ptarray[i].ToPoint();
}
return ret;
}
#endregion
#region properties
/// <summary>
/// gets or sets the x-coordinate
/// </summary>
public double X
{
get{return _x;}
set{_x=value;}
}
/// <summary>
/// gets or sets the y-coordinate
/// </summary>
public double Y
{
get{return _y;}
set{_y=value;}
}
/// <summary>
/// gets or sets the z-coordinate
/// </summary>
public double Z
{
get{return _z;}
set{_z=value;}
}
/// <summary>
/// gets or sets the scaling data
/// </summary>
public double W
{
get{return _w;}
set{_w=value;}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** Class: CurrentTimeZone
**
**
** Purpose:
** This class represents the current system timezone. It is
** the only meaningful implementation of the TimeZone class
** available in this version.
**
** The only TimeZone that we support in version 1 is the
** CurrentTimeZone as determined by the system timezone.
**
**
============================================================*/
namespace System {
using System;
using System.Diagnostics.Contracts;
using System.Text;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
//
// Currently, this is the only supported timezone.
// The values of the timezone is from the current system timezone setting in the
// control panel.
//
#if FEATURE_CORECLR
[Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")]
#endif
[Serializable]
internal class CurrentSystemTimeZone : TimeZone {
// <BUGBUG>BUGBUG :
// One problem is when user changes the current timezone. We
// are not able to update currentStandardName/currentDaylightName/
// currentDaylightChanges.
// We need WM_TIMECHANGE to do this or use
// RegNotifyChangeKeyValue() to monitor </BUGBUG>
//
private const long TicksPerMillisecond = 10000;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
private const long TicksPerMinute = TicksPerSecond * 60;
// The per-year information is cached in in this instance value. As a result it can
// be cleaned up by CultureInfo.ClearCachedData, which will clear the instance of this object
private Hashtable m_CachedDaylightChanges = new Hashtable();
// Standard offset in ticks to the Universal time if
// no daylight saving is in used.
// E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000.
// (1 millisecond = 10000 ticks)
private long m_ticksOffset;
private String m_standardName;
private String m_daylightName;
[System.Security.SecuritySafeCritical] // auto-generated
internal CurrentSystemTimeZone() {
m_ticksOffset = nativeGetTimeZoneMinuteOffset() * TicksPerMinute;
m_standardName = null;
m_daylightName = null;
}
public override String StandardName {
[System.Security.SecuritySafeCritical] // auto-generated
get {
if (m_standardName == null) {
m_standardName = nativeGetStandardName();
}
return (m_standardName);
}
}
public override String DaylightName {
[System.Security.SecuritySafeCritical] // auto-generated
get {
if (m_daylightName == null) {
m_daylightName = nativeGetDaylightName();
if (m_daylightName == null) {
m_daylightName = this.StandardName;
}
}
return (m_daylightName);
}
}
internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguousLocalDst) {
// Get the daylight changes for the year of the specified time.
TimeSpan offset = new TimeSpan(m_ticksOffset);
DaylightTime daylightTime = GetDaylightChanges(time.Year);
isAmbiguousLocalDst= false;
if (daylightTime == null || daylightTime.Delta.Ticks == 0) {
return offset.Ticks;
}
// The start and end times represent the range of universal times that are in DST for that year.
// Within that there is an ambiguous hour, usually right at the end, but at the beginning in
// the unusual case of a negative daylight savings delta.
DateTime startTime = daylightTime.Start - offset;
DateTime endTime = daylightTime.End - offset - daylightTime.Delta;
DateTime ambiguousStart;
DateTime ambiguousEnd;
if (daylightTime.Delta.Ticks > 0) {
ambiguousStart = endTime - daylightTime.Delta;
ambiguousEnd = endTime;
} else {
ambiguousStart = startTime;
ambiguousEnd = startTime - daylightTime.Delta;
}
Boolean isDst = false;
if (startTime > endTime) {
// In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
// Note, the summer in the southern hemisphere begins late in the year.
isDst = (time < endTime || time >= startTime);
}
else {
// In northern hemisphere, the daylight saving time starts in the middle of the year.
isDst = (time>=startTime && time<endTime);
}
if (isDst) {
offset += daylightTime.Delta;
// See if the resulting local time becomes ambiguous. This must be captured here or the
// DateTime will not be able to round-trip back to UTC accurately.
if (time >= ambiguousStart && time < ambiguousEnd ) {
isAmbiguousLocalDst = true;
}
}
return offset.Ticks;
}
public override DateTime ToLocalTime(DateTime time) {
if (time.Kind == DateTimeKind.Local) {
return time;
}
Boolean isAmbiguousLocalDst = false;
Int64 offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst);
long tick = time.Ticks + offset;
if (tick>DateTime.MaxTicks) {
return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
}
if (tick<DateTime.MinTicks) {
return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
}
return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
}
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
private static Object InternalSyncObject {
get {
if (s_InternalSyncObject == null) {
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override DaylightTime GetDaylightChanges(int year) {
if (year < 1 || year > 9999) {
throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 9999));
}
Contract.EndContractBlock();
Object objYear = (Object)year;
if (!m_CachedDaylightChanges.Contains(objYear)) {
lock (InternalSyncObject) {
if (!m_CachedDaylightChanges.Contains(objYear)) {
//
// rawData is an array of 17 short (16 bit) numbers.
// The first 8 numbers contains the
// year/month/day/dayOfWeek/hour/minute/second/millisecond for the starting time of daylight saving time.
// The next 8 numbers contains the
// year/month/day/dayOfWeek/hour/minute/second/millisecond for the ending time of daylight saving time.
// The last short number is the delta to the standard offset in minutes.
//
short[] rawData = nativeGetDaylightChanges(year);
if (rawData == null) {
//
// If rawData is null, it means that daylight saving time is not used
// in this timezone. So keep currentDaylightChanges as the empty array.
//
m_CachedDaylightChanges.Add(objYear, new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero));
} else {
DateTime start;
DateTime end;
TimeSpan delta;
//
// Store the start of daylight saving time.
//
start = GetDayOfWeek(year, (rawData[0] != 0), rawData[1], rawData[2],
rawData[3],
rawData[4], rawData[5], rawData[6], rawData[7]);
//
// Store the end of daylight saving time.
//
end = GetDayOfWeek(year, (rawData[8] != 0), rawData[9], rawData[10],
rawData[11],
rawData[12], rawData[13], rawData[14], rawData[15]);
delta = new TimeSpan(rawData[16] * TicksPerMinute);
DaylightTime currentDaylightChanges = new DaylightTime(start, end, delta);
m_CachedDaylightChanges.Add(objYear, currentDaylightChanges);
}
}
}
}
DaylightTime result = (DaylightTime)m_CachedDaylightChanges[objYear];
return result;
}
public override TimeSpan GetUtcOffset(DateTime time) {
if (time.Kind == DateTimeKind.Utc) {
return TimeSpan.Zero;
}
else {
return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset);
}
}
//
// Return the (numberOfSunday)th day of week in a particular year/month.
//
private static DateTime GetDayOfWeek(int year, bool fixedDate, int month, int targetDayOfWeek, int numberOfSunday, int hour, int minute, int second, int millisecond) {
DateTime time;
if (fixedDate) {
//
// Create a Fixed-Date transition time based on the supplied parameters
// For Fixed-Dated transition times, the 'numberOfSunday' parameter actually
// represents the day of the month.
//
// if the day is out of range for the month then use the last day of the month
int day = DateTime.DaysInMonth(year, month);
time = new DateTime(year, month, (day < numberOfSunday) ? day : numberOfSunday,
hour, minute, second, millisecond, DateTimeKind.Local);
}
else if (numberOfSunday <= 4) {
//
// Get the (numberOfSunday)th Sunday.
//
time = new DateTime(year, month, 1, hour, minute, second, millisecond, DateTimeKind.Local);
int dayOfWeek = (int)time.DayOfWeek;
int delta = targetDayOfWeek - dayOfWeek;
if (delta < 0) {
delta += 7;
}
delta += 7 * (numberOfSunday - 1);
if (delta > 0) {
time = time.AddDays(delta);
}
} else {
//
// If numberOfSunday is greater than 4, we will get the last sunday.
//
Calendar cal = GregorianCalendar.GetDefaultInstance();
time = new DateTime(year, month, cal.GetDaysInMonth(year, month), hour, minute, second, millisecond, DateTimeKind.Local);
// This is the day of week for the last day of the month.
int dayOfWeek = (int)time.DayOfWeek;
int delta = dayOfWeek - targetDayOfWeek;
if (delta < 0) {
delta += 7;
}
if (delta > 0) {
time = time.AddDays(-delta);
}
}
return (time);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int nativeGetTimeZoneMinuteOffset();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String nativeGetDaylightName();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static String nativeGetStandardName();
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static short[] nativeGetDaylightChanges(int year);
} // class CurrentSystemTimeZone
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Configuration;
using System.Xml.Linq;
using MarkdownSharp;
using ServiceStack.Common.ServiceModel;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.Configuration;
using ServiceStack.Logging;
using ServiceStack.Logging.Support.Logging;
using ServiceStack.Markdown;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceModel;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Extensions;
using ServiceStack.WebHost.Endpoints.Support;
namespace ServiceStack.WebHost.Endpoints
{
public class EndpointHostConfig
{
private static ILog log = LogManager.GetLogger(typeof(EndpointHostConfig));
public static readonly string PublicKey = "<RSAKeyValue><Modulus>xRzMrP3m+3kvT6239OP1YuWIfc/S7qF5NJiPe2/kXnetXiuYtSL4bQRIX1qYh4Cz+dXqZE/sNGJJ4jl2iJQa1tjp+rK28EG6gcuTDHJdvOBBF+aSwJy1MSiT8D0KtP6pe2uvjl9m3jZP/8uRePZTSkt/GjlPOk85JXzOsyzemlaLFiJoGImGvp8dw8vQ7jzA3Ynmywpt5OQxklJfrfALHJ93ny1M5lN5Q+bGPEHLXNCXfF05EA0l9mZpa4ouicYvlbY/OAwefFXIwPQN9ER6Pu7Eq9XWLvnh1YUH8HDckuKK+ESWbAuOgnVbUDEF1BreoWutJ//a/oLDR87Q36cmwQ==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
public static readonly string LicensePublicKey = "<RSAKeyValue><Modulus>19kx2dJoOIrMYypMTf8ssiCALJ7RS/Iz2QG0rJtYJ2X0+GI+NrgOCapkh/9aDVBieobdClnuBgW08C5QkfBdLRqsptiSu50YIqzVaNBMwZPT0e7Ke02L/fV/M/fVPsolHwzMstKhdWGdK8eNLF4SsLEcvnb79cx3/GnZbXku/ro5eOrTseKL3s4nM4SdMRNn7rEAU0o0Ijb3/RQbhab8IIRB4pHwk1mB+j/mcAQAtMerwpHfwpEBLWlQyVpu0kyKJCEkQjbaPzvfglDRpyBOT5GMUnrcTT/sBr5kSJYpYrgHnA5n4xJnvrnyFqdzXwgGFlikRTbc60pk1cQEWcHgYw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
public static bool SkipPathValidation = false;
/// <summary>
/// Use: \[Route\("[^\/] regular expression to find violating routes in your sln
/// </summary>
public static bool SkipRouteValidation = false;
public static string ServiceStackPath = null;
private static EndpointHostConfig instance;
public static EndpointHostConfig Instance
{
get
{
if (instance == null)
{
instance = new EndpointHostConfig
{
MetadataTypesConfig = new MetadataTypesConfig(addDefaultXmlNamespace: "http://schemas.servicestack.net/types"),
WsdlServiceNamespace = "http://schemas.servicestack.net/types",
WsdlSoapActionNamespace = "http://schemas.servicestack.net/types",
MetadataPageBodyHtml = @"<br />
<h3><a href=""https://github.com/ServiceStack/ServiceStack/wiki/Clients-overview"">Clients Overview</a></h3>",
MetadataOperationPageBodyHtml = @"<br />
<h3><a href=""https://github.com/ServiceStack/ServiceStack/wiki/Clients-overview"">Clients Overview</a></h3>",
MetadataCustomPath = "Views/Templates/Metadata/",
UseCustomMetadataTemplates = false,
LogFactory = new NullLogFactory(),
EnableAccessRestrictions = true,
WebHostPhysicalPath = "~".MapServerPath(),
ServiceStackHandlerFactoryPath = ServiceStackPath,
MetadataRedirectPath = null,
DefaultContentType = null,
AllowJsonpRequests = true,
AllowRouteContentTypeExtensions = true,
AllowNonHttpOnlyCookies = false,
UseHttpsLinks = false,
DebugMode = false,
DefaultDocuments = new List<string> {
"default.htm",
"default.html",
"default.cshtml",
"default.md",
"index.htm",
"index.html",
"default.aspx",
"default.ashx",
},
GlobalResponseHeaders = new Dictionary<string, string> { { "X-Powered-By", Env.ServerUserAgent } },
IgnoreFormatsInMetadata = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase),
AllowFileExtensions = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
{
"js", "css", "htm", "html", "shtm", "txt", "xml", "rss", "csv", "pdf",
"jpg", "jpeg", "gif", "png", "bmp", "ico", "tif", "tiff", "svg",
"avi", "divx", "m3u", "mov", "mp3", "mpeg", "mpg", "qt", "vob", "wav", "wma", "wmv",
"flv", "xap", "xaml", "ogg", "mp4", "webm", "eot", "ttf", "woff"
},
DebugAspNetHostEnvironment = Env.IsMono ? "FastCGI" : "IIS7",
DebugHttpListenerHostEnvironment = Env.IsMono ? "XSP" : "WebServer20",
EnableFeatures = Feature.All,
WriteErrorsToResponse = true,
ReturnsInnerException = true,
MarkdownOptions = new MarkdownOptions(),
MarkdownBaseType = typeof(MarkdownViewBase),
MarkdownGlobalHelpers = new Dictionary<string, Type>(),
HtmlReplaceTokens = new Dictionary<string, string>(),
AddMaxAgeForStaticMimeTypes = new Dictionary<string, TimeSpan> {
{ "image/gif", TimeSpan.FromHours(1) },
{ "image/png", TimeSpan.FromHours(1) },
{ "image/jpeg", TimeSpan.FromHours(1) },
},
AppendUtf8CharsetOnContentTypes = new HashSet<string> { ContentType.Json, },
RawHttpHandlers = new List<Func<IHttpRequest, IHttpHandler>>(),
RouteNamingConventions = new List<RouteNamingConventionDelegate> {
RouteNamingConvention.WithRequestDtoName,
RouteNamingConvention.WithMatchingAttributes,
RouteNamingConvention.WithMatchingPropertyNames
},
CustomHttpHandlers = new Dictionary<HttpStatusCode, IServiceStackHttpHandler>(),
GlobalHtmlErrorHttpHandler = null,
MapExceptionToStatusCode = new Dictionary<Type, int>(),
OnlySendSessionCookiesSecurely = false,
RestrictAllCookiesToDomain = null,
DefaultJsonpCacheExpiration = new TimeSpan(0, 20, 0),
MetadataVisibility = EndpointAttributes.Any,
Return204NoContentForEmptyResponse = true,
AllowPartialResponses = true,
AllowAclUrlReservation = true,
IgnoreWarningsOnPropertyNames = new List<string> {
"format", "callback", "debug", "_", "authsecret"
}
};
if (instance.ServiceStackHandlerFactoryPath == null)
{
InferHttpHandlerPath();
}
}
return instance;
}
}
public EndpointHostConfig(string serviceName, ServiceManager serviceManager)
: this()
{
this.ServiceName = serviceName;
this.ServiceManager = serviceManager;
}
public EndpointHostConfig()
{
if (instance == null) return;
//Get a copy of the singleton already partially configured
this.MetadataTypesConfig = instance.MetadataTypesConfig;
this.WsdlServiceNamespace = instance.WsdlServiceNamespace;
this.WsdlSoapActionNamespace = instance.WsdlSoapActionNamespace;
this.MetadataPageBodyHtml = instance.MetadataPageBodyHtml;
this.MetadataOperationPageBodyHtml = instance.MetadataOperationPageBodyHtml;
this.MetadataCustomPath = instance.MetadataCustomPath;
this.UseCustomMetadataTemplates = instance.UseCustomMetadataTemplates;
this.EnableAccessRestrictions = instance.EnableAccessRestrictions;
this.ServiceEndpointsMetadataConfig = instance.ServiceEndpointsMetadataConfig;
this.LogFactory = instance.LogFactory;
this.EnableAccessRestrictions = instance.EnableAccessRestrictions;
this.WebHostUrl = instance.WebHostUrl;
this.WebHostPhysicalPath = instance.WebHostPhysicalPath;
this.DefaultRedirectPath = instance.DefaultRedirectPath;
this.MetadataRedirectPath = instance.MetadataRedirectPath;
this.ServiceStackHandlerFactoryPath = instance.ServiceStackHandlerFactoryPath;
this.DefaultContentType = instance.DefaultContentType;
this.AllowJsonpRequests = instance.AllowJsonpRequests;
this.AllowRouteContentTypeExtensions = instance.AllowRouteContentTypeExtensions;
this.DebugMode = instance.DebugMode;
this.DefaultDocuments = instance.DefaultDocuments;
this.GlobalResponseHeaders = instance.GlobalResponseHeaders;
this.IgnoreFormatsInMetadata = instance.IgnoreFormatsInMetadata;
this.AllowFileExtensions = instance.AllowFileExtensions;
this.EnableFeatures = instance.EnableFeatures;
this.WriteErrorsToResponse = instance.WriteErrorsToResponse;
this.ReturnsInnerException = instance.ReturnsInnerException;
this.MarkdownOptions = instance.MarkdownOptions;
this.MarkdownBaseType = instance.MarkdownBaseType;
this.MarkdownGlobalHelpers = instance.MarkdownGlobalHelpers;
this.HtmlReplaceTokens = instance.HtmlReplaceTokens;
this.AddMaxAgeForStaticMimeTypes = instance.AddMaxAgeForStaticMimeTypes;
this.AppendUtf8CharsetOnContentTypes = instance.AppendUtf8CharsetOnContentTypes;
this.RawHttpHandlers = instance.RawHttpHandlers;
this.RouteNamingConventions = instance.RouteNamingConventions;
this.CustomHttpHandlers = instance.CustomHttpHandlers;
this.GlobalHtmlErrorHttpHandler = instance.GlobalHtmlErrorHttpHandler;
this.MapExceptionToStatusCode = instance.MapExceptionToStatusCode;
this.OnlySendSessionCookiesSecurely = instance.OnlySendSessionCookiesSecurely;
this.RestrictAllCookiesToDomain = instance.RestrictAllCookiesToDomain;
this.DefaultJsonpCacheExpiration = instance.DefaultJsonpCacheExpiration;
this.MetadataVisibility = instance.MetadataVisibility;
this.Return204NoContentForEmptyResponse = Return204NoContentForEmptyResponse;
this.AllowNonHttpOnlyCookies = instance.AllowNonHttpOnlyCookies;
this.AllowPartialResponses = instance.AllowPartialResponses;
this.IgnoreWarningsOnPropertyNames = instance.IgnoreWarningsOnPropertyNames;
this.PreExecuteServiceFilter = instance.PreExecuteServiceFilter;
this.PostExecuteServiceFilter = instance.PostExecuteServiceFilter;
this.FallbackRestPath = instance.FallbackRestPath;
this.AllowAclUrlReservation = instance.AllowAclUrlReservation;
this.AdminAuthSecret = instance.AdminAuthSecret;
}
public static string GetAppConfigPath()
{
if (EndpointHost.AppHost == null) return null;
var configPath = "~/web.config".MapHostAbsolutePath();
if (File.Exists(configPath))
return configPath;
configPath = "~/Web.config".MapHostAbsolutePath(); //*nix FS FTW!
if (File.Exists(configPath))
return configPath;
var appHostDll = new FileInfo(EndpointHost.AppHost.GetType().Assembly.Location).Name;
configPath = "~/{0}.config".Fmt(appHostDll).MapAbsolutePath();
return File.Exists(configPath) ? configPath : null;
}
const string NamespacesAppSettingsKey = "servicestack.razor.namespaces";
private static HashSet<string> razorNamespaces;
public static HashSet<string> RazorNamespaces
{
get
{
if (razorNamespaces != null)
return razorNamespaces;
razorNamespaces = new HashSet<string>();
//Infer from <system.web.webPages.razor> - what VS.NET's intell-sense uses
var configPath = GetAppConfigPath();
if (configPath != null)
{
var xml = configPath.ReadAllText();
var doc = XElement.Parse(xml);
doc.AnyElement("system.web.webPages.razor")
.AnyElement("pages")
.AnyElement("namespaces")
.AllElements("add").ToList()
.ForEach(x => razorNamespaces.Add(x.AnyAttribute("namespace").Value));
}
//E.g. <add key="servicestack.razor.namespaces" value="System,ServiceStack.Text" />
if (ConfigUtils.GetNullableAppSetting(NamespacesAppSettingsKey) != null)
{
ConfigUtils.GetListFromAppSetting(NamespacesAppSettingsKey)
.ForEach(x => razorNamespaces.Add(x));
}
//log.Debug("Loaded Razor Namespaces: in {0}: {1}: {2}"
// .Fmt(configPath, "~/Web.config".MapHostAbsolutePath(), razorNamespaces.Dump()));
return razorNamespaces;
}
}
private static System.Configuration.Configuration GetAppConfig()
{
Assembly entryAssembly;
//Read the user-defined path in the Web.Config
if (EndpointHost.AppHost is AppHostBase)
return WebConfigurationManager.OpenWebConfiguration("~/");
if ((entryAssembly = Assembly.GetEntryAssembly()) != null)
return ConfigurationManager.OpenExeConfiguration(entryAssembly.Location);
return null;
}
private static void InferHttpHandlerPath()
{
try
{
var config = GetAppConfig();
if (config == null) return;
SetPathsFromConfiguration(config, null);
if (instance.MetadataRedirectPath == null)
{
foreach (ConfigurationLocation location in config.Locations)
{
SetPathsFromConfiguration(location.OpenConfiguration(), (location.Path ?? "").ToLower());
if (instance.MetadataRedirectPath != null) { break; }
}
}
if (!SkipPathValidation && instance.MetadataRedirectPath == null)
{
throw new ConfigurationErrorsException(
"Unable to infer ServiceStack's <httpHandler.Path/> from the Web.Config\n"
+ "Check with http://www.servicestack.net/ServiceStack.Hello/ to ensure you have configured ServiceStack properly.\n"
+ "Otherwise you can explicitly set your httpHandler.Path by setting: EndpointHostConfig.ServiceStackPath");
}
}
catch (Exception) { }
}
private static void SetPathsFromConfiguration(System.Configuration.Configuration config, string locationPath)
{
if (config == null)
return;
//standard config
var handlersSection = config.GetSection("system.web/httpHandlers") as HttpHandlersSection;
if (handlersSection != null)
{
for (var i = 0; i < handlersSection.Handlers.Count; i++)
{
var httpHandler = handlersSection.Handlers[i];
if (!httpHandler.Type.StartsWith("ServiceStack"))
continue;
SetPaths(httpHandler.Path, locationPath);
break;
}
}
//IIS7+ integrated mode system.webServer/handlers
var pathsNotSet = instance.MetadataRedirectPath == null;
if (pathsNotSet)
{
var webServerSection = config.GetSection("system.webServer");
if (webServerSection != null)
{
var rawXml = webServerSection.SectionInformation.GetRawXml();
if (!String.IsNullOrEmpty(rawXml))
{
SetPaths(ExtractHandlerPathFromWebServerConfigurationXml(rawXml), locationPath);
}
}
//In some MVC Hosts auto-inferencing doesn't work, in these cases assume the most likely default of "/api" path
pathsNotSet = instance.MetadataRedirectPath == null;
if (pathsNotSet)
{
var isMvcHost = Type.GetType("System.Web.Mvc.Controller") != null;
if (isMvcHost)
{
SetPaths("api", null);
}
}
}
}
private static void SetPaths(string handlerPath, string locationPath)
{
if (handlerPath == null) return;
if (locationPath == null)
{
handlerPath = handlerPath.Replace("*", String.Empty);
}
instance.ServiceStackHandlerFactoryPath = locationPath ??
(String.IsNullOrEmpty(handlerPath) ? null : handlerPath);
instance.MetadataRedirectPath = PathUtils.CombinePaths(
null != locationPath ? instance.ServiceStackHandlerFactoryPath : handlerPath
, "metadata");
}
private static string ExtractHandlerPathFromWebServerConfigurationXml(string rawXml)
{
return XDocument.Parse(rawXml).Root.Element("handlers")
.Descendants("add")
.Where(handler => EnsureHandlerTypeAttribute(handler).StartsWith("ServiceStack"))
.Select(handler => handler.Attribute("path").Value)
.FirstOrDefault();
}
private static string EnsureHandlerTypeAttribute(XElement handler)
{
if (handler.Attribute("type") != null && !String.IsNullOrEmpty(handler.Attribute("type").Value))
{
return handler.Attribute("type").Value;
}
return String.Empty;
}
public ServiceManager ServiceManager { get; internal set; }
public ServiceMetadata Metadata { get { return ServiceManager.Metadata; } }
public IServiceController ServiceController { get { return ServiceManager.ServiceController; } }
public MetadataTypesConfig MetadataTypesConfig { get; set; }
public string WsdlServiceNamespace { get; set; }
public string WsdlSoapActionNamespace { get; set; }
private EndpointAttributes metadataVisibility;
public EndpointAttributes MetadataVisibility
{
get { return metadataVisibility; }
set { metadataVisibility = value.ToAllowedFlagsSet(); }
}
public string MetadataPageBodyHtml { get; set; }
public string MetadataOperationPageBodyHtml { get; set; }
public string MetadataCustomPath { get; set; }
public bool UseCustomMetadataTemplates { get; set; }
public string ServiceName { get; set; }
public string SoapServiceName { get; set; }
public string DefaultContentType { get; set; }
public bool AllowJsonpRequests { get; set; }
public bool AllowRouteContentTypeExtensions { get; set; }
public bool DebugMode { get; set; }
public bool DebugOnlyReturnRequestInfo { get; set; }
public string DebugAspNetHostEnvironment { get; set; }
public string DebugHttpListenerHostEnvironment { get; set; }
public List<string> DefaultDocuments { get; private set; }
public List<string> IgnoreWarningsOnPropertyNames { get; private set; }
public HashSet<string> IgnoreFormatsInMetadata { get; set; }
public HashSet<string> AllowFileExtensions { get; set; }
public string WebHostUrl { get; set; }
public string WebHostPhysicalPath { get; set; }
public string ServiceStackHandlerFactoryPath { get; set; }
public string DefaultRedirectPath { get; set; }
public string MetadataRedirectPath { get; set; }
public ServiceEndpointsMetadataConfig ServiceEndpointsMetadataConfig { get; set; }
public ILogFactory LogFactory { get; set; }
public bool EnableAccessRestrictions { get; set; }
public bool UseBclJsonSerializers { get; set; }
public Dictionary<string, string> GlobalResponseHeaders { get; set; }
public Feature EnableFeatures { get; set; }
public bool ReturnsInnerException { get; set; }
public bool WriteErrorsToResponse { get; set; }
public MarkdownOptions MarkdownOptions { get; set; }
public Type MarkdownBaseType { get; set; }
public Dictionary<string, Type> MarkdownGlobalHelpers { get; set; }
public Dictionary<string, string> HtmlReplaceTokens { get; set; }
public HashSet<string> AppendUtf8CharsetOnContentTypes { get; set; }
public Dictionary<string, TimeSpan> AddMaxAgeForStaticMimeTypes { get; set; }
public List<Func<IHttpRequest, IHttpHandler>> RawHttpHandlers { get; set; }
public List<RouteNamingConventionDelegate> RouteNamingConventions { get; set; }
public Dictionary<HttpStatusCode, IServiceStackHttpHandler> CustomHttpHandlers { get; set; }
public IServiceStackHttpHandler GlobalHtmlErrorHttpHandler { get; set; }
public Dictionary<Type, int> MapExceptionToStatusCode { get; set; }
public bool OnlySendSessionCookiesSecurely { get; set; }
public string RestrictAllCookiesToDomain { get; set; }
public TimeSpan DefaultJsonpCacheExpiration { get; set; }
public bool Return204NoContentForEmptyResponse { get; set; }
public bool AllowPartialResponses { get; set; }
public bool AllowNonHttpOnlyCookies { get; set; }
public bool AllowAclUrlReservation { get; set; }
public bool UseHttpsLinks { get; set; }
public string AdminAuthSecret { get; set; }
private string defaultOperationNamespace;
public string DefaultOperationNamespace
{
get
{
if (this.defaultOperationNamespace == null)
{
this.defaultOperationNamespace = GetDefaultNamespace();
}
return this.defaultOperationNamespace;
}
set
{
this.defaultOperationNamespace = value;
}
}
private string GetDefaultNamespace()
{
if (!String.IsNullOrEmpty(this.defaultOperationNamespace)
|| this.ServiceController == null) return null;
foreach (var operationType in this.Metadata.RequestTypes)
{
var attrs = operationType.GetCustomAttributes(
typeof(DataContractAttribute), false);
if (attrs.Length <= 0) continue;
var attr = (DataContractAttribute)attrs[0];
if (String.IsNullOrEmpty(attr.Namespace)) continue;
return attr.Namespace;
}
return null;
}
public bool HasFeature(Feature feature)
{
return (feature & EndpointHost.Config.EnableFeatures) == feature;
}
public void AssertFeatures(Feature usesFeatures)
{
if (EndpointHost.Config.EnableFeatures == Feature.All) return;
if (!HasFeature(usesFeatures))
{
throw new UnauthorizedAccessException(
String.Format("'{0}' Features have been disabled by your administrator", usesFeatures));
}
}
public UnauthorizedAccessException UnauthorizedAccess(EndpointAttributes requestAttrs)
{
return new UnauthorizedAccessException(
String.Format("Request with '{0}' is not allowed", requestAttrs));
}
public void AssertContentType(string contentType)
{
if (EndpointHost.Config.EnableFeatures == Feature.All) return;
AssertFeatures(contentType.ToFeature());
}
public MetadataPagesConfig MetadataPagesConfig
{
get
{
return new MetadataPagesConfig(
Metadata,
ServiceEndpointsMetadataConfig,
IgnoreFormatsInMetadata,
EndpointHost.ContentTypeFilter.ContentTypeFormats.Keys.ToList());
}
}
public bool HasAccessToMetadata(IHttpRequest httpReq, IHttpResponse httpRes)
{
if (!HasFeature(Feature.Metadata))
{
EndpointHost.Config.HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Metadata Not Available");
return false;
}
if (MetadataVisibility != EndpointAttributes.Any)
{
var actualAttributes = httpReq.GetAttributes();
if ((actualAttributes & MetadataVisibility) != MetadataVisibility)
{
HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Metadata Not Visible");
return false;
}
}
return true;
}
public void HandleErrorResponse(IHttpRequest httpReq, IHttpResponse httpRes, HttpStatusCode errorStatus, string errorStatusDescription = null)
{
if (httpRes.IsClosed) return;
httpRes.StatusDescription = errorStatusDescription;
var handler = GetHandlerForErrorStatus(errorStatus);
handler.ProcessRequest(httpReq, httpRes, httpReq.OperationName);
}
public IServiceStackHttpHandler GetHandlerForErrorStatus(HttpStatusCode errorStatus)
{
var httpHandler = GetCustomErrorHandler(errorStatus);
switch (errorStatus)
{
case HttpStatusCode.Forbidden:
return httpHandler ?? new ForbiddenHttpHandler();
case HttpStatusCode.NotFound:
return httpHandler ?? new NotFoundHttpHandler();
}
if (CustomHttpHandlers != null)
{
CustomHttpHandlers.TryGetValue(HttpStatusCode.NotFound, out httpHandler);
}
return httpHandler ?? new NotFoundHttpHandler();
}
public IServiceStackHttpHandler GetCustomErrorHandler(int errorStatusCode)
{
try
{
return GetCustomErrorHandler((HttpStatusCode)errorStatusCode);
}
catch
{
return null;
}
}
public IServiceStackHttpHandler GetCustomErrorHandler(HttpStatusCode errorStatus)
{
IServiceStackHttpHandler httpHandler = null;
if (CustomHttpHandlers != null)
{
CustomHttpHandlers.TryGetValue(errorStatus, out httpHandler);
}
return httpHandler ?? GlobalHtmlErrorHttpHandler;
}
public IHttpHandler GetCustomErrorHttpHandler(HttpStatusCode errorStatus)
{
var ssHandler = GetCustomErrorHandler(errorStatus);
if (ssHandler == null) return null;
var httpHandler = ssHandler as IHttpHandler;
return httpHandler ?? new ServiceStackHttpHandler(ssHandler);
}
public Action<object, IHttpRequest, IHttpResponse> PreExecuteServiceFilter { get; set; }
public Action<object, IHttpRequest, IHttpResponse> PostExecuteServiceFilter { get; set; }
public FallbackRestPathDelegate FallbackRestPath { get; set; }
public bool HasValidAuthSecret(IHttpRequest req)
{
if (AdminAuthSecret != null)
{
var authSecret = req.GetParam("authsecret");
return authSecret == EndpointHost.Config.AdminAuthSecret;
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
namespace QarnotSDK {
/// <summary>
/// Job states.
/// </summary>
public sealed class QJobStates {
/// <summary>
/// The Job is active and ready to receive tasks.
/// </summary>
public static readonly string Active = "Active";
/// <summary>
/// The job is being completed
/// </summary>
public static readonly string Terminating = "Terminating";
/// <summary>
/// The Job is completed. (we can't dispatch in it anymore)
/// </summary>
public static readonly string Completed = "Completed";
/// <summary>
/// The job is currently being deleted.
/// </summary>
public static readonly string Deleting = "Deleting";
}
/// <summary>
/// This class manages Jobs life cycle: logical group of tasks.
/// </summary>
public partial class QJob {
/// <summary>
/// Reference to the api connection.
/// </summary>
protected Connection _api;
/// <summary>
/// The job resource uri.
/// </summary>
protected string _uri = null;
internal JobApi _jobApi { get; set; }
/// <summary>
/// The inner Connection object.
/// </summary>
[InternalDataApiName(IsFilterable=false, IsSelectable=false)]
public virtual Connection Connection { get { return _api; } }
/// <summary>
/// The job unique identifier. The Uuid is generated by the Api when the job is created.
/// </summary>
[InternalDataApiName(Name="Uuid")]
public virtual Guid Uuid { get { return _jobApi.Uuid; } }
/// <summary>
/// The Job name
/// </summary>
[InternalDataApiName(Name="Name")]
public virtual string Name
{
get => _jobApi.Name;
set => _jobApi.Name = value;
}
/// <summary>
/// The Job unique shortname
/// </summary>
[InternalDataApiName(Name="Shortname")]
public virtual string Shortname
{
get => _jobApi.Shortname;
set => _jobApi.Shortname = value;
}
/// <summary>
/// The related pool uuid
/// </summary>
[InternalDataApiName(Name="PoolUuid")]
public virtual Guid PoolUuid { get => _jobApi.PoolUuid.IsNullOrEmpty() ? default(Guid) : new Guid(_jobApi.PoolUuid); }
/// <summary>
/// Retrieve the job state (see QJobStates).
/// Available only after the submission. Use UpdateStatus or UpdateStatusAsync to refresh.
/// </summary>
[InternalDataApiName(Name="State")]
public virtual string State { get { return _jobApi?.State; } }
/// <summary>
/// Retrieve the job previous state (see QJobStates).
/// Available only after the submission. Use UpdateStatus or UpdateStatusAsync to refresh.
/// </summary>
[InternalDataApiName(Name="PreviousState")]
public virtual string PreviousState { get { return _jobApi?.PreviousState; } }
/// <summary>
/// Retrieve the job state transition utc time (see QJobStates).
/// Available only after the submission. Use UpdateStatus or UpdateStatusAsync to refresh.
/// </summary>
[InternalDataApiName(Name = "StateTransitionTime")]
public virtual DateTime? StateTransitionTime
{
get
{
if (_jobApi != null)
{
if (_jobApi.StateTransitionTime != default)
{
return _jobApi.StateTransitionTime;
}
}
return null;
}
}
/// <summary>
/// Retrieve the job previous state transition utc time (see QJobStates).
/// Available only after the submission. Use UpdateStatus or UpdateStatusAsync to refresh.
/// </summary>
[InternalDataApiName(Name = "PreviousStateTransitionTime")]
public virtual DateTime? PreviousStateTransitionTime
{
get
{
if (_jobApi != null)
{
if (_jobApi.PreviousStateTransitionTime != default)
{
return _jobApi.PreviousStateTransitionTime;
}
}
return null;
}
}
/// <summary>
/// The Job creation date
/// </summary>
[InternalDataApiName(Name="CreationDate")]
public virtual DateTime CreationDate { get => _jobApi.CreationDate; }
/// <summary>
/// The Job last modified date
/// </summary>
[InternalDataApiName(Name="LastModified")]
public virtual DateTime? LastModified
{
get
{
if (_jobApi != null)
{
if (_jobApi.LastModified != default)
{
return _jobApi.LastModified;
}
}
return null;
}
}
/// <summary>
/// The custom job tag list.
/// </summary>
[InternalDataApiName(Name = "Tags")]
public virtual List<string> Tags
{
get
{
return _jobApi.Tags;
}
}
/// <summary>
/// Set the a list of tags for the job.
/// </summary>
/// <param name="tags">Job tags.</param>
public virtual void SetTags(params String[] tags)
{
_jobApi.Tags = tags.Distinct().ToList();
}
/// <summary>
/// Boolean to indicate if the job use dependency behaviour.
/// Need to be true to allow the use of dependencies for tasks in this job.
/// </summary>
[InternalDataApiName(Name="UseDependencies")]
public virtual bool UseDependencies
{
get => _jobApi.UseDependencies;
set => _jobApi.UseDependencies = value;
}
/// <summary>
/// Wall time limit for the job execution.
/// Once this this time duration exceeded, the whole job will terminate
/// and the tasks linked will be canceled
/// </summary>
[InternalDataApiName(Name="MaxWallTime", IsFilterable=false, IsSelectable=false)]
public virtual TimeSpan MaximumWallTime
{
get
{
if (_jobApi.MaxWallTime.HasValue)
return _jobApi.MaxWallTime.Value;
return default(TimeSpan);
}
set
{
_jobApi.MaxWallTime = value;
}
}
/// <summary>
/// AutoDeleteOnCompletion: Field allowing the automatic deletion of the job when in a final state.
/// Must be set before the submission.
/// </summary>
[InternalDataApiName(IsFilterable = false, IsSelectable = false)]
public bool AutoDeleteOnCompletion {
get {
return _jobApi.AutoDeleteOnCompletion;
}
set {
_jobApi.AutoDeleteOnCompletion = value;
}
}
/// <summary>
/// CompletionTimeToLive: Final State Duration before deletion of the job.
/// Must be set before the submission.
/// </summary>
[InternalDataApiName(IsFilterable = false, IsSelectable = false)]
public TimeSpan CompletionTimeToLive {
get {
return _jobApi.CompletionTimeToLive;
}
set {
_jobApi.CompletionTimeToLive = value;
}
}
/// <summary>
/// The pool the job is attached to null if the job is not attached to a pool.
/// </summary>
[InternalDataApiName(IsFilterable=false, IsSelectable=false)]
public virtual QPool Pool
{
get
{
if (_jobApi.PoolUuid.IsNullOrEmpty())
return null;
return new QPool(_api, new Guid(_jobApi.PoolUuid));
}
}
internal QJob(Connection qapi, JobApi jobApi)
{
_api = qapi;
_uri = "jobs/" + jobApi.Uuid.ToString();
_jobApi = jobApi;
}
/// <summary>
/// Create a new job.
/// </summary>
/// <param name="connection">The inner connection object.</param>
/// <param name="name">The job name.</param>
/// <param name="pool">The pool we want the job to be attached to.</param>
/// <param name="shortname">The pool unique shortname.</param>
/// <param name="UseTaskDependencies">Bool to allow use of dependencies for tasks in this job.</param>
public QJob(Connection connection, string name, QPool pool=null, string shortname=default(string), bool UseTaskDependencies=false)
: this (connection, new JobApi())
{
_jobApi.Name = name;
_jobApi.Shortname = shortname;
if (pool != null)
_jobApi.PoolUuid = pool.Uuid.ToString();
_jobApi.UseDependencies = UseTaskDependencies;
_uri = "jobs/" + _jobApi.Shortname;
}
/// <summary>
/// Create a job object given an existing Uuid.
/// </summary>
/// <param name="connection">The inner connection object.</param>
/// <param name="uuid">The Uuid of an already existing job.</param>
public QJob(Connection connection, Guid uuid) : this(connection, new JobApi())
{
_uri = "jobs/" + uuid.ToString();
_jobApi.Uuid = uuid;
}
/// <summary>
/// Submit this job.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task SubmitAsync(CancellationToken cancellationToken=default(CancellationToken))
{
if (_api.IsReadOnly) throw new Exception("Can't submit jobs, this connection is configured in read-only mode");
using (var response = await _api._client.PostAsJsonAsync<JobApi>("jobs", _jobApi, cancellationToken))
{
await Utils.LookForErrorAndThrowAsync(_api._client, response,cancellationToken);
var result = await response.Content.ReadAsAsync<JobApi>(cancellationToken);
await PostSubmitAsync(result, cancellationToken);
}
}
/// <summary>
/// Update this job.
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task UpdateStatusAsync(CancellationToken cancellationToken = default(CancellationToken)) {
using (var response = await _api._client.GetAsync(_uri, cancellationToken))
{
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
var result = await response.Content.ReadAsAsync<JobApi>(cancellationToken);
_jobApi = result;
}
}
/// <summary>
/// Terminate an active job. (will cancel all remaining tasks)
/// </summary>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task TerminateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (_api.IsReadOnly) throw new Exception("Can't terminate jobs, this connection is configured in read-only mode");
using (var response = await _api._client.PostAsync(_uri + "/terminate", null, cancellationToken))
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
}
/// <summary>
/// Delete the job. If the job is active, the job is terminated and deleted.
/// </summary>
/// <param name="force">Optional boolean to force inner tasks to be deleted.</param>
/// <param name="cancellationToken">Optional token to cancel the request.</param>
/// <returns></returns>
public virtual async Task DeleteAsync(bool force=false, CancellationToken cancellationToken = default(CancellationToken))
{
if (_api.IsReadOnly) throw new Exception("Can't delete jobs, this connection is configured in read-only mode");
var deleteUri = _uri;
if (force)
deleteUri += "?force=true";
using (var response = await _api._client.DeleteAsync(deleteUri, cancellationToken))
await Utils.LookForErrorAndThrowAsync(_api._client, response, cancellationToken);
}
#region internals
internal async Task PostSubmitAsync(JobApi result, CancellationToken cancellationToken = default(CancellationToken))
{
_jobApi.Uuid = result.Uuid;
_uri = "jobs/" + _jobApi.Uuid.ToString();
await UpdateStatusAsync(cancellationToken);
}
#endregion
}
}
| |
using System;
using ColossalFramework;
using ColossalFramework.Math;
using TrafficManager.Traffic;
using TrafficManager.TrafficLight;
using UnityEngine;
using Random = UnityEngine.Random;
namespace TrafficManager.CustomAI
{
internal class CustomCarAI : CarAI
{
private const int MaxTrailingVehicles = 16384;
private const float FarLod = 1210000f;
private const float CloseLod = 250000f;
public void TrafficManagerSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos)
{
try
{
FindPathIfNeeded(vehicleId, ref vehicleData);
}
catch (InvalidOperationException)
{
return;
}
SpawnVehicleIfWaiting(vehicleId, ref vehicleData);
SimulateVehicleChain(vehicleId, ref vehicleData, physicsLodRefPos);
DespawnVehicles(vehicleId, vehicleData);
}
private void SimulateVehicleChain(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos)
{
var lastFramePosition = vehicleData.GetLastFramePosition();
var lodPhysics = CalculateLod(physicsLodRefPos, lastFramePosition);
SimulationStep(vehicleId, ref vehicleData, vehicleId, ref vehicleData, lodPhysics);
if (vehicleData.m_leadingVehicle != 0 || vehicleData.m_trailingVehicle == 0)
return;
var vehicleManager = Singleton<VehicleManager>.instance;
var trailingVehicleId = vehicleData.m_trailingVehicle;
SimulateTrailingVehicles(vehicleId, ref vehicleData, lodPhysics, trailingVehicleId, vehicleManager,
0);
}
private void DespawnVehicles(ushort vehicleId, Vehicle vehicleData)
{
DespawnInvalidVehicles(vehicleId, vehicleData);
DespawnVehicleIfOverBlockMax(vehicleId, vehicleData);
}
private void DespawnInvalidVehicles(ushort vehicleId, Vehicle vehicleData)
{
if ((vehicleData.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace)) ==
Vehicle.Flags.None && vehicleData.m_cargoParent == 0)
{
Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleId);
}
}
private void DespawnVehicleIfOverBlockMax(ushort vehicleId, Vehicle vehicleData)
{
var maxBlockingVehicles = CalculateMaxBlockingVehicleCount();
if (vehicleData.m_blockCounter >= maxBlockingVehicles && LoadingExtension.Instance.DespawnEnabled)
{
Singleton<VehicleManager>.instance.ReleaseVehicle(vehicleId);
}
}
private int CalculateMaxBlockingVehicleCount()
{
return (m_info.m_class.m_service > ItemClass.Service.Office) ? 150 : 100;
}
private void SimulateTrailingVehicles(ushort vehicleId, ref Vehicle vehicleData, int lodPhysics,
ushort leadingVehicleId, VehicleManager vehicleManager, int numberOfIterations)
{
if (leadingVehicleId == 0)
{
return;
}
var trailingVehicleId = vehicleManager.m_vehicles.m_buffer[leadingVehicleId].m_trailingVehicle;
var trailingVehicleInfo = vehicleManager.m_vehicles.m_buffer[trailingVehicleId].Info;
trailingVehicleInfo.m_vehicleAI.SimulationStep(trailingVehicleId,
ref vehicleManager.m_vehicles.m_buffer[trailingVehicleId], vehicleId,
ref vehicleData, lodPhysics);
if (++numberOfIterations > MaxTrailingVehicles)
{
CODebugBase<LogChannel>.Error(LogChannel.Core,
"Invalid list detected!\n" + Environment.StackTrace);
return;
}
SimulateTrailingVehicles(trailingVehicleId, ref vehicleData, lodPhysics, trailingVehicleId, vehicleManager,
numberOfIterations);
}
private static int CalculateLod(Vector3 physicsLodRefPos, Vector3 lastFramePosition)
{
int lodPhysics;
if (Vector3.SqrMagnitude(physicsLodRefPos - lastFramePosition) >= FarLod)
{
lodPhysics = 2;
}
else if (Vector3.SqrMagnitude(Singleton<SimulationManager>.
instance.m_simulationView.m_position - lastFramePosition) >= CloseLod)
{
lodPhysics = 1;
}
else
{
lodPhysics = 0;
}
return lodPhysics;
}
private void SpawnVehicleIfWaiting(ushort vehicleId, ref Vehicle vehicleData)
{
if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != Vehicle.Flags.None)
{
TrySpawn(vehicleId, ref vehicleData);
}
}
private void FindPathIfNeeded(ushort vehicleId, ref Vehicle vehicleData)
{
if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) == Vehicle.Flags.None) return;
if (!CanFindPath(vehicleId, ref vehicleData))
throw new InvalidOperationException("Path Not Available for Vehicle");
}
private bool CanFindPath(ushort vehicleId, ref Vehicle data)
{
var pathManager = Singleton<PathManager>.instance;
var pathFindFlags = pathManager.m_pathUnits.m_buffer[(int) ((UIntPtr) data.m_path)].m_pathFindFlags;
if ((pathFindFlags & 4) != 0)
{
data.m_pathPositionIndex = 255;
data.m_flags &= ~Vehicle.Flags.WaitingPath;
data.m_flags &= ~Vehicle.Flags.Arriving;
PathfindSuccess(vehicleId, ref data);
TrySpawn(vehicleId, ref data);
}
else if ((pathFindFlags & 8) != 0)
{
data.m_flags &= ~Vehicle.Flags.WaitingPath;
Singleton<PathManager>.instance.ReleasePath(data.m_path);
data.m_path = 0u;
PathfindFailure(vehicleId, ref data);
return false;
}
return true;
}
public void TmCalculateSegmentPosition(ushort vehicleId, ref Vehicle vehicleData, PathUnit.Position nextPosition,
PathUnit.Position position, uint laneId, byte offset, PathUnit.Position prevPos, uint prevLaneId,
byte prevOffset, out Vector3 pos, out Vector3 dir, out float maxSpeed)
{
var netManager = Singleton<NetManager>.instance;
netManager.m_lanes.m_buffer[(int)((UIntPtr) laneId)]
.CalculatePositionAndDirection(offset*0.003921569f, out pos, out dir);
var lastFrameData = vehicleData.GetLastFrameData();
var vehiclePositionLastFrame = lastFrameData.m_position;
// I think this is supposed to be the lane position?
var lanePosition = netManager.m_lanes.m_buffer[(int) ((UIntPtr) prevLaneId)]
.CalculatePosition(prevOffset*0.003921569f);
var num = 0.5f*lastFrameData.m_velocity.sqrMagnitude/m_info.m_braking + m_info.m_generatedInfo.m_size.z*0.5f;
if (vehicleData.Info.m_vehicleType == VehicleInfo.VehicleType.Car)
{
if (!TrafficPriority.VehicleList.ContainsKey(vehicleId))
{
TrafficPriority.VehicleList.Add(vehicleId, new PriorityCar());
}
}
if (Vector3.Distance(vehiclePositionLastFrame, lanePosition) >= num - 1f)
{
ushort destinationNode;
ushort nodeId3;
if (offset < position.m_offset)
{
destinationNode = netManager.m_segments.m_buffer[position.m_segment].m_startNode;
nodeId3 = netManager.m_segments.m_buffer[position.m_segment].m_endNode;
}
else
{
destinationNode = netManager.m_segments.m_buffer[position.m_segment].m_endNode;
nodeId3 = netManager.m_segments.m_buffer[position.m_segment].m_startNode;
}
var nodeId4 = prevOffset == 0 ? netManager.m_segments.m_buffer[prevPos.m_segment].m_startNode :
netManager.m_segments.m_buffer[prevPos.m_segment].m_endNode;
if (destinationNode == nodeId4)
{
var currentFrameIndex = Singleton<SimulationManager>.instance.m_currentFrameIndex;
var num5 = (uint) ((nodeId4 << 8)/32768);
var num6 = currentFrameIndex - num5 & 255u;
var flags = netManager.m_nodes.m_buffer[destinationNode].m_flags;
var flags2 =
(NetLane.Flags) netManager.m_lanes.m_buffer[(int) ((UIntPtr) prevLaneId)].m_flags;
var flag = (flags & NetNode.Flags.TrafficLights) != NetNode.Flags.None;
var flag2 = (flags & NetNode.Flags.LevelCrossing) != NetNode.Flags.None;
var flag3 = (flags2 & NetLane.Flags.JoinedJunction) != NetLane.Flags.None;
if ((flags & (NetNode.Flags.Junction | NetNode.Flags.OneWayOut | NetNode.Flags.OneWayIn)) ==
NetNode.Flags.Junction && netManager.m_nodes.m_buffer[destinationNode].CountSegments() != 2)
{
var len = vehicleData.CalculateTotalLength(vehicleId) + 2f;
if (!netManager.m_lanes.m_buffer[(int) ((UIntPtr) laneId)].CheckSpace(len))
{
var flag4 = false;
if (nextPosition.m_segment != 0 &&
netManager.m_lanes.m_buffer[(int) ((UIntPtr) laneId)].m_length < 30f)
{
var flags3 = netManager.m_nodes.m_buffer[nodeId3].m_flags;
if ((flags3 &
(NetNode.Flags.Junction | NetNode.Flags.OneWayOut | NetNode.Flags.OneWayIn)) !=
NetNode.Flags.Junction || netManager.m_nodes.m_buffer[nodeId3].CountSegments() == 2)
{
var laneId2 = PathManager.GetLaneID(nextPosition);
if (laneId2 != 0u)
{
flag4 = netManager.m_lanes.m_buffer[(int) ((UIntPtr) laneId2)].CheckSpace(len);
}
}
}
if (!flag4)
{
maxSpeed = 0f;
return;
}
}
}
if (vehicleData.Info.m_vehicleType == VehicleInfo.VehicleType.Car &&
TrafficPriority.VehicleList.ContainsKey(vehicleId) &&
TrafficPriority.IsPrioritySegment(destinationNode, prevPos.m_segment))
{
var currentFrameIndex2 = Singleton<SimulationManager>.instance.m_currentFrameIndex;
var frame = currentFrameIndex2 >> 4;
var prioritySegment = TrafficPriority.GetPrioritySegment(destinationNode, prevPos.m_segment);
if (TrafficPriority.VehicleList[vehicleId].ToNode != destinationNode ||
TrafficPriority.VehicleList[vehicleId].FromSegment != prevPos.m_segment)
{
if (TrafficPriority.VehicleList[vehicleId].ToNode != 0 &&
TrafficPriority.VehicleList[vehicleId].FromSegment != 0)
{
var oldNode = TrafficPriority.VehicleList[vehicleId].ToNode;
var oldSegment = TrafficPriority.VehicleList[vehicleId].FromSegment;
if (TrafficPriority.IsPrioritySegment(oldNode, oldSegment))
{
var oldPrioritySegment = TrafficPriority.GetPrioritySegment(oldNode, oldSegment);
TrafficPriority.VehicleList[vehicleId].WaitTime = 0;
TrafficPriority.VehicleList[vehicleId].Stopped = false;
oldPrioritySegment.RemoveCar(vehicleId);
}
}
// prevPos - current segment
// position - next segment
TrafficPriority.VehicleList[vehicleId].ToNode = destinationNode;
TrafficPriority.VehicleList[vehicleId].FromSegment = prevPos.m_segment;
TrafficPriority.VehicleList[vehicleId].ToSegment = position.m_segment;
TrafficPriority.VehicleList[vehicleId].ToLaneId = PathManager.GetLaneID(position);
TrafficPriority.VehicleList[vehicleId].FromLaneId = PathManager.GetLaneID(prevPos);
TrafficPriority.VehicleList[vehicleId].FromLaneFlags =
netManager.m_lanes.m_buffer[PathManager.GetLaneID(prevPos)].m_flags;
TrafficPriority.VehicleList[vehicleId].ReduceSpeedByValueToYield = Random.Range(13f,
18f);
prioritySegment.AddCar(vehicleId);
}
TrafficPriority.VehicleList[vehicleId].LastFrame = frame;
TrafficPriority.VehicleList[vehicleId].LastSpeed =
vehicleData.GetLastFrameData().m_velocity.sqrMagnitude;
}
if (flag && (!flag3 || flag2))
{
var nodeSimulation = CustomRoadAI.GetNodeSimulation(nodeId4);
var destinationInfo = netManager.m_nodes.m_buffer[destinationNode].Info;
RoadBaseAI.TrafficLightState vehicleLightState;
if (nodeSimulation == null ||
(nodeSimulation.FlagTimedTrafficLights && !nodeSimulation.TimedTrafficLightsActive))
{
RoadBaseAI.TrafficLightState pedestrianLightState;
bool flag5;
bool pedestrians;
RoadBaseAI.GetTrafficLightState(nodeId4,
ref netManager.m_segments.m_buffer[prevPos.m_segment],
currentFrameIndex - num5, out vehicleLightState, out pedestrianLightState, out flag5,
out pedestrians);
if (!flag5 && num6 >= 196u)
{
flag5 = true;
RoadBaseAI.SetTrafficLightState(nodeId4,
ref netManager.m_segments.m_buffer[prevPos.m_segment], currentFrameIndex - num5,
vehicleLightState, pedestrianLightState, flag5, pedestrians);
}
if ((vehicleData.m_flags & Vehicle.Flags.Emergency2) == Vehicle.Flags.None ||
destinationInfo.m_class.m_service != ItemClass.Service.Road)
{
switch (vehicleLightState)
{
case RoadBaseAI.TrafficLightState.RedToGreen:
if (num6 < 60u)
{
maxSpeed = 0f;
return;
}
break;
case RoadBaseAI.TrafficLightState.Red:
maxSpeed = 0f;
return;
case RoadBaseAI.TrafficLightState.GreenToRed:
if (num6 >= 30u)
{
maxSpeed = 0f;
return;
}
break;
}
}
}
else
{
var stopCar = false;
if (TrafficPriority.IsLeftSegment(prevPos.m_segment, position.m_segment, destinationNode))
{
vehicleLightState =
TrafficLightsManual.GetSegmentLight(nodeId4, prevPos.m_segment).GetLightLeft();
}
else if (TrafficPriority.IsRightSegment(prevPos.m_segment, position.m_segment, destinationNode))
{
vehicleLightState =
TrafficLightsManual.GetSegmentLight(nodeId4, prevPos.m_segment).GetLightRight();
}
else
{
vehicleLightState =
TrafficLightsManual.GetSegmentLight(nodeId4, prevPos.m_segment).GetLightMain();
}
if (vehicleLightState == RoadBaseAI.TrafficLightState.Green)
{
var hasIncomingCars = TrafficPriority.HasIncomingVehicles(vehicleId, destinationNode);
if (hasIncomingCars)
{
stopCar = true;
}
}
if ((vehicleData.m_flags & Vehicle.Flags.Emergency2) == Vehicle.Flags.None ||
destinationInfo.m_class.m_service != ItemClass.Service.Road)
{
switch (vehicleLightState)
{
case RoadBaseAI.TrafficLightState.RedToGreen:
if (num6 < 60u)
{
stopCar = true;
}
break;
case RoadBaseAI.TrafficLightState.Red:
stopCar = true;
break;
case RoadBaseAI.TrafficLightState.GreenToRed:
if (num6 >= 30u)
{
stopCar = true;
}
break;
}
}
if (stopCar)
{
maxSpeed = 0f;
return;
}
}
}
else
{
if (vehicleData.Info.m_vehicleType == VehicleInfo.VehicleType.Car &&
TrafficPriority.VehicleList.ContainsKey(vehicleId) &&
TrafficPriority.IsPrioritySegment(destinationNode, prevPos.m_segment))
{
var currentFrameIndex2 = Singleton<SimulationManager>.instance.m_currentFrameIndex;
var frame = currentFrameIndex2 >> 4;
var prioritySegment = TrafficPriority.GetPrioritySegment(destinationNode, prevPos.m_segment);
if (TrafficPriority.VehicleList[vehicleId].CarState == CarState.None)
{
TrafficPriority.VehicleList[vehicleId].CarState = CarState.Enter;
}
if ((vehicleData.m_flags & Vehicle.Flags.Emergency2) == Vehicle.Flags.None &&
TrafficPriority.VehicleList[vehicleId].CarState != CarState.Leave)
{
bool hasIncomingCars;
switch (prioritySegment.Type)
{
case PrioritySegment.PriorityType.Stop:
if (TrafficPriority.VehicleList[vehicleId].WaitTime < 75)
{
TrafficPriority.VehicleList[vehicleId].CarState = CarState.Stop;
if (vehicleData.GetLastFrameData().m_velocity.sqrMagnitude < 0.1f ||
TrafficPriority.VehicleList[vehicleId].Stopped)
{
TrafficPriority.VehicleList[vehicleId].Stopped = true;
TrafficPriority.VehicleList[vehicleId].WaitTime++;
if (TrafficPriority.VehicleList[vehicleId].WaitTime > 2)
{
hasIncomingCars = TrafficPriority.HasIncomingVehicles(vehicleId, destinationNode);
if (hasIncomingCars)
{
maxSpeed = 0f;
return;
}
TrafficPriority.VehicleList[vehicleId].CarState =
CarState.Leave;
}
else
{
maxSpeed = 0f;
return;
}
}
else
{
maxSpeed = 0f;
return;
}
}
else
{
TrafficPriority.VehicleList[vehicleId].CarState = CarState.Leave;
}
break;
case PrioritySegment.PriorityType.Yield:
if (TrafficPriority.VehicleList[vehicleId].WaitTime < 75)
{
TrafficPriority.VehicleList[vehicleId].WaitTime++;
TrafficPriority.VehicleList[vehicleId].CarState = CarState.Stop;
maxSpeed = 0f;
if (vehicleData.GetLastFrameData().m_velocity.sqrMagnitude <
TrafficPriority.VehicleList[vehicleId].ReduceSpeedByValueToYield)
{
hasIncomingCars = TrafficPriority.HasIncomingVehicles(vehicleId, destinationNode);
if (hasIncomingCars)
{
return;
}
}
else
{
maxSpeed = vehicleData.GetLastFrameData().m_velocity.sqrMagnitude -
TrafficPriority.VehicleList[vehicleId]
.ReduceSpeedByValueToYield;
return;
}
}
else
{
TrafficPriority.VehicleList[vehicleId].CarState = CarState.Leave;
}
break;
case PrioritySegment.PriorityType.Main:
TrafficPriority.VehicleList[vehicleId].WaitTime++;
TrafficPriority.VehicleList[vehicleId].CarState = CarState.Stop;
maxSpeed = 0f;
hasIncomingCars = TrafficPriority.HasIncomingVehicles(vehicleId, destinationNode);
if (hasIncomingCars)
{
TrafficPriority.VehicleList[vehicleId].Stopped = true;
return;
}
TrafficPriority.VehicleList[vehicleId].Stopped = false;
var info3 = netManager.m_segments.m_buffer[position.m_segment].Info;
if (info3.m_lanes != null && info3.m_lanes.Length > position.m_lane)
{
maxSpeed =
CalculateTargetSpeed(vehicleId, ref vehicleData,
info3.m_lanes[position.m_lane].m_speedLimit,
netManager.m_lanes.m_buffer[(int) ((UIntPtr) laneId)].m_curve)*0.8f;
}
else
{
maxSpeed = CalculateTargetSpeed(vehicleId, ref vehicleData, 1f, 0f)*
0.8f;
}
return;
}
}
else
{
TrafficPriority.VehicleList[vehicleId].CarState = CarState.Transit;
}
}
}
}
}
var info2 = netManager.m_segments.m_buffer[position.m_segment].Info;
if (info2.m_lanes != null && info2.m_lanes.Length > position.m_lane)
{
var laneSpeedLimit = info2.m_lanes[position.m_lane].m_speedLimit;
if (TrafficRoadRestrictions.IsSegment(position.m_segment))
{
var restrictionSegment = TrafficRoadRestrictions.GetSegment(position.m_segment);
if (restrictionSegment.SpeedLimits[position.m_lane] > 0.1f)
{
laneSpeedLimit = restrictionSegment.SpeedLimits[position.m_lane];
}
}
maxSpeed = CalculateTargetSpeed(vehicleId, ref vehicleData, laneSpeedLimit,
netManager.m_lanes.m_buffer[(int) ((UIntPtr) laneId)].m_curve);
}
else
{
maxSpeed = CalculateTargetSpeed(vehicleId, ref vehicleData, 1f, 0f);
}
}
public void TmCalculateSegmentPositionPathFinder(ushort vehicleId, ref Vehicle vehicleData,
PathUnit.Position position, uint laneId, byte offset, out Vector3 pos, out Vector3 dir, out float maxSpeed)
{
var instance = Singleton<NetManager>.instance;
instance.m_lanes.m_buffer[(int) ((UIntPtr) laneId)].CalculatePositionAndDirection(offset*0.003921569f,
out pos, out dir);
var info = instance.m_segments.m_buffer[position.m_segment].Info;
if (info.m_lanes != null && info.m_lanes.Length > position.m_lane)
{
var laneSpeedLimit = info.m_lanes[position.m_lane].m_speedLimit;
if (TrafficRoadRestrictions.IsSegment(position.m_segment))
{
var restrictionSegment = TrafficRoadRestrictions.GetSegment(position.m_segment);
if (restrictionSegment.SpeedLimits[position.m_lane] > 0.1f)
{
laneSpeedLimit = restrictionSegment.SpeedLimits[position.m_lane];
}
}
maxSpeed = CalculateTargetSpeed(vehicleId, ref vehicleData, laneSpeedLimit,
instance.m_lanes.m_buffer[(int) ((UIntPtr) laneId)].m_curve);
}
else
{
maxSpeed = CalculateTargetSpeed(vehicleId, ref vehicleData, 1f, 0f);
}
}
protected override bool StartPathFind(ushort vehicleId, ref Vehicle vehicleData, Vector3 startPos,
Vector3 endPos, bool startBothWays, bool endBothWays)
{
var info = m_info;
var allowUnderground = (vehicleData.m_flags & (Vehicle.Flags.Underground | Vehicle.Flags.Transition)) !=
Vehicle.Flags.None;
PathUnit.Position startPosA;
PathUnit.Position startPosB;
float num;
float num2;
PathUnit.Position endPosA;
PathUnit.Position endPosB;
float num3;
float num4;
const bool requireConnect = false;
const float maxDistance = 32f;
if (!PathManager.FindPathPosition(startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle,
info.m_vehicleType, allowUnderground, requireConnect, maxDistance, out startPosA, out startPosB,
out num, out num2) ||
!PathManager.FindPathPosition(endPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle,
info.m_vehicleType, false, requireConnect, 32f, out endPosA, out endPosB, out num3, out num4))
return false;
if (!startBothWays || num < 10f)
{
startPosB = default(PathUnit.Position);
}
if (!endBothWays || num3 < 10f)
{
endPosB = default(PathUnit.Position);
}
uint path;
if (!Singleton<CustomPathManager>.instance.CreatePath(out path,
ref Singleton<SimulationManager>.instance.m_randomizer,
Singleton<SimulationManager>.instance.m_currentBuildIndex, startPosA, startPosB, endPosA, endPosB,
default(PathUnit.Position), NetInfo.LaneType.Vehicle, info.m_vehicleType, 20000f, IsHeavyVehicle(),
IgnoreBlocked(vehicleId, ref vehicleData), false, false, vehicleData.Info.m_class.m_service))
return false;
if (vehicleData.m_path != 0u)
{
Singleton<CustomPathManager>.instance.ReleasePath(vehicleData.m_path);
}
vehicleData.m_path = path;
vehicleData.m_flags |= Vehicle.Flags.WaitingPath;
return true;
}
}
}
| |
using UnityEngine;
using System.Collections;
using XInputDotNetPure;
public class Attacks : MonoBehaviour
{
public AudioClip swordSwipeSound;
public AudioClip swordClashSound;
public AudioClip blockSound;
private AudioSource source;
private Character thisCharacter;
private string thisCharacterTag;
private Character thisOpponent;
public float quickAttackDamage = 5f;
public float heavyAttackDamage = 10f;
public float powerMoveSpeed = 10f;
public float reducedAttackDamage = 2f;
public float volume = 5f;
private float heavyCost = .1f;
private float powerCost = 0.5f;
private Animator animator;
private Animator opponent_animator;
private int collision_trigger = 0;
// Use this for initialization
private Vector3 desiredVelocity;
private float lastSqrMag;
bool canPowerMove = true;
bool isPowerMoving = false;
Rigidbody rb;
PlayerIndex playerIndex = (PlayerIndex)0;
PlayerIndex player2Index = (PlayerIndex)1;
GamePadState controller1State;
GamePadState controller2State;
float temp = 0;
void Start ()
{
source = GetComponent<AudioSource> ();
//inRange = false;
thisCharacterTag = transform.root.tag;
thisCharacter = GameObject.FindGameObjectWithTag (thisCharacterTag).GetComponent<Character> ();
if (gameObject.tag == "Player")
thisOpponent = GameObject.FindGameObjectWithTag ("Player2").GetComponent<Character> ();
else
thisOpponent = GameObject.FindGameObjectWithTag ("Player").GetComponent<Character> ();
animator = GameObject.FindGameObjectWithTag (thisCharacterTag).GetComponent<Animator> ();
//opponent_animator = GameObject.FindGameObjectWithTag ("Player").GetComponent<Animator> ();
rb = GameObject.FindGameObjectWithTag (thisCharacterTag).GetComponent<Rigidbody> ();
thisCharacter.resetCurrentAttack ();
}
// Update is called once per frame
void Update ()
{
if (animator.GetCurrentAnimatorStateInfo(0).IsName("PipeBlade|Taunt")||
animator.GetCurrentAnimatorStateInfo(0).IsName("SkyBlade|Taunt")||
animator.GetAnimatorTransitionInfo (0).IsName ("SkyBlade|Taunt -> SkyBlade|IdleAtSide"))
{
GetComponent<Collider>().enabled = false;
GetComponent<Collider>().enabled = false;
GameObject.Find ("Flame").GetComponent<Collider>().enabled = false;
}
else
{
GetComponent<Collider>().enabled = true;
GameObject.Find ("Flame").GetComponent<Collider>().enabled = true;
}
controller1State = GamePad.GetState (playerIndex);
controller2State = GamePad.GetState (player2Index);
#region checkMoving
float sqrMag = (thisCharacter.getOpponentTransform ().position - transform.position).sqrMagnitude;
if (sqrMag > lastSqrMag) {
// rigidbody has reached target and is now moving past it
// stop the rigidbody by setting the velocity to zero
desiredVelocity = Vector3.zero;
}
// make sure you update the lastSqrMag
lastSqrMag = sqrMag;
#endregion
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavyEndF")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|AerialHeavyEndF")){
animator.SetBool("Aerial", false);
}
if (thisCharacterTag == "Player") {
#region player1
if (controller1State.Triggers.Right > 0) {
if (thisCharacter.CharPowerBar > heavyCost)
{
thisCharacter.CharPowerBar -= heavyCost;
performHeavyAttack();
}
}
// Perform quick
else if (controller1State.Buttons.X == ButtonState.Pressed) {
performQuickAttack ();
} else if (controller1State.Buttons.X == ButtonState.Released) {
//curAttack = AttackType.Empty;
animator.SetBool ("Chain", false);
}
if (controller1State.Triggers.Left > 0) {
if (thisCharacter.getCharPowerBar () >= 1 && canPowerMove) {
// (Time.deltaTime/3+0.01f)
canPowerMove = false;
thisCharacter.setCharPowerBar (0);
performPowerMove ();
// isPowerMoving = true;
}
}
if (controller1State.Triggers.Left == 0)
{
if (isPowerMoving) {
rb.velocity = Vector3.zero;
}
temp = 0;
isPowerMoving = false;
canPowerMove = true;
}
}
#endregion
if (thisCharacterTag == "Player2") {
#region player2
if (controller2State.Triggers.Right > 0)
{
if (thisCharacter.CharPowerBar > heavyCost)
{
thisCharacter.CharPowerBar -= heavyCost;
performHeavyAttack();
}
} else if (controller2State.Buttons.X == ButtonState.Pressed) {
performQuickAttack ();
} else if (controller2State.Buttons.X == ButtonState.Released) {
//curAttack = AttackType.Empty;
animator.SetBool ("Chain", false);
}
if (controller2State.Triggers.Left > 0) {
if (thisCharacter.getCharPowerBar () >= powerCost && canPowerMove) {
// (Time.deltaTime/3+0.01f)
canPowerMove = false;
thisCharacter.CharPowerBar -= powerCost;
performPowerMove ();
// isPowerMoving = true;
}
}
if (controller2State.Triggers.Left == 0)
{
if (isPowerMoving) {
rb.velocity = Vector3.zero;
}
temp = 0;
isPowerMoving = false;
canPowerMove = true;
}
if(animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|Heavy")){
animator.SetBool("Heavy", false);
}
}
#endregion
//Animation Attack Assignment
if(animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickBack") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickForward") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickSecond") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickOverShoulder") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickFromSide") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickBack") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DashForward"))
{
thisCharacter.setCurrentAttack (Character.AttackType.Quick);
}
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|Heavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|AerialHeavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|AerialHeavyEndF") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|Heavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavyEndF") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavy"))
{
thisCharacter.setCurrentAttack (Character.AttackType.Heavy);
}
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DamageHeavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|DamageHeavy")) {
animator.SetBool ("Damaged", false);
}
if (!(animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|Heavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickBack") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickBack") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickForward") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|DamageHeavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|Heavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickOverShoulder") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickFromSide") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|AerialHeavy") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DamageHeavy")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DashForward")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DashBack")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|DashBack")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|DashForward")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavy")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavyEndF"))) {
animator.applyRootMotion = false;
}
if (thisCharacterTag == ("Player") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|Heavy") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavyEndF") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavy") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickOverShoulder") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickBack") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DashForward")&&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickFromSide")) {
thisCharacter.resetCurrentAttack ();
}
if (thisCharacterTag == ("Player2") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|Heavy") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|AerialHeavy") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickBack") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickSecond") &&
!animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickForward")) {
thisCharacter.resetCurrentAttack ();
}
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickBack")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickBack")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|Heavy")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DashForward")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DashBack")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|DashBack")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|DashForward")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|DamageHeavy")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DamageHeavy")) {
animator.applyRootMotion = true;
}
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickFromSide") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickOverShoulder") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickForward") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickBack")) {
animator.SetBool ("Attacking", false);
if (animator.GetCurrentAnimatorStateInfo (0).normalizedTime >= 0f &&
animator.GetCurrentAnimatorStateInfo (0).normalizedTime <= 0.1f) {
animator.SetBool ("Chain", false);
}
}
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|Heavy")) {
animator.SetBool ("Heavy", false);
}
// Run Animations
if (thisCharacter.moveDirection != Vector3.zero) {
animator.SetBool ("Running", true);
}
if (thisCharacter.moveDirection == Vector3.zero) {
animator.SetBool ("Running", false);
}
// Jump Animations
if (thisCharacter.isJumping) {
animator.SetBool ("Jumping", true);
}
if (thisCharacter.isJumping == false) {
animator.SetBool ("Jumping", false);
}
}
void OnCollisionEnter (Collision other)
{
if ((animator.GetCurrentAnimatorStateInfo(0).IsName("SkyBlade|AerialHeavy")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|AerialHeavy"))&&
(thisCharacter.CharPowerBar > heavyCost)){
animator.SetBool("Aerial", true);
thisCharacter.CharPowerBar -= heavyCost;
}
if ((other.collider.tag == "Weapon")) {
source.PlayOneShot (swordClashSound, volume);
thisCharacter.setWeaponHitToTrue ();
}
}
void OnCollisionExit (Collision other)
{
if (other.collider.tag == "Weapon") {
thisCharacter.setWeaponHitToFalse ();
}
}
private void performHeavyAttack ()
{
thisCharacter.setCurrentAttack (Character.AttackType.Heavy);
animator.applyRootMotion = true;
animator.SetBool ("Heavy", true);
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|Heavy")) {
animator.applyRootMotion = true;
source.PlayOneShot (swordSwipeSound, volume);
}
}
private void performQuickAttack ()
{
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavy")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|AerialHeavyEndF")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|AerialHeavyEndF")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickBack")){
animator.applyRootMotion = true;
}
thisCharacter.setCurrentAttack (Character.AttackType.Quick);
animator.SetBool ("Attacking", true);
if (animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickFromSide") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|QuickOverShoulder") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("SkyBlade|DashForward") ||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickBack")||
animator.GetCurrentAnimatorStateInfo (0).IsName ("PipeBlade|QuickForward")) {
source.PlayOneShot (swordSwipeSound, volume);
animator.SetBool ("Chain", true);
animator.applyRootMotion = true;
}
}
private void performPowerMove ()
{
thisCharacter.startPowerParticle ();
thisCharacter.turnCharToFaceOpponent ();
thisCharacter.setCurrentAttack (Character.AttackType.Power);
Vector3 startPoint = transform.root.position;
Transform opp = thisCharacter.getOpponentTransform ();
Vector3 endPoint = opp.position+(opp.forward*5);
transform.root.position = endPoint;
//animator.SetBool ("Heavy", true);
// Vector3 dir = (endPoint - startPoint);
// rb.velocity = dir;
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// This provider is the data accessor for environment variables. It uses
/// the SessionStateProviderBase as the base class to produce a view on
/// session state data.
/// </summary>
[CmdletProvider(EnvironmentProvider.ProviderName, ProviderCapabilities.ShouldProcess)]
public sealed class EnvironmentProvider : SessionStateProviderBase
{
/// <summary>
/// Gets the name of the provider.
/// </summary>
public const string ProviderName = "Environment";
#region Constructor
/// <summary>
/// The constructor for the provider that exposes environment variables to the user
/// as drives.
/// </summary>
public EnvironmentProvider()
{
}
#endregion Constructor
#region DriveCmdletProvider overrides
/// <summary>
/// Initializes the alias drive.
/// </summary>
/// <returns>
/// An array of a single PSDriveInfo object representing the alias drive.
/// </returns>
protected override Collection<PSDriveInfo> InitializeDefaultDrives()
{
string description = SessionStateStrings.EnvironmentDriveDescription;
PSDriveInfo envDrive =
new PSDriveInfo(
DriveNames.EnvironmentDrive,
ProviderInfo,
string.Empty,
description,
null);
Collection<PSDriveInfo> drives = new Collection<PSDriveInfo>();
drives.Add(envDrive);
return drives;
}
#endregion DriveCmdletProvider overrides
#region protected members
/// <summary>
/// Gets a environment variable from session state.
/// </summary>
/// <param name="name">
/// The name of the environment variable to retrieve.
/// </param>
/// <returns>
/// A DictionaryEntry that represents the value of the environment variable.
/// </returns>
internal override object GetSessionStateItem(string name)
{
Dbg.Diagnostics.Assert(
!string.IsNullOrEmpty(name),
"The caller should verify this parameter");
object result = null;
string value = Environment.GetEnvironmentVariable(name);
if (value != null)
{
result = new DictionaryEntry(name, value);
}
return result;
}
/// <summary>
/// Sets the environment variable of the specified name to the specified value.
/// </summary>
/// <param name="name">
/// The name of the environment variable to set.
/// </param>
/// <param name="value">
/// The new value for the environment variable.
/// </param>
/// <param name="writeItem">
/// If true, the item that was set should be written to WriteItemObject.
/// </param>
internal override void SetSessionStateItem(string name, object value, bool writeItem)
{
Dbg.Diagnostics.Assert(
!string.IsNullOrEmpty(name),
"The caller should verify this parameter");
if (value == null)
{
Environment.SetEnvironmentVariable(name, null);
}
else
{
// First see if we got a DictionaryEntry which represents
// an item for this provider. If so, use the value from
// the dictionary entry.
if (value is DictionaryEntry)
{
value = ((DictionaryEntry)value).Value;
}
string stringValue = value as string;
if (stringValue == null)
{
// try using ETS to convert to a string.
PSObject wrappedObject = PSObject.AsPSObject(value);
stringValue = wrappedObject.ToString();
}
Environment.SetEnvironmentVariable(name, stringValue);
DictionaryEntry item = new DictionaryEntry(name, stringValue);
if (writeItem)
{
WriteItemObject(item, name, false);
}
}
}
/// <summary>
/// Removes the specified environment variable from session state.
/// </summary>
/// <param name="name">
/// The name of the environment variable to remove from session state.
/// </param>
internal override void RemoveSessionStateItem(string name)
{
Dbg.Diagnostics.Assert(
!string.IsNullOrEmpty(name),
"The caller should verify this parameter");
Environment.SetEnvironmentVariable(name, null);
}
/// <summary>
/// Gets a flattened view of the environment variables in session state.
/// </summary>
/// <returns>
/// An IDictionary representing the flattened view of the environment variables in
/// session state.
/// </returns>
internal override IDictionary GetSessionStateTable()
{
// Environment variables are case-sensitive on Unix and
// case-insensitive on Windows
#if UNIX
Dictionary<string, DictionaryEntry> providerTable =
new Dictionary<string, DictionaryEntry>(StringComparer.Ordinal);
#else
Dictionary<string, DictionaryEntry> providerTable =
new Dictionary<string, DictionaryEntry>(StringComparer.OrdinalIgnoreCase);
#endif
// The environment variables returns a dictionary of keys and values that are
// both strings. We want to return a dictionary with the key as a string and
// the value as the DictionaryEntry containing both the name and env variable
// value.
IDictionary environmentTable = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry entry in environmentTable)
{
if (!providerTable.TryAdd((string)entry.Key, entry))
{ // Windows only: duplicate key (variable name that differs only in case)
// NOTE: Even though this shouldn't happen, it can, e.g. when npm
// creates duplicate environment variables that differ only in case -
// see https://github.com/PowerShell/PowerShell/issues/6305.
// However, because retrieval *by name* later is invariably
// case-INsensitive, in effect only a *single* variable exists.
// We simply ask Environment.GetEnvironmentVariable() for the effective value
// and use that as the only entry, because for a given key 'foo' (and all its case variations),
// that is guaranteed to match what $env:FOO and [environment]::GetEnvironmentVariable('foo') return.
// (If, by contrast, we just used `entry` as-is every time a duplicate is encountered,
// it could - intermittently - represent a value *other* than the effective one.)
string effectiveValue = Environment.GetEnvironmentVariable((string)entry.Key);
if (((string)entry.Value).Equals(effectiveValue, StringComparison.Ordinal))
{ // We've found the effective definition.
// Note: We *recreate* the entry so that the specific name casing of the
// effective definition is also reflected. However, if the case variants
// define the same value, it is unspecified which name variant is reflected
// in Get-Item env: output; given the always case-insensitive nature of the retrieval,
// that shouldn't matter.
providerTable.Remove((string)entry.Key);
providerTable.Add((string)entry.Key, entry);
}
}
}
return providerTable;
}
/// <summary>
/// Gets the Value property of the DictionaryEntry item.
/// </summary>
/// <param name="item">
/// The item to get the value from.
/// </param>
/// <returns>
/// The value of the item.
/// </returns>
internal override object GetValueOfItem(object item)
{
Dbg.Diagnostics.Assert(
item != null,
"Caller should verify the item parameter");
object value = item;
if (item is DictionaryEntry)
{
value = ((DictionaryEntry)item).Value;
}
return value;
}
#endregion protected members
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Diagnostics;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.PythonTools.Debugger.DebugEngine {
// This class implements IDebugThread2 which represents a thread running in a program.
class AD7Thread : IDisposable, IDebugThread2, IDebugThread100 {
private readonly AD7Engine _engine;
private readonly PythonThread _debuggedThread;
private readonly uint _vsTid;
public AD7Thread(AD7Engine engine, PythonThread debuggedThread) {
_engine = engine;
_debuggedThread = debuggedThread;
_vsTid = engine.RegisterThreadId(debuggedThread.Id);
}
public void Dispose() {
_engine.UnregisterThreadId(_vsTid);
}
private string GetCurrentLocation(bool fIncludeModuleName) {
if (_debuggedThread.Frames != null && _debuggedThread.Frames.Count > 0) {
return _debuggedThread.Frames[0].FunctionName;
}
return Strings.DebugThreadUnknownLocation;
}
internal PythonThread GetDebuggedThread() {
return _debuggedThread;
}
private string Name {
get {
string result = _debuggedThread.Name;
// If our fake ID is actually different from the real ID, prepend real ID info to thread name so that user can see it somewhere.
if (_vsTid != _debuggedThread.Id) {
result = "[" + _debuggedThread.Id + "] " + result;
}
return result;
}
}
#region IDebugThread2 Members
// Determines whether the next statement can be set to the given stack frame and code context.
// We need to try the step to verify it accurately so we allow say ok here.
int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) {
return VSConstants.S_OK;
}
// Retrieves a list of the stack frames for this thread.
// We currently call into the process and get the frames. We might want to cache the frame info.
int IDebugThread2.EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 enumObject) {
var stackFrames = _debuggedThread.Frames;
if (stackFrames == null) {
enumObject = null;
return VSConstants.E_FAIL;
}
int numStackFrames = stackFrames.Count;
var frameInfoArray = new FRAMEINFO[numStackFrames];
for (int i = 0; i < numStackFrames; i++) {
AD7StackFrame frame = new AD7StackFrame(_engine, this, stackFrames[i]);
frame.SetFrameInfo(dwFieldSpec, out frameInfoArray[i]);
}
enumObject = new AD7FrameInfoEnum(frameInfoArray);
return VSConstants.S_OK;
}
// Get the name of the thread.
int IDebugThread2.GetName(out string threadName) {
threadName = Name;
return VSConstants.S_OK;
}
// Return the program that this thread belongs to.
int IDebugThread2.GetProgram(out IDebugProgram2 program) {
program = _engine;
return VSConstants.S_OK;
}
// Gets the system thread identifier.
int IDebugThread2.GetThreadId(out uint threadId) {
threadId = _vsTid;
return VSConstants.S_OK;
}
// Gets properties that describe a thread.
int IDebugThread2.GetThreadProperties(enum_THREADPROPERTY_FIELDS dwFields, THREADPROPERTIES[] propertiesArray) {
THREADPROPERTIES props = new THREADPROPERTIES();
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0) {
props.dwThreadId = _vsTid;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT) != 0) {
// sample debug engine doesn't support suspending threads
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0) {
props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_RUNNING;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_PRIORITY) != 0) {
props.bstrPriority = Strings.DebugThreadNormalPriority;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_PRIORITY;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0) {
props.bstrName = Name;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_LOCATION) != 0) {
props.bstrLocation = GetCurrentLocation(true);
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_LOCATION;
}
propertiesArray[0] = props;
return VSConstants.S_OK;
}
// Resume a thread.
// This is called when the user chooses "Unfreeze" from the threads window when a thread has previously been frozen.
int IDebugThread2.Resume(out uint suspendCount) {
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
internal const int E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = unchecked((int)0x80040105);
// Sets the next statement to the given stack frame and code context.
int IDebugThread2.SetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) {
var frame = (AD7StackFrame)stackFrame;
var context = (AD7MemoryAddress)codeContext;
if (TaskHelpers.RunSynchronouslyOnUIThread(ct => frame.StackFrame.SetLineNumber((int)context.LineNumber + 1, ct))) {
return VSConstants.S_OK;
} else if (frame.StackFrame.Thread.Process.StoppedForException) {
return E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION;
}
return VSConstants.E_FAIL;
}
// suspend a thread.
// This is called when the user chooses "Freeze" from the threads window
int IDebugThread2.Suspend(out uint suspendCount) {
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IDebugThread100 Members
int IDebugThread100.SetThreadDisplayName(string name) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadDisplayName(out string name) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM, which calls GetThreadProperties100()
name = "";
return VSConstants.E_NOTIMPL;
}
// Returns whether this thread can be used to do function/property evaluation.
int IDebugThread100.CanDoFuncEval() {
return VSConstants.S_FALSE;
}
int IDebugThread100.SetFlags(uint flags) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetFlags(out uint flags) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
flags = 0;
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadProperties100(uint dwFields, THREADPROPERTIES100[] props) {
// Invoke GetThreadProperties to get the VS7/8/9 properties
THREADPROPERTIES[] props90 = new THREADPROPERTIES[1];
enum_THREADPROPERTY_FIELDS dwFields90 = (enum_THREADPROPERTY_FIELDS)(dwFields & 0x3f);
int hRes = ((IDebugThread2)this).GetThreadProperties(dwFields90, props90);
props[0].bstrLocation = props90[0].bstrLocation;
props[0].bstrName = props90[0].bstrName;
props[0].bstrPriority = props90[0].bstrPriority;
props[0].dwFields = (uint)props90[0].dwFields;
props[0].dwSuspendCount = props90[0].dwSuspendCount;
props[0].dwThreadId = props90[0].dwThreadId;
props[0].dwThreadState = props90[0].dwThreadState;
// Populate the new fields
if (hRes == VSConstants.S_OK && dwFields != (uint)dwFields90) {
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME) != 0) {
// Thread display name is being requested
props[0].bstrDisplayName = Name;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME;
// Give this display name a higher priority than the default (0)
// so that it will actually be displayed
props[0].DisplayNamePriority = 10;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME_PRIORITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY) != 0) {
// Thread category is being requested
if (_debuggedThread.IsWorkerThread) {
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Worker;
} else {
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Main;
}
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID) != 0) {
// Thread category is being requested
props[0].dwThreadId = _vsTid;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY) != 0) {
// Thread cpu affinity is being requested
props[0].AffinityMask = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID) != 0) {
// Thread display name is being requested
props[0].priorityId = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID;
}
}
return hRes;
}
enum enum_THREADCATEGORY {
THREADCATEGORY_Worker = 0,
THREADCATEGORY_UI = (THREADCATEGORY_Worker + 1),
THREADCATEGORY_Main = (THREADCATEGORY_UI + 1),
THREADCATEGORY_RPC = (THREADCATEGORY_Main + 1),
THREADCATEGORY_Unknown = (THREADCATEGORY_RPC + 1)
}
#endregion
#region Uncalled interface methods
// These methods are not currently called by the Visual Studio debugger, so they don't need to be implemented
int IDebugThread2.GetLogicalThread(IDebugStackFrame2 stackFrame, out IDebugLogicalThread2 logicalThread) {
Debug.Fail("This function is not called by the debugger");
logicalThread = null;
return VSConstants.E_NOTIMPL;
}
int IDebugThread2.SetThreadName(string name) {
Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
using Microsoft.VisualBasic;
using System;
/// <summary>
/// Description of form/class/etc.
/// </summary>
public class solverAlgebraic
{
public enum Operations
{
Exponents = 1,
Parenthesis = 2,
Multiplication = 3,
Division = 3,
Addition = 4,
Subtraction = 4
}
/// <summary>
/// Enumerates Variable with live lookup, class:setting:parameter
/// customer has "Ethnic as String" parameter.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public string FillVariables(string expression)
{
string[] stringMediator = null;
string stringOutput = "";
string stringVariable = "";
bool booleanFirstEntry = false;
stringMediator = expression.Split((char)123);
//123={
foreach (string line in stringMediator) {
if (booleanFirstEntry == false) {
booleanFirstEntry = true;
if (!object.ReferenceEquals(line, ""))
stringOutput += line;
continue;
}
stringVariable = line.Split((char)125)[0];
//125=}
//58=:
// if (stringVariable.Split((char)58)[0].ToLower() == "customer") {
// gamecache.cacheCustomer.stringEthnic = stringVariable.Split((char)58)[2];
// gamecache.cacheCustomer.SettingRequest = stringVariable.Split((char)58)[1];
// stringOutput += gamecache.cacheCustomer.ReturnValue;
// } else if (stringVariable.Split((char)58)[0].ToLower() == "characterprofile") {
// gamecache.currentCharacter.InformationRequest = stringVariable.Split((char)58)[1];
// stringOutput += gamecache.currentCharacter.ReturnValue;
// } else if (stringVariable.Split((char)58)[0].ToLower() == "characterstatistics") {
// gamecache.currentCharacter.InformationRequest = stringVariable.Split((char)58)[1];
// stringOutput += gamecache.currentCharacter.ReturnValue;
// } else if (stringVariable.Split((char)58)[0].ToLower() == "playerprofile") {
// gamecache.currentCharacter.InformationRequest = stringVariable.Split((char)58)[1];
// stringOutput += gamecache.currentPlayer.ReturnValue;
// } else if (stringVariable.Split((char)58)[0].ToLower() == "playerstatistics") {
// gamecache.currentCharacter.InformationRequest = stringVariable.Split((char)58)[1];
// stringOutput += gamecache.currentPlayerStatistics.ReturnValue;
// }
stringOutput += line.Split((char)125)[1];
//Remainder with Operator's
}
return stringOutput;
}
/// <summary>
/// Evaluates a mathematical expression.
/// </summary>
/// <param name="expression">String; Mathematical expression to be evaluated.</param>
/// <returns>Double; Solution.</returns>
public double SimplifyAlgebraicExpression(string expression)
{
string result = expression.Replace(")(", ")*(");
char[] cArray = expression.ToCharArray();
Int32 oP = 0;
Int32 cP = 0;
string p = null;
//Part of the expression extracted to be solved.
string s = null;
//Solution
bool Bracket = false;
if (result.Contains("(")) {
char c = '\0';
//Fix any multiplication that may be without the operator. IE x(x), which is required to look like x*(x).
//Start at the first opening parenthesis
for (Int32 i = result.IndexOf("("); i <= (cArray.Length - 1); i++) {
if (cArray[i] == '(' && i - 1 >= 0) {
c = cArray[i - 1];
if (char.IsNumber(c)) {
result = result.Replace(c + "(", c + "*(");
}
}
//Continue to look for the first closing parenthesis.
if (cArray[i] == ')' && i + 1 <= cArray.Length - 1) {
c = cArray[i + 1];
if (char.IsNumber(c)) {
result = result.Replace(")" + c, ")*" + c);
}
}
}
//Loop through the expression until all parenthesis have been evaluated.
while (result.Contains("(")) {
cArray = result.ToCharArray();
//Start at the first opening parenthesis
for (Int32 i = result.IndexOf("("); i <= (cArray.Length - 1); i++) {
if (cArray[i] == '(') {
oP = i + 1;
//Remember the position of the opening parenthesis everytime one has been found.
}
//Continue to look for the first closing parenthesis.
if (cArray[i] == ')') {
cP = i;
//Remember the position.
break; // TODO: might not be correct. Was : Exit For
//Exit out of the for loop, we
}
}
p = result.Substring(oP, cP - oP);
//Extract the inner algebraic expression to be evaluated.
s = SimplifySubAlgebraicExpression(p).ToString();
//Make sure we're within range.
if (cP + 1 <= cArray.Length - 1) {
//Check if the sub algebraic expression as a whole has any exponents.
if (cArray[cP + 1] == '^') {
s = "[" + s + "]^";
//Add brackets around the solution, which will be handled when solving for exponents.
Bracket = true;
}
}
//Replace the sub expression including parenthesis with the solution to said sub expression.
if (Bracket) {
result = result.Replace("(" + p + ")^", s);
Bracket = false;
} else {
result = result.Replace("(" + p + ")", s);
}
cArray = result.ToCharArray();
//Update character array.
}
//Do it all over again till all parenthesis are gone.
}
//Finally solve for the last expression that may be, and return the solution.
return SimplifySubAlgebraicExpression(result);
}
/// <returns>Evaluates a sub expression - one that does not contain any parenthesis.</returns>
protected double SimplifySubAlgebraicExpression(string expression)
{
//The expression being passed cannot cotain any parenthesis.
if (!expression.Contains("(") | !expression.Contains(")")) {
string result = expression.Replace(" ", Constants.vbNullString);
char[] cArray = result.ToCharArray();
//Perform the order of operations.
//1) Solve exponents.
result = PerformOperation(result, Operations.Exponents);
//3) Solve all multiplication and division operations.
result = PerformOperation(result, Operations.Multiplication & Operations.Division);
//4) Solve all addition and subtraction operations.
result = PerformOperation(result, Operations.Addition & Operations.Subtraction);
return Convert.ToDouble(result);
//Return the final solution as a double.
} else {
System.Windows.Forms.MessageBox.Show("Expression cannot contain parenthesis.");
return 0;
}
}
/// <returns>Evaluates a particular operation(s) of an expression.</returns>
protected string PerformOperation(string expression, Operations Operation)
{
string result = expression.Replace(" ", Constants.vbNullString);
char[] cArray = result.ToCharArray();
switch (Operation) {
case Operations.Exponents:
if (result.Contains("^")) {
//Loop through the expression until all root have been evaluated.
while (result.Contains("^")) {
// Constant Exponent
string c = Constants.vbNullString;
string e = Constants.vbNullString;
double v = 0;
//Value.
bool Brackets = false;
//Obtain the constant.
if (cArray[(result.IndexOf("^") - 1)] == ']') {
for (Int32 i = (result.IndexOf("^") - 2); i >= 0; i += (-1)) {
if (cArray[i] == '[')
break; // TODO: might not be correct. Was : Exit For
c = cArray[i].ToString() + c;
}
Brackets = true;
} else {
for (Int32 i = (result.IndexOf("^") - 1); i >= 0; i += (-1)) {
if (char.IsNumber(cArray[i]) | cArray[i].ToString() == ".") {
c = cArray[i].ToString() + c;
} else {
break; // TODO: might not be correct. Was : Exit For
}
}
}
//Obtain the exponent.
for (Int32 i = result.IndexOf("^") + 1; i <= cArray.Length - 1; i++) {
if (char.IsNumber(cArray[i]) | cArray[i] == '.') {
e = e + cArray[i].ToString();
} else {
break; // TODO: might not be correct. Was : Exit For
}
}
//Calculate the value.
v = Math.Pow(Convert.ToDouble(c), Convert.ToDouble(e));
if (Brackets) {
result = result.Replace("[" + c + "]^" + e, v.ToString());
//Insert the value into the expression.
} else {
result = result.Replace(c + "^" + e, v.ToString());
//Insert the value into the expression.
}
cArray = result.ToCharArray();
//Update the character array.
}
}
break;
case Operations.Multiplication & Operations.Division:
//Both multiplication and division get processed the same.
if (result.Contains("/")) {
while (result.Contains("/")) {
string[] constants = new string[2];
double t = 0;
//Total
for (Int32 i = result.IndexOf("/") - 1; i >= 0; i += -1) {
if (char.IsNumber(cArray[i])) {
constants[0] = cArray[i].ToString() + constants[0];
} else {
break; // TODO: might not be correct. Was : Exit For
}
}
for (Int32 i = result.IndexOf("/") + 1; i <= cArray.Length - 1; i++) {
if (char.IsNumber(cArray[i])) {
constants[1] = constants[1] + cArray[i].ToString();
} else {
break; // TODO: might not be correct. Was : Exit For
}
}
t = Convert.ToDouble(constants[0]) / Convert.ToDouble(constants[1]);
result = result.Replace(constants[0] + "/" + constants[1], t.ToString());
cArray = result.ToCharArray();
}
}
if (result.Contains("*")) {
while (result.Contains("*")) {
string[] constants = new string[2];
double t = 0;
//Total
for (Int32 i = result.IndexOf("*") - 1; i >= 0; i += -1) {
if (char.IsNumber(cArray[i])) {
constants[0] = cArray[i].ToString() + constants[0];
} else {
break; // TODO: might not be correct. Was : Exit For
}
}
for (Int32 i = result.IndexOf("*") + 1; i <= cArray.Length - 1; i++) {
if (char.IsNumber(cArray[i])) {
constants[1] = constants[1] + cArray[i].ToString();
} else {
break; // TODO: might not be correct. Was : Exit For
}
}
t = Convert.ToDouble(constants[0]) * Convert.ToDouble(constants[1]);
result = result.Replace(constants[0] + "*" + constants[1], t.ToString());
cArray = result.ToCharArray();
}
}
break;
case Operations.Addition & Operations.Subtraction:
//Addition and subtraction must be processed at the same time.
if (result.Contains("+") | result.Contains("-")) {
string[] constants = null;
double t = 0;
//Total.
//Fix any double operators we may have left over.
if (result.Contains("+-"))
result = result.Replace("+-", "-");
if (result.Contains("-+"))
result = result.Replace("-+", "-");
if (result.Contains("++"))
result = result.Replace("++", "+");
if (result.Contains("--"))
result = result.Replace("--", "+");
//Add in the seperator at every operand.
result = result.Replace("+", " +");
result = result.Replace("-", " -");
//Split the result to obtain all constants.
constants = result.Split(' ');
for (Int32 i = 0; i <= constants.Length - 1; i++) {
if (constants[i] != Constants.vbNullString) {
t = t + Convert.ToDouble(constants[i]);
}
}
result = t.ToString();
}
break;
}
return result;
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace NServiceKit.FluentValidation.Internal
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Resources;
using Results;
using Validators;
/// <summary>
/// Defines a rule associated with a property.
/// </summary>
public class PropertyRule : IValidationRule {
readonly List<IPropertyValidator> validators = new List<IPropertyValidator>();
Func<CascadeMode> cascadeModeThunk = () => ValidatorOptions.CascadeMode;
/// <summary>
/// Property associated with this rule.
/// </summary>
public MemberInfo Member { get; private set; }
/// <summary>
/// Function that can be invoked to retrieve the value of the property.
/// </summary>
public Func<object, object> PropertyFunc { get; private set; }
/// <summary>
/// Expression that was used to create the rule.
/// </summary>
public LambdaExpression Expression { get; private set; }
/// <summary>
/// String source that can be used to retrieve the display name (if null, falls back to the property name)
/// </summary>
public IStringSource DisplayName { get; set; }
/// <summary>
/// Rule set that this rule belongs to (if specified)
/// </summary>
public string RuleSet { get; set; }
/// <summary>
/// Function that will be invoked if any of the validators associated with this rule fail.
/// </summary>
public Action<object> OnFailure { get; set; }
/// <summary>
/// The current validator being configured by this rule.
/// </summary>
public IPropertyValidator CurrentValidator { get; private set; }
/// <summary>
/// Type of the property being validated
/// </summary>
public Type TypeToValidate { get; private set; }
/// <summary>
/// Cascade mode for this rule.
/// </summary>
public CascadeMode CascadeMode {
get { return cascadeModeThunk(); }
set { cascadeModeThunk = () => value; }
}
/// <summary>
/// Validators associated with this rule.
/// </summary>
public IEnumerable<IPropertyValidator> Validators {
get { return validators.AsReadOnly(); }
}
/// <summary>
/// Creates a new property rule.
/// </summary>
/// <param name="member">Property</param>
/// <param name="propertyFunc">Function to get the property value</param>
/// <param name="expression">Lambda expression used to create the rule</param>
/// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
/// <param name="typeToValidate">Type to validate</param>
/// <param name="containerType">Container type that owns the property</param>
public PropertyRule(MemberInfo member, Func<object, object> propertyFunc, LambdaExpression expression, Func<CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType) {
Member = member;
PropertyFunc = propertyFunc;
Expression = expression;
OnFailure = x => { };
TypeToValidate = typeToValidate;
this.cascadeModeThunk = cascadeModeThunk;
PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member, expression);
string displayName = ValidatorOptions.DisplayNameResolver(containerType, member, expression);
if (!string.IsNullOrEmpty(displayName)) DisplayName = new StaticStringSource(displayName);
}
/// <summary>
/// Creates a new property rule from a lambda expression.
/// </summary>
public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression) {
return Create(expression, () => ValidatorOptions.CascadeMode);
}
/// <summary>
/// Creates a new property rule from a lambda expression.
/// </summary>
public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression, Func<CascadeMode> cascadeModeThunk) {
var member = expression.GetMember();
var compiled = expression.Compile();
return new PropertyRule(member, compiled.CoerceToNonGeneric(), expression, cascadeModeThunk, typeof(TProperty), typeof(T));
}
/// <summary>
/// Adds a validator to the rule.
/// </summary>
public void AddValidator(IPropertyValidator validator) {
CurrentValidator = validator;
validators.Add(validator);
}
/// <summary>
/// Replaces a validator in this rule. Used to wrap validators.
/// </summary>
public void ReplaceValidator(IPropertyValidator original, IPropertyValidator newValidator) {
var index = validators.IndexOf(original);
if (index > -1) {
validators[index] = newValidator;
if (ReferenceEquals(CurrentValidator, original)) {
CurrentValidator = newValidator;
}
}
}
/// <summary>
/// Returns the property name for the property being validated.
/// Returns null if it is not a property being validated (eg a method call)
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// Display name for the property.
/// </summary>
public string GetDisplayName() {
if (DisplayName != null) {
return DisplayName.GetString();
}
return PropertyName.SplitPascalCase();
}
/// <summary>
/// Performs validation using a validation context and returns a collection of Validation Failures.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A collection of validation failures</returns>
public virtual IEnumerable<ValidationFailure> Validate(ValidationContext context) {
EnsureValidPropertyName();
// Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator)
string propertyName = BuildPropertyName(context);
// Ensure that this rule is allowed to run.
// The validatselector has the opportunity to veto this before any of the validators execute.
if(! context.Selector.CanExecute(this, propertyName, context)) {
yield break;
}
var cascade = cascadeModeThunk();
bool hasAnyFailure = false;
// Invoke each validator and collect its results.
foreach (var validator in validators) {
var results = InvokePropertyValidator(context, validator, propertyName);
bool hasFailure = false;
foreach (var result in results) {
hasAnyFailure = true;
hasFailure = true;
yield return result;
}
// If there has been at least one failure, and our CascadeMode has been set to StopOnFirst
// then don't continue to the next rule
if (cascade == FluentValidation.CascadeMode.StopOnFirstFailure && hasFailure) {
break;
}
}
if (hasAnyFailure) {
// Callback if there has been at least one property validator failed.
OnFailure(context.InstanceToValidate);
}
}
/// <summary>
/// Invokes a property validator using the specified validation context.
/// </summary>
protected virtual IEnumerable<ValidationFailure> InvokePropertyValidator(ValidationContext context, IPropertyValidator validator, string propertyName) {
var propertyContext = new PropertyValidatorContext(context, this, propertyName);
return validator.Validate(propertyContext);
}
private void EnsureValidPropertyName() {
if (PropertyName == null && DisplayName == null) {
throw new InvalidOperationException(string.Format("Property name could not be automatically determined for expression {0}. Please specify either a custom property name by calling 'WithName'.", Expression));
}
}
private string BuildPropertyName(ValidationContext context) {
return context.PropertyChain.BuildPropertyName(PropertyName ?? DisplayName.GetString());
}
/// <summary>Applies the condition.</summary>
///
/// <param name="predicate"> The predicate.</param>
/// <param name="applyConditionTo">The apply condition to.</param>
public void ApplyCondition(Func<object, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
if (applyConditionTo == ApplyConditionTo.AllValidators) {
foreach (var validator in Validators.ToList()) {
var wrappedValidator = new DelegatingValidator(predicate, validator);
ReplaceValidator(validator, wrappedValidator);
}
}
else {
var wrappedValidator = new DelegatingValidator(predicate, CurrentValidator);
ReplaceValidator(CurrentValidator, wrappedValidator);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CSC.CSClassroom.Model.Assignments;
using CSC.CSClassroom.Model.Communications;
using CSC.CSClassroom.Model.Users;
using CSC.CSClassroom.Service.Assignments;
using CSC.CSClassroom.Service.Classrooms;
using CSC.CSClassroom.Service.Communications;
using CSC.CSClassroom.Service.Identity;
using CSC.CSClassroom.WebApp.Extensions;
using CSC.CSClassroom.WebApp.Filters;
using CSC.CSClassroom.WebApp.ViewModels.Assignment;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using ReflectionIT.Mvc.Paging;
namespace CSC.CSClassroom.WebApp.Controllers
{
/// <summary>
/// The announcement controller.
/// </summary>
[Route(ClassroomRoutePrefix)]
public class ClassroomHomeController : BaseClassroomController
{
/// <summary>
/// The classroom service.
/// </summary>
private IAnnouncementService AnnouncementService { get; }
/// <summary>
/// Constructor.
/// </summary>
public ClassroomHomeController(
BaseControllerArgs args,
IClassroomService classroomService,
IAnnouncementService announcementService)
: base(args, classroomService)
{
AnnouncementService = announcementService;
}
/// <summary>
/// Shows the home page for the class.
/// </summary>
[Route("")]
[ClassroomAuthorization(ClassroomRole.General)]
public async Task<IActionResult> Index(int page = 1)
{
var announcementsQuery = await AnnouncementService.GetAnnouncementsAsync
(
ClassroomName,
User.Id,
ClassroomRole >= ClassroomRole.Admin
);
var announcements = await PagingList.CreateAsync
(
announcementsQuery,
pageSize: 5,
pageIndex: page
);
return View(announcements);
}
/// <summary>
/// Creates a new assignment.
/// </summary>
[Route("PostAnnouncement")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public IActionResult PostAnnouncement()
{
ViewBag.OperationType = "Post";
return View("PostEditAnnouncement");
}
/// <summary>
/// Creates a new assignment.
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
[Route("PostAnnouncement")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> PostAnnouncement(Announcement announcement)
{
ModelState[nameof(Announcement.DatePosted)].ValidationState
= ModelValidationState.Valid;
if (ModelState.IsValid
&& await AnnouncementService.PostAnnouncementAsync
(
ClassroomName,
User.Id,
announcement,
FormatDateTime,
ModelErrors
))
{
return RedirectToAction("Index");
}
else
{
ViewBag.OperationType = "Post";
return View("PostEditAnnouncement", announcement);
}
}
/// <summary>
/// Edits an announcement.
/// </summary>
[Route("EditAnnouncement")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> EditAnnouncement(int announcementId)
{
var announcement = await AnnouncementService.GetAnnouncementAsync
(
ClassroomName,
announcementId
);
if (announcement == null)
{
return NotFound();
}
ViewBag.OperationType = "Edit";
return View("PostEditAnnouncement", announcement);
}
/// <summary>
/// Edits an announcement.
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
[Route("EditAnnouncement")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> EditAnnouncement(Announcement announcement)
{
ModelState[nameof(Announcement.DatePosted)].ValidationState
= ModelValidationState.Valid;
if (ModelState.IsValid
&& await AnnouncementService.EditAnnouncementAsync
(
ClassroomName,
announcement,
FormatDateTime,
ModelErrors
))
{
return RedirectToAction("Index");
}
else
{
ViewBag.OperationType = "Edit";
return View("PostEditAnnouncement", announcement);
}
}
/// <summary>
/// Deletes an announcement.
/// </summary>
[Route("Announcements/{announcementId}/Delete")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> DeleteAnnouncement(int announcementId)
{
var announcement = await AnnouncementService.GetAnnouncementAsync
(
ClassroomName,
announcementId
);
if (announcement == null)
{
return NotFound();
}
return View(announcement);
}
/// <summary>
/// Deletes an announcement.
/// </summary>
[HttpPost, ActionName("DeleteAnnouncement")]
[ValidateAntiForgeryToken]
[Route("Announcements/{announcementId}/Delete")]
[ClassroomAuthorization(ClassroomRole.Admin)]
public async Task<IActionResult> DeleteAnnouncementConfirmed(int announcementId)
{
await AnnouncementService.DeleteAnnouncementAsync(ClassroomName, announcementId);
return RedirectToAction("Index");
}
/// <summary>
/// Formats the given datetime object.
/// </summary>
private string FormatDateTime(DateTime dateTime)
{
return dateTime.FormatLongDateTime(TimeZoneProvider);
}
}
}
| |
using System;
using Gx;
using Gx.Agent;
using Gx.Common;
using Gx.Conclusion;
using Gx.Links;
using Gx.Records;
using Gx.Source;
using Gx.Types;
using System.Collections.Generic;
namespace Gx.Util
{
/// <summary>
/// A dictionary for looking up GEDCOM X data elements by their local id (i.e. "fragment identifier").
/// </summary>
public class GedcomxIdDictionary : GedcomxModelVisitorBase
{
private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();
/// <summary>
/// Initializes an id dictionary for the specified data set.
/// </summary>
/// <param name='gx'>
/// The data set.
/// </param>
public GedcomxIdDictionary(Gedcomx gx)
{
VisitGedcomx(gx);
}
/// <summary>
/// Initializes an id dictionary for the specified record set.
/// </summary>
/// <param name='rs'>
/// The record set.
/// </param>
public GedcomxIdDictionary(RecordSet rs)
{
VisitRecordSet(rs);
}
/// <summary>
/// Gets or sets the dictionary with an element of the specified id. If the specified key is not
/// found, a get operation throws a KeyNotFoundException, and a set operation creates a new element
/// with the specified key.
/// </summary>
/// <param name='key'>
/// The id.
/// </param>
public object this[string key]
{
get
{
return dictionary[key];
}
set
{
dictionary[key] = value;
}
}
/// <summary>
/// Whether the dictionary contains the specified key.
/// </summary>
/// <returns>
/// Whether the dictionary contains the specified key.
/// </returns>
/// <param name='key'>
/// The key to test.
/// </param>
public bool ContainsKey(string key)
{
return dictionary.ContainsKey(key);
}
/// <summary>
/// Gets the value associated with the specified id.
/// </summary>
/// <returns>
/// The data of the specified id.
/// </returns>
/// <param name='key'>
/// The id of the value to get.
/// </param>
/// <param name='value'>
/// When this method returns, contains the value associated with the specified key, if the key is found;
/// otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.
/// </param>
public bool TryGetValue(string key, out object value)
{
return dictionary.TryGetValue(key, out value);
}
/// <summary>
/// Resolve the value referenced by the specified URI. If the object is not resolved, a
/// KeyNotFoundException is thrown.
/// </summary>
/// <param name='uri'>
/// The URI.
/// </param>
public object Resolve(string uri)
{
int fragmentIndex = uri.IndexOf('#');
if (fragmentIndex >= 0)
{
return this[uri.Substring(fragmentIndex)];
}
else
{
throw new KeyNotFoundException();
}
}
/// <summary>
/// Attempts to resolve the value referenced by the specified URI.
/// </summary>
/// <param name='uri'>
/// The URI.
/// </param>
/// <param name='value'>
/// When this method returns, contains the resolved value, if it is resolved;
/// otherwise, the default value for the type of the value parameter.
/// This parameter is passed uninitialized.
/// </param>
public bool TryResolveValue(string uri, out object value)
{
value = null;
int fragmentIndex = uri.IndexOf('#');
if (fragmentIndex >= 0)
{
return TryGetValue(uri.Substring(fragmentIndex), out value);
}
else
{
return false;
}
}
/// <summary>
/// Visits the specified record set.
/// </summary>
/// <param name="rs">The record set to visit.</param>
public override void VisitRecordSet(RecordSet rs)
{
if (rs.Id != null)
{
this.dictionary.Add(rs.Id, rs);
}
base.VisitRecordSet(rs);
}
/// <summary>
/// Visits the specified <see cref="Gx.Gedcomx"/> entity.
/// </summary>
/// <param name="gx">The <see cref="Gx.Gedcomx"/> entity to visit.</param>
public override void VisitGedcomx(Gx.Gedcomx gx)
{
if (gx.Id != null)
{
this.dictionary.Add(gx.Id, gx);
}
base.VisitGedcomx(gx);
}
/// <summary>
/// Visits the document.
/// </summary>
/// <param name="document">The document to visit.</param>
public override void VisitDocument(Gx.Conclusion.Document document)
{
if (document.Id != null)
{
this.dictionary.Add(document.Id, document);
}
base.VisitDocument(document);
}
/// <summary>
/// Visits the place description.
/// </summary>
/// <param name="place">The place description to visit.</param>
public override void VisitPlaceDescription(Gx.Conclusion.PlaceDescription place)
{
if (place.Id != null)
{
this.dictionary.Add(place.Id, place);
}
base.VisitPlaceDescription(place);
}
/// <summary>
/// Visits the event.
/// </summary>
/// <param name="e">The event to visit.</param>
public override void VisitEvent(Gx.Conclusion.Event e)
{
if (e.Id != null)
{
this.dictionary.Add(e.Id, e);
}
base.VisitEvent(e);
}
/// <summary>
/// Visits the event role.
/// </summary>
/// <param name="role">The event role to visit.</param>
public override void VisitEventRole(Gx.Conclusion.EventRole role)
{
if (role.Id != null)
{
this.dictionary.Add(role.Id, role);
}
base.VisitEventRole(role);
}
/// <summary>
/// Visits the agent.
/// </summary>
/// <param name="agent">The agent to visit.</param>
public override void VisitAgent(Gx.Agent.Agent agent)
{
if (agent.Id != null)
{
this.dictionary.Add(agent.Id, agent);
}
base.VisitAgent(agent);
}
/// <summary>
/// Visits the source description.
/// </summary>
/// <param name="sourceDescription">The source description to visit.</param>
public override void VisitSourceDescription(Gx.Source.SourceDescription sourceDescription)
{
if (sourceDescription.Id != null)
{
this.dictionary.Add(sourceDescription.Id, sourceDescription);
}
base.VisitSourceDescription(sourceDescription);
}
/// <summary>
/// Visits the source citation.
/// </summary>
/// <param name="citation">The source citation to visit.</param>
public override void VisitSourceCitation(Gx.Source.SourceCitation citation)
{
if (citation.Id != null)
{
this.dictionary.Add(citation.Id, citation);
}
base.VisitSourceCitation(citation);
}
/// <summary>
/// Visits the collection.
/// </summary>
/// <param name="collection">The collection to visit.</param>
public override void VisitCollection(Collection collection)
{
if (collection.Id != null)
{
this.dictionary.Add(collection.Id, collection);
}
base.VisitCollection(collection);
}
/// <summary>
/// Visits the facet.
/// </summary>
/// <param name="facet">The facet to visit.</param>
public override void VisitFacet(Facet facet)
{
if (facet.Id != null)
{
this.dictionary.Add(facet.Id, facet);
}
base.VisitFacet(facet);
}
/// <summary>
/// Visits the record descriptor.
/// </summary>
/// <param name="recordDescriptor">The record descriptor to visit.</param>
public override void VisitRecordDescriptor(RecordDescriptor recordDescriptor)
{
if (recordDescriptor.Id != null)
{
this.dictionary.Add(recordDescriptor.Id, recordDescriptor);
}
base.VisitRecordDescriptor(recordDescriptor);
}
/// <summary>
/// Visits the field.
/// </summary>
/// <param name="field">The field to visit.</param>
public override void VisitField(Field field)
{
if (field.Id != null)
{
this.dictionary.Add(field.Id, field);
}
base.VisitField(field);
}
/// <summary>
/// Visits the field value.
/// </summary>
/// <param name="fieldValue">The field value to visit.</param>
public override void VisitFieldValue(FieldValue fieldValue)
{
if (fieldValue.Id != null)
{
this.dictionary.Add(fieldValue.Id, fieldValue);
}
base.VisitFieldValue(fieldValue);
}
/// <summary>
/// Visits the relationship.
/// </summary>
/// <param name="relationship">The relationship to visit.</param>
public override void VisitRelationship(Gx.Conclusion.Relationship relationship)
{
if (relationship.Id != null)
{
this.dictionary.Add(relationship.Id, relationship);
}
base.VisitRelationship(relationship);
}
/// <summary>
/// Visits the person.
/// </summary>
/// <param name="person">The person to visit.</param>
public override void VisitPerson(Gx.Conclusion.Person person)
{
if (person.Id != null)
{
this.dictionary.Add(person.Id, person);
}
base.VisitPerson(person);
}
/// <summary>
/// Visits the fact.
/// </summary>
/// <param name="fact">The fact to visit.</param>
public override void VisitFact(Gx.Conclusion.Fact fact)
{
if (fact.Id != null)
{
this.dictionary.Add(fact.Id, fact);
}
base.VisitFact(fact);
}
/// <summary>
/// Visits the place reference.
/// </summary>
/// <param name="place">The place reference to visit.</param>
public override void VisitPlaceReference(Gx.Conclusion.PlaceReference place)
{
if (place.Id != null)
{
this.dictionary.Add(place.Id, place);
}
base.VisitPlaceReference(place);
}
/// <summary>
/// Visits the date.
/// </summary>
/// <param name="date">The date to visit.</param>
public override void VisitDate(Gx.Conclusion.DateInfo date)
{
if (date.Id != null)
{
this.dictionary.Add(date.Id, date);
}
base.VisitDate(date);
}
/// <summary>
/// Visits the name.
/// </summary>
/// <param name="name">The name to visit.</param>
public override void VisitName(Gx.Conclusion.Name name)
{
if (name.Id != null)
{
this.dictionary.Add(name.Id, name);
}
base.VisitName(name);
}
/// <summary>
/// Visits the name form.
/// </summary>
/// <param name="form">The name form to visit.</param>
public override void VisitNameForm(Gx.Conclusion.NameForm form)
{
if (form.Id != null)
{
this.dictionary.Add(form.Id, form);
}
base.VisitNameForm(form);
}
/// <summary>
/// Visits the name part.
/// </summary>
/// <param name="part">The name part to visit.</param>
public override void VisitNamePart(Gx.Conclusion.NamePart part)
{
if (part.Id != null)
{
this.dictionary.Add(part.Id, part);
}
base.VisitNamePart(part);
}
/// <summary>
/// Visits the gender.
/// </summary>
/// <param name="gender">The gender to visit.</param>
public override void VisitGender(Gx.Conclusion.Gender gender)
{
if (gender.Id != null)
{
this.dictionary.Add(gender.Id, gender);
}
base.VisitGender(gender);
}
/// <summary>
/// Visits the source reference.
/// </summary>
/// <param name="sourceReference">The source reference to visit.</param>
public override void VisitSourceReference(Gx.Source.SourceReference sourceReference)
{
if (sourceReference.Id != null)
{
this.dictionary.Add(sourceReference.Id, sourceReference);
}
base.VisitSourceReference(sourceReference);
}
/// <summary>
/// Visits the note.
/// </summary>
/// <param name="note">The note to visit.</param>
public override void VisitNote(Gx.Common.Note note)
{
if (note.Id != null)
{
this.dictionary.Add(note.Id, note);
}
base.VisitNote(note);
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace Thinktecture.Text
{
/// <summary>
/// Static members of <see cref="Encoding"/>.
/// </summary>
public interface IEncodingGlobals
{
private class EncodingGlobals : IEncodingGlobals
{
}
/// <summary>
/// Default implementation of <see cref="IEncodingGlobals"/>.
/// </summary>
public static readonly IEncodingGlobals Instance = new EncodingGlobals();
/// <summary>Gets an encoding for the UTF-16 format that uses the big endian byte order.</summary>
/// <returns>An encoding object for the UTF-16 format that uses the big endian byte order.</returns>
IEncoding BigEndianUnicode => Encoding.BigEndianUnicode.ToInterface();
/// <summary>Gets an encoding for the UTF-16 format using the little endian byte order.</summary>
/// <returns>An encoding for the UTF-16 format using the little endian byte order.</returns>
IEncoding Unicode => Encoding.Unicode.ToInterface();
/// <summary>Gets an encoding for the UTF-8 format.</summary>
/// <returns>An encoding for the UTF-8 format.</returns>
// ReSharper disable once InconsistentNaming
IEncoding UTF8 => Encoding.UTF8.ToInterface();
/// <summary>Gets an encoding for the operating system's current ANSI code page.</summary>
/// <returns>An encoding for the operating system's current ANSI code page.</returns>
/// <filterpriority>1</filterpriority>
IEncoding Default => Encoding.Default.ToInterface();
/// <summary>Gets an encoding for the ASCII (7-bit) character set.</summary>
/// <returns>An encoding for the ASCII (7-bit) character set.</returns>
/// <filterpriority>1</filterpriority>
// ReSharper disable once InconsistentNaming
IEncoding ASCII => Encoding.ASCII.ToInterface();
#if NET5_0
/// <summary>Gets an encoding for the Latin1 character set (ISO-8859-1).</summary>
IEncoding Latin1 => Encoding.Latin1.ToInterface();
#endif
/// <summary>Gets an encoding for the UTF-7 format.</summary>
/// <returns>An encoding for the UTF-7 format.</returns>
/// <filterpriority>1</filterpriority>
// ReSharper disable once InconsistentNaming
[Obsolete("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.")]
IEncoding UTF7 => Encoding.UTF7.ToInterface();
/// <summary>Gets an encoding for the UTF-32 format using the little endian byte order.</summary>
/// <returns>An encoding object for the UTF-32 format using the little endian byte order.</returns>
/// <filterpriority>1</filterpriority>
// ReSharper disable once InconsistentNaming
IEncoding UTF32 => Encoding.UTF32.ToInterface();
/// <summary>Converts an entire byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The target encoding format. </param>
/// <param name="bytes">The bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(IEncoding srcEncoding, IEncoding dstEncoding, byte[] bytes)
{
return Encoding.Convert(srcEncoding.ToImplementation(), dstEncoding.ToImplementation(), bytes);
}
/// <summary>Converts an entire byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The target encoding format. </param>
/// <param name="bytes">The bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(IEncoding srcEncoding, Encoding dstEncoding, byte[] bytes)
{
return Encoding.Convert(srcEncoding.ToImplementation(), dstEncoding, bytes);
}
/// <summary>Converts an entire byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The target encoding format. </param>
/// <param name="bytes">The bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(Encoding srcEncoding, IEncoding dstEncoding, byte[] bytes)
{
return Encoding.Convert(srcEncoding, dstEncoding.ToImplementation(), bytes);
}
/// <summary>Converts an entire byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the results of converting <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding format of <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The target encoding format. </param>
/// <param name="bytes">The bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes)
{
return Encoding.Convert(srcEncoding, dstEncoding, bytes);
}
/// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The encoding of the output array. </param>
/// <param name="bytes">The array of bytes to convert. </param>
/// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param>
/// <param name="count">The number of bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(IEncoding srcEncoding, IEncoding dstEncoding, byte[] bytes, int index, int count)
{
return Encoding.Convert(srcEncoding.ToImplementation(), dstEncoding.ToImplementation(), bytes, index, count);
}
/// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The encoding of the output array. </param>
/// <param name="bytes">The array of bytes to convert. </param>
/// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param>
/// <param name="count">The number of bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(IEncoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count)
{
return Encoding.Convert(srcEncoding.ToImplementation(), dstEncoding, bytes, index, count);
}
/// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The encoding of the output array. </param>
/// <param name="bytes">The array of bytes to convert. </param>
/// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param>
/// <param name="count">The number of bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(Encoding srcEncoding, IEncoding dstEncoding, byte[] bytes, int index, int count)
{
return Encoding.Convert(srcEncoding, dstEncoding.ToImplementation(), bytes, index, count);
}
/// <summary>Converts a range of bytes in a byte array from one encoding to another.</summary>
/// <returns>An array of type <see cref="T:System.Byte" /> containing the result of converting a range of bytes in <paramref name="bytes" /> from <paramref name="srcEncoding" /> to <paramref name="dstEncoding" />.</returns>
/// <param name="srcEncoding">The encoding of the source array, <paramref name="bytes" />. </param>
/// <param name="dstEncoding">The encoding of the output array. </param>
/// <param name="bytes">The array of bytes to convert. </param>
/// <param name="index">The index of the first element of <paramref name="bytes" /> to convert. </param>
/// <param name="count">The number of bytes to convert. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="srcEncoding" /> is null.-or- <paramref name="dstEncoding" /> is null.-or- <paramref name="bytes" /> is null. </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index" /> and <paramref name="count" /> do not specify a valid range in the byte array. </exception>
/// <exception cref="T:System.Text.DecoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-srcEncoding.<see cref="P:System.Text.Encoding.DecoderFallback" /> is set to <see cref="T:System.Text.DecoderExceptionFallback" />.</exception>
/// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (see Character Encoding in the .NET Framework for complete explanation)-and-dstEncoding.<see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception>
byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count)
{
return Encoding.Convert(srcEncoding, dstEncoding, bytes, index, count);
}
#if NET5_0
/// <summary>Creates a <see cref="T:System.IO.Stream" /> that serves to transcode data between an inner <see cref="T:System.Text.Encoding" /> and an outer <see cref="T:System.Text.Encoding" />, similar to <see cref="M:System.Text.Encoding.Convert(System.Text.Encoding,System.Text.Encoding,System.Byte[])" />.</summary>
/// <param name="innerStream">The stream to wrap.</param>
/// <param name="innerStreamEncoding">The encoding associated with <paramref name="innerStream" />.</param>
/// <param name="outerStreamEncoding">The encoding associated with the <see cref="T:System.IO.Stream" /> that's returned by this method.</param>
/// <param name="leaveOpen">
/// <see langword="true" /> if disposing the <see cref="T:System.IO.Stream" /> returned by this method should <em>not</em> dispose <paramref name="innerStream" />.</param>
/// <returns>A stream that transcodes the contents of <paramref name="innerStream" /> as <paramref name="outerStreamEncoding" />.</returns>
Stream CreateTranscodingStream(
Stream innerStream,
IEncoding innerStreamEncoding,
IEncoding outerStreamEncoding,
bool leaveOpen = false)
{
return Encoding.CreateTranscodingStream(innerStream, innerStreamEncoding.ToImplementation(), outerStreamEncoding.ToImplementation(), leaveOpen);
}
#endif
/// <summary>Returns the encoding associated with the specified code page name.</summary>
/// <returns>The encoding associated with the specified code page.</returns>
/// <param name="name">The code page name of the preferred encoding. Any value returned by the <see cref="P:System.Text.Encoding.WebName" /> property is valid. Possible values are listed in the Name column of the table that appears in the <see cref="T:System.Text.Encoding" /> class topic.</param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="name" /> is not a valid code page name.-or- The code page indicated by <paramref name="name" /> is not supported by the underlying platform. </exception>
IEncoding GetEncoding(string name)
{
return Encoding.GetEncoding(name).ToInterface();
}
/// <summary>Returns the encoding associated with the specified code page identifier.</summary>
/// <returns>The encoding that is associated with the specified code page.</returns>
/// <param name="codepage">The code page identifier of the preferred encoding. Possible values are listed in the Code Page column of the table that appears in the <see cref="T:System.Text.Encoding" /> class topic.-or- 0 (zero), to use the default encoding. </param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="codepage" /> is less than zero or greater than 65535. </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="codepage" /> is not supported by the underlying platform. </exception>
/// <exception cref="T:System.NotSupportedException">
/// <paramref name="codepage" /> is not supported by the underlying platform. </exception>
/// <filterpriority>1</filterpriority>
IEncoding GetEncoding(int codepage)
{
return Encoding.GetEncoding(codepage).ToInterface();
}
/// <summary>Returns the encoding associated with the specified code page identifier. Parameters specify an error handler for characters that cannot be encoded and byte sequences that cannot be decoded.</summary>
/// <returns>The encoding that is associated with the specified code page.</returns>
/// <param name="codepage">The code page identifier of the preferred encoding. Possible values are listed in the Code Page column of the table that appears in the <see cref="T:System.Text.Encoding" /> class topic.-or- 0 (zero), to use the default encoding. </param>
/// <param name="encoderFallback">An object that provides an error-handling procedure when a character cannot be encoded with the current encoding. </param>
/// <param name="decoderFallback">An object that provides an error-handling procedure when a byte sequence cannot be decoded with the current encoding. </param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="codepage" /> is less than zero or greater than 65535. </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="codepage" /> is not supported by the underlying platform. </exception>
/// <exception cref="T:System.NotSupportedException">
/// <paramref name="codepage" /> is not supported by the underlying platform. </exception>
/// <filterpriority>1</filterpriority>
IEncoding GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback)
{
return Encoding.GetEncoding(codepage, encoderFallback, decoderFallback).ToInterface();
}
/// <summary>Returns the encoding associated with the specified code page name. Parameters specify an error handler for characters that cannot be encoded and byte sequences that cannot be decoded.</summary>
/// <returns>The encoding that is associated with the specified code page.</returns>
/// <param name="name">The code page name of the preferred encoding. Any value returned by the <see cref="P:System.Text.Encoding.WebName" /> property is valid. Possible values are listed in the Name column of the table that appears in the <see cref="T:System.Text.Encoding" /> class topic.</param>
/// <param name="encoderFallback">An object that provides an error-handling procedure when a character cannot be encoded with the current encoding. </param>
/// <param name="decoderFallback">An object that provides an error-handling procedure when a byte sequence cannot be decoded with the current encoding. </param>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="name" /> is not a valid code page name.-or- The code page indicated by <paramref name="name" /> is not supported by the underlying platform. </exception>
/// <filterpriority>1</filterpriority>
IEncoding GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback)
{
return Encoding.GetEncoding(name, encoderFallback, decoderFallback).ToInterface();
}
/// <summary>Returns an array that contains all encodings.</summary>
/// <returns>An array that contains all encodings.</returns>
/// <filterpriority>1</filterpriority>
EncodingInfo[] GetEncodings()
{
return Encoding.GetEncodings();
}
/// <summary>Registers an encoding provider. </summary>
/// <param name="provider">A subclass of <see cref="T:System.Text.EncodingProvider" /> that provides access to additional character encodings. </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="provider" /> is null. </exception>
void RegisterProvider(EncodingProvider provider)
{
Encoding.RegisterProvider(provider);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A07_Country_Child (editable child object).<br/>
/// This is a generated base class of <see cref="A07_Country_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A06_Country"/> collection.
/// </remarks>
[Serializable]
public partial class A07_Country_Child : BusinessBase<A07_Country_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int country_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Country Child Name");
/// <summary>
/// Gets or sets the Country Child Name.
/// </summary>
/// <value>The Country Child Name.</value>
public string Country_Child_Name
{
get { return GetProperty(Country_Child_NameProperty); }
set { SetProperty(Country_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A07_Country_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="A07_Country_Child"/> object.</returns>
internal static A07_Country_Child NewA07_Country_Child()
{
return DataPortal.CreateChild<A07_Country_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="A07_Country_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A07_Country_Child"/> object.</returns>
internal static A07_Country_Child GetA07_Country_Child(SafeDataReader dr)
{
A07_Country_Child obj = new A07_Country_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A07_Country_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A07_Country_Child()
{
// 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="A07_Country_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="A07_Country_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name"));
// parent properties
country_ID1 = dr.GetInt32("Country_ID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="A07_Country_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(A06_Country parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddA07_Country_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="A07_Country_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(A06_Country parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateA07_Country_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Country_Child_Name", ReadProperty(Country_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="A07_Country_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(A06_Country parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteA07_Country_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Country_ID1", parent.Country_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using AutoTest.Core.Configuration;
using Rhino.Mocks;
using AutoTest.Core.Messaging;
using AutoTest.Core.Caching.Projects;
using System.IO;
using AutoTest.Core.DebugLog;
using System;
namespace AutoTest.Test.Core.Configuration
{
class TestConfigLocator : ILocateWriteLocation
{
public string GetLogfile()
{
return "";
}
public string GetConfigurationFile()
{
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
return Path.Combine(path, "AutoTest.ForTests.config");
}
}
[TestFixture]
public class ConfigTest
{
private Config _config;
private IMessageBus _bus;
private string _overridConfig;
[SetUp]
public void SetUp()
{
_overridConfig = Path.GetTempFileName();
_bus = MockRepository.GenerateMock<IMessageBus>();
_config = new Config(_bus, new TestConfigLocator());
}
[TearDown]
public void TearDown()
{
if (File.Exists(_overridConfig))
File.Delete(_overridConfig);
}
[Test]
public void Should_read_directory_to_watch()
{
_config.WatchDirectores[0].ShouldEqual("TestResources");
}
[Test]
public void Should_read_default_build_executable()
{
var document = new ProjectDocument(ProjectType.CSharp);
_config.BuildExecutable(document).ShouldEqual(@"C:\Somefolder\MSBuild.exe");
}
[Test]
public void Should_get_framework_spesific_build_executable()
{
var document = new ProjectDocument(ProjectType.CSharp);
document.SetFramework("v3.5");
_config.BuildExecutable(document).ShouldEqual(@"C:\SomefolderOther\MSBuild.exe");
}
[Test]
public void Should_get_product_version_spesific_build_executable()
{
var document = new ProjectDocument(ProjectType.CSharp);
document.SetFramework("v3.5");
document.SetVSVersion("9.0.30729");
_config.BuildExecutable(document).ShouldEqual(@"C:\ProductVersionFolder\MSBuild.exe");
}
[Test]
public void Should_read_default_nunit_testrunner_path()
{
_config.NunitTestRunner("").ShouldEqual(@"C:\Somefolder\NUnit\nunit-console.exe");
}
[Test]
public void Should_read_nunit_testrunner_path()
{
_config.NunitTestRunner("v3.5").ShouldEqual(@"C:\SomefolderOther\NUnit\nunit-console.exe");
}
[Test]
public void Should_read_default_mstest_testrunner_path()
{
_config.MSTestRunner("").ShouldEqual(@"C:\Somefolder\MSTest.exe");
}
[Test]
public void Should_read_mstest_testrunner_path()
{
_config.MSTestRunner("v3.5").ShouldEqual(@"C:\SomefolderOther\MSTest.exe");
}
[Test]
public void Should_read_code_editor()
{
var editor = _config.CodeEditor;
editor.Executable.ShouldEqual(@"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv");
editor.Arguments.ShouldEqual("/Edit \"[[CodeFile]]\" /command \"Edit.Goto [[LineNumber]]\"");
}
[Test]
public void Should_read_debug_flag()
{
var state = _config.DebuggingEnabled;
state.ShouldBeTrue();
}
[Test]
public void Should_read_default_xunit_testrunner_path()
{
_config.XunitTestRunner("").ShouldEqual(@"C:\Somefolder\XUnit\xunit.console.exe");
}
[Test]
public void Should_read_xunit_testrunner_path()
{
_config.XunitTestRunner("v3.5").ShouldEqual(@"C:\SomefolderOther\XUnit\xunit.console.exe");
}
[Test]
public void Should_read_growl_executable()
{
_config.GrowlNotify.ShouldEqual(@"C:\Meh\growlnotify.exe");
}
[Test]
public void Should_read_notify_on_start()
{
_config.NotifyOnRunStarted.ShouldBeFalse();
}
[Test]
public void Should_read_notify_on_completed()
{
_config.NotifyOnRunCompleted.ShouldBeFalse();
}
[Test]
public void Should_get_watch_ignore_file()
{
var file = Path.Combine("TestResources", "myignorefile.txt");
using (var writer = new StreamWriter(file))
{
writer.WriteLine("MyFolder");
writer.WriteLine(@"OtherFolder\SomeFile.txt");
writer.WriteLine(@"OhYeah\*");
writer.WriteLine("*TestOutput.xml");
writer.WriteLine("!meh.txt");
writer.WriteLine(" #Comment");
writer.WriteLine("");
}
_config.BuildIgnoreListFromPath("TestResources");
_config.WatchIgnoreList.Length.ShouldEqual(4);
_config.WatchIgnoreList[0].ShouldEqual("MyFolder");
_config.WatchIgnoreList[1].ShouldEqual(@"OtherFolder/SomeFile.txt");
_config.WatchIgnoreList[2].ShouldEqual(@"OhYeah/*");
_config.WatchIgnoreList[3].ShouldEqual("*TestOutput.xml");
if (File.Exists(file))
File.Delete(file);
}
[Test]
public void Should_get_watch_ignore_file_from_absolute_path()
{
var file = Path.Combine("TestResources", "myignorefile.txt");
using (var writer = new StreamWriter(file))
{
writer.WriteLine("MyFolder");
writer.WriteLine(@"OtherFolder\SomeFile.txt");
writer.WriteLine(@"OhYeah\*");
writer.WriteLine("*TestOutput.xml");
writer.WriteLine("!meh.txt");
writer.WriteLine(" #Comment");
writer.WriteLine("");
}
createMergeFile();
_config.Merge(_overridConfig);
_config.BuildIgnoreListFromPath("");
_config.WatchIgnoreList.Length.ShouldEqual(4);
_config.WatchIgnoreList[0].ShouldEqual("MyFolder");
_config.WatchIgnoreList[1].ShouldEqual(@"OtherFolder/SomeFile.txt");
_config.WatchIgnoreList[2].ShouldEqual(@"OhYeah/*");
_config.WatchIgnoreList[3].ShouldEqual("*TestOutput.xml");
if (File.Exists(file))
File.Delete(file);
}
[Test]
public void Should_set_to_empty_array_if_file_doesnt_exist()
{
_config.BuildIgnoreListFromPath("SomeInvalidDirectory");
_config.WatchIgnoreList.Length.ShouldEqual(0);
}
[Test]
public void Should_get_test_assemblies_to_ignore()
{
_config.TestAssembliesToIgnore[0].ShouldEqual("*System.dll");
_config.TestAssembliesToIgnore[1].ShouldEqual("meh.exe");
}
[Test]
public void Should_get_test_categories_to_ignore()
{
_config.TestCategoriesToIgnore[0].ShouldEqual("Category1");
_config.TestCategoriesToIgnore[1].ShouldEqual("Category2");
}
[Test]
public void Should_get_delay()
{
_config.FileChangeBatchDelay.ShouldEqual(95);
}
[Test]
public void Should_get_custom_output_path()
{
_config.CustomOutputPath.ShouldEqual(@"bin\CustomOutput");
}
[Test]
public void Should_get_specific_test_runner()
{
_config.GetSpesificNunitTestRunner("v3.5").ShouldEqual(@"C:\SomefolderOther\NUnit\nunit-console.exe");
}
[Test]
public void Should_return_when_null_when_geting_specific_test_runner_for_nonexisting_version()
{
_config.GetSpesificNunitTestRunner("v1.0").ShouldBeNull();
}
[Test]
public void Should_get_failed_first_pre_processor_setting()
{
_config.RerunFailedTestsFirst.ShouldBeTrue();
}
[Test]
public void Should_merge_two_config_files()
{
createMergeFile();
var document = new ProjectDocument(ProjectType.CSharp);
var document35 = new ProjectDocument(ProjectType.CSharp);
document35.SetFramework("v3.5");
_config.Merge(_overridConfig);
_config.BuildExecutable(document).ShouldEqual("");
_config.NunitTestRunner(document.Framework).ShouldEqual(@"C:\Somefolder\NUnit\nunit-console.exe");
_config.NunitTestRunner(document35.Framework).ShouldEqual("NewTestRunner");
_config.GrowlNotify.ShouldEqual("another_growl_notifier");
_config.TestAssembliesToIgnore[2].ShouldEqual("MergedRule.dll");
_config.FileChangeBatchDelay.ShouldEqual(800);
}
[Test]
public void Should_read_build_solution_when_watching_solution()
{
_config.WhenWatchingSolutionBuildSolution.ShouldBeTrue();
}
[Test]
public void Should_build_solution()
{
_config.ShouldBuildSolution.ShouldBeFalse();
}
[Test]
public void Should_get_autotest_runner_setting()
{
_config.UseAutoTestTestRunner.ShouldBeFalse();
}
[Test]
public void Should_start_paused_setting()
{
_config.StartPaused.ShouldBeTrue();
}
[Test]
public void Should_use_lowest_common_denominator_path()
{
_config.UseLowestCommonDenominatorAsWatchPath.ShouldBeFalse();
}
[Test]
public void Should_read_key_store_of_all_settings()
{
_config.AllSettings("SomCustomStuff").ShouldEqual("content");
}
[Test]
public void Should_merge_key_store_of_all_settings()
{
createMergeFile();
_config.Merge(_overridConfig);
_config.AllSettings("SomCustomStuff").ShouldEqual("modified content");
_config.AllSettings("AnotherSetting").ShouldEqual("something");
}
[Test]
public void Should_get_watch_all_strategy()
{
_config.WatchAllFiles.ShouldBeTrue();
}
[Test]
public void Should_get_parallel_test_run_setting()
{
_config.RunAssembliesInParallel.ShouldBeTrue();
}
[Test]
public void Should_get_test_runner_compatibility_mode()
{
_config.TestRunnerCompatibilityMode.ShouldBeTrue();
}
[Test]
public void Should_get_log_resycle_size()
{
_config.LogRecycleSize.ShouldEqual(123456789);
}
[Test]
public void Should_get_msbuild_additional_parameters()
{
_config.MSBuildAdditionalParameters.ShouldEqual("more params");
}
[Test]
public void Should_get_msbuild_parallel_build_count()
{
Assert.That(_config.MSBuildParallelBuildCount, Is.EqualTo(3));
}
[Test]
public void Should_get_projects_to_ignore()
{
_config.ProjectsToIgnore[0].ShouldEqual("*MyProject.csproj");
_config.ProjectsToIgnore[1].ShouldEqual("FullPathTo/aproject.csproj");
}
[Test]
public void Should_get_autotest_provider()
{
_config.Providers.ShouldEqual("php");
}
private void createMergeFile()
{
if (File.Exists(_overridConfig))
File.Delete(_overridConfig);
var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var file = Path.Combine(path, Path.Combine("TestResources", "myignorefile.txt"));
using (var writer = new StreamWriter(_overridConfig))
{
writer.WriteLine("<configuration>");
writer.WriteLine("<BuildExecutable override=\"exclude\">some_text_just_to_make_sure_no_its_not_used</BuildExecutable>");
writer.WriteLine("<NUnitTestRunner framework=\"v3.5\" override=\"merge\">NewTestRunner</NUnitTestRunner>");
writer.WriteLine("<growlnotify>another_growl_notifier</growlnotify>");
writer.WriteLine("<ShouldIgnoreTestAssembly override=\"merge\">");
writer.WriteLine("<Assembly>MergedRule.dll</Assembly>");
writer.WriteLine("</ShouldIgnoreTestAssembly>");
writer.WriteLine(string.Format("<IgnoreFile>{0}</IgnoreFile>", file));
writer.WriteLine("<changedetectiondelay>800</changedetectiondelay>");
writer.WriteLine("<SomCustomStuff>modified content</SomCustomStuff>");
writer.WriteLine("<AnotherSetting>something</AnotherSetting>");
writer.WriteLine("</configuration>");
}
}
}
}
| |
// 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 AddScalarSingle()
{
var test = new SimpleBinaryOpTest__AddScalarSingle();
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__AddScalarSingle
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[ElementCount];
private static Single[] _data2 = new Single[ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single> _dataTable;
static SimpleBinaryOpTest__AddScalarSingle()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__AddScalarSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse.AddScalar(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse.AddScalar(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse.AddScalar(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse).GetMethod(nameof(Sse.AddScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse).GetMethod(nameof(Sse.AddScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse).GetMethod(nameof(Sse.AddScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse.AddScalar(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.AddScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.AddScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.AddScalar(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AddScalarSingle();
var result = Sse.AddScalar(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse.AddScalar(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, 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 = "")
{
Single[] inArray1 = new Single[ElementCount];
Single[] inArray2 = new Single[ElementCount];
Single[] outArray = new Single[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.AddScalar)}<Single>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
#if BIT64
using nuint = System.UInt64;
using nint = System.Int64;
#else
using nuint = System.UInt32;
using nint = System.Int32;
#endif
//
// The implementations of most the methods in this file are provided as intrinsics.
// In CoreCLR, the body of the functions are replaced by the EE with unsafe code. See see getILIntrinsicImplementationForUnsafe for details.
// In CoreRT, see Internal.IL.Stubs.UnsafeIntrinsics for details.
//
namespace Internal.Runtime.CompilerServices
{
//
// Subsetted clone of System.Runtime.CompilerServices.Unsafe for internal runtime use.
// Keep in sync with https://github.com/dotnet/corefx/tree/master/src/System.Runtime.CompilerServices.Unsafe.
//
/// <summary>
/// For internal use only. Contains generic, low-level functionality for manipulating pointers.
/// </summary>
[CLSCompliant(false)]
public static unsafe class Unsafe
{
/// <summary>
/// Returns a pointer to the given by-ref parameter.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void* AsPointer<T>(ref T value)
{
throw new PlatformNotSupportedException();
// ldarg.0
// conv.u
// ret
}
/// <summary>
/// Returns the size of an object of the given type parameter.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int SizeOf<T>()
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
#endif
throw new PlatformNotSupportedException();
// sizeof !!0
// ret
}
/// <summary>
/// Casts the given object to the specified type, performs no dynamic type checking.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T As<T>(object value) where T : class
{
throw new PlatformNotSupportedException();
// ldarg.0
// ret
}
/// <summary>
/// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo"/>.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref TTo As<TFrom, TTo>(ref TFrom source)
{
throw new PlatformNotSupportedException();
// ldarg.0
// ret
}
/// <summary>
/// Adds an element offset to the given reference.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T Add<T>(ref T source, int elementOffset)
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
throw new PlatformNotSupportedException();
#else
return ref AddByteOffset(ref source, (IntPtr)(elementOffset * (nint)SizeOf<T>()));
#endif
}
/// <summary>
/// Adds an element offset to the given reference.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T Add<T>(ref T source, IntPtr elementOffset)
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
throw new PlatformNotSupportedException();
#else
return ref AddByteOffset(ref source, (IntPtr)((nint)elementOffset * (nint)SizeOf<T>()));
#endif
}
/// <summary>
/// Adds an element offset to the given pointer.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void* Add<T>(void* source, int elementOffset)
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
throw new PlatformNotSupportedException();
#else
return (byte*)source + (elementOffset * (nint)SizeOf<T>());
#endif
}
/// <summary>
/// Adds an element offset to the given reference.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static ref T AddByteOffset<T>(ref T source, nuint byteOffset)
{
return ref AddByteOffset(ref source, (IntPtr)(void*)byteOffset);
}
/// <summary>
/// Determines whether the specified references point to the same location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool AreSame<T>(ref T left, ref T right)
{
throw new PlatformNotSupportedException();
// ldarg.0
// ldarg.1
// ceq
// ret
}
/// <summary>
/// Determines whether the memory address referenced by <paramref name="left"/> is greater than
/// the memory address referenced by <paramref name="right"/>.
/// </summary>
/// <remarks>
/// This check is conceptually similar to "(void*)(&left) > (void*)(&right)".
/// </remarks>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
{
throw new PlatformNotSupportedException();
// ldarg.0
// ldarg.1
// cgt.un
// ret
}
/// <summary>
/// Determines whether the memory address referenced by <paramref name="left"/> is less than
/// the memory address referenced by <paramref name="right"/>.
/// </summary>
/// <remarks>
/// This check is conceptually similar to "(void*)(&left) < (void*)(&right)".
/// </remarks>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsAddressLessThan<T>(ref T left, ref T right)
{
throw new PlatformNotSupportedException();
// ldarg.0
// ldarg.1
// clt.un
// ret
}
/// <summary>
/// Initializes a block of memory at the given location with a given initial value
/// without assuming architecture dependent alignment of the address.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
{
for (uint i = 0; i < byteCount; i++)
AddByteOffset(ref startAddress, i) = value;
}
/// <summary>
/// Reads a value of type <typeparamref name="T"/> from the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ReadUnaligned<T>(void* source)
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
throw new PlatformNotSupportedException();
#else
return Unsafe.As<byte, T>(ref *(byte*)source);
#endif
}
/// <summary>
/// Reads a value of type <typeparamref name="T"/> from the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T ReadUnaligned<T>(ref byte source)
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
throw new PlatformNotSupportedException();
#else
return Unsafe.As<byte, T>(ref source);
#endif
}
/// <summary>
/// Writes a value of type <typeparamref name="T"/> to the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteUnaligned<T>(void* destination, T value)
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
throw new PlatformNotSupportedException();
#else
Unsafe.As<byte, T>(ref *(byte*)destination) = value;
#endif
}
/// <summary>
/// Writes a value of type <typeparamref name="T"/> to the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteUnaligned<T>(ref byte destination, T value)
{
#if CORECLR
typeof(T).ToString(); // Type token used by the actual method body
throw new PlatformNotSupportedException();
#else
Unsafe.As<byte, T>(ref destination) = value;
#endif
}
/// <summary>
/// Adds an element offset to the given reference.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset)
{
// This method is implemented by the toolchain
throw new PlatformNotSupportedException();
// ldarg.0
// ldarg.1
// add
// ret
}
/// <summary>
/// Reads a value of type <typeparamref name="T"/> from the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Read<T>(void* source)
{
return Unsafe.As<byte, T>(ref *(byte*)source);
}
/// <summary>
/// Reads a value of type <typeparamref name="T"/> from the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Read<T>(ref byte source)
{
return Unsafe.As<byte, T>(ref source);
}
/// <summary>
/// Writes a value of type <typeparamref name="T"/> to the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write<T>(void* destination, T value)
{
Unsafe.As<byte, T>(ref *(byte*)destination) = value;
}
/// <summary>
/// Writes a value of type <typeparamref name="T"/> to the given location.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write<T>(ref byte destination, T value)
{
Unsafe.As<byte, T>(ref destination) = value;
}
/// <summary>
/// Reinterprets the given location as a reference to a value of type <typeparamref name="T"/>.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T AsRef<T>(void* source)
{
return ref Unsafe.As<byte, T>(ref *(byte*)source);
}
/// <summary>
/// Reinterprets the given location as a reference to a value of type <typeparamref name="T"/>.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T AsRef<T>(in T source)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Determines the byte offset from origin to target from the given references.
/// </summary>
[Intrinsic]
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IntPtr ByteOffset<T>(ref T origin, ref T target)
{
throw new PlatformNotSupportedException();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
namespace System.IO.Compression
{
/// <summary>
/// Provides a wrapper around the ZLib decompression API
/// </summary>
internal sealed class Inflater : IDisposable
{
private bool _finished; // Whether the end of the stream has been reached
private bool _isDisposed; // Prevents multiple disposals
private ZLibNative.ZLibStreamHandle _zlibStream; // The handle to the primary underlying zlib stream
private GCHandle _inputBufferHandle; // The handle to the buffer that provides input to _zlibStream
private readonly object _syncLock = new object(); // Used to make writing to unmanaged structures atomic
private const int minWindowBits = -15; // WindowBits must be between -8..-15 to ignore the header, 8..15 for
private const int maxWindowBits = 47; // zlib headers, 24..31 for GZip headers, or 40..47 for either Zlib or GZip
#region Exposed Members
/// <summary>
/// Initialized the Inflater with the given windowBits size
/// </summary>
internal Inflater(int windowBits)
{
Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits);
_finished = false;
_isDisposed = false;
InflateInit(windowBits);
}
public int AvailableOutput
{
get
{
return (int)_zlibStream.AvailOut;
}
}
/// <summary>
/// Returns true if the end of the stream has been reached.
/// </summary>
public bool Finished()
{
return _finished && _zlibStream.AvailIn == 0 && _zlibStream.AvailOut == 0;
}
public unsafe bool Inflate(out byte b)
{
fixed (byte* bufPtr = &b)
{
int bytesRead = InflateVerified(bufPtr, 1);
Debug.Assert(bytesRead == 0 || bytesRead == 1);
return bytesRead != 0;
}
}
public unsafe int Inflate(byte[] bytes, int offset, int length)
{
// If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read.
if (length == 0)
return 0;
Debug.Assert(null != bytes, "Can't pass in a null output buffer!");
fixed (byte* bufPtr = bytes)
{
return InflateVerified(bufPtr + offset, length);
}
}
public unsafe int InflateVerified(byte* bufPtr, int length)
{
// State is valid; attempt inflation
try
{
int bytesRead;
if (ReadInflateOutput(bufPtr, length, ZLibNative.FlushCode.NoFlush, out bytesRead) == ZLibNative.ErrorCode.StreamEnd)
{
_finished = true;
}
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necessary:
if (0 == _zlibStream.AvailIn && _inputBufferHandle.IsAllocated)
{
DeallocateInputBufferHandle();
}
}
}
public bool NeedsInput()
{
return _zlibStream.AvailIn == 0;
}
public void SetInput(byte[] inputBuffer, int startIndex, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(inputBuffer != null);
Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length);
Debug.Assert(!_inputBufferHandle.IsAllocated);
if (0 == count)
return;
lock (_syncLock)
{
_inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned);
_zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex;
_zlibStream.AvailIn = (uint)count;
_finished = false;
}
}
[SecuritySafeCritical]
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
if (_inputBufferHandle.IsAllocated)
DeallocateInputBufferHandle();
_isDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Inflater()
{
Dispose(false);
}
#endregion
#region Helper Methods
/// <summary>
/// Creates the ZStream that will handle inflation
/// </summary>
[SecuritySafeCritical]
private void InflateInit(int windowBits)
{
ZLibNative.ErrorCode error;
try
{
error = ZLibNative.CreateZLibStreamForInflate(out _zlibStream, windowBits);
}
catch (Exception exception) // could not load the ZLib dll
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, exception);
}
switch (error)
{
case ZLibNative.ErrorCode.Ok: // Successful initialization
return;
case ZLibNative.ErrorCode.MemError: // Not enough memory
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.VersionError: //zlib library is incompatible with the version assumed
throw new ZLibException(SR.ZLibErrorVersionMismatch, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.StreamError: // Parameters are invalid
throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
}
}
/// <summary>
/// Wrapper around the ZLib inflate function, configuring the stream appropriately.
/// </summary>
private unsafe ZLibNative.ErrorCode ReadInflateOutput(byte* bufPtr, int length, ZLibNative.FlushCode flushCode, out int bytesRead)
{
lock (_syncLock)
{
_zlibStream.NextOut = (IntPtr)bufPtr;
_zlibStream.AvailOut = (uint)length;
ZLibNative.ErrorCode errC = Inflate(flushCode);
bytesRead = length - (int)_zlibStream.AvailOut;
return errC;
}
}
/// <summary>
/// Wrapper around the ZLib inflate function
/// </summary>
[SecuritySafeCritical]
private ZLibNative.ErrorCode Inflate(ZLibNative.FlushCode flushCode)
{
ZLibNative.ErrorCode errC;
try
{
errC = _zlibStream.Inflate(flushCode);
}
catch (Exception cause) // could not load the Zlib DLL correctly
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZLibNative.ErrorCode.Ok: // progress has been made inflating
case ZLibNative.ErrorCode.StreamEnd: // The end of the input stream has been reached
return errC;
case ZLibNative.ErrorCode.BufError: // No room in the output buffer - inflate() can be called again with more space to continue
return errC;
case ZLibNative.ErrorCode.MemError: // Not enough memory to complete the operation
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.DataError: // The input data was corrupted (input stream not conforming to the zlib format or incorrect check value)
throw new InvalidDataException(SR.UnsupportedCompression);
case ZLibNative.ErrorCode.StreamError: //the stream structure was inconsistent (for example if next_in or next_out was NULL),
throw new ZLibException(SR.ZLibErrorInconsistentStream, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
}
}
/// <summary>
/// Frees the GCHandle being used to store the input buffer
/// </summary>
private void DeallocateInputBufferHandle()
{
Debug.Assert(_inputBufferHandle.IsAllocated);
lock (_syncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
_inputBufferHandle.Free();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Compression.Tests
{
public class BrotliStreamTests
{
static string brTestFile(string fileName) => Path.Combine("BrotliTestData", fileName);
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void GetSetReadWriteTimeout()
{
int sec = 10;
var writeStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(writeStream, CompressionMode.Compress);
brotliCompressStream.ReadTimeout = sec;
brotliCompressStream.WriteTimeout = sec;
Assert.Equal(brotliCompressStream.ReadTimeout, sec);
Assert.Equal(brotliCompressStream.WriteTimeout, sec);
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void BaseStreamCompress()
{
var writeStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(writeStream, CompressionMode.Compress);
writeStream.Dispose();
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void BaseStreamDecompress()
{
var writeStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(writeStream, CompressionMode.Decompress);
writeStream.Dispose();
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void DecompressCanRead()
{
var memoryInputStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Decompress);
Assert.True(brotliCompressStream.CanRead);
brotliCompressStream.Dispose();
Assert.False(brotliCompressStream.CanRead);
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void CompressCanWrite()
{
var memoryInputStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress);
Assert.True(brotliCompressStream.CanWrite);
brotliCompressStream.Dispose();
Assert.False(brotliCompressStream.CanWrite);
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void CanDisposeBaseStream()
{
var memoryInputStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress);
memoryInputStream.Dispose(); // This would throw if this was invalid
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void CanDisposeBrotliStream()
{
var memoryInputStream = new MemoryStream();
using (var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress))
{
brotliCompressStream.Dispose();
Assert.Throws<ObjectDisposedException>( delegate { brotliCompressStream.CopyTo(memoryInputStream); });
brotliCompressStream.Dispose(); // Should be a no-op
}
memoryInputStream = new MemoryStream();
using (var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Decompress))
{
brotliCompressStream.Dispose();
Assert.Throws<ObjectDisposedException>(delegate { brotliCompressStream.CopyTo(memoryInputStream); }); // Base Stream should be null after dispose
brotliCompressStream.Dispose(); // Should be a no-op
}
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void Flush()
{
var memoryInputStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress);
brotliCompressStream.Flush();
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void DoubleFlush()
{
var memoryInputStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress);
brotliCompressStream.Flush();
brotliCompressStream.Flush();
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void DoubleDispose()
{
var memoryInputStream = new MemoryStream();
using (var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress))
{
brotliCompressStream.Dispose();
brotliCompressStream.Dispose();
}
using (var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Decompress))
{
brotliCompressStream.Dispose();
brotliCompressStream.Dispose();
}
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void FlushThenDispose()
{
var memoryInputStream = new MemoryStream();
using (var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress))
{
brotliCompressStream.Flush();
brotliCompressStream.Dispose();
}
using (var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Decompress))
{
brotliCompressStream.Flush();
brotliCompressStream.Dispose();
}
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void TestSeekMethobrotliCompressStreamDecompress()
{
var memoryInputStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Decompress);
Assert.False(brotliCompressStream.CanSeek, "CanSeek should be false");
Assert.Throws<NotSupportedException>(delegate { long value = brotliCompressStream.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = brotliCompressStream.Position; });
Assert.Throws<NotSupportedException>(delegate { brotliCompressStream.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { brotliCompressStream.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { brotliCompressStream.Seek(100L, SeekOrigin.Begin); });
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void TestSeekMethobrotliCompressStreamCompress()
{
var memoryInputStream = new MemoryStream();
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Compress);
Assert.False(brotliCompressStream.CanSeek, "CanSeek should be false");
Assert.Throws<NotSupportedException>(delegate { long value = brotliCompressStream.Length; });
Assert.Throws<NotSupportedException>(delegate { long value = brotliCompressStream.Position; });
Assert.Throws<NotSupportedException>(delegate { brotliCompressStream.Position = 100L; });
Assert.Throws<NotSupportedException>(delegate { brotliCompressStream.SetLength(100L); });
Assert.Throws<NotSupportedException>(delegate { brotliCompressStream.Seek(100L, SeekOrigin.Begin); });
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void CanReadBaseStreamAfterDispose()
{
var memoryInputStream = new MemoryStream(File.ReadAllBytes(brTestFile("BrotliTest.txt.br")));
var brotliCompressStream = new BrotliStream(memoryInputStream, CompressionMode.Decompress, true);
var baseStream = memoryInputStream;
brotliCompressStream.Dispose();
int size = 1024;
byte[] bytes = new byte[size];
baseStream.Read(bytes, 0, size); // This will throw if the underlying stream is not writable as expected
}
[Fact(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
public void ReadWriteArgumentValidation()
{
using (var brotliCompressStream = new BrotliStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<ArgumentNullException>(() => brotliCompressStream.Write(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Write(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Write(new byte[1], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Write(new byte[1], 0, 2));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Write(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => brotliCompressStream.Read(new byte[1], 0, 1));
brotliCompressStream.Write(new byte[1], 0, 0);
}
using (var brotliCompressStream = new BrotliStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>(() => brotliCompressStream.Read(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Read(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Read(new byte[1], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Read(new byte[1], 0, 2));
Assert.Throws<ArgumentOutOfRangeException>(() => brotliCompressStream.Read(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => brotliCompressStream.Write(new byte[1], 0, 1));
var data = new byte[1] { 42 };
Assert.Equal(0, brotliCompressStream.Read(data, 0, 0));
Assert.Equal(42, data[0]);
}
}
[Theory(Skip = "Fails in VS - System.BadImageFormatException : An attempt was made to load a program with an incorrect format.")]
[InlineData(1, 5)]
[InlineData(1023, 1023 * 10)]
[InlineData(1024 * 1024, 1024 * 1024)]
public void RoundtripCompressDecompress(int chunkSize, int totalSize)
{
byte[] data = new byte[totalSize];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = new BrotliStream(compressed, CompressionMode.Compress, true))
{
for (int i = 0; i < data.Length; i += chunkSize)
{
compressor.Write(data, i, chunkSize);
}
compressor.Dispose();
}
compressed.Position = 0;
ValidateCompressedData(chunkSize, compressed.ToArray(), data);
compressed.Dispose();
}
private void ValidateCompressedData(int chunkSize, byte[] compressedData, byte[] expected)
{
MemoryStream compressed = new MemoryStream(compressedData);
using (MemoryStream decompressed = new MemoryStream())
using (var decompressor = new BrotliStream(compressed, CompressionMode.Decompress, true))
{
decompressor.CopyTo(decompressed, expected.Length);
Assert.Equal<byte>(expected, decompressed.ToArray());
}
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using UnitTests.GrainInterfaces;
using Xunit;
namespace UnitTests.Grains
{
internal class SimpleActivateDeactivateTestGrain : Grain, ISimpleActivateDeactivateTestGrain
{
private ILogger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public SimpleActivateDeactivateTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override async Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingActivate = true;
await watcher.RecordActivateCall(Data.ActivationId.ToString());
Assert.True(doingActivate, "Activate method still running");
doingActivate = false;
}
public override async Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingDeactivate = true;
await watcher.RecordDeactivateCall(Data.ActivationId.ToString());
Assert.True(doingDeactivate, "Deactivate method still running");
doingDeactivate = false;
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return Task.CompletedTask;
}
}
internal class TailCallActivateDeactivateTestGrain : Grain, ITailCallActivateDeactivateTestGrain
{
private ILogger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public TailCallActivateDeactivateTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingActivate = true;
return watcher.RecordActivateCall(Data.ActivationId.ToString())
.ContinueWith((Task t) =>
{
Assert.False(t.IsFaulted, "RecordActivateCall failed");
Assert.True(doingActivate, "Doing Activate");
doingActivate = false;
});
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingDeactivate = true;
return watcher.RecordDeactivateCall(Data.ActivationId.ToString())
.ContinueWith((Task t) =>
{
Assert.False(t.IsFaulted, "RecordDeactivateCall failed");
Assert.True(doingDeactivate, "Doing Deactivate");
doingDeactivate = false;
});
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return Task.CompletedTask;
}
}
internal class LongRunningActivateDeactivateTestGrain : Grain, ILongRunningActivateDeactivateTestGrain
{
private ILogger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public LongRunningActivateDeactivateTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override async Task OnActivateAsync()
{
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Not doing Activate yet");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingActivate = true;
logger.Info("OnActivateAsync");
// Spawn Task to run on default .NET thread pool
var task = Task.Factory.StartNew(() =>
{
logger.Info("Started-OnActivateAsync-SubTask");
Assert.True(TaskScheduler.Current == TaskScheduler.Default,
"Running under default .NET Task scheduler");
Assert.True(doingActivate, "Still doing Activate in Sub-Task");
logger.Info("Finished-OnActivateAsync-SubTask");
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
await task;
logger.Info("Started-OnActivateAsync");
await watcher.RecordActivateCall(Data.ActivationId.ToString());
Assert.True(doingActivate, "Doing Activate");
logger.Info("OnActivateAsync-Sleep");
Thread.Sleep(TimeSpan.FromSeconds(1));
Assert.True(doingActivate, "Still doing Activate after Sleep");
logger.Info("Finished-OnActivateAsync");
doingActivate = false;
}
public override async Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
Assert.False(doingActivate, "Not doing Activate yet");
Assert.False(doingDeactivate, "Not doing Deactivate yet");
doingDeactivate = true;
logger.Info("Started-OnDeactivateAsync");
await watcher.RecordDeactivateCall(Data.ActivationId.ToString());
Assert.True(doingDeactivate, "Doing Deactivate");
logger.Info("OnDeactivateAsync-Sleep");
Thread.Sleep(TimeSpan.FromSeconds(1));
logger.Info("Finished-OnDeactivateAsync");
doingDeactivate = false;
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return Task.CompletedTask;
}
}
internal class TaskActionActivateDeactivateTestGrain : Grain, ITaskActionActivateDeactivateTestGrain
{
private ILogger logger;
private IActivateDeactivateWatcherGrain watcher;
private bool doingActivate;
private bool doingDeactivate;
public TaskActionActivateDeactivateTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override async Task OnActivateAsync()
{
Assert.NotNull(TaskScheduler.Current);
Assert.NotEqual(TaskScheduler.Current, TaskScheduler.Default);
var startMe =
new Task(
() =>
{
Assert.NotNull(TaskScheduler.Current);
Assert.NotEqual(TaskScheduler.Current, TaskScheduler.Default);
logger.Info("OnActivateAsync");
watcher = GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
Assert.False(doingActivate, "Not doing Activate");
Assert.False(doingDeactivate, "Not doing Deactivate");
doingActivate = true;
});
// we want to use Task.ContinueWith with an async lambda, an explicitly typed variable is required to avoid
// writing code that doesn't do what i think it is doing.
Func<Task> asyncCont =
async () =>
{
Assert.NotNull(TaskScheduler.Current);
Assert.NotEqual(TaskScheduler.Current, TaskScheduler.Default);
logger.Info("Started-OnActivateAsync");
Assert.True(doingActivate, "Doing Activate 1");
Assert.False(doingDeactivate, "Not doing Deactivate");
try
{
logger.Info("Calling RecordActivateCall");
await watcher.RecordActivateCall(Data.ActivationId.ToString());
logger.Info("Returned from calling RecordActivateCall");
}
catch (Exception exc)
{
var msg = "RecordActivateCall failed with error " + exc;
logger.Error(0, msg);
Assert.True(false, msg);
}
Assert.True(doingActivate, "Doing Activate 2");
Assert.False(doingDeactivate, "Not doing Deactivate");
await Task.Delay(TimeSpan.FromSeconds(1));
doingActivate = false;
logger.Info("Finished-OnActivateAsync");
};
var awaitMe = startMe.ContinueWith(_ => asyncCont()).Unwrap();
startMe.Start();
await awaitMe;
}
public override Task OnDeactivateAsync()
{
Task.Factory.StartNew(() => logger.Info("OnDeactivateAsync"));
Assert.False(doingActivate, "Not doing Activate");
Assert.False(doingDeactivate, "Not doing Deactivate");
doingDeactivate = true;
logger.Info("Started-OnDeactivateAsync");
return watcher.RecordDeactivateCall(Data.ActivationId.ToString())
.ContinueWith((Task t) =>
{
Assert.False(t.IsFaulted, "RecordDeactivateCall failed");
Assert.True(doingDeactivate, "Doing Deactivate");
Thread.Sleep(TimeSpan.FromSeconds(1));
doingDeactivate = false;
})
.ContinueWith((Task t) => logger.Info("Finished-OnDeactivateAsync"),
TaskContinuationOptions.ExecuteSynchronously);
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
return Task.FromResult(Data.ActivationId.ToString());
}
public Task DoDeactivate()
{
logger.Info("DoDeactivate");
Assert.False(doingActivate, "Activate method should have finished");
Assert.False(doingDeactivate, "Deactivate method should not be running yet");
DeactivateOnIdle();
return Task.CompletedTask;
}
}
public class BadActivateDeactivateTestGrain : Grain, IBadActivateDeactivateTestGrain
{
private ILogger logger;
public BadActivateDeactivateTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
throw new ApplicationException("Thrown from Application-OnActivateAsync");
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
throw new ApplicationException("Thrown from Application-OnDeactivateAsync");
}
public Task ThrowSomething()
{
logger.Info("ThrowSomething");
throw new InvalidOperationException("Exception should have been thrown from Activate");
}
public Task<long> GetKey()
{
logger.Info("GetKey");
//return this.GetPrimaryKeyLong();
throw new InvalidOperationException("Exception should have been thrown from Activate");
}
}
internal class BadConstructorTestGrain : Grain, IBadConstructorTestGrain
{
public BadConstructorTestGrain()
{
throw new ApplicationException("Thrown from Constructor");
}
public override Task OnActivateAsync()
{
throw new NotImplementedException("OnActivateAsync should not have been called");
}
public override Task OnDeactivateAsync()
{
throw new NotImplementedException("OnDeactivateAsync() should not have been called");
}
public Task<string> DoSomething()
{
throw new NotImplementedException("DoSomething should not have been called");
}
}
internal class DeactivatingWhileActivatingTestGrain : Grain, IDeactivatingWhileActivatingTestGrain
{
private ILogger logger;
public DeactivatingWhileActivatingTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
logger.Info("OnActivateAsync");
this.DeactivateOnIdle();
return Task.CompletedTask;
}
public override Task OnDeactivateAsync()
{
logger.Info("OnDeactivateAsync");
return Task.CompletedTask;
}
public Task<string> DoSomething()
{
logger.Info("DoSomething");
throw new NotImplementedException("DoSomething should not have been called");
}
}
internal class CreateGrainReferenceTestGrain : Grain, ICreateGrainReferenceTestGrain
{
private ILogger logger;
//private IEchoGrain orleansManagedGrain;
private ITestGrain grain;
public CreateGrainReferenceTestGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
grain = GrainFactory.GetGrain<ITestGrain>(1);
logger.Info("OnActivateAsync");
grain = GrainFactory.GetGrain<ITestGrain>(1);
return Task.CompletedTask;
}
public async Task<string> DoSomething()
{
logger.Info("DoSomething");
var guid = Guid.NewGuid();
await grain.SetLabel(guid.ToString());
var label = await grain.GetLabel();
if (string.IsNullOrEmpty(label))
{
throw new ArgumentException("Bad data: Null label returned");
}
return Data.ActivationId.ToString();
}
public async Task ForwardCall(IBadActivateDeactivateTestGrain otherGrain)
{
logger.Info("ForwardCall to " + otherGrain);
await otherGrain.ThrowSomething();
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
namespace Mosa.ClassLib
{
/// <summary>
/// Implements a Red Black Tree list
/// </summary>
/// <typeparam name="K"></typeparam>
/// <typeparam name="T"></typeparam>
public class RedBlackTree<K, T> where K : System.IComparable
{
/// <summary>
///
/// </summary>
protected enum Color
{
/// <summary>
///
/// </summary>
Red = 1,
/// <summary>
///
/// </summary>
Black = 0
};
/// <summary>
///
/// </summary>
/// <typeparam name="X"></typeparam>
/// <typeparam name="Y"></typeparam>
protected class RedBlackTreeNode<X, Y> where X : System.IComparable
{
/// <summary>
///
/// </summary>
public Color color;
/// <summary>
///
/// </summary>
public Y data;
/// <summary>
///
/// </summary>
public X key;
/// <summary>
///
/// </summary>
public RedBlackTreeNode<X, Y> parent;
/// <summary>
///
/// </summary>
public RedBlackTreeNode<X, Y> left;
/// <summary>
///
/// </summary>
public RedBlackTreeNode<X, Y> right;
/// <summary>
/// Initializes a new instance
/// </summary>
/// <param name="key">The key.</param>
/// <param name="data">The data.</param>
/// <param name="color">The color.</param>
public RedBlackTreeNode(X key, Y data, Color color)
{
this.key = key;
this.color = color;
this.data = data;
}
}
/// <summary>
///
/// </summary>
protected RedBlackTreeNode<K, T> root;
/// <summary>
///
/// </summary>
protected uint size = 0;
/// <summary>
/// Gets the size.
/// </summary>
/// <value>The size.</value>
public uint Size { get { return size; } }
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
root = null;
size = 0;
}
/// <summary>
/// Determines whether [contains] [the specified key].
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified key]; otherwise, <c>false</c>.
/// </returns>
protected bool Contains(K key)
{
RedBlackTreeNode<K, T> cur = root;
while (cur != null)
{
int cmp = key.CompareTo(cur.key);
//int cmp = (cur.key == key) ? 0 : (cur.key < key ? -1, 1);
if (cmp == 0)
return true;
if (cmp < 0) /* less than */
cur = cur.left;
else
cur = cur.right;
}
return false;
}
/// <summary>
/// Inserts the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="data">The data.</param>
public void Insert(K key, T data)
{
RedBlackTreeNode<K, T> newnode = new RedBlackTree<K, T>.RedBlackTreeNode<K, T>(key, data, Color.Red);
if (root == null)
root = newnode;
else
Insert(root, newnode); // inserts into the binary tree
InsertCase1(newnode);
size++;
}
/// <summary>
/// Deletes the specified key.
/// </summary>
/// <param name="key">The key.</param>
public void Delete(K key)
{
RedBlackTreeNode<K, T> deletenode = Find(key);
if (deletenode == null)
return; // node was not found; exception in the future?
if (IsLeaf(deletenode))
root = null; // was the only node in the tree
else
DeleteOneChild(deletenode);
size--;
}
/// <summary>
/// Finds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
protected RedBlackTreeNode<K, T> Find(K key)
{
RedBlackTreeNode<K, T> cur = root;
while (cur != null)
{
int cmp = key.CompareTo(cur.key);
if (cmp == 0)
return cur;
if (cmp < 0) /* less than */
cur = cur.left;
else
cur = cur.right;
}
return null;
}
/// <summary>
/// Inserts the specified parent.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="newnode">The newnode.</param>
protected void Insert(RedBlackTreeNode<K, T> parent, RedBlackTreeNode<K, T> newnode)
{
int cmp = newnode.key.CompareTo(parent.key);
if (cmp < 0) /* less than */
{
if (parent.left == null)
{
newnode.parent = parent;
parent.left = newnode;
}
else
Insert(parent.left, newnode);
}
else
if (parent.right == null)
{
newnode.parent = parent;
parent.right = newnode;
}
else
Insert(parent.right, newnode);
}
/// <summary>
/// Gets the grandparent.
/// </summary>
/// <param name="n">The n.</param>
/// <returns></returns>
protected RedBlackTreeNode<K, T> GetGrandparent(RedBlackTreeNode<K, T> n)
{
if ((n != null) && (n.parent != null))
return n.parent.parent;
else
return null;
}
/// <summary>
/// Gets the uncle.
/// </summary>
/// <param name="n">The n.</param>
/// <returns></returns>
protected RedBlackTreeNode<K, T> GetUncle(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> g = GetGrandparent(n);
if (g == null)
return null;
if (n.parent == g.left)
return g.right;
else
return g.left;
}
/// <summary>
/// Rotates the right.
/// </summary>
/// <param name="q">The q.</param>
protected void RotateRight(RedBlackTreeNode<K, T> q)
{
RedBlackTreeNode<K, T> r = q.parent;
RedBlackTreeNode<K, T> p = q.left;
RedBlackTreeNode<K, T> b = p.right;
if (r == null)
root = p;
else
if (r.left == q)
r.left = p;
else
r.right = p;
p.parent = r;
p.right = q;
q.left = b;
q.parent = p;
if (b != null)
b.parent = q;
}
/// <summary>
/// Rotates the left.
/// </summary>
/// <param name="p">The p.</param>
protected void RotateLeft(RedBlackTreeNode<K, T> p)
{
RedBlackTreeNode<K, T> r = p.parent;
RedBlackTreeNode<K, T> q = p.right;
RedBlackTreeNode<K, T> b = q.left;
if (r == null)
root = q;
else
if (r.left == p)
r.left = q;
else
r.right = q;
q.parent = r;
q.left = p;
p.right = b;
p.parent = q;
if (b != null)
b.parent = p;
}
/// <summary>
/// Determines whether the specified n is leaf.
/// </summary>
/// <param name="n">The n.</param>
/// <returns>
/// <c>true</c> if the specified n is leaf; otherwise, <c>false</c>.
/// </returns>
protected bool IsLeaf(RedBlackTreeNode<K, T> n)
{
return ((n.left == null) && (n.right == null));
}
/// <summary>
/// Replaces the node.
/// </summary>
/// <param name="n">The n.</param>
/// <param name="c">The c.</param>
protected void ReplaceNode(RedBlackTreeNode<K, T> n, RedBlackTreeNode<K, T> c)
{
if (n.parent.left == n)
n.parent.left = c;
else
n.parent.right = c;
c.parent = n.parent;
}
/// <summary>
/// Inserts the case1.
/// </summary>
/// <param name="n">The n.</param>
protected void InsertCase1(RedBlackTreeNode<K, T> n)
{
if (n.parent == null)
n.color = Color.Black;
else
InsertCase2(n);
}
/// <summary>
/// Inserts the case2.
/// </summary>
/// <param name="n">The n.</param>
protected void InsertCase2(RedBlackTreeNode<K, T> n)
{
if (n.parent.color == Color.Black)
return;
else
InsertCase3(n);
}
/// <summary>
/// Inserts the case3.
/// </summary>
/// <param name="n">The n.</param>
protected void InsertCase3(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> u = GetUncle(n);
RedBlackTreeNode<K, T> g;
if ((u != null) && (u.color == Color.Red))
{
n.parent.color = Color.Black;
u.color = Color.Black;
g = GetGrandparent(n);
g.color = Color.Red;
InsertCase1(g);
}
else
{
InsertCase4(n);
}
}
/// <summary>
/// Inserts the case4.
/// </summary>
/// <param name="n">The n.</param>
protected void InsertCase4(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> g = GetGrandparent(n);
if ((n == n.parent.right) && (n.parent == g.left))
{
RotateLeft(n.parent);
n = n.left;
}
else if ((n == n.parent.left) && (n.parent == g.right))
{
RotateRight(n.parent);
n = n.right;
}
InsertCase5(n);
}
/// <summary>
/// Inserts the case5.
/// </summary>
/// <param name="n">The n.</param>
protected void InsertCase5(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> g = GetGrandparent(n);
n.parent.color = Color.Black;
g.color = Color.Red;
if ((n == n.parent.left) && (n.parent == g.left))
{
RotateRight(g);
}
else
{
RotateLeft(g);
}
}
/// <summary>
/// Gets the sibling.
/// </summary>
/// <param name="n">The n.</param>
/// <returns></returns>
protected RedBlackTreeNode<K, T> GetSibling(RedBlackTreeNode<K, T> n)
{
if (n == n.parent.left)
return n.parent.right;
else
return n.parent.left;
}
/// <summary>
/// Deletes the one child.
/// </summary>
/// <param name="n">The n.</param>
protected void DeleteOneChild(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> child = IsLeaf(n.right) ? n.left : n.right;
ReplaceNode(n, child);
if (n.color == Color.Black)
{
if (child.color == Color.Red)
child.color = Color.Black;
else
DeleteCase1(child);
}
}
/// <summary>
/// Deletes the case1.
/// </summary>
/// <param name="n">The n.</param>
protected void DeleteCase1(RedBlackTreeNode<K, T> n)
{
if (n.parent != null)
DeleteCase2(n);
}
/// <summary>
/// Deletes the case2.
/// </summary>
/// <param name="n">The n.</param>
protected void DeleteCase2(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> s = GetSibling(n);
if (s.color == Color.Red)
{
n.parent.color = Color.Red;
s.color = Color.Black;
if (n == n.parent.left)
RotateLeft(n.parent);
else
RotateRight(n.parent);
}
DeleteCase3(n);
}
/// <summary>
/// Deletes the case3.
/// </summary>
/// <param name="n">The n.</param>
protected void DeleteCase3(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> s = GetSibling(n);
if ((n.parent.color == Color.Black) &&
(s.color == Color.Black) &&
(s.left.color == Color.Black) &&
(s.right.color == Color.Black))
{
s.color = Color.Red;
DeleteCase1(n.parent);
}
else
DeleteCase4(n);
}
/// <summary>
/// Deletes the case4.
/// </summary>
/// <param name="n">The n.</param>
protected void DeleteCase4(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> s = GetSibling(n);
if ((n.parent.color == Color.Red) &&
(s.color == Color.Black) &&
(s.left.color == Color.Black) &&
(s.right.color == Color.Black))
{
s.color = Color.Red;
n.parent.color = Color.Black;
}
else
DeleteCase5(n);
}
/// <summary>
/// Deletes the case5.
/// </summary>
/// <param name="n">The n.</param>
protected void DeleteCase5(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> s = GetSibling(n);
if ((n == n.parent.left) &&
(s.color == Color.Black) &&
(s.left.color == Color.Red) &&
(s.right.color == Color.Black))
{
s.color = Color.Red;
s.left.color = Color.Black;
RotateRight(s);
}
else if ((n == n.parent.right) &&
(s.color == Color.Black) &&
(s.right.color == Color.Red) &&
(s.left.color == Color.Black))
{
s.color = Color.Red;
s.right.color = Color.Black;
RotateLeft(s);
}
DeleteCase6(n);
}
/// <summary>
/// Deletes the case6.
/// </summary>
/// <param name="n">The n.</param>
protected void DeleteCase6(RedBlackTreeNode<K, T> n)
{
RedBlackTreeNode<K, T> s = GetSibling(n);
s.color = n.parent.color;
n.parent.color = Color.Black;
if (n == n.parent.left)
{
s.right.color = Color.Black;
RotateLeft(n.parent);
}
else
{
s.left.color = Color.Black;
RotateRight(n.parent);
}
}
/// <summary>
/// Finds the min.
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
protected RedBlackTreeNode<K, T> FindMin(RedBlackTreeNode<K, T> s)
{
if (s == null)
return null;
RedBlackTreeNode<K, T> cur = s;
while (cur.left != null)
cur = cur.left;
return cur;
}
/// <summary>
/// Finds the max.
/// </summary>
/// <param name="s">The s.</param>
/// <returns></returns>
protected RedBlackTreeNode<K, T> FindMax(RedBlackTreeNode<K, T> s)
{
if (s == null)
return null;
RedBlackTreeNode<K, T> cur = s;
while (cur.right != null)
cur = cur.right;
return cur;
}
}
}
| |
// UpdateManager.cs, 10.06.2019
// Copyright (C) Dominic Beger 17.06.2019
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using nUpdate.Core;
using nUpdate.Exceptions;
using nUpdate.Internal.Core;
using nUpdate.Internal.Core.Localization;
using nUpdate.Internal.Core.Operations;
using nUpdate.Internal.Properties;
using nUpdate.Shared.Core;
namespace nUpdate.Updating
{
/// <summary>
/// Provides functionality to update .NET-applications.
/// </summary>
public partial class UpdateManager : IDisposable
{
private readonly string _applicationUpdateDirectory = Path.Combine(Path.GetTempPath(), "nUpdate",
Application.ProductName);
private readonly Dictionary<UpdateVersion, string> _packageFilePaths = new Dictionary<UpdateVersion, string>();
private Dictionary<UpdateVersion, IEnumerable<Operation>> _packageOperations; // obsolete
private bool _disposed;
private readonly ManualResetEvent _searchManualResetEvent = new ManualResetEvent(false);
private CancellationTokenSource _downloadCancellationTokenSource = new CancellationTokenSource();
private CultureInfo _languageCulture = new CultureInfo("en");
private LocalizationProperties _lp;
private CancellationTokenSource _searchCancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateManager" /> class.
/// </summary>
/// <param name="updateConfigurationFileUri">The URI of the update configuration file.</param>
/// <param name="publicKey">The public key for the validity check of the update packages.</param>
/// <param name="languageCulture">
/// The language culture to use. If no value is provided, the default one ("en") will be
/// used.
/// </param>
/// <param name="currentVersion">
/// The current version of that should be used for the update checks. This parameter has a
/// higher priority than the <see cref="nUpdateVersionAttribute" /> and will replace it, if specified.
/// </param>
/// <remarks>
/// The public key can be found in the overview of your project when you're opening it in nUpdate Administration.
/// If you have problems inserting the data (or if you want to save time) you can scroll down there and follow the
/// steps of the category "Copy data" which will automatically generate the necessary code for you.
/// </remarks>
public UpdateManager(Uri updateConfigurationFileUri, string publicKey,
CultureInfo languageCulture = null, UpdateVersion currentVersion = null)
{
UpdateConfigurationFileUri = updateConfigurationFileUri ??
throw new ArgumentNullException(nameof(updateConfigurationFileUri));
if (string.IsNullOrEmpty(publicKey))
throw new ArgumentNullException(nameof(publicKey));
PublicKey = publicKey;
CultureFilePaths = new Dictionary<CultureInfo, string>();
Arguments = new List<UpdateArgument>();
var projectAssembly = Assembly.GetCallingAssembly();
var nUpateVersionAttribute =
projectAssembly.GetCustomAttributes(false).OfType<nUpdateVersionAttribute>().SingleOrDefault();
// TODO: This is just there to make sure we don't create an API-change that would require a new Major version. This will be changed/removed in v4.0.
// Before v3.0-beta8 it was not possible to provide the current version except using the nUpdateVersionAttribute.
// In order to allow specific features, e.g. updating another application and not the current one (as it's done by a launcher), there must be a way to provide this version separately.
// So, if an argument is specified for the "currentVersion" parameter, we will use this one instead of the nUpdateVersionAttribute.
if (currentVersion != null)
{
CurrentVersion = currentVersion;
}
else
{
// Neither the nUpdateVersionAttribute nor the additional parameter argument was provided.
if (nUpateVersionAttribute == null)
throw new ArgumentException(
"The version string couldn't be loaded because the nUpdateVersionAttribute isn't implemented in the executing assembly and no version was provided explicitly.");
CurrentVersion = new UpdateVersion(nUpateVersionAttribute.VersionString);
}
// TODO: This is just there to make sure we don't create an API-change that would require a new Major version. This will be changed/removed in v4.0.
// Before v3.0-beta5 it was not possible to use custom languages due to a mistake in the architecture. So we can be pretty sure that nobody specifies a custom CultureInfo in the constructor.
// We only need these two lines for those who specified one of the implemented CultureInfos here as they shouldn't have to change anything when updating to v3.0-beta5.
// Nevertheless, it's therefore possible to use custom CultureInfos just by leaving the optional parameter "null" and specifying the culture using the corresponding properties. So, both cases are covered with that solution.
if (languageCulture != null && LocalizationHelper.IsIntegratedCulture(languageCulture, CultureFilePaths))
LanguageCulture = languageCulture;
else
throw new ArgumentException($"The culture \"{languageCulture}\" is not defined.");
if (UseCustomInstallerUserInterface && string.IsNullOrEmpty(CustomInstallerUiAssemblyPath))
throw new ArgumentException(
"The property \"CustomInstallerUiAssemblyPath\" is not initialized although \"UseCustomInstallerUserInterface\" is set to \"true\"");
Initialize();
}
/// <summary>
/// Gets or sets the arguments that should be handled over to the application once the update installation has
/// completed.
/// </summary>
public List<UpdateArgument> Arguments { get; set; }
/// <summary>
/// Gets or sets the paths to the files that contain the localized strings of their corresponding
/// <see cref="CultureInfo" />.
/// </summary>
public Dictionary<CultureInfo, string> CultureFilePaths { get; set; }
/// <summary>
/// Gets or sets the version of the current application.
/// </summary>
internal UpdateVersion CurrentVersion { get; set; }
/// <summary>
/// Gets or sets the path of the assembly file that contains the user interface data for nUpdate UpdateInstaller.
/// </summary>
public string CustomInstallerUiAssemblyPath { get; set; }
/// <summary>
/// Gets or sets the update installer options for the host application.
/// </summary>
public HostApplicationOptions HostApplicationOptions { get; set; }
/// <summary>
/// Gets or sets the HTTP(S) authentication credentials.
/// </summary>
public NetworkCredential HttpAuthenticationCredentials { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user should be able to update to alpha versions, or not.
/// </summary>
public bool IncludeAlpha { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user should be able to update to beta versions, or not.
/// </summary>
public bool IncludeBeta { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the current computer should be included into the statistics, or not.
/// </summary>
public bool IncludeCurrentPcIntoStatistics { get; set; } = true;
/// <summary>
/// Gets or sets the additional conditions that determine whether an update should be loaded or not.
/// </summary>
public List<KeyValuePair<string, string>> Conditions { get; set; }
/// <summary>
/// Gets or sets the culture of the language to use.
/// </summary>
/// <remarks>
/// "en" (English) and "de" (German) are currently the only language cultures that are already implemented in
/// nUpdate. In order to use own languages download the language template from
/// <see href="http://www.nupdate.net/langtemplate.json" />, edit it, save it as a JSON-file and add a new entry to
/// property
/// CultureFilePaths with the relating CultureInfo and path which locates the JSON-file on the client's
/// system (e. g. AppData).
/// </remarks>
public CultureInfo LanguageCulture
{
get => _languageCulture;
set
{
if (!LocalizationHelper.IsIntegratedCulture(value, CultureFilePaths) &&
!CultureFilePaths.ContainsKey(_languageCulture))
throw new ArgumentException(
"The localization file of the culture set does not exist.");
_lp = LocalizationHelper.GetLocalizationProperties(value, CultureFilePaths);
_languageCulture = value;
}
}
/// <summary>
/// Gets the package configurations for all available updates.
/// </summary>
public IEnumerable<UpdateConfiguration> PackageConfigurations { get; internal set; }
/// <summary>
/// Gets or sets the proxy to use.
/// </summary>
public WebProxy Proxy { get; set; }
/// <summary>
/// Gets or sets the public key for checking the validity of the signature.
/// </summary>
public string PublicKey { get; }
public bool RunInstallerAsAdmin { get; set; } = true;
/// <summary>
/// Gets or sets the timeout in milliseconds that should be used when searching for updates.
/// </summary>
/// <remarks>By default, this is set to 10.000 milliseconds.</remarks>
public int SearchTimeout { get; set; } = 10000;
/// <summary>
/// Gets the total size of all update packages.
/// </summary>
public double TotalSize { get; private set; }
/// <summary>
/// Gets or sets the URI of the update configuration file.
/// </summary>
public Uri UpdateConfigurationFileUri { get; }
/// <summary>
/// Gets or sets a value indicating whether the nUpdate UpdateInstaller should use a custom user interface, or not.
/// </summary>
/// <remarks>
/// This property also requires <see cref="CustomInstallerUiAssemblyPath" /> to be set, if the value is
/// <c>true</c>.
/// </remarks>
public bool UseCustomInstallerUserInterface { get; set; }
public bool UseDynamicUpdateUri { get; set; } = false;
/// <summary>
/// Cancels the download.
/// </summary>
/// <remarks>If there is no download task running, nothing will happen.</remarks>
[Obsolete("CancelDownload has been renamed to CancelDownloadAsync which should be used instead.")]
public void CancelDownload()
{
CancelDownloadAsync();
}
/// <summary>
/// Cancels the download, if it is running asynchronously.
/// </summary>
/// <remarks>If there is no asynchronous download task running, nothing will happen.</remarks>
public void CancelDownloadAsync()
{
_downloadCancellationTokenSource.Cancel();
}
/// <summary>
/// Cancels the update search, if it is running asynchronously.
/// </summary>
/// <remarks>If there is no asynchronous search task running, nothing will happen.</remarks>
[Obsolete("CancelSearch has been renamed to CancelSearchAsync which should be used instead.")]
public void CancelSearch()
{
CancelSearchAsync();
}
/// <summary>
/// Cancels the update search.
/// </summary>
/// <remarks>If there is no search task running, nothing will happen.</remarks>
public void CancelSearchAsync()
{
_searchCancellationTokenSource.Cancel();
}
private void Cleanup()
{
_packageFilePaths.Clear();
}
private Uri ConvertPackageUri(Uri updatePackageUri)
{
if (!UseDynamicUpdateUri)
return updatePackageUri;
if (updatePackageUri == null)
throw new ArgumentNullException(nameof(updatePackageUri));
// The segment of the correct update package URI should include: "/", "x.x.x.x/", "*.zip".
if (updatePackageUri.Segments.Length < 3)
throw new ArgumentException($"\"{updatePackageUri}\" is not a valid update package URI.",
nameof(updatePackageUri));
var packageNameSegment = updatePackageUri.Segments.Last();
var versionSegment = updatePackageUri.Segments[updatePackageUri.Segments.Length - 2];
var baseUri = UpdateConfigurationFileUri.GetLeftPart(UriPartial.Authority);
var path = string.Join(string.Empty, UpdateConfigurationFileUri.Segments, 0,
UpdateConfigurationFileUri.Segments.Length - 1);
return new Uri($"{baseUri}{path}{versionSegment}{packageNameSegment}");
}
private Uri ConvertStatisticsUri(Uri statisticsUri)
{
if (!UseDynamicUpdateUri)
return statisticsUri;
if (statisticsUri == null)
throw new ArgumentNullException(nameof(statisticsUri));
// The segment of the correct update php file URI should include: "/", "*.php".
if (statisticsUri.Segments.Length < 2)
throw new ArgumentException($"\"{statisticsUri}\" is not a valid statistics file URI.",
nameof(statisticsUri));
var phpFileName = statisticsUri.Segments.Last();
var baseUri = UpdateConfigurationFileUri.GetLeftPart(UriPartial.Authority);
var path = string.Join(string.Empty, UpdateConfigurationFileUri.Segments, 0,
UpdateConfigurationFileUri.Segments.Length - 1);
return new Uri($"{baseUri}{path}{phpFileName}");
}
/// <summary>
/// Deletes the downloaded update packages.
/// </summary>
public void DeletePackages()
{
foreach (var filePathItem in _packageFilePaths.Where(item => File.Exists(item.Value)))
File.Delete(filePathItem.Value);
}
/// <summary>
/// Releases all managed and unmanaged resources used by the current <see cref="UpdateManager" />-instance.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
/// unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (!disposing || _disposed)
return;
_searchCancellationTokenSource.Dispose();
_downloadCancellationTokenSource.Dispose();
_disposed = true;
}
private double? GetUpdatePackageSize(Uri packageUri)
{
try
{
var req = WebRequestWrapper.Create(packageUri);
req.Method = "HEAD";
if (HttpAuthenticationCredentials != null)
req.Credentials = HttpAuthenticationCredentials;
using (var resp = req.GetResponse())
{
if (double.TryParse(resp.Headers.Get("Content-Length"), out var contentLength))
return contentLength;
}
}
catch
{
return null;
}
return null;
}
private void Initialize()
{
try
{
var updateDirDirectoryInfo = new DirectoryInfo(_applicationUpdateDirectory);
if (updateDirDirectoryInfo.Exists)
updateDirDirectoryInfo.Empty();
else
updateDirDirectoryInfo.Create();
}
catch (Exception ex)
{
throw new IOException(string.Format(_lp.MainFolderCreationExceptionText,
ex.Message));
}
}
/// <summary>
/// Starts the nUpdate UpdateInstaller to unpack the package and start the updating process.
/// </summary>
public void InstallPackage()
{
var installerDirectory = Path.Combine(Path.GetTempPath(), "nUpdate Installer");
var dotNetZipPath = Path.Combine(installerDirectory, "DotNetZip.dll");
var guiInterfacePath = Path.Combine(installerDirectory, "nUpdate.UpdateInstaller.Client.GuiInterface.dll");
var jsonNetPath = Path.Combine(installerDirectory, "Newtonsoft.Json.dll");
var installerFilePath = Path.Combine(installerDirectory, "nUpdate UpdateInstaller.exe");
var unpackerAppPdbPath = Path.Combine(installerDirectory, "nUpdate UpdateInstaller.pdb");
if (Directory.Exists(installerDirectory))
Directory.Delete(installerDirectory, true);
Directory.CreateDirectory(installerDirectory);
File.WriteAllBytes(dotNetZipPath, Resources.DotNetZip);
File.WriteAllBytes(guiInterfacePath, Resources.nUpdate_UpdateInstaller_Client_GuiInterface);
File.WriteAllBytes(jsonNetPath, Resources.Newtonsoft_Json);
File.WriteAllBytes(installerFilePath, Resources.nUpdate_UpdateInstaller);
File.WriteAllBytes(unpackerAppPdbPath, Resources.nUpdate_UpdateInstaller_pdb);
string[] args =
{
$"\"{string.Join("%", _packageFilePaths.Select(item => item.Value))}\"",
$"\"{Application.StartupPath}\"",
$"\"{Application.ExecutablePath}\"",
$"\"{Application.ProductName}\"",
_packageOperations == null ? string.Empty : $"\"{Convert.ToBase64String(Encoding.UTF8.GetBytes(Serializer.Serialize(_packageOperations)))}\"",
$"\"{(UseCustomInstallerUserInterface ? CustomInstallerUiAssemblyPath : string.Empty)}\"",
_lp.InstallerExtractingFilesText,
_lp.InstallerCopyingText,
_lp.FileDeletingOperationText,
_lp.FileRenamingOperationText,
_lp.RegistrySubKeyCreateOperationText,
_lp.RegistrySubKeyDeleteOperationText,
_lp.RegistryNameValuePairDeleteValueOperationText,
_lp.RegistryNameValuePairSetValueOperationText,
_lp.ProcessStartOperationText,
_lp.ProcessStopOperationText,
_lp.ServiceStartOperationText,
_lp.ServiceStopOperationText,
_lp.InstallerUpdatingErrorCaption,
_lp.InstallerInitializingErrorCaption,
$"\"{Convert.ToBase64String(Encoding.UTF8.GetBytes(Serializer.Serialize(Arguments)))}\"",
$"\"{HostApplicationOptions}\"",
$"\"{_lp.InstallerFileInUseError}\"",
$"\"{Process.GetCurrentProcess().Id}\""
};
var startInfo = new ProcessStartInfo
{
FileName = installerFilePath,
Arguments = string.Join("|", args),
UseShellExecute = true,
};
if (RunInstallerAsAdmin)
startInfo.Verb = "runas";
try
{
Process.Start(startInfo);
}
catch (Win32Exception ex)
{
DeletePackages();
Cleanup();
if (ex.NativeErrorCode != 1223)
throw;
return;
}
if (HostApplicationOptions != HostApplicationOptions.None)
TerminateApplication();
}
/// <summary>
/// Terminates the application.
/// </summary>
/// <remarks>
/// If your apllication doesn't terminate correctly or if you want to perform custom actions before terminating,
/// then override this method and implement your own code.
/// </remarks>
public virtual void TerminateApplication()
{
Environment.Exit(0);
}
/// <summary>
/// Returns a value indicating whether the signature of each package is valid, or not. If a package contains an invalid
/// signature, it will be deleted.
/// </summary>
/// <returns>Returns <c>true</c> if the package is valid; otherwise <c>false</c>.</returns>
/// <exception cref="FileNotFoundException">The update package to check could not be found.</exception>
/// <exception cref="ArgumentException">The signature of the update package is invalid.</exception>
public bool ValidatePackages()
{
bool Validate(KeyValuePair<UpdateVersion, string> filePathItem)
{
if (!File.Exists(filePathItem.Value))
throw new FileNotFoundException(string.Format(_lp.PackageFileNotFoundExceptionText,
filePathItem.Key.FullText));
var configuration =
PackageConfigurations.First(config => config.LiteralVersion == filePathItem.Key.ToString());
if (configuration.Signature == null || configuration.Signature.Length <= 0)
throw new ArgumentException($"Signature of version \"{configuration}\" is null or empty.");
using (var stream = File.Open(filePathItem.Value, FileMode.Open))
{
RsaManager rsa;
try
{
rsa = new RsaManager(PublicKey);
}
catch
{
return false;
}
return rsa.VerifyData(stream, Convert.FromBase64String(configuration.Signature));
}
}
if (_packageFilePaths.All(Validate))
return true;
try
{
DeletePackages();
}
catch (Exception ex)
{
throw new PackageDeleteException(ex.Message);
}
Cleanup();
return false;
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmStockItemNew
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmStockItemNew() : base()
{
Load += frmStockItemNew_Load;
KeyPress += frmStockItemNew_KeyPress;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdBack;
public System.Windows.Forms.Button cmdBack {
get { return withEventsField_cmdBack; }
set {
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click -= cmdBack_Click;
}
withEventsField_cmdBack = value;
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click += cmdBack_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdNext;
public System.Windows.Forms.Button cmdNext {
get { return withEventsField_cmdNext; }
set {
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click -= cmdNext_Click;
}
withEventsField_cmdNext = value;
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click += cmdNext_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdPackSize;
public System.Windows.Forms.Button cmdPackSize {
get { return withEventsField_cmdPackSize; }
set {
if (withEventsField_cmdPackSize != null) {
withEventsField_cmdPackSize.Click -= cmdPackSize_Click;
}
withEventsField_cmdPackSize = value;
if (withEventsField_cmdPackSize != null) {
withEventsField_cmdPackSize.Click += cmdPackSize_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdStockGroup;
public System.Windows.Forms.Button cmdStockGroup {
get { return withEventsField_cmdStockGroup; }
set {
if (withEventsField_cmdStockGroup != null) {
withEventsField_cmdStockGroup.Click -= cmdStockGroup_Click;
}
withEventsField_cmdStockGroup = value;
if (withEventsField_cmdStockGroup != null) {
withEventsField_cmdStockGroup.Click += cmdStockGroup_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdPricingGroup;
public System.Windows.Forms.Button cmdPricingGroup {
get { return withEventsField_cmdPricingGroup; }
set {
if (withEventsField_cmdPricingGroup != null) {
withEventsField_cmdPricingGroup.Click -= cmdPricingGroup_Click;
}
withEventsField_cmdPricingGroup = value;
if (withEventsField_cmdPricingGroup != null) {
withEventsField_cmdPricingGroup.Click += cmdPricingGroup_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdDeposit;
public System.Windows.Forms.Button cmdDeposit {
get { return withEventsField_cmdDeposit; }
set {
if (withEventsField_cmdDeposit != null) {
withEventsField_cmdDeposit.Click -= cmdDeposit_Click;
}
withEventsField_cmdDeposit = value;
if (withEventsField_cmdDeposit != null) {
withEventsField_cmdDeposit.Click += cmdDeposit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdSupplier;
public System.Windows.Forms.Button cmdSupplier {
get { return withEventsField_cmdSupplier; }
set {
if (withEventsField_cmdSupplier != null) {
withEventsField_cmdSupplier.Click -= cmdSupplier_Click;
}
withEventsField_cmdSupplier = value;
if (withEventsField_cmdSupplier != null) {
withEventsField_cmdSupplier.Click += cmdSupplier_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdShrink;
public System.Windows.Forms.Button cmdShrink {
get { return withEventsField_cmdShrink; }
set {
if (withEventsField_cmdShrink != null) {
withEventsField_cmdShrink.Click -= cmdShrink_Click;
}
withEventsField_cmdShrink = value;
if (withEventsField_cmdShrink != null) {
withEventsField_cmdShrink.Click += cmdShrink_Click;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtCost;
public System.Windows.Forms.TextBox txtCost {
get { return withEventsField_txtCost; }
set {
if (withEventsField_txtCost != null) {
withEventsField_txtCost.Enter -= txtCost_Enter;
withEventsField_txtCost.KeyPress -= txtCost_KeyPress;
withEventsField_txtCost.Leave -= txtCost_Leave;
}
withEventsField_txtCost = value;
if (withEventsField_txtCost != null) {
withEventsField_txtCost.Enter += txtCost_Enter;
withEventsField_txtCost.KeyPress += txtCost_KeyPress;
withEventsField_txtCost.Leave += txtCost_Leave;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtQuantity;
public System.Windows.Forms.TextBox txtQuantity {
get { return withEventsField_txtQuantity; }
set {
if (withEventsField_txtQuantity != null) {
withEventsField_txtQuantity.Enter -= txtQuantity_Enter;
withEventsField_txtQuantity.KeyPress -= txtQuantity_KeyPress;
withEventsField_txtQuantity.Leave -= txtQuantity_Leave;
}
withEventsField_txtQuantity = value;
if (withEventsField_txtQuantity != null) {
withEventsField_txtQuantity.Enter += txtQuantity_Enter;
withEventsField_txtQuantity.KeyPress += txtQuantity_KeyPress;
withEventsField_txtQuantity.Leave += txtQuantity_Leave;
}
}
}
private myDataGridView withEventsField_cmbShrink;
public myDataGridView cmbShrink {
get { return withEventsField_cmbShrink; }
set {
if (withEventsField_cmbShrink != null) {
withEventsField_cmbShrink.KeyDown -= cmbShrink_KeyDown;
}
withEventsField_cmbShrink = value;
if (withEventsField_cmbShrink != null) {
withEventsField_cmbShrink.KeyDown += cmbShrink_KeyDown;
}
}
}
public System.Windows.Forms.Label _lblLabels_1;
public System.Windows.Forms.Label _lblLabels_10;
public System.Windows.Forms.Label _lblLabels_2;
public System.Windows.Forms.GroupBox Frame1;
private System.Windows.Forms.TextBox withEventsField_txtReceipt;
public System.Windows.Forms.TextBox txtReceipt {
get { return withEventsField_txtReceipt; }
set {
if (withEventsField_txtReceipt != null) {
withEventsField_txtReceipt.Enter -= txtReceipt_Enter;
}
withEventsField_txtReceipt = value;
if (withEventsField_txtReceipt != null) {
withEventsField_txtReceipt.Enter += txtReceipt_Enter;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtName;
public System.Windows.Forms.TextBox txtName {
get { return withEventsField_txtName; }
set {
if (withEventsField_txtName != null) {
withEventsField_txtName.Enter -= txtName_Enter;
withEventsField_txtName.Leave -= txtName_Leave;
}
withEventsField_txtName = value;
if (withEventsField_txtName != null) {
withEventsField_txtName.Enter += txtName_Enter;
withEventsField_txtName.Leave += txtName_Leave;
}
}
}
public System.Windows.Forms.PictureBox Picture1;
private myDataGridView withEventsField_cmbPricingGroup;
public myDataGridView cmbPricingGroup {
get { return withEventsField_cmbPricingGroup; }
set {
if (withEventsField_cmbPricingGroup != null) {
withEventsField_cmbPricingGroup.KeyDown -= cmbPricingGroup_KeyDown;
}
withEventsField_cmbPricingGroup = value;
if (withEventsField_cmbPricingGroup != null) {
withEventsField_cmbPricingGroup.KeyDown += cmbPricingGroup_KeyDown;
}
}
}
private myDataGridView withEventsField_cmbStockGroup;
public myDataGridView cmbStockGroup {
get { return withEventsField_cmbStockGroup; }
set {
if (withEventsField_cmbStockGroup != null) {
withEventsField_cmbStockGroup.KeyDown -= cmbStockGroup_KeyDown;
}
withEventsField_cmbStockGroup = value;
if (withEventsField_cmbStockGroup != null) {
withEventsField_cmbStockGroup.KeyDown += cmbStockGroup_KeyDown;
}
}
}
private myDataGridView withEventsField_cmbDeposit;
public myDataGridView cmbDeposit {
get { return withEventsField_cmbDeposit; }
set {
if (withEventsField_cmbDeposit != null) {
withEventsField_cmbDeposit.KeyDown -= cmbDeposit_KeyDown;
}
withEventsField_cmbDeposit = value;
if (withEventsField_cmbDeposit != null) {
withEventsField_cmbDeposit.KeyDown += cmbDeposit_KeyDown;
}
}
}
private myDataGridView withEventsField_cmbSupplier;
public myDataGridView cmbSupplier {
get { return withEventsField_cmbSupplier; }
set {
if (withEventsField_cmbSupplier != null) {
withEventsField_cmbSupplier.KeyDown -= cmbSupplier_KeyDown;
}
withEventsField_cmbSupplier = value;
if (withEventsField_cmbSupplier != null) {
withEventsField_cmbSupplier.KeyDown += cmbSupplier_KeyDown;
}
}
}
private myDataGridView withEventsField_cmbPackSize;
public myDataGridView cmbPackSize {
get { return withEventsField_cmbPackSize; }
set {
if (withEventsField_cmbPackSize != null) {
withEventsField_cmbPackSize.KeyDown -= cmbPackSize_KeyDown;
}
withEventsField_cmbPackSize = value;
if (withEventsField_cmbPackSize != null) {
withEventsField_cmbPackSize.KeyDown += cmbPackSize_KeyDown;
}
}
}
public System.Windows.Forms.Label _lblLabels_5;
public System.Windows.Forms.Label _lblLabels_8;
public System.Windows.Forms.Label _lblLabels_7;
public System.Windows.Forms.Label _lblLabels_4;
public System.Windows.Forms.Label _lblLabels_3;
public System.Windows.Forms.Label _lblLabels_0;
public System.Windows.Forms.Label _lblLabels_6;
public System.Windows.Forms.GroupBox _frmMode_1;
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdCustom;
public System.Windows.Forms.Button cmdCustom {
get { return withEventsField_cmdCustom; }
set {
if (withEventsField_cmdCustom != null) {
withEventsField_cmdCustom.Click -= cmdCustom_Click;
}
withEventsField_cmdCustom = value;
if (withEventsField_cmdCustom != null) {
withEventsField_cmdCustom.Click += cmdCustom_Click;
}
}
}
private myDataGridView withEventsField_DataList1;
public myDataGridView DataList1 {
get { return withEventsField_DataList1; }
set {
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick -= DataList1_DblClick;
withEventsField_DataList1.KeyPress -= DataList1_KeyPress;
}
withEventsField_DataList1 = value;
if (withEventsField_DataList1 != null) {
withEventsField_DataList1.DoubleClick += DataList1_DblClick;
withEventsField_DataList1.KeyPress += DataList1_KeyPress;
}
}
}
public System.Windows.Forms.Label lblRecords;
public System.Windows.Forms.Label _lbl_35;
public System.Windows.Forms.GroupBox _frmMode_0;
//Public WithEvents frmMode As Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray
//Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockItemNew));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.cmdBack = new System.Windows.Forms.Button();
this.cmdNext = new System.Windows.Forms.Button();
this._frmMode_1 = new System.Windows.Forms.GroupBox();
this.cmdPackSize = new System.Windows.Forms.Button();
this.cmdStockGroup = new System.Windows.Forms.Button();
this.cmdPricingGroup = new System.Windows.Forms.Button();
this.cmdDeposit = new System.Windows.Forms.Button();
this.cmdSupplier = new System.Windows.Forms.Button();
this.Frame1 = new System.Windows.Forms.GroupBox();
this.cmdShrink = new System.Windows.Forms.Button();
this.txtCost = new System.Windows.Forms.TextBox();
this.txtQuantity = new System.Windows.Forms.TextBox();
this.cmbShrink = new myDataGridView();
this._lblLabels_1 = new System.Windows.Forms.Label();
this._lblLabels_10 = new System.Windows.Forms.Label();
this._lblLabels_2 = new System.Windows.Forms.Label();
this.txtReceipt = new System.Windows.Forms.TextBox();
this.txtName = new System.Windows.Forms.TextBox();
this.Picture1 = new System.Windows.Forms.PictureBox();
this.cmbPricingGroup = new myDataGridView();
this.cmbStockGroup = new myDataGridView();
this.cmbDeposit = new myDataGridView();
this.cmbSupplier = new myDataGridView();
this.cmbPackSize = new myDataGridView();
this._lblLabels_5 = new System.Windows.Forms.Label();
this._lblLabels_8 = new System.Windows.Forms.Label();
this._lblLabels_7 = new System.Windows.Forms.Label();
this._lblLabels_4 = new System.Windows.Forms.Label();
this._lblLabels_3 = new System.Windows.Forms.Label();
this._lblLabels_0 = new System.Windows.Forms.Label();
this._lblLabels_6 = new System.Windows.Forms.Label();
this._frmMode_0 = new System.Windows.Forms.GroupBox();
this.txtSearch = new System.Windows.Forms.TextBox();
this.cmdCustom = new System.Windows.Forms.Button();
this.DataList1 = new myDataGridView();
this.lblRecords = new System.Windows.Forms.Label();
this._lbl_35 = new System.Windows.Forms.Label();
//Me.frmMode = New Microsoft.VisualBasic.Compatibility.VB6.GroupBoxArray(components)
//Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
//Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components)
this._frmMode_1.SuspendLayout();
this.Frame1.SuspendLayout();
this._frmMode_0.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.cmbShrink).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbPricingGroup).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbStockGroup).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbDeposit).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbSupplier).BeginInit();
((System.ComponentModel.ISupportInitialize)this.cmbPackSize).BeginInit();
((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit();
//CType(Me.frmMode, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit()
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit()
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "New Stock Item";
this.ClientSize = new System.Drawing.Size(366, 413);
this.Location = new System.Drawing.Point(3, 22);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmStockItemNew";
this.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBack.Text = "E&xit";
this.cmdBack.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdBack.Size = new System.Drawing.Size(97, 43);
this.cmdBack.Location = new System.Drawing.Point(4, 364);
this.cmdBack.TabIndex = 20;
this.cmdBack.TabStop = false;
this.cmdBack.BackColor = System.Drawing.SystemColors.Control;
this.cmdBack.CausesValidation = true;
this.cmdBack.Enabled = true;
this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBack.Name = "cmdBack";
this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNext.Text = "&Next >>";
this.cmdNext.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdNext.Size = new System.Drawing.Size(96, 43);
this.cmdNext.Location = new System.Drawing.Point(266, 364);
this.cmdNext.TabIndex = 19;
this.cmdNext.TabStop = false;
this.cmdNext.BackColor = System.Drawing.SystemColors.Control;
this.cmdNext.CausesValidation = true;
this.cmdNext.Enabled = true;
this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNext.Name = "cmdNext";
this._frmMode_1.Text = "New \"Stock Item\" Details.";
this._frmMode_1.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._frmMode_1.Size = new System.Drawing.Size(357, 353);
this._frmMode_1.Location = new System.Drawing.Point(96, 6);
this._frmMode_1.TabIndex = 0;
this._frmMode_1.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_1.Enabled = true;
this._frmMode_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_1.Visible = true;
this._frmMode_1.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_1.Name = "_frmMode_1";
this.cmdPackSize.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPackSize.Text = "...";
this.cmdPackSize.Size = new System.Drawing.Size(25, 19);
this.cmdPackSize.Location = new System.Drawing.Point(326, 158);
this.cmdPackSize.TabIndex = 36;
this.cmdPackSize.BackColor = System.Drawing.SystemColors.Control;
this.cmdPackSize.CausesValidation = true;
this.cmdPackSize.Enabled = true;
this.cmdPackSize.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPackSize.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPackSize.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPackSize.TabStop = true;
this.cmdPackSize.Name = "cmdPackSize";
this.cmdStockGroup.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdStockGroup.Text = "...";
this.cmdStockGroup.Size = new System.Drawing.Size(25, 19);
this.cmdStockGroup.Location = new System.Drawing.Point(326, 134);
this.cmdStockGroup.TabIndex = 31;
this.cmdStockGroup.BackColor = System.Drawing.SystemColors.Control;
this.cmdStockGroup.CausesValidation = true;
this.cmdStockGroup.Enabled = true;
this.cmdStockGroup.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdStockGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdStockGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdStockGroup.TabStop = true;
this.cmdStockGroup.Name = "cmdStockGroup";
this.cmdPricingGroup.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPricingGroup.Text = "...";
this.cmdPricingGroup.Size = new System.Drawing.Size(25, 19);
this.cmdPricingGroup.Location = new System.Drawing.Point(326, 110);
this.cmdPricingGroup.TabIndex = 30;
this.cmdPricingGroup.BackColor = System.Drawing.SystemColors.Control;
this.cmdPricingGroup.CausesValidation = true;
this.cmdPricingGroup.Enabled = true;
this.cmdPricingGroup.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPricingGroup.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPricingGroup.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPricingGroup.TabStop = true;
this.cmdPricingGroup.Name = "cmdPricingGroup";
this.cmdDeposit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdDeposit.Text = "...";
this.cmdDeposit.Size = new System.Drawing.Size(25, 19);
this.cmdDeposit.Location = new System.Drawing.Point(326, 86);
this.cmdDeposit.TabIndex = 29;
this.cmdDeposit.BackColor = System.Drawing.SystemColors.Control;
this.cmdDeposit.CausesValidation = true;
this.cmdDeposit.Enabled = true;
this.cmdDeposit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdDeposit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdDeposit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdDeposit.TabStop = true;
this.cmdDeposit.Name = "cmdDeposit";
this.cmdSupplier.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdSupplier.Text = "...";
this.cmdSupplier.Size = new System.Drawing.Size(25, 19);
this.cmdSupplier.Location = new System.Drawing.Point(326, 62);
this.cmdSupplier.TabIndex = 28;
this.cmdSupplier.BackColor = System.Drawing.SystemColors.Control;
this.cmdSupplier.CausesValidation = true;
this.cmdSupplier.Enabled = true;
this.cmdSupplier.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdSupplier.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdSupplier.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdSupplier.TabStop = true;
this.cmdSupplier.Name = "cmdSupplier";
this.Frame1.Size = new System.Drawing.Size(343, 75);
this.Frame1.Location = new System.Drawing.Point(8, 200);
this.Frame1.TabIndex = 21;
this.Frame1.BackColor = System.Drawing.SystemColors.Control;
this.Frame1.Enabled = true;
this.Frame1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Frame1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Frame1.Visible = true;
this.Frame1.Padding = new System.Windows.Forms.Padding(0);
this.Frame1.Name = "Frame1";
this.cmdShrink.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdShrink.Text = "...";
this.cmdShrink.Size = new System.Drawing.Size(25, 19);
this.cmdShrink.Location = new System.Drawing.Point(230, 40);
this.cmdShrink.TabIndex = 32;
this.cmdShrink.BackColor = System.Drawing.SystemColors.Control;
this.cmdShrink.CausesValidation = true;
this.cmdShrink.Enabled = true;
this.cmdShrink.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdShrink.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdShrink.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdShrink.TabStop = true;
this.cmdShrink.Name = "cmdShrink";
this.txtCost.AutoSize = false;
this.txtCost.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtCost.Size = new System.Drawing.Size(56, 19);
this.txtCost.Location = new System.Drawing.Point(282, 14);
this.txtCost.TabIndex = 25;
this.txtCost.Text = "0.00";
this.txtCost.AcceptsReturn = true;
this.txtCost.BackColor = System.Drawing.SystemColors.Window;
this.txtCost.CausesValidation = true;
this.txtCost.Enabled = true;
this.txtCost.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtCost.HideSelection = true;
this.txtCost.ReadOnly = false;
this.txtCost.MaxLength = 0;
this.txtCost.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtCost.Multiline = false;
this.txtCost.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtCost.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtCost.TabStop = true;
this.txtCost.Visible = true;
this.txtCost.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtCost.Name = "txtCost";
this.txtQuantity.AutoSize = false;
this.txtQuantity.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.txtQuantity.Size = new System.Drawing.Size(34, 19);
this.txtQuantity.Location = new System.Drawing.Point(68, 14);
this.txtQuantity.TabIndex = 23;
this.txtQuantity.Text = "1";
this.txtQuantity.AcceptsReturn = true;
this.txtQuantity.BackColor = System.Drawing.SystemColors.Window;
this.txtQuantity.CausesValidation = true;
this.txtQuantity.Enabled = true;
this.txtQuantity.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtQuantity.HideSelection = true;
this.txtQuantity.ReadOnly = false;
this.txtQuantity.MaxLength = 0;
this.txtQuantity.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtQuantity.Multiline = false;
this.txtQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtQuantity.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtQuantity.TabStop = true;
this.txtQuantity.Visible = true;
this.txtQuantity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtQuantity.Name = "txtQuantity";
//cmbShrink.OcxState = CType(resources.GetObject("cmbShrink.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbShrink.Size = new System.Drawing.Size(91, 21);
this.cmbShrink.Location = new System.Drawing.Point(132, 38);
this.cmbShrink.TabIndex = 27;
this.cmbShrink.Name = "cmbShrink";
this._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_1.Text = "and you sell in shrinks of";
this._lblLabels_1.Size = new System.Drawing.Size(115, 13);
this._lblLabels_1.Location = new System.Drawing.Point(14, 42);
this._lblLabels_1.TabIndex = 26;
this._lblLabels_1.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_1.Enabled = true;
this._lblLabels_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_1.UseMnemonic = true;
this._lblLabels_1.Visible = true;
this._lblLabels_1.AutoSize = true;
this._lblLabels_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_1.Name = "_lblLabels_1";
this._lblLabels_10.Text = "Units in a case/carton, which costs";
this._lblLabels_10.Size = new System.Drawing.Size(167, 13);
this._lblLabels_10.Location = new System.Drawing.Point(106, 16);
this._lblLabels_10.TabIndex = 24;
this._lblLabels_10.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lblLabels_10.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_10.Enabled = true;
this._lblLabels_10.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_10.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_10.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_10.UseMnemonic = true;
this._lblLabels_10.Visible = true;
this._lblLabels_10.AutoSize = true;
this._lblLabels_10.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_10.Name = "_lblLabels_10";
this._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_2.Text = "There are ";
this._lblLabels_2.Size = new System.Drawing.Size(49, 13);
this._lblLabels_2.Location = new System.Drawing.Point(14, 16);
this._lblLabels_2.TabIndex = 22;
this._lblLabels_2.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_2.Enabled = true;
this._lblLabels_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_2.UseMnemonic = true;
this._lblLabels_2.Visible = true;
this._lblLabels_2.AutoSize = true;
this._lblLabels_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_2.Name = "_lblLabels_2";
this.txtReceipt.AutoSize = false;
this.txtReceipt.Size = new System.Drawing.Size(241, 19);
this.txtReceipt.Location = new System.Drawing.Point(82, 40);
this.txtReceipt.MaxLength = 40;
this.txtReceipt.TabIndex = 4;
this.txtReceipt.Text = "[New Product]";
this.txtReceipt.AcceptsReturn = true;
this.txtReceipt.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtReceipt.BackColor = System.Drawing.SystemColors.Window;
this.txtReceipt.CausesValidation = true;
this.txtReceipt.Enabled = true;
this.txtReceipt.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtReceipt.HideSelection = true;
this.txtReceipt.ReadOnly = false;
this.txtReceipt.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtReceipt.Multiline = false;
this.txtReceipt.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtReceipt.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtReceipt.TabStop = true;
this.txtReceipt.Visible = true;
this.txtReceipt.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtReceipt.Name = "txtReceipt";
this.txtName.AutoSize = false;
this.txtName.Size = new System.Drawing.Size(241, 19);
this.txtName.Location = new System.Drawing.Point(82, 18);
this.txtName.MaxLength = 128;
this.txtName.TabIndex = 2;
this.txtName.Text = "[New Product]";
this.txtName.AcceptsReturn = true;
this.txtName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtName.BackColor = System.Drawing.SystemColors.Window;
this.txtName.CausesValidation = true;
this.txtName.Enabled = true;
this.txtName.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtName.HideSelection = true;
this.txtName.ReadOnly = false;
this.txtName.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtName.Multiline = false;
this.txtName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtName.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtName.TabStop = true;
this.txtName.Visible = true;
this.txtName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtName.Name = "txtName";
this.Picture1.Size = new System.Drawing.Size(295, 4);
this.Picture1.Location = new System.Drawing.Point(28, 192);
this.Picture1.TabIndex = 13;
this.Picture1.TabStop = false;
this.Picture1.Dock = System.Windows.Forms.DockStyle.None;
this.Picture1.BackColor = System.Drawing.SystemColors.Control;
this.Picture1.CausesValidation = true;
this.Picture1.Enabled = true;
this.Picture1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Picture1.Cursor = System.Windows.Forms.Cursors.Default;
this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Picture1.Visible = true;
this.Picture1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Picture1.Name = "Picture1";
//cmbPricingGroup.OcxState = CType(resources.GetObject("cmbPricingGroup.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbPricingGroup.Size = new System.Drawing.Size(241, 21);
this.cmbPricingGroup.Location = new System.Drawing.Point(82, 108);
this.cmbPricingGroup.TabIndex = 10;
this.cmbPricingGroup.Name = "cmbPricingGroup";
//cmbStockGroup.OcxState = CType(resources.GetObject("cmbStockGroup.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbStockGroup.Size = new System.Drawing.Size(241, 21);
this.cmbStockGroup.Location = new System.Drawing.Point(82, 132);
this.cmbStockGroup.TabIndex = 12;
this.cmbStockGroup.Name = "cmbStockGroup";
//cmbDeposit.OcxState = CType(resources.GetObject("cmbDeposit.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbDeposit.Size = new System.Drawing.Size(241, 21);
this.cmbDeposit.Location = new System.Drawing.Point(82, 84);
this.cmbDeposit.TabIndex = 8;
this.cmbDeposit.Name = "cmbDeposit";
//cmbSupplier.OcxState = CType(resources.GetObject("cmbSupplier.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbSupplier.Size = new System.Drawing.Size(241, 21);
this.cmbSupplier.Location = new System.Drawing.Point(82, 60);
this.cmbSupplier.TabIndex = 6;
this.cmbSupplier.Name = "cmbSupplier";
//cmbPackSize.OcxState = CType(resources.GetObject("cmbPackSize.OcxState"), System.Windows.Forms.AxHost.State)
this.cmbPackSize.Size = new System.Drawing.Size(241, 21);
this.cmbPackSize.Location = new System.Drawing.Point(82, 156);
this.cmbPackSize.TabIndex = 35;
this.cmbPackSize.Name = "cmbPackSize";
this._lblLabels_5.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_5.Text = "Pack Size:";
this._lblLabels_5.Size = new System.Drawing.Size(51, 13);
this._lblLabels_5.Location = new System.Drawing.Point(28, 160);
this._lblLabels_5.TabIndex = 34;
this._lblLabels_5.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_5.Enabled = true;
this._lblLabels_5.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_5.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_5.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_5.UseMnemonic = true;
this._lblLabels_5.Visible = true;
this._lblLabels_5.AutoSize = true;
this._lblLabels_5.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_5.Name = "_lblLabels_5";
this._lblLabels_8.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_8.Text = "Receipt Name:";
this._lblLabels_8.Size = new System.Drawing.Size(71, 13);
this._lblLabels_8.Location = new System.Drawing.Point(6, 45);
this._lblLabels_8.TabIndex = 3;
this._lblLabels_8.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_8.Enabled = true;
this._lblLabels_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_8.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_8.UseMnemonic = true;
this._lblLabels_8.Visible = true;
this._lblLabels_8.AutoSize = true;
this._lblLabels_8.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_8.Name = "_lblLabels_8";
this._lblLabels_7.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_7.Text = "Display Name:";
this._lblLabels_7.Size = new System.Drawing.Size(68, 13);
this._lblLabels_7.Location = new System.Drawing.Point(10, 20);
this._lblLabels_7.TabIndex = 1;
this._lblLabels_7.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_7.Enabled = true;
this._lblLabels_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_7.UseMnemonic = true;
this._lblLabels_7.Visible = true;
this._lblLabels_7.AutoSize = true;
this._lblLabels_7.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_7.Name = "_lblLabels_7";
this._lblLabels_4.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_4.Text = "Stock Group:";
this._lblLabels_4.Size = new System.Drawing.Size(63, 13);
this._lblLabels_4.Location = new System.Drawing.Point(14, 138);
this._lblLabels_4.TabIndex = 11;
this._lblLabels_4.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_4.Enabled = true;
this._lblLabels_4.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_4.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_4.UseMnemonic = true;
this._lblLabels_4.Visible = true;
this._lblLabels_4.AutoSize = true;
this._lblLabels_4.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_4.Name = "_lblLabels_4";
this._lblLabels_3.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_3.Text = "Pricing Group:";
this._lblLabels_3.Size = new System.Drawing.Size(67, 13);
this._lblLabels_3.Location = new System.Drawing.Point(10, 114);
this._lblLabels_3.TabIndex = 9;
this._lblLabels_3.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_3.Enabled = true;
this._lblLabels_3.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_3.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_3.UseMnemonic = true;
this._lblLabels_3.Visible = true;
this._lblLabels_3.AutoSize = true;
this._lblLabels_3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_3.Name = "_lblLabels_3";
this._lblLabels_0.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_0.Text = "Supplier:";
this._lblLabels_0.Size = new System.Drawing.Size(41, 13);
this._lblLabels_0.Location = new System.Drawing.Point(36, 66);
this._lblLabels_0.TabIndex = 5;
this._lblLabels_0.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_0.Enabled = true;
this._lblLabels_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_0.UseMnemonic = true;
this._lblLabels_0.Visible = true;
this._lblLabels_0.AutoSize = true;
this._lblLabels_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_0.Name = "_lblLabels_0";
this._lblLabels_6.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lblLabels_6.Text = "Deposit:";
this._lblLabels_6.Size = new System.Drawing.Size(39, 13);
this._lblLabels_6.Location = new System.Drawing.Point(38, 90);
this._lblLabels_6.TabIndex = 7;
this._lblLabels_6.BackColor = System.Drawing.Color.Transparent;
this._lblLabels_6.Enabled = true;
this._lblLabels_6.ForeColor = System.Drawing.SystemColors.ControlText;
this._lblLabels_6.Cursor = System.Windows.Forms.Cursors.Default;
this._lblLabels_6.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lblLabels_6.UseMnemonic = true;
this._lblLabels_6.Visible = true;
this._lblLabels_6.AutoSize = true;
this._lblLabels_6.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lblLabels_6.Name = "_lblLabels_6";
this._frmMode_0.Text = "Select the Product for the New \"Stock Item\".";
this._frmMode_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._frmMode_0.Size = new System.Drawing.Size(357, 355);
this._frmMode_0.Location = new System.Drawing.Point(4, 4);
this._frmMode_0.TabIndex = 15;
this._frmMode_0.BackColor = System.Drawing.SystemColors.Control;
this._frmMode_0.Enabled = true;
this._frmMode_0.ForeColor = System.Drawing.SystemColors.ControlText;
this._frmMode_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._frmMode_0.Visible = true;
this._frmMode_0.Padding = new System.Windows.Forms.Padding(0);
this._frmMode_0.Name = "_frmMode_0";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(291, 19);
this.txtSearch.Location = new System.Drawing.Point(57, 18);
this.txtSearch.TabIndex = 16;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtSearch.Name = "txtSearch";
this.cmdCustom.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdCustom.Text = "The product I want is not in this list.";
this.cmdCustom.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdCustom.Size = new System.Drawing.Size(336, 37);
this.cmdCustom.Location = new System.Drawing.Point(12, 306);
this.cmdCustom.TabIndex = 18;
this.cmdCustom.BackColor = System.Drawing.SystemColors.Control;
this.cmdCustom.CausesValidation = true;
this.cmdCustom.Enabled = true;
this.cmdCustom.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdCustom.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdCustom.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdCustom.TabStop = true;
this.cmdCustom.Name = "cmdCustom";
//'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State)
this.DataList1.Size = new System.Drawing.Size(336, 225);
this.DataList1.Location = new System.Drawing.Point(12, 44);
this.DataList1.TabIndex = 17;
this.DataList1.Name = "DataList1";
this.lblRecords.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lblRecords.Text = "Displayed Records 0 of 0";
this.lblRecords.Font = new System.Drawing.Font("Verdana", 9.75f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(0));
this.lblRecords.Size = new System.Drawing.Size(336, 17);
this.lblRecords.Location = new System.Drawing.Point(12, 272);
this.lblRecords.TabIndex = 33;
this.lblRecords.BackColor = System.Drawing.SystemColors.Control;
this.lblRecords.Enabled = true;
this.lblRecords.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblRecords.Cursor = System.Windows.Forms.Cursors.Default;
this.lblRecords.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblRecords.UseMnemonic = true;
this.lblRecords.Visible = true;
this.lblRecords.AutoSize = false;
this.lblRecords.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblRecords.Name = "lblRecords";
this._lbl_35.Text = "Search";
this._lbl_35.Size = new System.Drawing.Size(43, 16);
this._lbl_35.Location = new System.Drawing.Point(15, 21);
this._lbl_35.TabIndex = 14;
this._lbl_35.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_35.BackColor = System.Drawing.SystemColors.Control;
this._lbl_35.Enabled = true;
this._lbl_35.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_35.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_35.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_35.UseMnemonic = true;
this._lbl_35.Visible = true;
this._lbl_35.AutoSize = false;
this._lbl_35.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_35.Name = "_lbl_35";
this.Controls.Add(cmdBack);
this.Controls.Add(cmdNext);
this.Controls.Add(_frmMode_1);
this.Controls.Add(_frmMode_0);
this._frmMode_1.Controls.Add(cmdPackSize);
this._frmMode_1.Controls.Add(cmdStockGroup);
this._frmMode_1.Controls.Add(cmdPricingGroup);
this._frmMode_1.Controls.Add(cmdDeposit);
this._frmMode_1.Controls.Add(cmdSupplier);
this._frmMode_1.Controls.Add(Frame1);
this._frmMode_1.Controls.Add(txtReceipt);
this._frmMode_1.Controls.Add(txtName);
this._frmMode_1.Controls.Add(Picture1);
this._frmMode_1.Controls.Add(cmbPricingGroup);
this._frmMode_1.Controls.Add(cmbStockGroup);
this._frmMode_1.Controls.Add(cmbDeposit);
this._frmMode_1.Controls.Add(cmbSupplier);
this._frmMode_1.Controls.Add(cmbPackSize);
this._frmMode_1.Controls.Add(_lblLabels_5);
this._frmMode_1.Controls.Add(_lblLabels_8);
this._frmMode_1.Controls.Add(_lblLabels_7);
this._frmMode_1.Controls.Add(_lblLabels_4);
this._frmMode_1.Controls.Add(_lblLabels_3);
this._frmMode_1.Controls.Add(_lblLabels_0);
this._frmMode_1.Controls.Add(_lblLabels_6);
this.Frame1.Controls.Add(cmdShrink);
this.Frame1.Controls.Add(txtCost);
this.Frame1.Controls.Add(txtQuantity);
this.Frame1.Controls.Add(cmbShrink);
this.Frame1.Controls.Add(_lblLabels_1);
this.Frame1.Controls.Add(_lblLabels_10);
this.Frame1.Controls.Add(_lblLabels_2);
this._frmMode_0.Controls.Add(txtSearch);
this._frmMode_0.Controls.Add(cmdCustom);
this._frmMode_0.Controls.Add(DataList1);
this._frmMode_0.Controls.Add(lblRecords);
this._frmMode_0.Controls.Add(_lbl_35);
//Me.frmMode.SetIndex(_frmMode_1, CType(1, Short))
//Me.frmMode.SetIndex(_frmMode_0, CType(0, Short))
//Me.lbl.SetIndex(_lbl_35, CType(35, Short))
//Me.lblLabels.SetIndex(_lblLabels_1, CType(1, Short))
//Me.lblLabels.SetIndex(_lblLabels_10, CType(10, Short))
//Me.lblLabels.SetIndex(_lblLabels_2, CType(2, Short))
//Me.lblLabels.SetIndex(_lblLabels_5, CType(5, Short))
//Me.lblLabels.SetIndex(_lblLabels_8, CType(8, Short))
//Me.lblLabels.SetIndex(_lblLabels_7, CType(7, Short))
//Me.lblLabels.SetIndex(_lblLabels_4, CType(4, Short))
//Me.lblLabels.SetIndex(_lblLabels_3, CType(3, Short))
//Me.lblLabels.SetIndex(_lblLabels_0, CType(0, Short))
//Me.lblLabels.SetIndex(_lblLabels_6, CType(6, Short))
//CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit()
//CType(Me.frmMode, System.ComponentModel.ISupportInitialize).EndInit()
((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbPackSize).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbSupplier).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbDeposit).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbStockGroup).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbPricingGroup).EndInit();
((System.ComponentModel.ISupportInitialize)this.cmbShrink).EndInit();
this._frmMode_1.ResumeLayout(false);
this.Frame1.ResumeLayout(false);
this._frmMode_0.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
//
// Copyright (c) 2012-2014 Piotr Fusik <piotr@fusik.info>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if DOTNET35
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Sooda.Linq
{
enum SoodaLinqMethod
{
Unknown,
Queryable_Where,
Queryable_OrderBy,
Queryable_OrderByDescending,
Queryable_ThenBy,
Queryable_ThenByDescending,
Queryable_Skip,
Queryable_Take,
Queryable_Select,
Queryable_SelectIndexed,
Queryable_GroupBy,
Queryable_Reverse,
Queryable_Distinct,
Queryable_OfType,
Queryable_Except,
Queryable_Intersect,
Queryable_Union,
Queryable_First,
Queryable_FirstFiltered,
Queryable_FirstOrDefault,
Queryable_FirstOrDefaultFiltered,
Queryable_Last,
Queryable_LastFiltered,
Queryable_LastOrDefault,
Queryable_LastOrDefaultFiltered,
Queryable_Single,
Queryable_SingleFiltered,
Queryable_SingleOrDefault,
Queryable_SingleOrDefaultFiltered,
Queryable_AverageNullable,
Enumerable_All,
Enumerable_Any,
Enumerable_AnyFiltered,
Enumerable_Contains,
Enumerable_Count,
Enumerable_CountFiltered,
Enumerable_Average,
Enumerable_Max,
Enumerable_Min,
Enumerable_Sum,
ICollection_Contains,
Object_GetType,
Object_InstanceEquals,
Object_StaticEquals,
String_Concat,
String_Like,
String_Remove,
String_Substring,
String_Replace,
String_ToLower,
String_ToUpper,
String_StartsWith,
String_EndsWith,
String_Contains,
String_IsNullOrEmpty,
Int_ToString,
Long_ToString,
Double_ToString,
Decimal_ToString,
Bool_ToString,
Math_Abs,
Math_Acos,
Math_Asin,
Math_Atan,
Math_Cos,
Math_Exp,
Math_Floor,
Math_Pow,
Math_Round,
Math_Sign,
Math_Sin,
Math_Sqrt,
Math_Tan,
SoodaObject_GetPrimaryKeyValue,
SoodaObject_GetLabel,
SoodaObject_GetItem,
}
static class SoodaLinqMethodDictionary
{
static Dictionary<MethodInfo, SoodaLinqMethod> _method2id;
static MethodInfo Ungeneric(MethodInfo method)
{
Type type = method.DeclaringType;
if (type.IsGenericType)
method = type.GetGenericTypeDefinition().GetMethod(method.Name);
return method.IsGenericMethod ? method.GetGenericMethodDefinition() : method;
}
static MethodInfo MethodOf(Expression<Action> lambda)
{
return Ungeneric(((MethodCallExpression) lambda.Body).Method);
}
static Dictionary<MethodInfo, SoodaLinqMethod> Initialize()
{
Dictionary<MethodInfo, SoodaLinqMethod> method2id = new Dictionary<MethodInfo, SoodaLinqMethod>();
Expression<Func<object, bool>> predicate = o => true;
Expression<Func<object, int>> selector = o => 0;
Expression<Func<object, decimal>> selectorM = o => 0;
Expression<Func<object, double>> selectorD = o => 0;
Expression<Func<object, long>> selectorL = o => 0;
Expression<Func<object, int?>> selectorN = o => 0;
Expression<Func<object, decimal?>> selectorNM = o => 0;
Expression<Func<object, double?>> selectorND = o => 0;
Expression<Func<object, long?>> selectorNL = o => 0;
method2id.Add(MethodOf(() => Queryable.Where(null, predicate)), SoodaLinqMethod.Queryable_Where);
method2id.Add(MethodOf(() => Queryable.OrderBy(null, selector)), SoodaLinqMethod.Queryable_OrderBy);
method2id.Add(MethodOf(() => Queryable.OrderByDescending(null, selector)), SoodaLinqMethod.Queryable_OrderByDescending);
method2id.Add(MethodOf(() => Queryable.ThenBy(null, selector)), SoodaLinqMethod.Queryable_ThenBy);
method2id.Add(MethodOf(() => Queryable.ThenByDescending(null, selector)), SoodaLinqMethod.Queryable_ThenByDescending);
method2id.Add(MethodOf(() => Queryable.Skip<object>(null, 0)), SoodaLinqMethod.Queryable_Skip);
method2id.Add(MethodOf(() => Queryable.Take<object>(null, 0)), SoodaLinqMethod.Queryable_Take);
method2id.Add(MethodOf(() => Queryable.Select(null, selector)), SoodaLinqMethod.Queryable_Select);
method2id.Add(MethodOf(() => Queryable.Select(null, (object o, int i) => i)), SoodaLinqMethod.Queryable_SelectIndexed);
method2id.Add(MethodOf(() => Queryable.GroupBy(null, selector)), SoodaLinqMethod.Queryable_GroupBy);
method2id.Add(MethodOf(() => Queryable.Reverse<object>(null)), SoodaLinqMethod.Queryable_Reverse);
method2id.Add(MethodOf(() => Queryable.Distinct<object>(null)), SoodaLinqMethod.Queryable_Distinct);
method2id.Add(MethodOf(() => Queryable.OfType<object>(null)), SoodaLinqMethod.Queryable_OfType);
method2id.Add(MethodOf(() => Queryable.Except<object>(null, null)), SoodaLinqMethod.Queryable_Except);
method2id.Add(MethodOf(() => Queryable.Intersect<object>(null, null)), SoodaLinqMethod.Queryable_Intersect);
method2id.Add(MethodOf(() => Queryable.Union<object>(null, null)), SoodaLinqMethod.Queryable_Union);
method2id.Add(MethodOf(() => Queryable.All(null, predicate)), SoodaLinqMethod.Enumerable_All);
method2id.Add(MethodOf(() => Queryable.Any<object>(null)), SoodaLinqMethod.Enumerable_Any);
method2id.Add(MethodOf(() => Queryable.Any(null, predicate)), SoodaLinqMethod.Enumerable_AnyFiltered);
method2id.Add(MethodOf(() => Queryable.Contains<object>(null, null)), SoodaLinqMethod.Enumerable_Contains);
method2id.Add(MethodOf(() => Queryable.Count<object>(null)), SoodaLinqMethod.Enumerable_Count);
method2id.Add(MethodOf(() => Queryable.Count(null, predicate)), SoodaLinqMethod.Enumerable_CountFiltered);
method2id.Add(MethodOf(() => Queryable.First<object>(null)), SoodaLinqMethod.Queryable_First);
method2id.Add(MethodOf(() => Queryable.First(null, predicate)), SoodaLinqMethod.Queryable_FirstFiltered);
method2id.Add(MethodOf(() => Queryable.FirstOrDefault<object>(null)), SoodaLinqMethod.Queryable_FirstOrDefault);
method2id.Add(MethodOf(() => Queryable.FirstOrDefault(null, predicate)), SoodaLinqMethod.Queryable_FirstOrDefaultFiltered);
method2id.Add(MethodOf(() => Queryable.Last<object>(null)), SoodaLinqMethod.Queryable_Last);
method2id.Add(MethodOf(() => Queryable.Last(null, predicate)), SoodaLinqMethod.Queryable_LastFiltered);
method2id.Add(MethodOf(() => Queryable.LastOrDefault<object>(null)), SoodaLinqMethod.Queryable_LastOrDefault);
method2id.Add(MethodOf(() => Queryable.LastOrDefault(null, predicate)), SoodaLinqMethod.Queryable_LastOrDefaultFiltered);
method2id.Add(MethodOf(() => Queryable.Single<object>(null)), SoodaLinqMethod.Queryable_Single);
method2id.Add(MethodOf(() => Queryable.Single(null, predicate)), SoodaLinqMethod.Queryable_SingleFiltered);
method2id.Add(MethodOf(() => Queryable.SingleOrDefault<object>(null)), SoodaLinqMethod.Queryable_SingleOrDefault);
method2id.Add(MethodOf(() => Queryable.SingleOrDefault(null, predicate)), SoodaLinqMethod.Queryable_SingleOrDefaultFiltered);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<decimal>) null)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<double>) null)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<int>) null)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<long>) null)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<decimal?>) null)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<double?>) null)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<int?>) null)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Average((IQueryable<long?>) null)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Max<int>(null)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Queryable.Min<int>(null)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<decimal>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<double>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<int>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<long>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<decimal?>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<double?>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<int?>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum((IQueryable<long?>) null)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Average(null, selectorM)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average(null, selectorD)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average(null, selector)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average(null, selectorL)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Queryable.Average(null, selectorNM)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Average(null, selectorND)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Average(null, selectorN)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Average(null, selectorNL)), SoodaLinqMethod.Queryable_AverageNullable);
method2id.Add(MethodOf(() => Queryable.Max(null, selector)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Queryable.Min(null, selector)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Queryable.Sum(null, selectorM)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum(null, selectorD)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum(null, selector)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum(null, selectorL)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum(null, selectorNM)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum(null, selectorND)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum(null, selectorN)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Queryable.Sum(null, selectorNL)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.All(null, (object o) => true)), SoodaLinqMethod.Enumerable_All);
method2id.Add(MethodOf(() => Enumerable.Any<object>(null)), SoodaLinqMethod.Enumerable_Any);
method2id.Add(MethodOf(() => Enumerable.Any(null, (object o) => true)), SoodaLinqMethod.Enumerable_AnyFiltered);
method2id.Add(MethodOf(() => Enumerable.Contains<object>(null, null)), SoodaLinqMethod.Enumerable_Contains);
method2id.Add(MethodOf(() => Enumerable.Count<object>(null)), SoodaLinqMethod.Enumerable_Count);
method2id.Add(MethodOf(() => Enumerable.Count(null, (object o) => true)), SoodaLinqMethod.Enumerable_CountFiltered);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => 0M)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => 0D)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => 0)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => 0L)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => (decimal?) 0)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => (double?) 0)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => (int?) 0)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Average(null, (object o) => (long?) 0)), SoodaLinqMethod.Enumerable_Average);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => 0M)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => 0D)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => 0)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => 0L)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => (decimal?) 0)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => (double?) 0)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => (int?) 0)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => (long?) 0)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Max(null, (object o) => string.Empty)), SoodaLinqMethod.Enumerable_Max);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => 0M)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => 0D)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => 0)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => 0L)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => (decimal?) 0)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => (double?) 0)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => (int?) 0)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => (long?) 0)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Min(null, (object o) => string.Empty)), SoodaLinqMethod.Enumerable_Min);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => 0M)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => 0D)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => 0)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => 0L)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => (decimal?) 0)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => (double?) 0)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => (int?) 0)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => Enumerable.Sum(null, (object o) => (long?) 0)), SoodaLinqMethod.Enumerable_Sum);
method2id.Add(MethodOf(() => ((ICollection<object>) null).Contains(null)), SoodaLinqMethod.ICollection_Contains);
method2id.Add(MethodOf(() => ((List<object>) null).Contains(null)), SoodaLinqMethod.ICollection_Contains);
method2id.Add(MethodOf(() => ((System.Collections.ArrayList) null).Contains(null)), SoodaLinqMethod.ICollection_Contains);
method2id.Add(MethodOf(() => ((System.Collections.IList) null).Contains(null)), SoodaLinqMethod.ICollection_Contains);
method2id.Add(MethodOf(() => ((Sooda.ObjectMapper.SoodaObjectCollectionWrapperGeneric<object>) null).Contains(null)), SoodaLinqMethod.ICollection_Contains);
method2id.Add(MethodOf(() => string.Empty.GetType()), SoodaLinqMethod.Object_GetType);
method2id.Add(MethodOf(() => ((object) null).Equals(null)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => false.Equals(false)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => 0M.Equals(0M)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => 0D.Equals(0D)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => 0.Equals(0)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => 0L.Equals(0L)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => string.Empty.Equals(string.Empty)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => DateTime.Now.Equals(DateTime.Now)), SoodaLinqMethod.Object_InstanceEquals);
method2id.Add(MethodOf(() => object.Equals(null, null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => string.Equals(null, null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => DateTime.Equals(DateTime.Now, DateTime.Now)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlBoolean.Equals(SqlBoolean.Null, SqlBoolean.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlDateTime.Equals(SqlDateTime.Null, SqlDateTime.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlDecimal.Equals(SqlDecimal.Null, SqlDecimal.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlDouble.Equals(SqlDouble.Null, SqlDouble.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlGuid.Equals(SqlGuid.Null, SqlGuid.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlInt32.Equals(SqlInt32.Null, SqlInt32.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlInt64.Equals(SqlInt64.Null, SqlInt64.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlSingle.Equals(SqlSingle.Null, SqlSingle.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => SqlString.Equals(SqlString.Null, SqlString.Null)), SoodaLinqMethod.Object_StaticEquals);
method2id.Add(MethodOf(() => string.Concat(string.Empty, string.Empty)), SoodaLinqMethod.String_Concat);
method2id.Add(MethodOf(() => LinqUtils.Like(string.Empty, string.Empty)), SoodaLinqMethod.String_Like);
method2id.Add(MethodOf(() => string.Empty.Remove(0)), SoodaLinqMethod.String_Remove);
method2id.Add(MethodOf(() => string.Empty.Substring(0, 0)), SoodaLinqMethod.String_Substring);
method2id.Add(MethodOf(() => string.Empty.Replace(string.Empty, string.Empty)), SoodaLinqMethod.String_Replace);
method2id.Add(MethodOf(() => string.Empty.ToLower()), SoodaLinqMethod.String_ToLower);
method2id.Add(MethodOf(() => string.Empty.ToUpper()), SoodaLinqMethod.String_ToUpper);
method2id.Add(MethodOf(() => string.Empty.StartsWith(string.Empty)), SoodaLinqMethod.String_StartsWith);
method2id.Add(MethodOf(() => string.Empty.EndsWith(string.Empty)), SoodaLinqMethod.String_EndsWith);
method2id.Add(MethodOf(() => string.Empty.Contains(string.Empty)), SoodaLinqMethod.String_Contains);
method2id.Add(MethodOf(() => string.IsNullOrEmpty(null)), SoodaLinqMethod.String_IsNullOrEmpty);
method2id.Add(MethodOf(() => 0.ToString()), SoodaLinqMethod.Int_ToString);
method2id.Add(MethodOf(() => 0L.ToString()), SoodaLinqMethod.Long_ToString);
method2id.Add(MethodOf(() => 0D.ToString()), SoodaLinqMethod.Double_ToString);
method2id.Add(MethodOf(() => 0M.ToString()), SoodaLinqMethod.Decimal_ToString);
method2id.Add(MethodOf(() => false.ToString()), SoodaLinqMethod.Bool_ToString);
method2id.Add(MethodOf(() => Math.Abs(0M)), SoodaLinqMethod.Math_Abs);
method2id.Add(MethodOf(() => Math.Abs(0D)), SoodaLinqMethod.Math_Abs);
method2id.Add(MethodOf(() => Math.Abs((short) 0)), SoodaLinqMethod.Math_Abs);
method2id.Add(MethodOf(() => Math.Abs(0)), SoodaLinqMethod.Math_Abs);
method2id.Add(MethodOf(() => Math.Abs(0L)), SoodaLinqMethod.Math_Abs);
method2id.Add(MethodOf(() => Math.Abs((sbyte) 0)), SoodaLinqMethod.Math_Abs);
method2id.Add(MethodOf(() => Math.Abs(0F)), SoodaLinqMethod.Math_Abs);
method2id.Add(MethodOf(() => Math.Acos(0)), SoodaLinqMethod.Math_Acos);
method2id.Add(MethodOf(() => Math.Asin(0)), SoodaLinqMethod.Math_Asin);
method2id.Add(MethodOf(() => Math.Atan(0)), SoodaLinqMethod.Math_Atan);
method2id.Add(MethodOf(() => Math.Cos(0)), SoodaLinqMethod.Math_Cos);
method2id.Add(MethodOf(() => Math.Exp(0)), SoodaLinqMethod.Math_Exp);
method2id.Add(MethodOf(() => Math.Floor(0M)), SoodaLinqMethod.Math_Floor);
method2id.Add(MethodOf(() => Math.Floor(0D)), SoodaLinqMethod.Math_Floor);
method2id.Add(MethodOf(() => Math.Pow(1, 1)), SoodaLinqMethod.Math_Pow);
method2id.Add(MethodOf(() => Math.Round(0M, 0)), SoodaLinqMethod.Math_Round);
method2id.Add(MethodOf(() => Math.Round(0D, 0)), SoodaLinqMethod.Math_Round);
method2id.Add(MethodOf(() => Math.Sign(0M)), SoodaLinqMethod.Math_Sign);
method2id.Add(MethodOf(() => Math.Sign(0D)), SoodaLinqMethod.Math_Sign);
method2id.Add(MethodOf(() => Math.Sign((short) 0)), SoodaLinqMethod.Math_Sign);
method2id.Add(MethodOf(() => Math.Sign(0)), SoodaLinqMethod.Math_Sign);
method2id.Add(MethodOf(() => Math.Sign(0L)), SoodaLinqMethod.Math_Sign);
method2id.Add(MethodOf(() => Math.Sign((sbyte) 0)), SoodaLinqMethod.Math_Sign);
method2id.Add(MethodOf(() => Math.Sign(0F)), SoodaLinqMethod.Math_Sign);
method2id.Add(MethodOf(() => Math.Sin(0)), SoodaLinqMethod.Math_Sin);
method2id.Add(MethodOf(() => Math.Sqrt(0)), SoodaLinqMethod.Math_Sqrt);
method2id.Add(MethodOf(() => Math.Tan(0)), SoodaLinqMethod.Math_Tan);
method2id.Add(MethodOf(() => ((SoodaObject) null).GetPrimaryKeyValue()), SoodaLinqMethod.SoodaObject_GetPrimaryKeyValue);
method2id.Add(MethodOf(() => ((SoodaObject) null).GetLabel(false)), SoodaLinqMethod.SoodaObject_GetLabel);
// doesn't compile: method2id.Add(MethodOf(() => ((SoodaObject) null)[string.Empty]), SoodaLinqMethod.SoodaObject_GetItem);
method2id.Add(typeof(SoodaObject).GetMethod("get_Item"), SoodaLinqMethod.SoodaObject_GetItem);
_method2id = method2id;
return method2id;
}
public static SoodaLinqMethod Get(MethodInfo method)
{
Dictionary<MethodInfo, SoodaLinqMethod> method2id = _method2id ?? Initialize();
SoodaLinqMethod id;
method2id.TryGetValue(Ungeneric(method), out id);
return id;
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System;
internal class NullableTest1
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((char?)o) == null;
}
public static void Run()
{
char? s = null;
Console.WriteLine("char");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest2
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((bool?)o) == null;
}
public static void Run()
{
bool? s = null;
Console.WriteLine("bool");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest3
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((byte?)o) == null;
}
public static void Run()
{
byte? s = null;
Console.WriteLine("byte");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest4
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((sbyte?)o) == null;
}
public static void Run()
{
sbyte? s = null;
Console.WriteLine("sbyte");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest5
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((short?)o) == null;
}
public static void Run()
{
short? s = null;
Console.WriteLine("short");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest6
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ushort?)o) == null;
}
public static void Run()
{
ushort? s = null;
Console.WriteLine("ushort");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest7
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((int?)o) == null;
}
public static void Run()
{
int? s = null;
Console.WriteLine("int");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest8
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((uint?)o) == null;
}
public static void Run()
{
uint? s = null;
Console.WriteLine("uint");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest9
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((long?)o) == null;
}
public static void Run()
{
long? s = null;
Console.WriteLine("long");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest10
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ulong?)o) == null;
}
public static void Run()
{
ulong? s = null;
Console.WriteLine("ulong");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest11
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((float?)o) == null;
}
public static void Run()
{
float? s = null;
Console.WriteLine("float");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest12
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((double?)o) == null;
}
public static void Run()
{
double? s = null;
Console.WriteLine("double");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest13
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((decimal?)o) == null;
}
public static void Run()
{
decimal? s = null;
Console.WriteLine("decimal");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest14
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((IntPtr?)o) == null;
}
public static void Run()
{
IntPtr? s = null;
Console.WriteLine("IntPtr");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest15
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((UIntPtr?)o) == null;
}
public static void Run()
{
UIntPtr? s = null;
Console.WriteLine("UIntPtr");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest16
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((Guid?)o) == null;
}
public static void Run()
{
Guid? s = null;
Console.WriteLine("Guid");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest17
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((GCHandle?)o) == null;
}
public static void Run()
{
GCHandle? s = null;
Console.WriteLine("GCHandle");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest18
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ByteE?)o) == null;
}
public static void Run()
{
ByteE? s = null;
Console.WriteLine("ByteE");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest19
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((IntE?)o) == null;
}
public static void Run()
{
IntE? s = null;
Console.WriteLine("IntE");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest20
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((LongE?)o) == null;
}
public static void Run()
{
LongE? s = null;
Console.WriteLine("LongE");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest21
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((EmptyStruct?)o) == null;
}
public static void Run()
{
EmptyStruct? s = null;
Console.WriteLine("EmptyStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest22
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStruct?)o) == null;
}
public static void Run()
{
NotEmptyStruct? s = null;
Console.WriteLine("NotEmptyStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest23
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructQ?)o) == null;
}
public static void Run()
{
NotEmptyStructQ? s = null;
Console.WriteLine("NotEmptyStructQ");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest24
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructA?)o) == null;
}
public static void Run()
{
NotEmptyStructA? s = null;
Console.WriteLine("NotEmptyStructA");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest25
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructQA?)o) == null;
}
public static void Run()
{
NotEmptyStructQA? s = null;
Console.WriteLine("NotEmptyStructQA");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest26
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((EmptyStructGen<int>?)o) == null;
}
public static void Run()
{
EmptyStructGen<int>? s = null;
Console.WriteLine("EmptyStructGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest27
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructGen<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructGen<int>? s = null;
Console.WriteLine("NotEmptyStructGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest28
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGen<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGen<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest29
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGenA<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGenA<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGenA<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest30
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGenQ<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGenQ<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGenQ<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest31
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NotEmptyStructConstrainedGenQA<int>?)o) == null;
}
public static void Run()
{
NotEmptyStructConstrainedGenQA<int>? s = null;
Console.WriteLine("NotEmptyStructConstrainedGenQA<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest32
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NestedStruct?)o) == null;
}
public static void Run()
{
NestedStruct? s = null;
Console.WriteLine("NestedStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest33
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((NestedStructGen<int>?)o) == null;
}
public static void Run()
{
NestedStructGen<int>? s = null;
Console.WriteLine("NestedStructGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest34
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ExplicitFieldOffsetStruct?)o) == null;
}
public static void Run()
{
ExplicitFieldOffsetStruct? s = null;
Console.WriteLine("ExplicitFieldOffsetStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest37
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((MarshalAsStruct?)o) == null;
}
public static void Run()
{
MarshalAsStruct? s = null;
Console.WriteLine("MarshalAsStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest38
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementOneInterface?)o) == null;
}
public static void Run()
{
ImplementOneInterface? s = null;
Console.WriteLine("ImplementOneInterface");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest39
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementTwoInterface?)o) == null;
}
public static void Run()
{
ImplementTwoInterface? s = null;
Console.WriteLine("ImplementTwoInterface");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest40
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementOneInterfaceGen<int>?)o) == null;
}
public static void Run()
{
ImplementOneInterfaceGen<int>? s = null;
Console.WriteLine("ImplementOneInterfaceGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest41
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementTwoInterfaceGen<int>?)o) == null;
}
public static void Run()
{
ImplementTwoInterfaceGen<int>? s = null;
Console.WriteLine("ImplementTwoInterfaceGen<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest42
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((ImplementAllInterface<int>?)o) == null;
}
public static void Run()
{
ImplementAllInterface<int>? s = null;
Console.WriteLine("ImplementAllInterface<int>");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest43
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((WithMultipleGCHandleStruct?)o) == null;
}
public static void Run()
{
WithMultipleGCHandleStruct? s = null;
Console.WriteLine("WithMultipleGCHandleStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest44
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((WithOnlyFXTypeStruct?)o) == null;
}
public static void Run()
{
WithOnlyFXTypeStruct? s = null;
Console.WriteLine("WithOnlyFXTypeStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class NullableTest45
{
private static bool BoxUnboxToNQGen<T>(T o)
{
return ((object)o) == null;
}
private static bool BoxUnboxToQGen<T>(T? o) where T : struct
{
return ((T?)o) == null;
}
private static bool BoxUnboxToNQ(object o)
{
return o == null;
}
private static bool BoxUnboxToQ(object o)
{
return ((MixedAllStruct?)o) == null;
}
public static void Run()
{
MixedAllStruct? s = null;
Console.WriteLine("MixedAllStruct");
Assert.IsTrue(BoxUnboxToNQ(s));
Assert.IsTrue(BoxUnboxToQ(s));
Assert.IsTrue(BoxUnboxToNQGen(s));
Assert.IsTrue(BoxUnboxToQGen(s));
}
}
internal class Test
{
private static int Main()
{
try
{
NullableTest1.Run();
NullableTest2.Run();
NullableTest3.Run();
NullableTest4.Run();
NullableTest5.Run();
NullableTest6.Run();
NullableTest7.Run();
NullableTest8.Run();
NullableTest9.Run();
NullableTest10.Run();
NullableTest11.Run();
NullableTest12.Run();
NullableTest13.Run();
NullableTest14.Run();
NullableTest15.Run();
NullableTest16.Run();
NullableTest17.Run();
NullableTest18.Run();
NullableTest19.Run();
NullableTest20.Run();
NullableTest21.Run();
NullableTest22.Run();
NullableTest23.Run();
NullableTest24.Run();
NullableTest25.Run();
NullableTest26.Run();
NullableTest27.Run();
NullableTest28.Run();
NullableTest29.Run();
NullableTest30.Run();
NullableTest31.Run();
NullableTest32.Run();
NullableTest33.Run();
NullableTest34.Run();
NullableTest37.Run();
NullableTest38.Run();
NullableTest39.Run();
NullableTest40.Run();
NullableTest41.Run();
NullableTest42.Run();
NullableTest43.Run();
NullableTest44.Run();
NullableTest45.Run();
}
catch (Exception ex)
{
Console.WriteLine("Test FAILED");
Console.WriteLine(ex);
return 666;
}
Console.WriteLine("Test SUCCESS");
return 100;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class MessageProcessingHandlerTest
{
[Fact]
public void Ctor_CreateDispose_Success()
{
using (var handler = new MockHandler())
{
Assert.Null(handler.InnerHandler);
}
}
[Fact]
public void Ctor_CreateWithHandlerDispose_Success()
{
using (var handler = new MockHandler(new MockTransportHandler()))
{
Assert.NotNull(handler.InnerHandler);
}
}
[Fact]
public void Ctor_CreateWithNullHandler_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new MockHandler(null));
}
[Fact]
public void SendAsync_NullRequest_ThrowsArgumentNullException()
{
var transport = new MockTransportHandler();
var handler = new MockHandler(transport);
Assert.Throws<ArgumentNullException>(() => { Task t = handler.TestSendAsync(null, CancellationToken.None); });
}
[Fact]
public async Task SendAsync_CallMethod_ProcessRequestAndProcessResponseCalled()
{
var transport = new MockTransportHandler();
var handler = new MockHandler(transport);
await handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None);
Assert.Equal(1, handler.ProcessRequestCount);
Assert.Equal(1, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_InnerHandlerThrows_ThrowWithoutCallingProcessRequest()
{
var transport = new MockTransportHandler(true); // Throw if Send/SendAsync() is called.
var handler = new MockHandler(transport);
await Assert.ThrowsAsync<MockException>(() => handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None));
Assert.Equal(1, handler.ProcessRequestCount);
Assert.Equal(0, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_InnerHandlerReturnsNullResponse_ThrowInvalidOperationExceptionWithoutCallingProcessRequest()
{
var transport = new MockTransportHandler(() => { return null; });
var handler = new MockHandler(transport);
await Assert.ThrowsAsync<InvalidOperationException>(() => handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None));
Assert.Equal(1, handler.ProcessRequestCount);
Assert.Equal(0, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_ProcessRequestThrows_ThrowWithoutCallingProcessRequestNorInnerHandler()
{
var transport = new MockTransportHandler();
// ProcessRequest() throws exception.
var handler = new MockHandler(transport, true, () => { throw new MockException(); });
// Note that ProcessRequest() is called by SendAsync(). However, the exception is not thrown
// by SendAsync(). Instead, the returned Task is marked as faulted and contains the exception.
await Assert.ThrowsAsync<MockException>(() => handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None));
Assert.Equal(0, transport.SendAsyncCount);
Assert.Equal(1, handler.ProcessRequestCount);
Assert.Equal(0, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_ProcessResponseThrows_TaskIsFaulted()
{
var transport = new MockTransportHandler();
// ProcessResponse() throws exception.
var handler = new MockHandler(transport, false, () => { throw new MockException(); });
// Throwing an exception in ProcessResponse() will cause the Task to complete as 'faulted'.
await Assert.ThrowsAsync<MockException>(() => handler.TestSendAsync(new HttpRequestMessage(), CancellationToken.None));
Assert.Equal(1, transport.SendAsyncCount);
Assert.Equal(1, handler.ProcessRequestCount);
Assert.Equal(1, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_OperationCanceledWhileInnerHandlerIsWorking_TaskSetToIsCanceled()
{
var cts = new CancellationTokenSource();
// We simulate a cancellation happening while the inner handler was processing the request, by letting
// the inner mock handler call Cancel() and behave like if another thread called cancel while it was
// processing.
var transport = new MockTransportHandler(cts); // inner handler will cancel.
var handler = new MockHandler(transport);
await Assert.ThrowsAsync<TaskCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token));
Assert.Equal(0, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_OperationCanceledWhileProcessRequestIsExecuted_TaskSetToIsCanceled()
{
var cts = new CancellationTokenSource();
var transport = new MockTransportHandler();
// ProcessRequest will cancel.
var handler = new MockHandler(transport, true,
() => { cts.Cancel(); cts.Token.ThrowIfCancellationRequested(); });
// Note that even ProcessMessage() is called on the same thread, we don't expect SendAsync() to throw.
// SendAsync() must complete successfully, but the Task will be canceled.
await Assert.ThrowsAsync<TaskCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token));
Assert.Equal(0, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_OperationCanceledWhileProcessResponseIsExecuted_TaskSetToIsCanceled()
{
var cts = new CancellationTokenSource();
var transport = new MockTransportHandler();
// ProcessResponse will cancel.
var handler = new MockHandler(transport, false,
() => { cts.Cancel(); cts.Token.ThrowIfCancellationRequested(); });
await Assert.ThrowsAsync<TaskCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token));
}
[Fact]
public async Task SendAsync_ProcessRequestThrowsOperationCanceledExceptionNotBoundToCts_TaskSetToIsFaulted()
{
var cts = new CancellationTokenSource();
var transport = new MockTransportHandler();
// ProcessRequest will throw a random OperationCanceledException() not related to cts. We also cancel
// the cts to make sure the code behaves correctly even if cts is canceled & an OperationCanceledException
// was thrown.
var handler = new MockHandler(transport, true,
() => { cts.Cancel(); throw new OperationCanceledException("custom"); });
await Assert.ThrowsAsync<OperationCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token));
Assert.Equal(0, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_ProcessResponseThrowsOperationCanceledExceptionNotBoundToCts_TaskSetToIsFaulted()
{
var cts = new CancellationTokenSource();
var transport = new MockTransportHandler();
// ProcessResponse will throw a random OperationCanceledException() not related to cts. We also cancel
// the cts to make sure the code behaves correctly even if cts is canceled & an OperationCanceledException
// was thrown.
var handler = new MockHandler(transport, false,
() => { cts.Cancel(); throw new OperationCanceledException("custom"); });
await Assert.ThrowsAsync<OperationCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token));
Assert.Equal(1, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_ProcessRequestThrowsOperationCanceledExceptionUsingOtherCts_TaskSetToIsFaulted()
{
var cts = new CancellationTokenSource();
var otherCts = new CancellationTokenSource();
var transport = new MockTransportHandler();
// ProcessRequest will throw a random OperationCanceledException() not related to cts. We also cancel
// the cts to make sure the code behaves correctly even if cts is canceled & an OperationCanceledException
// was thrown.
var handler = new MockHandler(transport, true,
() => { cts.Cancel(); throw new OperationCanceledException("custom", otherCts.Token); });
await Assert.ThrowsAsync<OperationCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token));
Assert.Equal(0, handler.ProcessResponseCount);
}
[Fact]
public async Task SendAsync_ProcessResponseThrowsOperationCanceledExceptionUsingOtherCts_TaskSetToIsFaulted()
{
var cts = new CancellationTokenSource();
var otherCts = new CancellationTokenSource();
var transport = new MockTransportHandler();
// ProcessResponse will throw a random OperationCanceledException() not related to cts. We also cancel
// the cts to make sure the code behaves correctly even if cts is canceled & an OperationCanceledException
// was thrown.
var handler = new MockHandler(transport, false,
() => { cts.Cancel(); throw new OperationCanceledException("custom", otherCts.Token); });
await Assert.ThrowsAsync<OperationCanceledException>(() => handler.TestSendAsync(new HttpRequestMessage(), cts.Token));
Assert.Equal(1, handler.ProcessResponseCount);
}
#region Helper methods
public class MockException : Exception
{
public MockException() { }
public MockException(string message) : base(message) { }
public MockException(string message, Exception inner) : base(message, inner) { }
}
private class MockHandler : MessageProcessingHandler
{
private bool _callInProcessRequest;
private Action _customAction;
public int ProcessRequestCount { get; private set; }
public int ProcessResponseCount { get; private set; }
public MockHandler()
: base()
{
}
public MockHandler(HttpMessageHandler innerHandler)
: this(innerHandler, true, null)
{
}
public MockHandler(HttpMessageHandler innerHandler, bool callInProcessRequest, Action customAction)
: base(innerHandler)
{
_customAction = customAction;
_callInProcessRequest = callInProcessRequest;
}
public Task<HttpResponseMessage> TestSendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return SendAsync(request, cancellationToken);
}
protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request,
CancellationToken cancellationToken)
{
ProcessRequestCount++;
Assert.NotNull(request);
if (_callInProcessRequest && (_customAction != null))
{
_customAction();
}
return request;
}
protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response,
CancellationToken cancellationToken)
{
ProcessResponseCount++;
Assert.NotNull(response);
if (!_callInProcessRequest && (_customAction != null))
{
_customAction();
}
return response;
}
}
private class MockTransportHandler : HttpMessageHandler
{
private bool _alwaysThrow;
private CancellationTokenSource _cts;
private Func<HttpResponseMessage> _mockResultDelegate;
public int SendAsyncCount { get; private set; }
public MockTransportHandler(Func<HttpResponseMessage> mockResultDelegate)
{
_mockResultDelegate = mockResultDelegate;
}
public MockTransportHandler()
{
}
public MockTransportHandler(bool alwaysThrow)
{
_alwaysThrow = alwaysThrow;
}
public MockTransportHandler(CancellationTokenSource cts)
{
_cts = cts;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
SendAsyncCount++;
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
if (_cts != null)
{
_cts.Cancel();
tcs.TrySetCanceled();
}
if (_alwaysThrow)
{
tcs.TrySetException(new MockException());
}
else
{
if (_mockResultDelegate == null)
{
tcs.TrySetResult(new HttpResponseMessage());
}
else
{
tcs.TrySetResult(_mockResultDelegate());
}
}
return tcs.Task;
}
}
#endregion
}
}
| |
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Orleans.Serialization.Cloning;
using Orleans.Serialization.Codecs;
using Orleans.Serialization.Invocation;
using Orleans.Serialization.Serializers;
using Microsoft.Extensions.DependencyInjection;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// Properties common to <see cref="GrainReference"/> instances with the same <see cref="Runtime.GrainType"/> and <see cref="GrainInterfaceType"/>.
/// </summary>
public class GrainReferenceShared
{
public GrainReferenceShared(
GrainType graintype,
GrainInterfaceType grainInterfaceType,
ushort interfaceVersion,
IGrainReferenceRuntime runtime,
InvokeMethodOptions invokeMethodOptions,
IServiceProvider serviceProvider)
{
this.GrainType = graintype;
this.InterfaceType = grainInterfaceType;
this.Runtime = runtime;
this.InvokeMethodOptions = invokeMethodOptions;
this.ServiceProvider = serviceProvider;
this.InterfaceVersion = interfaceVersion;
}
public IGrainReferenceRuntime Runtime { get; }
public GrainType GrainType { get; }
public GrainInterfaceType InterfaceType { get; }
public InvokeMethodOptions InvokeMethodOptions { get; }
public IServiceProvider ServiceProvider { get; }
public ushort InterfaceVersion { get; }
}
[RegisterSerializer]
internal class GrainReferenceCodec : GeneralizedReferenceTypeSurrogateCodec<IAddressable, GrainReferenceSurrogate>
{
private readonly IGrainFactory _grainFactory;
public GrainReferenceCodec(IGrainFactory grainFactory, IValueSerializer<GrainReferenceSurrogate> surrogateSerializer) : base(surrogateSerializer)
{
_grainFactory = grainFactory;
}
public override IAddressable ConvertFromSurrogate(ref GrainReferenceSurrogate surrogate)
{
return _grainFactory.GetGrain(surrogate.GrainId, surrogate.GrainInterfaceType);
}
public override void ConvertToSurrogate(IAddressable value, ref GrainReferenceSurrogate surrogate)
{
var refValue = value.AsReference();
surrogate = new GrainReferenceSurrogate
{
GrainId = refValue.GrainId,
GrainInterfaceType = refValue.InterfaceType
};
}
}
[RegisterCopier]
internal class GrainReferenceCopier : IDeepCopier<GrainReference>, IDerivedTypeCopier
{
public GrainReference DeepCopy(GrainReference input, CopyContext context) => input;
}
internal class GrainReferenceCopierProvider : ISpecializableCopier
{
public IDeepCopier GetSpecializedCodec(Type type) => (IDeepCopier)Activator.CreateInstance(typeof(TypedGrainReferenceCopier<>).MakeGenericType(type));
public bool IsSupportedType(Type type) => typeof(IAddressable).IsAssignableFrom(type) && type.IsInterface;
}
internal class TypedGrainReferenceCopier<TInterface> : IDeepCopier<TInterface>
{
public TInterface DeepCopy(TInterface input, CopyContext context)
{
if (input is null) return input;
if (input is GrainReference) return input;
if (input is IGrainObserver observer)
{
GrainReferenceCodecProvider.ThrowGrainObserverInvalidException(observer);
}
var addressable = (IAddressable)input;
var grainReference = addressable.AsReference();
return (TInterface)grainReference.Runtime.Cast(addressable, typeof(TInterface));
}
}
internal class GrainReferenceCodecProvider : ISpecializableCodec
{
private readonly IServiceProvider _serviceProvider;
public GrainReferenceCodecProvider(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider;
public IFieldCodec GetSpecializedCodec(Type type) => (IFieldCodec)ActivatorUtilities.GetServiceOrCreateInstance(_serviceProvider, typeof(TypedGrainReferenceCodec<>).MakeGenericType(type));
public bool IsSupportedType(Type type) => typeof(IAddressable).IsAssignableFrom(type);
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ThrowGrainObserverInvalidException(IGrainObserver observer)
=> throw new NotSupportedException($"IGrainObserver parameters must be GrainReference or Grain and cannot be type {observer.GetType()}. Did you forget to CreateObjectReference?");
}
internal class TypedGrainReferenceCodec<T> : GeneralizedReferenceTypeSurrogateCodec<T, GrainReferenceSurrogate> where T : class, IAddressable
{
private readonly IGrainFactory _grainFactory;
public TypedGrainReferenceCodec(IGrainFactory grainFactory, IValueSerializer<GrainReferenceSurrogate> surrogateSerializer) : base(surrogateSerializer)
{
_grainFactory = grainFactory;
}
public override T ConvertFromSurrogate(ref GrainReferenceSurrogate surrogate)
{
return (T)_grainFactory.GetGrain(surrogate.GrainId, surrogate.GrainInterfaceType);
}
public override void ConvertToSurrogate(T value, ref GrainReferenceSurrogate surrogate)
{
// Check that the typical case is false before performing the more expensive interface check
if (value is not GrainReference refValue)
{
if (value is IGrainObserver observer)
{
GrainReferenceCodecProvider.ThrowGrainObserverInvalidException(observer);
}
refValue = (GrainReference)(object)value.AsReference<T>();
}
surrogate = new GrainReferenceSurrogate
{
GrainId = refValue.GrainId,
GrainInterfaceType = refValue.InterfaceType
};
}
}
[GenerateSerializer]
internal struct GrainReferenceSurrogate
{
[Id(1)]
public GrainId GrainId { get; set; }
[Id(2)]
public GrainInterfaceType GrainInterfaceType { get; set; }
}
/// <summary>
/// This is the base class for all typed grain references.
/// </summary>
public class GrainReference : IAddressable, IEquatable<GrainReference>
{
[NonSerialized]
private GrainReferenceShared _shared;
[NonSerialized]
private IdSpan _key;
internal GrainReferenceShared Shared => _shared ?? throw new GrainReferenceNotBoundException(this);
internal IGrainReferenceRuntime Runtime => Shared.Runtime;
public GrainId GrainId => GrainId.Create(_shared.GrainType, _key);
public GrainInterfaceType InterfaceType => _shared.InterfaceType;
/// <summary>Constructs a reference to the grain with the specified Id.</summary>
protected GrainReference(GrainReferenceShared shared, IdSpan key)
{
_shared = shared;
_key = key;
}
/// <summary>Constructs a reference to the grain with the specified ID.</summary>
internal static GrainReference FromGrainId(GrainReferenceShared shared, GrainId grainId)
{
return new GrainReference(shared, grainId.Key);
}
public virtual TGrainInterface Cast<TGrainInterface>() where TGrainInterface : IAddressable => (TGrainInterface)_shared.Runtime.Cast(this, typeof(TGrainInterface));
/// <summary>
/// Tests this reference for equality to another object.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="obj">The object to test for equality against this reference.</param>
/// <returns><c>true</c> if the object is equal to this reference.</returns>
public override bool Equals(object obj)
{
return Equals(obj as GrainReference);
}
public bool Equals(GrainReference other) => other is GrainReference && this.GrainId.Equals(other.GrainId);
/// <summary> Calculates a hash code for a grain reference. </summary>
public override int GetHashCode() => this.GrainId.GetHashCode();
/// <summary>Get a uniform hash code for this grain reference.</summary>
public uint GetUniformHashCode()
{
// GrainId already includes the hashed type code for generic arguments.
return GrainId.GetUniformHashCode();
}
/// <summary>
/// Compares two references for equality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns>
public static bool operator ==(GrainReference reference1, GrainReference reference2)
{
if (reference1 is null) return reference2 is null;
return reference1.Equals(reference2);
}
/// <summary>
/// Compares two references for inequality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns>
public static bool operator !=(GrainReference reference1, GrainReference reference2)
{
if (reference1 is null) return !(reference2 is null);
return !reference1.Equals(reference2);
}
/// <summary>
/// Implemented by generated subclasses to return a constant.
/// </summary>
public virtual int InterfaceTypeCode
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Return the method name associated with the specified interfaceId and methodId values.
/// </summary>
/// <param name="interfaceId">Interface Id</param>
/// <param name="methodId">Method Id</param>
/// <returns>Method name string.</returns>
public virtual string GetMethodName(int interfaceId, int methodId)
{
throw new InvalidOperationException("Should be overridden by subclass");
}
/// <summary>
/// Implemented in generated code.
/// </summary>
public virtual ushort InterfaceVersion
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Return the name of the interface for this GrainReference.
/// Implemented in Orleans generated code.
/// </summary>
public virtual string InterfaceName => InterfaceType.ToStringUtf8();
/// <summary>Returns a string representation of this reference.</summary>
public override string ToString() => $"GrainReference:{GrainId}:{InterfaceType}";
/// <summary>
/// Called from generated code.
/// </summary>
protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None)
{
this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | _shared.InvokeMethodOptions);
}
/// <summary>
/// Called from generated code.
/// </summary>
protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None)
{
return this.Runtime.InvokeMethodAsync<T>(this, methodId, arguments, options | _shared.InvokeMethodOptions);
}
}
[DefaultInvokableBaseType(typeof(ValueTask<>), typeof(Request<>))]
[DefaultInvokableBaseType(typeof(ValueTask), typeof(Request))]
[DefaultInvokableBaseType(typeof(Task<>), typeof(TaskRequest<>))]
[DefaultInvokableBaseType(typeof(Task), typeof(TaskRequest))]
[DefaultInvokableBaseType(typeof(void), typeof(VoidRequest))]
public abstract class NewGrainReference : GrainReference
{
protected NewGrainReference(GrainReferenceShared shared, IdSpan key) : base(shared, key)
{
}
public override ushort InterfaceVersion => Shared.InterfaceVersion;
protected TInvokable GetInvokable<TInvokable>() => ActivatorUtilities.GetServiceOrCreateInstance<TInvokable>(Shared.ServiceProvider);
protected void SendRequest(IResponseCompletionSource callback, IInvokable body)
{
var request = (RequestBase)body;
this.Runtime.SendRequest(this, callback, body, request.Options);
}
protected ValueTask<T> InvokeAsync<T>(IInvokable body)
{
var request = (RequestBase)body;
return this.Runtime.InvokeMethodAsync<T>(this, body, request.Options);
}
}
[GenerateSerializer]
public abstract class RequestBase : IInvokable
{
[field: NonSerialized]
public InvokeMethodOptions Options { get; private set; }
public abstract int ArgumentCount { get; }
public void AddInvokeMethodOptions(InvokeMethodOptions options)
{
Options |= options;
}
public abstract ValueTask<Response> Invoke();
public abstract TTarget GetTarget<TTarget>();
public abstract void SetTarget<TTargetHolder>(TTargetHolder holder) where TTargetHolder : ITargetHolder;
public abstract TArgument GetArgument<TArgument>(int index);
public abstract void SetArgument<TArgument>(int index, in TArgument value);
public abstract void Dispose();
public abstract string MethodName { get; }
public abstract Type[] MethodTypeArguments { get; }
public abstract string InterfaceName { get; }
public abstract Type InterfaceType { get; }
public abstract Type[] InterfaceTypeArguments { get; }
public abstract Type[] ParameterTypes { get; }
public abstract MethodInfo Method { get; }
}
[GenerateSerializer]
public abstract class Request : RequestBase
{
public override ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.Completed);
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask resultTask)
{
try
{
await resultTask;
return Response.Completed;
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract ValueTask InvokeInner();
}
[GenerateSerializer]
public abstract class Request<TResult> : RequestBase
{
public override ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.Result));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(ValueTask<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract ValueTask<TResult> InvokeInner();
}
[GenerateSerializer]
public abstract class TaskRequest<TResult> : RequestBase
{
public override ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
return new ValueTask<Response>(Response.FromResult(resultTask.GetAwaiter().GetResult()));
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(Task<TResult> resultTask)
{
try
{
var result = await resultTask;
return Response.FromResult(result);
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract Task<TResult> InvokeInner();
}
[GenerateSerializer]
public abstract class TaskRequest : RequestBase
{
public override ValueTask<Response> Invoke()
{
try
{
var resultTask = InvokeInner();
var status = resultTask.Status;
if (resultTask.IsCompleted)
{
resultTask.GetAwaiter().GetResult();
return new ValueTask<Response>(Response.Completed);
}
return CompleteInvokeAsync(resultTask);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
private static async ValueTask<Response> CompleteInvokeAsync(Task resultTask)
{
try
{
await resultTask;
return Response.Completed;
}
catch (Exception exception)
{
return Response.FromException(exception);
}
}
// Generated
protected abstract Task InvokeInner();
}
[GenerateSerializer]
public abstract class VoidRequest : RequestBase
{
public override ValueTask<Response> Invoke()
{
try
{
InvokeInner();
return new ValueTask<Response>(Response.Completed);
}
catch (Exception exception)
{
return new ValueTask<Response>(Response.FromException(exception));
}
}
// Generated
protected abstract void InvokeInner();
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public static class TernaryArrayNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableBoolArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
bool?[][] array2 = new bool?[][] { null, new bool?[0], new bool?[] { true, false }, new bool?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableBoolArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableByteArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
byte?[][] array2 = new byte?[][] { null, new byte?[0], new byte?[] { 0, 1, byte.MaxValue }, new byte?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableByteArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableCharArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
char?[][] array2 = new char?[][] { null, new char?[0], new char?[] { '\0', '\b', 'A', '\uffff' }, new char?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableCharArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableDecimalArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
decimal?[][] array2 = new decimal?[][] { null, new decimal?[0], new decimal?[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }, new decimal?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableDecimalArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableDoubleArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
double?[][] array2 = new double?[][] { null, new double?[0], new double?[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity }, new double?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableDoubleArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableFloatArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
float?[][] array2 = new float?[][] { null, new float?[0], new float?[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity }, new float?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableFloatArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableIntArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
int?[][] array2 = new int?[][] { null, new int?[0], new int?[] { 0, 1, -1, int.MinValue, int.MaxValue }, new int?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableIntArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableLongArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
long?[][] array2 = new long?[][] { null, new long?[0], new long?[] { 0, 1, -1, long.MinValue, long.MaxValue }, new long?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableLongArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableStructArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
S?[][] array2 = new S?[][] { null, new S?[0], new S?[] { default(S), new S() }, new S?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableStructArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableSByteArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
sbyte?[][] array2 = new sbyte?[][] { null, new sbyte?[0], new sbyte?[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }, new sbyte?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableSByteArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableStructWithStringArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Sc?[][] array2 = new Sc?[][] { null, new Sc?[0], new Sc?[] { default(Sc), new Sc(), new Sc(null) }, new Sc?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableStructWithStringArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableStructWithStringAndFieldArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Scs?[][] array2 = new Scs?[][] { null, new Scs?[0], new Scs?[] { default(Scs), new Scs(), new Scs(null, new S()) }, new Scs?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableStructWithStringAndFieldArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableShortArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
short?[][] array2 = new short?[][] { null, new short?[0], new short?[] { 0, 1, -1, short.MinValue, short.MaxValue }, new short?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableShortArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableStructWithTwoValuesArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Sp?[][] array2 = new Sp?[][] { null, new Sp?[0], new Sp?[] { default(Sp), new Sp(), new Sp(5, 5.0) }, new Sp?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableStructWithTwoValuesArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableStructWithValueArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
Ss?[][] array2 = new Ss?[][] { null, new Ss?[0], new Ss?[] { default(Ss), new Ss(), new Ss(new S()) }, new Ss?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableStructWithValueArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableUIntArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
uint?[][] array2 = new uint?[][] { null, new uint?[0], new uint?[] { 0, 1, uint.MaxValue }, new uint?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableUIntArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableULongArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
ulong?[][] array2 = new ulong?[][] { null, new ulong?[0], new ulong?[] { 0, 1, ulong.MaxValue }, new ulong?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableULongArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableUShortArrayTest(bool useInterpreter)
{
bool[] array1 = new bool[] { false, true };
ushort?[][] array2 = new ushort?[][] { null, new ushort?[0], new ushort?[] { 0, 1, ushort.MaxValue }, new ushort?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableUShortArray(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableGenericWithStructRestrictionArrayWithEnumTest(bool useInterpreter)
{
CheckTernaryArrayNullableGenericWithStructRestrictionArrayHelper<E>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableGenericWithStructRestrictionArrayWithStructTest(bool useInterpreter)
{
CheckTernaryArrayNullableGenericWithStructRestrictionArrayHelper<S>(useInterpreter);
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckTernaryArrayNullableGenericWithStructRestrictionArrayWithStructWithStringAndFieldTest(bool useInterpreter)
{
CheckTernaryArrayNullableGenericWithStructRestrictionArrayHelper<Scs>(useInterpreter);
}
#endregion
#region Generic helpers
private static void CheckTernaryArrayNullableGenericWithStructRestrictionArrayHelper<Ts>(bool useInterpreter) where Ts : struct
{
bool[] array1 = new bool[] { false, true };
Ts?[][] array2 = new Ts?[][] { null, new Ts?[0], new Ts?[] { default(Ts), new Ts() }, new Ts?[100] };
for (int i = 0; i < array1.Length; i++)
{
for (int j = 0; j < array2.Length; j++)
{
for (int k = 0; k < array2.Length; k++)
{
VerifyArrayNullableGenericWithStructRestrictionArray<Ts>(array1[i], array2[j], array2[k], useInterpreter);
}
}
}
}
#endregion
#region Test verifiers
private static void VerifyArrayNullableBoolArray(bool condition, bool?[] a, bool?[] b, bool useInterpreter)
{
Expression<Func<bool?[]>> e =
Expression.Lambda<Func<bool?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(bool?[])),
Expression.Constant(b, typeof(bool?[]))),
Enumerable.Empty<ParameterExpression>());
Func<bool?[]> f = e.Compile(useInterpreter);
bool?[] result = default(bool?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
bool?[] expected = default(bool?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableByteArray(bool condition, byte?[] a, byte?[] b, bool useInterpreter)
{
Expression<Func<byte?[]>> e =
Expression.Lambda<Func<byte?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(byte?[])),
Expression.Constant(b, typeof(byte?[]))),
Enumerable.Empty<ParameterExpression>());
Func<byte?[]> f = e.Compile(useInterpreter);
byte?[] result = default(byte?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
byte?[] expected = default(byte?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableCharArray(bool condition, char?[] a, char?[] b, bool useInterpreter)
{
Expression<Func<char?[]>> e =
Expression.Lambda<Func<char?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(char?[])),
Expression.Constant(b, typeof(char?[]))),
Enumerable.Empty<ParameterExpression>());
Func<char?[]> f = e.Compile(useInterpreter);
char?[] result = default(char?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
char?[] expected = default(char?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableDecimalArray(bool condition, decimal?[] a, decimal?[] b, bool useInterpreter)
{
Expression<Func<decimal?[]>> e =
Expression.Lambda<Func<decimal?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(decimal?[])),
Expression.Constant(b, typeof(decimal?[]))),
Enumerable.Empty<ParameterExpression>());
Func<decimal?[]> f = e.Compile(useInterpreter);
decimal?[] result = default(decimal?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
decimal?[] expected = default(decimal?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableDoubleArray(bool condition, double?[] a, double?[] b, bool useInterpreter)
{
Expression<Func<double?[]>> e =
Expression.Lambda<Func<double?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(double?[])),
Expression.Constant(b, typeof(double?[]))),
Enumerable.Empty<ParameterExpression>());
Func<double?[]> f = e.Compile(useInterpreter);
double?[] result = default(double?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
double?[] expected = default(double?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableFloatArray(bool condition, float?[] a, float?[] b, bool useInterpreter)
{
Expression<Func<float?[]>> e =
Expression.Lambda<Func<float?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(float?[])),
Expression.Constant(b, typeof(float?[]))),
Enumerable.Empty<ParameterExpression>());
Func<float?[]> f = e.Compile(useInterpreter);
float?[] result = default(float?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
float?[] expected = default(float?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableIntArray(bool condition, int?[] a, int?[] b, bool useInterpreter)
{
Expression<Func<int?[]>> e =
Expression.Lambda<Func<int?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(int?[])),
Expression.Constant(b, typeof(int?[]))),
Enumerable.Empty<ParameterExpression>());
Func<int?[]> f = e.Compile(useInterpreter);
int?[] result = default(int?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
int?[] expected = default(int?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableLongArray(bool condition, long?[] a, long?[] b, bool useInterpreter)
{
Expression<Func<long?[]>> e =
Expression.Lambda<Func<long?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(long?[])),
Expression.Constant(b, typeof(long?[]))),
Enumerable.Empty<ParameterExpression>());
Func<long?[]> f = e.Compile(useInterpreter);
long?[] result = default(long?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
long?[] expected = default(long?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableStructArray(bool condition, S?[] a, S?[] b, bool useInterpreter)
{
Expression<Func<S?[]>> e =
Expression.Lambda<Func<S?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(S?[])),
Expression.Constant(b, typeof(S?[]))),
Enumerable.Empty<ParameterExpression>());
Func<S?[]> f = e.Compile(useInterpreter);
S?[] result = default(S?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
S?[] expected = default(S?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableSByteArray(bool condition, sbyte?[] a, sbyte?[] b, bool useInterpreter)
{
Expression<Func<sbyte?[]>> e =
Expression.Lambda<Func<sbyte?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(sbyte?[])),
Expression.Constant(b, typeof(sbyte?[]))),
Enumerable.Empty<ParameterExpression>());
Func<sbyte?[]> f = e.Compile(useInterpreter);
sbyte?[] result = default(sbyte?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
sbyte?[] expected = default(sbyte?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableStructWithStringArray(bool condition, Sc?[] a, Sc?[] b, bool useInterpreter)
{
Expression<Func<Sc?[]>> e =
Expression.Lambda<Func<Sc?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sc?[])),
Expression.Constant(b, typeof(Sc?[]))),
Enumerable.Empty<ParameterExpression>());
Func<Sc?[]> f = e.Compile(useInterpreter);
Sc?[] result = default(Sc?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Sc?[] expected = default(Sc?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableStructWithStringAndFieldArray(bool condition, Scs?[] a, Scs?[] b, bool useInterpreter)
{
Expression<Func<Scs?[]>> e =
Expression.Lambda<Func<Scs?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Scs?[])),
Expression.Constant(b, typeof(Scs?[]))),
Enumerable.Empty<ParameterExpression>());
Func<Scs?[]> f = e.Compile(useInterpreter);
Scs?[] result = default(Scs?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Scs?[] expected = default(Scs?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableShortArray(bool condition, short?[] a, short?[] b, bool useInterpreter)
{
Expression<Func<short?[]>> e =
Expression.Lambda<Func<short?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(short?[])),
Expression.Constant(b, typeof(short?[]))),
Enumerable.Empty<ParameterExpression>());
Func<short?[]> f = e.Compile(useInterpreter);
short?[] result = default(short?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
short?[] expected = default(short?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableStructWithTwoValuesArray(bool condition, Sp?[] a, Sp?[] b, bool useInterpreter)
{
Expression<Func<Sp?[]>> e =
Expression.Lambda<Func<Sp?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Sp?[])),
Expression.Constant(b, typeof(Sp?[]))),
Enumerable.Empty<ParameterExpression>());
Func<Sp?[]> f = e.Compile(useInterpreter);
Sp?[] result = default(Sp?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Sp?[] expected = default(Sp?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableStructWithValueArray(bool condition, Ss?[] a, Ss?[] b, bool useInterpreter)
{
Expression<Func<Ss?[]>> e =
Expression.Lambda<Func<Ss?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ss?[])),
Expression.Constant(b, typeof(Ss?[]))),
Enumerable.Empty<ParameterExpression>());
Func<Ss?[]> f = e.Compile(useInterpreter);
Ss?[] result = default(Ss?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Ss?[] expected = default(Ss?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableUIntArray(bool condition, uint?[] a, uint?[] b, bool useInterpreter)
{
Expression<Func<uint?[]>> e =
Expression.Lambda<Func<uint?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(uint?[])),
Expression.Constant(b, typeof(uint?[]))),
Enumerable.Empty<ParameterExpression>());
Func<uint?[]> f = e.Compile(useInterpreter);
uint?[] result = default(uint?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
uint?[] expected = default(uint?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableULongArray(bool condition, ulong?[] a, ulong?[] b, bool useInterpreter)
{
Expression<Func<ulong?[]>> e =
Expression.Lambda<Func<ulong?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ulong?[])),
Expression.Constant(b, typeof(ulong?[]))),
Enumerable.Empty<ParameterExpression>());
Func<ulong?[]> f = e.Compile(useInterpreter);
ulong?[] result = default(ulong?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
ulong?[] expected = default(ulong?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableUShortArray(bool condition, ushort?[] a, ushort?[] b, bool useInterpreter)
{
Expression<Func<ushort?[]>> e =
Expression.Lambda<Func<ushort?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(ushort?[])),
Expression.Constant(b, typeof(ushort?[]))),
Enumerable.Empty<ParameterExpression>());
Func<ushort?[]> f = e.Compile(useInterpreter);
ushort?[] result = default(ushort?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
ushort?[] expected = default(ushort?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
private static void VerifyArrayNullableGenericWithStructRestrictionArray<Ts>(bool condition, Ts?[] a, Ts?[] b, bool useInterpreter) where Ts : struct
{
Expression<Func<Ts?[]>> e =
Expression.Lambda<Func<Ts?[]>>(
Expression.Condition(
Expression.Constant(condition, typeof(bool)),
Expression.Constant(a, typeof(Ts?[])),
Expression.Constant(b, typeof(Ts?[]))),
Enumerable.Empty<ParameterExpression>());
Func<Ts?[]> f = e.Compile(useInterpreter);
Ts?[] result = default(Ts?[]);
Exception fEx = null;
try
{
result = f();
}
catch (Exception ex)
{
fEx = ex;
}
Ts?[] expected = default(Ts?[]);
Exception csEx = null;
try
{
expected = condition ? a : b;
}
catch (Exception ex)
{
csEx = ex;
}
if (fEx != null || csEx != null)
{
Assert.NotNull(fEx);
Assert.NotNull(csEx);
Assert.Equal(csEx.GetType(), fEx.GetType());
}
else
{
Assert.Equal(expected, result);
}
}
#endregion
}
}
| |
using Util = Saklient.Util;
using HttpException = Saklient.Errors.HttpException;
using HttpBadGatewayException = Saklient.Errors.HttpBadGatewayException;
using HttpBadRequestException = Saklient.Errors.HttpBadRequestException;
using HttpConflictException = Saklient.Errors.HttpConflictException;
using HttpExpectationFailedException = Saklient.Errors.HttpExpectationFailedException;
using HttpFailedDependencyException = Saklient.Errors.HttpFailedDependencyException;
using HttpForbiddenException = Saklient.Errors.HttpForbiddenException;
using HttpGatewayTimeoutException = Saklient.Errors.HttpGatewayTimeoutException;
using HttpGoneException = Saklient.Errors.HttpGoneException;
using HttpHttpVersionNotSupportedException = Saklient.Errors.HttpHttpVersionNotSupportedException;
using HttpInsufficientStorageException = Saklient.Errors.HttpInsufficientStorageException;
using HttpInternalServerErrorException = Saklient.Errors.HttpInternalServerErrorException;
using HttpLengthRequiredException = Saklient.Errors.HttpLengthRequiredException;
using HttpLockedException = Saklient.Errors.HttpLockedException;
using HttpMethodNotAllowedException = Saklient.Errors.HttpMethodNotAllowedException;
using HttpNotAcceptableException = Saklient.Errors.HttpNotAcceptableException;
using HttpNotExtendedException = Saklient.Errors.HttpNotExtendedException;
using HttpNotFoundException = Saklient.Errors.HttpNotFoundException;
using HttpNotImplementedException = Saklient.Errors.HttpNotImplementedException;
using HttpPaymentRequiredException = Saklient.Errors.HttpPaymentRequiredException;
using HttpPreconditionFailedException = Saklient.Errors.HttpPreconditionFailedException;
using HttpProxyAuthenticationRequiredException = Saklient.Errors.HttpProxyAuthenticationRequiredException;
using HttpRequestEntityTooLargeException = Saklient.Errors.HttpRequestEntityTooLargeException;
using HttpRequestTimeoutException = Saklient.Errors.HttpRequestTimeoutException;
using HttpRequestUriTooLongException = Saklient.Errors.HttpRequestUriTooLongException;
using HttpRequestedRangeNotSatisfiableException = Saklient.Errors.HttpRequestedRangeNotSatisfiableException;
using HttpServiceUnavailableException = Saklient.Errors.HttpServiceUnavailableException;
using HttpUnauthorizedException = Saklient.Errors.HttpUnauthorizedException;
using HttpUnprocessableEntityException = Saklient.Errors.HttpUnprocessableEntityException;
using HttpUnsupportedMediaTypeException = Saklient.Errors.HttpUnsupportedMediaTypeException;
using HttpUpgradeRequiredException = Saklient.Errors.HttpUpgradeRequiredException;
using HttpVariantAlsoNegotiatesException = Saklient.Errors.HttpVariantAlsoNegotiatesException;
using AccessApiKeyDisabledException = Saklient.Cloud.Errors.AccessApiKeyDisabledException;
using AccessSakuraException = Saklient.Cloud.Errors.AccessSakuraException;
using AccessStaffException = Saklient.Cloud.Errors.AccessStaffException;
using AccessTokenException = Saklient.Cloud.Errors.AccessTokenException;
using AccessXhrOrApiKeyException = Saklient.Cloud.Errors.AccessXhrOrApiKeyException;
using AccountNotFoundException = Saklient.Cloud.Errors.AccountNotFoundException;
using AccountNotSpecifiedException = Saklient.Cloud.Errors.AccountNotSpecifiedException;
using AmbiguousIdentifierException = Saklient.Cloud.Errors.AmbiguousIdentifierException;
using AmbiguousZoneException = Saklient.Cloud.Errors.AmbiguousZoneException;
using ApiProxyTimeoutException = Saklient.Cloud.Errors.ApiProxyTimeoutException;
using ApiProxyTimeoutNonGetException = Saklient.Cloud.Errors.ApiProxyTimeoutNonGetException;
using ArchiveIsIncompleteException = Saklient.Cloud.Errors.ArchiveIsIncompleteException;
using BootFailureByLockException = Saklient.Cloud.Errors.BootFailureByLockException;
using BootFailureInGroupException = Saklient.Cloud.Errors.BootFailureInGroupException;
using BusyException = Saklient.Cloud.Errors.BusyException;
using CantResizeSmallerException = Saklient.Cloud.Errors.CantResizeSmallerException;
using CdromDeviceLockedException = Saklient.Cloud.Errors.CdromDeviceLockedException;
using CdromDisabledException = Saklient.Cloud.Errors.CdromDisabledException;
using CdromInUseException = Saklient.Cloud.Errors.CdromInUseException;
using CdromIsIncompleteException = Saklient.Cloud.Errors.CdromIsIncompleteException;
using ConnectToSameSwitchException = Saklient.Cloud.Errors.ConnectToSameSwitchException;
using ContractCreationException = Saklient.Cloud.Errors.ContractCreationException;
using CopyToItselfException = Saklient.Cloud.Errors.CopyToItselfException;
using DeleteDiskB4TemplateException = Saklient.Cloud.Errors.DeleteDiskB4TemplateException;
using DeleteIpV6NetsFirstException = Saklient.Cloud.Errors.DeleteIpV6NetsFirstException;
using DeleteResB4AccountException = Saklient.Cloud.Errors.DeleteResB4AccountException;
using DeleteRouterB4SwitchException = Saklient.Cloud.Errors.DeleteRouterB4SwitchException;
using DeleteStaticRouteFirstException = Saklient.Cloud.Errors.DeleteStaticRouteFirstException;
using DisabledInSandboxException = Saklient.Cloud.Errors.DisabledInSandboxException;
using DisconnectB4DeleteException = Saklient.Cloud.Errors.DisconnectB4DeleteException;
using DisconnectB4UpdateException = Saklient.Cloud.Errors.DisconnectB4UpdateException;
using DiskConnectionLimitException = Saklient.Cloud.Errors.DiskConnectionLimitException;
using DiskIsCopyingException = Saklient.Cloud.Errors.DiskIsCopyingException;
using DiskIsNotAvailableException = Saklient.Cloud.Errors.DiskIsNotAvailableException;
using DiskLicenseMismatchException = Saklient.Cloud.Errors.DiskLicenseMismatchException;
using DiskOrSsInMigrationException = Saklient.Cloud.Errors.DiskOrSsInMigrationException;
using DiskStockRunOutException = Saklient.Cloud.Errors.DiskStockRunOutException;
using DnsARecordNotFoundException = Saklient.Cloud.Errors.DnsARecordNotFoundException;
using DnsAaaaRecordNotFoundException = Saklient.Cloud.Errors.DnsAaaaRecordNotFoundException;
using DnsPtrUpdateFailureException = Saklient.Cloud.Errors.DnsPtrUpdateFailureException;
using DontCreateInSandboxException = Saklient.Cloud.Errors.DontCreateInSandboxException;
using DuplicateAccountCodeException = Saklient.Cloud.Errors.DuplicateAccountCodeException;
using DuplicateEntryException = Saklient.Cloud.Errors.DuplicateEntryException;
using DuplicateUserCodeException = Saklient.Cloud.Errors.DuplicateUserCodeException;
using FileNotUploadedException = Saklient.Cloud.Errors.FileNotUploadedException;
using FilterArrayComparisonException = Saklient.Cloud.Errors.FilterArrayComparisonException;
using FilterBadOperatorException = Saklient.Cloud.Errors.FilterBadOperatorException;
using FilterNullComparisonException = Saklient.Cloud.Errors.FilterNullComparisonException;
using FilterUnknownOperatorException = Saklient.Cloud.Errors.FilterUnknownOperatorException;
using FtpCannotCloseException = Saklient.Cloud.Errors.FtpCannotCloseException;
using FtpIsAlreadyCloseException = Saklient.Cloud.Errors.FtpIsAlreadyCloseException;
using FtpIsAlreadyOpenException = Saklient.Cloud.Errors.FtpIsAlreadyOpenException;
using FtpMustBeClosedException = Saklient.Cloud.Errors.FtpMustBeClosedException;
using HostOperationFailureException = Saklient.Cloud.Errors.HostOperationFailureException;
using IllegalDasUsageException = Saklient.Cloud.Errors.IllegalDasUsageException;
using InMigrationException = Saklient.Cloud.Errors.InMigrationException;
using InvalidFormatException = Saklient.Cloud.Errors.InvalidFormatException;
using InvalidParamCombException = Saklient.Cloud.Errors.InvalidParamCombException;
using InvalidRangeException = Saklient.Cloud.Errors.InvalidRangeException;
using InvalidUriArgumentException = Saklient.Cloud.Errors.InvalidUriArgumentException;
using IpV6NetAlreadyAttachedException = Saklient.Cloud.Errors.IpV6NetAlreadyAttachedException;
using LimitCountInAccountException = Saklient.Cloud.Errors.LimitCountInAccountException;
using LimitCountInMemberException = Saklient.Cloud.Errors.LimitCountInMemberException;
using LimitCountInNetworkException = Saklient.Cloud.Errors.LimitCountInNetworkException;
using LimitCountInRouterException = Saklient.Cloud.Errors.LimitCountInRouterException;
using LimitCountInZoneException = Saklient.Cloud.Errors.LimitCountInZoneException;
using LimitMemoryInAccountException = Saklient.Cloud.Errors.LimitMemoryInAccountException;
using LimitSizeInAccountException = Saklient.Cloud.Errors.LimitSizeInAccountException;
using MissingIsoImageException = Saklient.Cloud.Errors.MissingIsoImageException;
using MissingParamException = Saklient.Cloud.Errors.MissingParamException;
using MustBeOfSameZoneException = Saklient.Cloud.Errors.MustBeOfSameZoneException;
using NoDisplayResponseException = Saklient.Cloud.Errors.NoDisplayResponseException;
using NotForRouterException = Saklient.Cloud.Errors.NotForRouterException;
using NotReplicatingException = Saklient.Cloud.Errors.NotReplicatingException;
using NotWithHybridconnException = Saklient.Cloud.Errors.NotWithHybridconnException;
using OldStoragePlanException = Saklient.Cloud.Errors.OldStoragePlanException;
using OperationFailureException = Saklient.Cloud.Errors.OperationFailureException;
using OperationTimeoutException = Saklient.Cloud.Errors.OperationTimeoutException;
using OriginalHashMismatchException = Saklient.Cloud.Errors.OriginalHashMismatchException;
using PacketFilterApplyingException = Saklient.Cloud.Errors.PacketFilterApplyingException;
using PacketFilterVersionMismatchException = Saklient.Cloud.Errors.PacketFilterVersionMismatchException;
using ParamIpNotFoundException = Saklient.Cloud.Errors.ParamIpNotFoundException;
using ParamResNotFoundException = Saklient.Cloud.Errors.ParamResNotFoundException;
using PaymentCreditCardException = Saklient.Cloud.Errors.PaymentCreditCardException;
using PaymentPaymentException = Saklient.Cloud.Errors.PaymentPaymentException;
using PaymentRegistrationException = Saklient.Cloud.Errors.PaymentRegistrationException;
using PaymentTelCertificationException = Saklient.Cloud.Errors.PaymentTelCertificationException;
using PaymentUnpayableException = Saklient.Cloud.Errors.PaymentUnpayableException;
using PenaltyOperationException = Saklient.Cloud.Errors.PenaltyOperationException;
using ReplicaAlreadyExistsException = Saklient.Cloud.Errors.ReplicaAlreadyExistsException;
using ReplicaNotFoundException = Saklient.Cloud.Errors.ReplicaNotFoundException;
using ResAlreadyConnectedException = Saklient.Cloud.Errors.ResAlreadyConnectedException;
using ResAlreadyDisconnectedException = Saklient.Cloud.Errors.ResAlreadyDisconnectedException;
using ResAlreadyExistsException = Saklient.Cloud.Errors.ResAlreadyExistsException;
using ResUsedInZoneException = Saklient.Cloud.Errors.ResUsedInZoneException;
using ResourcePathNotFoundException = Saklient.Cloud.Errors.ResourcePathNotFoundException;
using RunOutOfIpAddressException = Saklient.Cloud.Errors.RunOutOfIpAddressException;
using SameLicenseRequiredException = Saklient.Cloud.Errors.SameLicenseRequiredException;
using ServerCouldNotStopException = Saklient.Cloud.Errors.ServerCouldNotStopException;
using ServerIsCleaningException = Saklient.Cloud.Errors.ServerIsCleaningException;
using ServerOperationFailureException = Saklient.Cloud.Errors.ServerOperationFailureException;
using ServerPowerMustBeDownException = Saklient.Cloud.Errors.ServerPowerMustBeDownException;
using ServerPowerMustBeUpException = Saklient.Cloud.Errors.ServerPowerMustBeUpException;
using ServiceTemporarilyUnavailableException = Saklient.Cloud.Errors.ServiceTemporarilyUnavailableException;
using SizeMismatchException = Saklient.Cloud.Errors.SizeMismatchException;
using SnapshotInMigrationException = Saklient.Cloud.Errors.SnapshotInMigrationException;
using StillCreatingException = Saklient.Cloud.Errors.StillCreatingException;
using StorageAbnormalException = Saklient.Cloud.Errors.StorageAbnormalException;
using StorageOperationFailureException = Saklient.Cloud.Errors.StorageOperationFailureException;
using SwitchHybridConnectedException = Saklient.Cloud.Errors.SwitchHybridConnectedException;
using TemplateFtpIsOpenException = Saklient.Cloud.Errors.TemplateFtpIsOpenException;
using TemplateIsIncompleteException = Saklient.Cloud.Errors.TemplateIsIncompleteException;
using TooManyRequestException = Saklient.Cloud.Errors.TooManyRequestException;
using UnknownException = Saklient.Cloud.Errors.UnknownException;
using UnknownOsTypeException = Saklient.Cloud.Errors.UnknownOsTypeException;
using UnsupportedResClassException = Saklient.Cloud.Errors.UnsupportedResClassException;
using UserNotSpecifiedException = Saklient.Cloud.Errors.UserNotSpecifiedException;
using VncProxyRequestFailureException = Saklient.Cloud.Errors.VncProxyRequestFailureException;
namespace Saklient.Errors
{
public class ExceptionFactory
{
/// <summary>
/// <param name="status" />
/// <param name="code" />
/// <param name="message" />
/// </summary>
public static HttpException Create(long status, string code=null, string message="")
{
switch (code) {
case "access_apikey_disabled": {
return new AccessApiKeyDisabledException(status, code, message);
}
case "access_sakura": {
return new AccessSakuraException(status, code, message);
}
case "access_staff": {
return new AccessStaffException(status, code, message);
}
case "access_token": {
return new AccessTokenException(status, code, message);
}
case "access_xhr_or_apikey": {
return new AccessXhrOrApiKeyException(status, code, message);
}
case "account_not_found": {
return new AccountNotFoundException(status, code, message);
}
case "account_not_specified": {
return new AccountNotSpecifiedException(status, code, message);
}
case "ambiguous_identifier": {
return new AmbiguousIdentifierException(status, code, message);
}
case "ambiguous_zone": {
return new AmbiguousZoneException(status, code, message);
}
case "apiproxy_timeout": {
return new ApiProxyTimeoutException(status, code, message);
}
case "apiproxy_timeout_non_get": {
return new ApiProxyTimeoutNonGetException(status, code, message);
}
case "archive_is_incomplete": {
return new ArchiveIsIncompleteException(status, code, message);
}
case "bad_gateway": {
return new HttpBadGatewayException(status, code, message);
}
case "bad_request": {
return new HttpBadRequestException(status, code, message);
}
case "boot_failure_by_lock": {
return new BootFailureByLockException(status, code, message);
}
case "boot_failure_in_group": {
return new BootFailureInGroupException(status, code, message);
}
case "busy": {
return new BusyException(status, code, message);
}
case "cant_resize_smaller": {
return new CantResizeSmallerException(status, code, message);
}
case "cdrom_device_locked": {
return new CdromDeviceLockedException(status, code, message);
}
case "cdrom_disabled": {
return new CdromDisabledException(status, code, message);
}
case "cdrom_in_use": {
return new CdromInUseException(status, code, message);
}
case "cdrom_is_incomplete": {
return new CdromIsIncompleteException(status, code, message);
}
case "conflict": {
return new HttpConflictException(status, code, message);
}
case "connect_to_same_switch": {
return new ConnectToSameSwitchException(status, code, message);
}
case "contract_creation": {
return new ContractCreationException(status, code, message);
}
case "copy_to_itself": {
return new CopyToItselfException(status, code, message);
}
case "delete_disk_b4_template": {
return new DeleteDiskB4TemplateException(status, code, message);
}
case "delete_ipv6nets_first": {
return new DeleteIpV6NetsFirstException(status, code, message);
}
case "delete_res_b4_account": {
return new DeleteResB4AccountException(status, code, message);
}
case "delete_router_b4_switch": {
return new DeleteRouterB4SwitchException(status, code, message);
}
case "delete_static_route_first": {
return new DeleteStaticRouteFirstException(status, code, message);
}
case "disabled_in_sandbox": {
return new DisabledInSandboxException(status, code, message);
}
case "disconnect_b4_delete": {
return new DisconnectB4DeleteException(status, code, message);
}
case "disconnect_b4_update": {
return new DisconnectB4UpdateException(status, code, message);
}
case "disk_connection_limit": {
return new DiskConnectionLimitException(status, code, message);
}
case "disk_is_copying": {
return new DiskIsCopyingException(status, code, message);
}
case "disk_is_not_available": {
return new DiskIsNotAvailableException(status, code, message);
}
case "disk_license_mismatch": {
return new DiskLicenseMismatchException(status, code, message);
}
case "disk_stock_run_out": {
return new DiskStockRunOutException(status, code, message);
}
case "diskorss_in_migration": {
return new DiskOrSsInMigrationException(status, code, message);
}
case "dns_a_record_not_found": {
return new DnsARecordNotFoundException(status, code, message);
}
case "dns_aaaa_record_not_found": {
return new DnsAaaaRecordNotFoundException(status, code, message);
}
case "dns_ptr_update_failure": {
return new DnsPtrUpdateFailureException(status, code, message);
}
case "dont_create_in_sandbox": {
return new DontCreateInSandboxException(status, code, message);
}
case "duplicate_account_code": {
return new DuplicateAccountCodeException(status, code, message);
}
case "duplicate_entry": {
return new DuplicateEntryException(status, code, message);
}
case "duplicate_user_code": {
return new DuplicateUserCodeException(status, code, message);
}
case "expectation_failed": {
return new HttpExpectationFailedException(status, code, message);
}
case "failed_dependency": {
return new HttpFailedDependencyException(status, code, message);
}
case "file_not_uploaded": {
return new FileNotUploadedException(status, code, message);
}
case "filter_array_comparison": {
return new FilterArrayComparisonException(status, code, message);
}
case "filter_bad_operator": {
return new FilterBadOperatorException(status, code, message);
}
case "filter_null_comparison": {
return new FilterNullComparisonException(status, code, message);
}
case "filter_unknown_operator": {
return new FilterUnknownOperatorException(status, code, message);
}
case "forbidden": {
return new HttpForbiddenException(status, code, message);
}
case "ftp_cannot_close": {
return new FtpCannotCloseException(status, code, message);
}
case "ftp_is_already_close": {
return new FtpIsAlreadyCloseException(status, code, message);
}
case "ftp_is_already_open": {
return new FtpIsAlreadyOpenException(status, code, message);
}
case "ftp_must_be_closed": {
return new FtpMustBeClosedException(status, code, message);
}
case "gateway_timeout": {
return new HttpGatewayTimeoutException(status, code, message);
}
case "gone": {
return new HttpGoneException(status, code, message);
}
case "host_operation_failure": {
return new HostOperationFailureException(status, code, message);
}
case "http_version_not_supported": {
return new HttpHttpVersionNotSupportedException(status, code, message);
}
case "illegal_das_usage": {
return new IllegalDasUsageException(status, code, message);
}
case "in_migration": {
return new InMigrationException(status, code, message);
}
case "insufficient_storage": {
return new HttpInsufficientStorageException(status, code, message);
}
case "internal_server_error": {
return new HttpInternalServerErrorException(status, code, message);
}
case "invalid_format": {
return new InvalidFormatException(status, code, message);
}
case "invalid_param_comb": {
return new InvalidParamCombException(status, code, message);
}
case "invalid_range": {
return new InvalidRangeException(status, code, message);
}
case "invalid_uri_argument": {
return new InvalidUriArgumentException(status, code, message);
}
case "ipv6net_already_attached": {
return new IpV6NetAlreadyAttachedException(status, code, message);
}
case "length_required": {
return new HttpLengthRequiredException(status, code, message);
}
case "limit_count_in_account": {
return new LimitCountInAccountException(status, code, message);
}
case "limit_count_in_member": {
return new LimitCountInMemberException(status, code, message);
}
case "limit_count_in_network": {
return new LimitCountInNetworkException(status, code, message);
}
case "limit_count_in_router": {
return new LimitCountInRouterException(status, code, message);
}
case "limit_count_in_zone": {
return new LimitCountInZoneException(status, code, message);
}
case "limit_memory_in_account": {
return new LimitMemoryInAccountException(status, code, message);
}
case "limit_size_in_account": {
return new LimitSizeInAccountException(status, code, message);
}
case "locked": {
return new HttpLockedException(status, code, message);
}
case "method_not_allowed": {
return new HttpMethodNotAllowedException(status, code, message);
}
case "missing_iso_image": {
return new MissingIsoImageException(status, code, message);
}
case "missing_param": {
return new MissingParamException(status, code, message);
}
case "must_be_of_same_zone": {
return new MustBeOfSameZoneException(status, code, message);
}
case "no_display_response": {
return new NoDisplayResponseException(status, code, message);
}
case "not_acceptable": {
return new HttpNotAcceptableException(status, code, message);
}
case "not_extended": {
return new HttpNotExtendedException(status, code, message);
}
case "not_for_router": {
return new NotForRouterException(status, code, message);
}
case "not_found": {
return new HttpNotFoundException(status, code, message);
}
case "not_implemented": {
return new HttpNotImplementedException(status, code, message);
}
case "not_replicating": {
return new NotReplicatingException(status, code, message);
}
case "not_with_hybridconn": {
return new NotWithHybridconnException(status, code, message);
}
case "old_storage_plan": {
return new OldStoragePlanException(status, code, message);
}
case "operation_failure": {
return new OperationFailureException(status, code, message);
}
case "operation_timeout": {
return new OperationTimeoutException(status, code, message);
}
case "original_hash_mismatch": {
return new OriginalHashMismatchException(status, code, message);
}
case "packetfilter_applying": {
return new PacketFilterApplyingException(status, code, message);
}
case "packetfilter_version_mismatch": {
return new PacketFilterVersionMismatchException(status, code, message);
}
case "param_ip_not_found": {
return new ParamIpNotFoundException(status, code, message);
}
case "param_res_not_found": {
return new ParamResNotFoundException(status, code, message);
}
case "payment_creditcard": {
return new PaymentCreditCardException(status, code, message);
}
case "payment_payment": {
return new PaymentPaymentException(status, code, message);
}
case "payment_registration": {
return new PaymentRegistrationException(status, code, message);
}
case "payment_required": {
return new HttpPaymentRequiredException(status, code, message);
}
case "payment_telcertification": {
return new PaymentTelCertificationException(status, code, message);
}
case "payment_unpayable": {
return new PaymentUnpayableException(status, code, message);
}
case "penalty_operation": {
return new PenaltyOperationException(status, code, message);
}
case "precondition_failed": {
return new HttpPreconditionFailedException(status, code, message);
}
case "proxy_authentication_required": {
return new HttpProxyAuthenticationRequiredException(status, code, message);
}
case "replica_already_exists": {
return new ReplicaAlreadyExistsException(status, code, message);
}
case "replica_not_found": {
return new ReplicaNotFoundException(status, code, message);
}
case "request_entity_too_large": {
return new HttpRequestEntityTooLargeException(status, code, message);
}
case "request_timeout": {
return new HttpRequestTimeoutException(status, code, message);
}
case "request_uri_too_long": {
return new HttpRequestUriTooLongException(status, code, message);
}
case "requested_range_not_satisfiable": {
return new HttpRequestedRangeNotSatisfiableException(status, code, message);
}
case "res_already_connected": {
return new ResAlreadyConnectedException(status, code, message);
}
case "res_already_disconnected": {
return new ResAlreadyDisconnectedException(status, code, message);
}
case "res_already_exists": {
return new ResAlreadyExistsException(status, code, message);
}
case "res_used_in_zone": {
return new ResUsedInZoneException(status, code, message);
}
case "resource_path_not_found": {
return new ResourcePathNotFoundException(status, code, message);
}
case "run_out_of_ipaddress": {
return new RunOutOfIpAddressException(status, code, message);
}
case "same_license_required": {
return new SameLicenseRequiredException(status, code, message);
}
case "server_could_not_stop": {
return new ServerCouldNotStopException(status, code, message);
}
case "server_is_cleaning": {
return new ServerIsCleaningException(status, code, message);
}
case "server_operation_failure": {
return new ServerOperationFailureException(status, code, message);
}
case "server_power_must_be_down": {
return new ServerPowerMustBeDownException(status, code, message);
}
case "server_power_must_be_up": {
return new ServerPowerMustBeUpException(status, code, message);
}
case "service_temporarily_unavailable": {
return new ServiceTemporarilyUnavailableException(status, code, message);
}
case "service_unavailable": {
return new HttpServiceUnavailableException(status, code, message);
}
case "size_mismatch": {
return new SizeMismatchException(status, code, message);
}
case "snapshot_in_migration": {
return new SnapshotInMigrationException(status, code, message);
}
case "still_creating": {
return new StillCreatingException(status, code, message);
}
case "storage_abnormal": {
return new StorageAbnormalException(status, code, message);
}
case "storage_operation_failure": {
return new StorageOperationFailureException(status, code, message);
}
case "switch_hybrid_connected": {
return new SwitchHybridConnectedException(status, code, message);
}
case "template_ftp_is_open": {
return new TemplateFtpIsOpenException(status, code, message);
}
case "template_is_incomplete": {
return new TemplateIsIncompleteException(status, code, message);
}
case "too_many_request": {
return new TooManyRequestException(status, code, message);
}
case "unauthorized": {
return new HttpUnauthorizedException(status, code, message);
}
case "unknown": {
return new UnknownException(status, code, message);
}
case "unknown_os_type": {
return new UnknownOsTypeException(status, code, message);
}
case "unprocessable_entity": {
return new HttpUnprocessableEntityException(status, code, message);
}
case "unsupported_media_type": {
return new HttpUnsupportedMediaTypeException(status, code, message);
}
case "unsupported_res_class": {
return new UnsupportedResClassException(status, code, message);
}
case "upgrade_required": {
return new HttpUpgradeRequiredException(status, code, message);
}
case "user_not_specified": {
return new UserNotSpecifiedException(status, code, message);
}
case "variant_also_negotiates": {
return new HttpVariantAlsoNegotiatesException(status, code, message);
}
case "vnc_proxy_request_failure": {
return new VncProxyRequestFailureException(status, code, message);
}
}
switch (status) {
case 400: {
return new HttpBadRequestException(status, code, message);
}
case 401: {
return new HttpUnauthorizedException(status, code, message);
}
case 402: {
return new HttpPaymentRequiredException(status, code, message);
}
case 403: {
return new HttpForbiddenException(status, code, message);
}
case 404: {
return new HttpNotFoundException(status, code, message);
}
case 405: {
return new HttpMethodNotAllowedException(status, code, message);
}
case 406: {
return new HttpNotAcceptableException(status, code, message);
}
case 407: {
return new HttpProxyAuthenticationRequiredException(status, code, message);
}
case 408: {
return new HttpRequestTimeoutException(status, code, message);
}
case 409: {
return new HttpConflictException(status, code, message);
}
case 410: {
return new HttpGoneException(status, code, message);
}
case 411: {
return new HttpLengthRequiredException(status, code, message);
}
case 412: {
return new HttpPreconditionFailedException(status, code, message);
}
case 413: {
return new HttpRequestEntityTooLargeException(status, code, message);
}
case 415: {
return new HttpUnsupportedMediaTypeException(status, code, message);
}
case 416: {
return new HttpRequestedRangeNotSatisfiableException(status, code, message);
}
case 417: {
return new HttpExpectationFailedException(status, code, message);
}
case 422: {
return new HttpUnprocessableEntityException(status, code, message);
}
case 423: {
return new HttpLockedException(status, code, message);
}
case 424: {
return new HttpFailedDependencyException(status, code, message);
}
case 426: {
return new HttpUpgradeRequiredException(status, code, message);
}
case 500: {
return new HttpRequestUriTooLongException(status, code, message);
}
case 501: {
return new HttpNotImplementedException(status, code, message);
}
case 502: {
return new HttpBadGatewayException(status, code, message);
}
case 503: {
return new HttpServiceUnavailableException(status, code, message);
}
case 504: {
return new HttpGatewayTimeoutException(status, code, message);
}
case 505: {
return new HttpHttpVersionNotSupportedException(status, code, message);
}
case 506: {
return new HttpVariantAlsoNegotiatesException(status, code, message);
}
case 507: {
return new HttpInsufficientStorageException(status, code, message);
}
case 510: {
return new HttpNotExtendedException(status, code, message);
}
}
return new HttpException(status, code, message);
}
}
}
| |
using J2N;
using J2N.Runtime.CompilerServices;
using J2N.Text;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Arrays = Lucene.Net.Support.Arrays;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Util.Automaton
{
/*
* 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>
/// Builds a minimal, deterministic <see cref="Automaton"/> that accepts a set of
/// strings. The algorithm requires sorted input data, but is very fast
/// (nearly linear with the input size).
/// </summary>
/// <seealso cref="Build(ICollection{BytesRef})"/>
/// <seealso cref="BasicAutomata.MakeStringUnion(ICollection{BytesRef})"/>
internal sealed class DaciukMihovAutomatonBuilder
{
/// <summary>
/// DFSA state with <see cref="char"/> labels on transitions.
/// </summary>
public sealed class State // LUCENENET NOTE: Made public because it is returned from a public member
{
/// <summary>
/// An empty set of labels. </summary>
private static readonly int[] NO_LABELS = Arrays.Empty<int>();
/// <summary>
/// An empty set of states. </summary>
private static readonly State[] NO_STATES = Arrays.Empty<State>();
/// <summary>
/// Labels of outgoing transitions. Indexed identically to <see cref="states"/>.
/// Labels must be sorted lexicographically.
/// </summary>
internal int[] labels = NO_LABELS;
/// <summary>
/// States reachable from outgoing transitions. Indexed identically to
/// <see cref="labels"/>.
/// </summary>
internal State[] states = NO_STATES;
/// <summary>
/// <c>true</c> if this state corresponds to the end of at least one
/// input sequence.
/// </summary>
internal bool is_final;
/// <summary>
/// Returns the target state of a transition leaving this state and labeled
/// with <paramref name="label"/>. If no such transition exists, returns
/// <c>null</c>.
/// </summary>
internal State GetState(int label)
{
int index = Array.BinarySearch(labels, label);
return index >= 0 ? states[index] : null;
}
/// <summary>
/// Two states are equal if:
/// <list type="bullet">
/// <item><description>They have an identical number of outgoing transitions, labeled with
/// the same labels.</description></item>
/// <item><description>Corresponding outgoing transitions lead to the same states (to states
/// with an identical right-language).</description></item>
/// </list>
/// </summary>
public override bool Equals(object obj)
{
State other = (State)obj;
return is_final == other.is_final && Arrays.Equals(this.labels, other.labels) && ReferenceEquals(this.states, other.states);
}
/// <summary>
/// Compute the hash code of the <i>current</i> status of this state.
/// </summary>
public override int GetHashCode()
{
int hash = is_final ? 1 : 0;
hash ^= hash * 31 + this.labels.Length;
foreach (int c in this.labels)
{
hash ^= hash * 31 + c;
}
/*
* Compare the right-language of this state using reference-identity of
* outgoing states. this is possible because states are interned (stored
* in registry) and traversed in post-order, so any outgoing transitions
* are already interned.
*/
foreach (State s in this.states)
{
hash ^= s.GetHashCode();
}
return hash;
}
/// <summary>
/// Return <c>true</c> if this state has any children (outgoing
/// transitions).
/// </summary>
internal bool HasChildren => labels.Length > 0;
/// <summary>
/// Create a new outgoing transition labeled <paramref name="label"/> and return
/// the newly created target state for this transition.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal State NewState(int label)
{
if (Debugging.AssertsEnabled) Debugging.Assert(Array.BinarySearch(labels, label) < 0, "State already has transition labeled: {0}", label);
labels = Arrays.CopyOf(labels, labels.Length + 1);
states = Arrays.CopyOf(states, states.Length + 1);
labels[labels.Length - 1] = label;
return states[states.Length - 1] = new State();
}
/// <summary>
/// Return the most recent transitions's target state.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal State LastChild() // LUCENENET NOTE: Kept this a method because there is another overload
{
if (Debugging.AssertsEnabled) Debugging.Assert(HasChildren, "No outgoing transitions.");
return states[states.Length - 1];
}
/// <summary>
/// Return the associated state if the most recent transition is labeled with
/// <paramref name="label"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal State LastChild(int label)
{
int index = labels.Length - 1;
State s = null;
if (index >= 0 && labels[index] == label)
{
s = states[index];
}
if (Debugging.AssertsEnabled) Debugging.Assert(s == GetState(label));
return s;
}
/// <summary>
/// Replace the last added outgoing transition's target state with the given
/// <paramref name="state"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ReplaceLastChild(State state)
{
if (Debugging.AssertsEnabled) Debugging.Assert(HasChildren, "No outgoing transitions.");
states[states.Length - 1] = state;
}
/// <summary>
/// Compare two lists of objects for reference-equality.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool ReferenceEquals(object[] a1, object[] a2)
{
if (a1.Length != a2.Length)
{
return false;
}
for (int i = 0; i < a1.Length; i++)
{
if (a1[i] != a2[i])
{
return false;
}
}
return true;
}
}
/// <summary>
/// A "registry" for state interning.
/// </summary>
private Dictionary<State, State> stateRegistry = new Dictionary<State, State>();
/// <summary>
/// Root automaton state.
/// </summary>
private readonly State root = new State();
/// <summary>
/// Previous sequence added to the automaton in <see cref="Add(CharsRef)"/>.
/// </summary>
private CharsRef previous;
/// <summary>
/// A comparer used for enforcing sorted UTF8 order, used in assertions only.
/// </summary>
private static readonly IComparer<CharsRef> comparer =
#pragma warning disable 612, 618
CharsRef.UTF16SortedAsUTF8Comparer;
#pragma warning restore 612, 618
/// <summary>
/// Add another character sequence to this automaton. The sequence must be
/// lexicographically larger or equal compared to any previous sequences added
/// to this automaton (the input must be sorted).
/// </summary>
public void Add(CharsRef current)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(stateRegistry != null, "Automaton already built.");
Debugging.Assert(previous is null || comparer.Compare(previous, current) <= 0, "Input must be in sorted UTF-8 order: {0} >= {1}", previous, current);
Debugging.Assert(SetPrevious(current));
}
// Descend in the automaton (find matching prefix).
int pos = 0, max = current.Length;
State next, state = root;
while (pos < max && (next = state.LastChild(Character.CodePointAt(current, pos))) != null)
{
state = next;
// todo, optimize me
pos += Character.CharCount(Character.CodePointAt(current, pos));
}
if (state.HasChildren)
{
ReplaceOrRegister(state);
}
AddSuffix(state, current, pos);
}
/// <summary>
/// Finalize the automaton and return the root state. No more strings can be
/// added to the builder after this call.
/// </summary>
/// <returns> Root automaton state. </returns>
public State Complete()
{
if (this.stateRegistry is null)
{
throw IllegalStateException.Create();
}
if (root.HasChildren)
{
ReplaceOrRegister(root);
}
stateRegistry = null;
return root;
}
/// <summary>
/// Internal recursive traversal for conversion.
/// </summary>
/// <param name="s"></param>
/// <param name="visited">Must use a dictionary with <see cref="IdentityEqualityComparer{State}.Default"/> passed into its constructor.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Util.Automaton.State Convert(State s, IDictionary<State, Util.Automaton.State> visited)
{
if (visited.TryGetValue(s, out Util.Automaton.State converted) && converted != null)
{
return converted;
}
converted = new Util.Automaton.State
{
Accept = s.is_final
};
visited[s] = converted;
int i = 0;
int[] labels = s.labels;
foreach (DaciukMihovAutomatonBuilder.State target in s.states)
{
converted.AddTransition(new Transition(labels[i++], Convert(target, visited)));
}
return converted;
}
/// <summary>
/// Build a minimal, deterministic automaton from a sorted list of <see cref="BytesRef"/> representing
/// strings in UTF-8. These strings must be binary-sorted.
/// </summary>
public static Automaton Build(ICollection<BytesRef> input)
{
DaciukMihovAutomatonBuilder builder = new DaciukMihovAutomatonBuilder();
CharsRef scratch = new CharsRef();
foreach (BytesRef b in input)
{
UnicodeUtil.UTF8toUTF16(b, scratch);
builder.Add(scratch);
}
return new Automaton
{
initial = Convert(builder.Complete(), new JCG.Dictionary<State, Lucene.Net.Util.Automaton.State>(IdentityEqualityComparer<State>.Default)),
deterministic = true
};
}
/// <summary>
/// Copy <paramref name="current"/> into an internal buffer.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool SetPrevious(CharsRef current)
{
// don't need to copy, once we fix https://issues.apache.org/jira/browse/LUCENE-3277
// still, called only from assert
previous = CharsRef.DeepCopyOf(current);
return true;
}
/// <summary>
/// Replace last child of <paramref name="state"/> with an already registered state
/// or stateRegistry the last child state.
/// </summary>
private void ReplaceOrRegister(State state)
{
State child = state.LastChild();
if (child.HasChildren)
{
ReplaceOrRegister(child);
}
if (stateRegistry.TryGetValue(child, out State registered))
{
state.ReplaceLastChild(registered);
}
else
{
stateRegistry[child] = child;
}
}
/// <summary>
/// Add a suffix of <paramref name="current"/> starting at <paramref name="fromIndex"/>
/// (inclusive) to state <paramref name="state"/>.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void AddSuffix(State state, ICharSequence current, int fromIndex) // LUCENENET: CA1822: Mark members as static
{
int len = current.Length;
while (fromIndex < len)
{
int cp = Character.CodePointAt(current, fromIndex);
state = state.NewState(cp);
fromIndex += Character.CharCount(cp);
}
state.is_final = true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Infrastructure
{
public class ControllerActionInvokerTest : CommonResourceInvokerTest
{
#region Diagnostics
[Fact]
public async Task Invoke_WritesDiagnostic_ActionSelected()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor()
{
FilterDescriptors = new List<FilterDescriptor>(),
Parameters = new List<ParameterDescriptor>(),
BoundProperties = new List<ParameterDescriptor>(),
};
actionDescriptor.MethodInfo = typeof(TestController).GetMethod(nameof(TestController.ActionMethod));
actionDescriptor.ControllerTypeInfo = typeof(TestController).GetTypeInfo();
var listener = new TestDiagnosticListener();
var routeData = new RouteData();
routeData.Values.Add("tag", "value");
var filter = Mock.Of<IFilterMetadata>();
var invoker = CreateInvoker(
new[] { filter },
actionDescriptor,
controller: new TestController(),
diagnosticListener: listener,
routeData: routeData);
// Act
await invoker.InvokeAsync();
// Assert
Assert.NotNull(listener.BeforeAction?.ActionDescriptor);
Assert.NotNull(listener.BeforeAction?.HttpContext);
var routeValues = listener.BeforeAction?.RouteData?.Values;
Assert.NotNull(routeValues);
Assert.Equal(1, routeValues.Count);
Assert.Contains(routeValues, kvp => kvp.Key == "tag" && string.Equals(kvp.Value, "value"));
}
[Fact]
public async Task Invoke_WritesDiagnostic_ActionInvoked()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor()
{
FilterDescriptors = new List<FilterDescriptor>(),
Parameters = new List<ParameterDescriptor>(),
BoundProperties = new List<ParameterDescriptor>(),
};
actionDescriptor.MethodInfo = typeof(TestController).GetMethod(nameof(TestController.ActionMethod));
actionDescriptor.ControllerTypeInfo = typeof(TestController).GetTypeInfo();
var listener = new TestDiagnosticListener();
var filter = Mock.Of<IFilterMetadata>();
var invoker = CreateInvoker(
new[] { filter },
actionDescriptor,
controller: new TestController(),
diagnosticListener: listener);
// Act
await invoker.InvokeAsync();
// Assert
Assert.NotNull(listener.AfterAction?.ActionDescriptor);
Assert.NotNull(listener.AfterAction?.HttpContext);
}
#endregion
#region Controller Context
[Fact]
public async Task AddingValueProviderFactory_AtResourceFilter_IsAvailableInControllerContext()
{
// Arrange
var valueProviderFactory2 = Mock.Of<IValueProviderFactory>();
var resourceFilter = new Mock<IResourceFilter>();
resourceFilter
.Setup(f => f.OnResourceExecuting(It.IsAny<ResourceExecutingContext>()))
.Callback<ResourceExecutingContext>((resourceExecutingContext) =>
{
resourceExecutingContext.ValueProviderFactories.Add(valueProviderFactory2);
});
var valueProviderFactory1 = Mock.Of<IValueProviderFactory>();
var valueProviderFactories = new List<IValueProviderFactory>();
valueProviderFactories.Add(valueProviderFactory1);
var invoker = CreateInvoker(
new IFilterMetadata[] { resourceFilter.Object }, valueProviderFactories: valueProviderFactories);
// Act
await invoker.InvokeAsync();
// Assert
var controllerContext = Assert.IsType<ControllerActionInvoker>(invoker).ControllerContext;
Assert.NotNull(controllerContext);
Assert.Equal(2, controllerContext.ValueProviderFactories.Count);
Assert.Same(valueProviderFactory1, controllerContext.ValueProviderFactories[0]);
Assert.Same(valueProviderFactory2, controllerContext.ValueProviderFactories[1]);
}
[Fact]
public async Task DeletingValueProviderFactory_AtResourceFilter_IsNotAvailableInControllerContext()
{
// Arrange
var resourceFilter = new Mock<IResourceFilter>();
resourceFilter
.Setup(f => f.OnResourceExecuting(It.IsAny<ResourceExecutingContext>()))
.Callback<ResourceExecutingContext>((resourceExecutingContext) =>
{
resourceExecutingContext.ValueProviderFactories.RemoveAt(0);
});
var valueProviderFactory1 = Mock.Of<IValueProviderFactory>();
var valueProviderFactory2 = Mock.Of<IValueProviderFactory>();
var valueProviderFactories = new List<IValueProviderFactory>();
valueProviderFactories.Add(valueProviderFactory1);
valueProviderFactories.Add(valueProviderFactory2);
var invoker = CreateInvoker(
new IFilterMetadata[] { resourceFilter.Object }, valueProviderFactories: valueProviderFactories);
// Act
await invoker.InvokeAsync();
// Assert
var controllerContext = Assert.IsType<ControllerActionInvoker>(invoker).ControllerContext;
Assert.NotNull(controllerContext);
Assert.Equal(1, controllerContext.ValueProviderFactories.Count);
Assert.Same(valueProviderFactory2, controllerContext.ValueProviderFactories[0]);
}
#endregion
#region Action Filters
[Fact]
public async Task InvokeAction_InvokesActionFilter()
{
// Arrange
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(filter.Object, result: Result);
// Act
await invoker.InvokeAsync();
// Assert
filter.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
filter.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
Assert.Same(Result, result);
}
[Fact]
public async Task InvokeAction_InvokesAsyncActionFilter()
{
// Arrange
IActionResult result = null;
var filter = new Mock<IAsyncActionFilter>(MockBehavior.Strict);
filter
.Setup(f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()))
.Returns<ActionExecutingContext, ActionExecutionDelegate>(async (context, next) =>
{
var resultContext = await next();
result = resultContext.Result;
})
.Verifiable();
var invoker = CreateInvoker(filter.Object, result: Result);
// Act
await invoker.InvokeAsync();
// Assert
filter.Verify(
f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()),
Times.Once());
Assert.Same(Result, result);
}
[Fact]
public async Task InvokeAction_InvokesActionFilter_ShortCircuit()
{
// Arrange
var result = new Mock<IActionResult>(MockBehavior.Strict);
result
.Setup(r => r.ExecuteResultAsync(It.IsAny<ActionContext>()))
.Returns(Task.FromResult(true))
.Verifiable();
ActionExecutedContext context = null;
var actionFilter1 = new Mock<IActionFilter>(MockBehavior.Strict);
actionFilter1.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
actionFilter1
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => context = c)
.Verifiable();
var actionFilter2 = new Mock<IActionFilter>(MockBehavior.Strict);
actionFilter2
.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
.Callback<ActionExecutingContext>(c => c.Result = result.Object)
.Verifiable();
var actionFilter3 = new Mock<IActionFilter>(MockBehavior.Strict);
var resultFilter = new Mock<IResultFilter>(MockBehavior.Strict);
resultFilter.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>())).Verifiable();
resultFilter.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>())).Verifiable();
var invoker = CreateInvoker(new IFilterMetadata[]
{
actionFilter1.Object,
actionFilter2.Object,
actionFilter3.Object,
resultFilter.Object,
});
// Act
await invoker.InvokeAsync();
// Assert
result.Verify(r => r.ExecuteResultAsync(It.IsAny<ActionContext>()), Times.Once());
actionFilter1.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
actionFilter1.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
actionFilter2.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
actionFilter2.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Never());
resultFilter.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
resultFilter.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
Assert.True(context.Canceled);
Assert.Same(context.Result, result.Object);
}
[Fact]
public async Task InvokeAction_InvokesAsyncActionFilter_ShortCircuit_WithResult()
{
// Arrange
var result = new Mock<IActionResult>(MockBehavior.Strict);
result
.Setup(r => r.ExecuteResultAsync(It.IsAny<ActionContext>()))
.Returns(Task.FromResult(true))
.Verifiable();
ActionExecutedContext context = null;
var actionFilter1 = new Mock<IActionFilter>(MockBehavior.Strict);
actionFilter1.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
actionFilter1
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => context = c)
.Verifiable();
var actionFilter2 = new Mock<IAsyncActionFilter>(MockBehavior.Strict);
actionFilter2
.Setup(f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()))
.Returns<ActionExecutingContext, ActionExecutionDelegate>((c, next) =>
{
// Notice we're not calling next
c.Result = result.Object;
return Task.FromResult(true);
})
.Verifiable();
var actionFilter3 = new Mock<IActionFilter>(MockBehavior.Strict);
var resultFilter1 = new Mock<IResultFilter>(MockBehavior.Strict);
resultFilter1.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>())).Verifiable();
resultFilter1.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>())).Verifiable();
var resultFilter2 = new Mock<IResultFilter>(MockBehavior.Strict);
resultFilter2.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>())).Verifiable();
resultFilter2.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>())).Verifiable();
var invoker = CreateInvoker(new IFilterMetadata[]
{
actionFilter1.Object,
actionFilter2.Object,
actionFilter3.Object,
resultFilter1.Object,
resultFilter2.Object,
});
// Act
await invoker.InvokeAsync();
// Assert
result.Verify(r => r.ExecuteResultAsync(It.IsAny<ActionContext>()), Times.Once());
actionFilter1.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
actionFilter1.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
actionFilter2.Verify(
f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()),
Times.Once());
resultFilter1.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
resultFilter1.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
resultFilter2.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
resultFilter2.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
Assert.True(context.Canceled);
Assert.Same(context.Result, result.Object);
}
[Fact]
public async Task InvokeAction_InvokesAsyncActionFilter_ShortCircuit_WithoutResult()
{
// Arrange
ActionExecutedContext context = null;
var actionFilter1 = new Mock<IActionFilter>(MockBehavior.Strict);
actionFilter1.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
actionFilter1
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => context = c)
.Verifiable();
var actionFilter2 = new Mock<IAsyncActionFilter>(MockBehavior.Strict);
actionFilter2
.Setup(f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()))
.Returns<ActionExecutingContext, ActionExecutionDelegate>((c, next) =>
{
// Notice we're not calling next
return Task.FromResult(true);
})
.Verifiable();
var actionFilter3 = new Mock<IActionFilter>(MockBehavior.Strict);
var resultFilter = new Mock<IResultFilter>(MockBehavior.Strict);
resultFilter.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>())).Verifiable();
resultFilter.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>())).Verifiable();
var invoker = CreateInvoker(new IFilterMetadata[]
{
actionFilter1.Object,
actionFilter2.Object,
actionFilter3.Object,
resultFilter.Object,
});
// Act
await invoker.InvokeAsync();
// Assert
actionFilter1.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
actionFilter1.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
actionFilter2.Verify(
f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()),
Times.Once());
resultFilter.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
resultFilter.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
Assert.True(context.Canceled);
Assert.Null(context.Result);
}
[Fact]
public async Task InvokeAction_InvokesAsyncActionFilter_ShortCircuit_WithResult_CallNext()
{
// Arrange
var actionFilter = new Mock<IAsyncActionFilter>(MockBehavior.Strict);
actionFilter
.Setup(f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()))
.Returns<ActionExecutingContext, ActionExecutionDelegate>(async (c, next) =>
{
c.Result = new EmptyResult();
await next();
})
.Verifiable();
var message =
"If an IAsyncActionFilter provides a result value by setting the Result property of " +
"ActionExecutingContext to a non-null value, then it cannot call the next filter by invoking " +
"ActionExecutionDelegate.";
var invoker = CreateInvoker(actionFilter.Object);
// Act & Assert
await ExceptionAssert.ThrowsAsync<InvalidOperationException>(
async () => await invoker.InvokeAsync(),
message);
}
[Fact]
public async Task InvokeAction_InvokesActionFilter_WithExceptionThrownByAction()
{
// Arrange
ActionExecutedContext context = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c =>
{
context = c;
// Handle the exception so the test doesn't throw.
Assert.False(c.ExceptionHandled);
c.ExceptionHandled = true;
})
.Verifiable();
var invoker = CreateInvoker(filter.Object, exception: Exception);
// Act
await invoker.InvokeAsync();
// Assert
filter.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
filter.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
Assert.Same(Exception, context.Exception);
Assert.Null(context.Result);
}
[Fact]
public async Task InvokeAction_InvokesActionFilter_WithExceptionThrownByActionFilter()
{
// Arrange
var exception = new DataMisalignedException();
ActionExecutedContext context = null;
var filter1 = new Mock<IActionFilter>(MockBehavior.Strict);
filter1.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter1
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c =>
{
context = c;
// Handle the exception so the test doesn't throw.
Assert.False(c.ExceptionHandled);
c.ExceptionHandled = true;
})
.Verifiable();
var filter2 = new Mock<IActionFilter>(MockBehavior.Strict);
filter2
.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
.Callback<ActionExecutingContext>(c => { throw exception; })
.Verifiable();
var invoker = CreateInvoker(new[] { filter1.Object, filter2.Object });
// Act
await invoker.InvokeAsync();
// Assert
filter1.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
filter1.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
filter2.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
filter2.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Never());
Assert.Same(exception, context.Exception);
Assert.Null(context.Result);
}
[Fact]
public async Task InvokeAction_InvokesAsyncActionFilter_WithExceptionThrownByActionFilter()
{
// Arrange
var exception = new DataMisalignedException();
ActionExecutedContext context = null;
var filter1 = new Mock<IAsyncActionFilter>(MockBehavior.Strict);
filter1
.Setup(f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()))
.Returns<ActionExecutingContext, ActionExecutionDelegate>(async (c, next) =>
{
context = await next();
// Handle the exception so the test doesn't throw.
Assert.False(context.ExceptionHandled);
context.ExceptionHandled = true;
})
.Verifiable();
var filter2 = new Mock<IActionFilter>(MockBehavior.Strict);
filter2.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter2
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => { throw exception; })
.Verifiable();
var invoker = CreateInvoker(new IFilterMetadata[] { filter1.Object, filter2.Object });
// Act
await invoker.InvokeAsync();
// Assert
filter1.Verify(
f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()),
Times.Once());
filter2.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
Assert.Same(exception, context.Exception);
Assert.Null(context.Result);
}
[Fact]
public async Task InvokeAction_InvokesActionFilter_HandleException()
{
// Arrange
var result = new Mock<IActionResult>(MockBehavior.Strict);
result
.Setup(r => r.ExecuteResultAsync(It.IsAny<ActionContext>()))
.Returns<ActionContext>((context) => Task.FromResult(true))
.Verifiable();
var actionFilter = new Mock<IActionFilter>(MockBehavior.Strict);
actionFilter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
actionFilter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c =>
{
// Handle the exception so the test doesn't throw.
Assert.False(c.ExceptionHandled);
c.ExceptionHandled = true;
c.Result = result.Object;
})
.Verifiable();
var resultFilter = new Mock<IResultFilter>(MockBehavior.Strict);
resultFilter.Setup(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>())).Verifiable();
resultFilter.Setup(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>())).Verifiable();
var invoker = CreateInvoker(
new IFilterMetadata[] { actionFilter.Object, resultFilter.Object },
exception: Exception);
// Act
await invoker.InvokeAsync();
// Assert
actionFilter.Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());
actionFilter.Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
resultFilter.Verify(f => f.OnResultExecuting(It.IsAny<ResultExecutingContext>()), Times.Once());
resultFilter.Verify(f => f.OnResultExecuted(It.IsAny<ResultExecutedContext>()), Times.Once());
result.Verify(r => r.ExecuteResultAsync(It.IsAny<ActionContext>()), Times.Once());
}
[Fact]
public async Task InvokeAction_InvokesAsyncResourceFilter_WithActionResult_FromActionFilter()
{
// Arrange
var expected = Mock.Of<IActionResult>();
ResourceExecutedContext context = null;
var resourceFilter = new Mock<IAsyncResourceFilter>(MockBehavior.Strict);
resourceFilter
.Setup(f => f.OnResourceExecutionAsync(It.IsAny<ResourceExecutingContext>(), It.IsAny<ResourceExecutionDelegate>()))
.Returns<ResourceExecutingContext, ResourceExecutionDelegate>(async (c, next) =>
{
context = await next();
})
.Verifiable();
var actionFilter = new Mock<IActionFilter>(MockBehavior.Strict);
actionFilter
.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
.Callback<ActionExecutingContext>((c) =>
{
c.Result = expected;
});
var invoker = CreateInvoker(new IFilterMetadata[] { resourceFilter.Object, actionFilter.Object });
// Act
await invoker.InvokeAsync();
// Assert
Assert.Same(expected, context.Result);
resourceFilter.Verify(
f => f.OnResourceExecutionAsync(It.IsAny<ResourceExecutingContext>(), It.IsAny<ResourceExecutionDelegate>()),
Times.Once());
}
[Fact]
public async Task InvokeAction_InvokesAsyncResourceFilter_HandleException_FromActionFilter()
{
// Arrange
var expected = new DataMisalignedException();
ResourceExecutedContext context = null;
var resourceFilter = new Mock<IAsyncResourceFilter>(MockBehavior.Strict);
resourceFilter
.Setup(f => f.OnResourceExecutionAsync(It.IsAny<ResourceExecutingContext>(), It.IsAny<ResourceExecutionDelegate>()))
.Returns<ResourceExecutingContext, ResourceExecutionDelegate>(async (c, next) =>
{
context = await next();
context.ExceptionHandled = true;
})
.Verifiable();
var actionFilter = new Mock<IActionFilter>(MockBehavior.Strict);
actionFilter
.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
.Callback<ActionExecutingContext>((c) =>
{
throw expected;
});
var invoker = CreateInvoker(new IFilterMetadata[] { resourceFilter.Object, actionFilter.Object });
// Act
await invoker.InvokeAsync();
// Assert
Assert.Same(expected, context.Exception);
Assert.Same(expected, context.ExceptionDispatchInfo.SourceException);
resourceFilter.Verify(
f => f.OnResourceExecutionAsync(It.IsAny<ResourceExecutingContext>(), It.IsAny<ResourceExecutionDelegate>()),
Times.Once());
}
[Fact]
public async Task InvokeAction_InvokesAsyncResourceFilter_HandlesException_FromExceptionFilter()
{
// Arrange
var expected = new DataMisalignedException();
ResourceExecutedContext context = null;
var resourceFilter = new Mock<IAsyncResourceFilter>(MockBehavior.Strict);
resourceFilter
.Setup(f => f.OnResourceExecutionAsync(It.IsAny<ResourceExecutingContext>(), It.IsAny<ResourceExecutionDelegate>()))
.Returns<ResourceExecutingContext, ResourceExecutionDelegate>(async (c, next) =>
{
context = await next();
context.ExceptionHandled = true;
})
.Verifiable();
var exceptionFilter = new Mock<IExceptionFilter>(MockBehavior.Strict);
exceptionFilter
.Setup(f => f.OnException(It.IsAny<ExceptionContext>()))
.Callback<ExceptionContext>((c) =>
{
throw expected;
});
var invoker = CreateInvoker(new IFilterMetadata[] { resourceFilter.Object, exceptionFilter.Object }, exception: Exception);
// Act
await invoker.InvokeAsync();
// Assert
Assert.Same(expected, context.Exception);
Assert.Same(expected, context.ExceptionDispatchInfo.SourceException);
resourceFilter.Verify(
f => f.OnResourceExecutionAsync(It.IsAny<ResourceExecutingContext>(), It.IsAny<ResourceExecutionDelegate>()),
Times.Once());
}
[Fact]
public async Task InvokeAction_ExceptionBubbling_AsyncActionFilter_To_ResourceFilter()
{
// Arrange
var resourceFilter = new Mock<IAsyncResourceFilter>(MockBehavior.Strict);
resourceFilter
.Setup(f => f.OnResourceExecutionAsync(It.IsAny<ResourceExecutingContext>(), It.IsAny<ResourceExecutionDelegate>()))
.Returns<ResourceExecutingContext, ResourceExecutionDelegate>(async (c, next) =>
{
var context = await next();
Assert.Same(Exception, context.Exception);
context.ExceptionHandled = true;
});
var actionFilter1 = new Mock<IAsyncActionFilter>(MockBehavior.Strict);
actionFilter1
.Setup(f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()))
.Returns<ActionExecutingContext, ActionExecutionDelegate>(async (c, next) =>
{
await next();
});
var actionFilter2 = new Mock<IAsyncActionFilter>(MockBehavior.Strict);
actionFilter2
.Setup(f => f.OnActionExecutionAsync(It.IsAny<ActionExecutingContext>(), It.IsAny<ActionExecutionDelegate>()))
.Returns<ActionExecutingContext, ActionExecutionDelegate>(async (c, next) =>
{
await next();
});
var invoker = CreateInvoker(
new IFilterMetadata[]
{
resourceFilter.Object,
actionFilter1.Object,
actionFilter2.Object,
},
// The action won't run
exception: Exception);
// Act & Assert
await invoker.InvokeAsync();
}
#endregion
#region Action Method Signatures
[Fact]
public async Task InvokeAction_AsyncAction_TaskReturnType()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.TaskAction), actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
Assert.IsType<EmptyResult>(result);
}
[Fact]
public async Task InvokeAction_AsyncAction_TaskOfValueReturnType()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.TaskValueTypeAction), actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<ObjectResult>(result);
Assert.Equal(inputParam1, contentResult.Value);
}
[Fact]
public async Task InvokeAction_AsyncAction_WithAsyncKeywordThrows()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.TaskActionWithException), actionParameters);
// Act and Assert
await Assert.ThrowsAsync<NotImplementedException>(
() => invoker.InvokeAsync());
}
[Fact]
public async Task InvokeAction_AsyncAction_WithoutAsyncThrows()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.TaskActionWithExceptionWithoutAsync), actionParameters);
// Act and Assert
await Assert.ThrowsAsync<NotImplementedException>(
() => invoker.InvokeAsync());
}
[Fact]
public async Task InvokeAction_AsyncAction_WithExceptionsAfterAwait()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.TaskActionThrowAfterAwait), actionParameters);
var expectedException = "Argument Exception";
// Act and Assert
var ex = await Assert.ThrowsAsync<ArgumentException>(
() => invoker.InvokeAsync());
Assert.Equal(expectedException, ex.Message);
}
[Fact]
public async Task InvokeAction_SyncAction()
{
// Arrange
var inputString = "hello";
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.Echo), new Dictionary<string, object>() { { "input", inputString } });
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<ObjectResult>(result);
Assert.Equal(inputString, contentResult.Value);
}
[Fact]
public async Task InvokeAction_SyncAction_WithException()
{
// Arrange
var inputString = "hello";
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.EchoWithException),
new Dictionary<string, object>() { { "input", inputString } });
// Act & Assert
await Assert.ThrowsAsync<NotImplementedException>(
() => invoker.InvokeAsync());
}
[Fact]
public async Task InvokeAction_SyncMethod_WithArgumentDictionary_DefaultValueAttributeUsed()
{
// Arrange
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.EchoWithDefaultValue),
new Dictionary<string, object>());
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<ObjectResult>(result);
Assert.Equal("hello", contentResult.Value);
}
[Fact]
public async Task InvokeAction_SyncMethod_WithArgumentArray_DefaultValueAttributeIgnored()
{
// Arrange
var inputString = "test";
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.EchoWithDefaultValue),
new Dictionary<string, object>() { { "input", inputString } });
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<ObjectResult>(result);
Assert.Equal(inputString, contentResult.Value);
}
[Fact]
public async Task InvokeAction_SyncMethod_WithArgumentDictionary_DefaultParameterValueUsed()
{
// Arrange
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.EchoWithDefaultValueAndAttribute),
new Dictionary<string, object>());
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<ObjectResult>(result);
Assert.Equal("world", contentResult.Value);
}
[Fact]
public async Task InvokeAction_SyncMethod_WithArgumentDictionary_AnyValue_HasPrecedenceOverDefaults()
{
// Arrange
var inputString = "test";
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.EchoWithDefaultValueAndAttribute),
new Dictionary<string, object>() { { "input", inputString } });
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<ObjectResult>(result);
Assert.Equal(inputString, contentResult.Value);
}
[Fact]
public async Task InvokeAction_AsyncAction_WithCustomTaskReturnType()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.TaskActionWithCustomTaskReturnType),
actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
Assert.IsType<EmptyResult>(result);
}
[Fact]
public async Task InvokeAction_AsyncAction_WithCustomTaskOfTReturnType()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.TaskActionWithCustomTaskOfTReturnType),
actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
Assert.IsType<ObjectResult>(result);
Assert.IsType<int>(((ObjectResult)result).Value);
Assert.Equal(1, ((ObjectResult)result).Value);
}
[Fact]
public async Task InvokeAction_AsyncAction_ReturningUnwrappedTask()
{
// Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", inputParam1 }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.UnwrappedTask), actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
Assert.IsType<EmptyResult>(result);
}
[Fact]
public async Task InvokeAction_AsyncActionWithTaskOfObjectReturnType_AndReturningTaskOfActionResult()
{
// Arrange
var actionParameters = new Dictionary<string, object> { ["value"] = 3 };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result);
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.AsyncActionMethodReturningActionResultWithTaskOfObjectAsReturnType),
actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
var testResult = Assert.IsType<TestActionResult>(result);
Assert.Equal(3, testResult.Value);
}
[Fact]
public async Task InvokeAction_ActionWithObjectReturnType_AndReturningActionResult()
{
// Arrange
var actionParameters = new Dictionary<string, object> { ["value"] = 3 };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result);
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.ActionMethodReturningActionResultWithObjectAsReturnType),
actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
var testResult = Assert.IsType<TestActionResult>(result);
Assert.Equal(3, testResult.Value);
}
[Fact]
public async Task InvokeAction_AsyncMethod_ParametersInRandomOrder()
{
//Arrange
var inputParam1 = 1;
var inputParam2 = "Second Parameter";
// Note that the order of parameters is reversed
var actionParameters = new Dictionary<string, object> { { "s", inputParam2 }, { "i", inputParam1 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.TaskValueTypeAction),
actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<ObjectResult>(result);
Assert.Equal(inputParam1, contentResult.Value);
}
[Theory]
[InlineData(nameof(TestController.AsyncActionMethodWithTestActionResult))]
[InlineData(nameof(TestController.ActionMethodWithTestActionResult))]
public async Task InvokeAction_ReturnTypeAsIActionResult_ReturnsExpected(string methodName)
{
//Arrange
var inputParam = 1;
var actionParameters = new Dictionary<string, object> { { "value", inputParam } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
methodName,
actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
var contentResult = Assert.IsType<TestActionResult>(result);
Assert.Equal(inputParam, contentResult.Value);
}
[Fact]
public async Task InvokeAction_AsyncMethod_InvalidParameterValueThrows()
{
//Arrange
var inputParam2 = "Second Parameter";
var actionParameters = new Dictionary<string, object> { { "i", "Some Invalid Value" }, { "s", inputParam2 } };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
nameof(TestController.TaskValueTypeAction),
actionParameters);
// Act & Assert
await Assert.ThrowsAsync<InvalidCastException>(
() => invoker.InvokeAsync());
}
[Theory]
[InlineData(nameof(TestController.ActionMethodWithNullActionResult), typeof(IActionResult))]
[InlineData(nameof(TestController.TestActionMethodWithNullActionResult), typeof(TestActionResult))]
[InlineData(nameof(TestController.AsyncActionMethodWithNullActionResult), typeof(IActionResult))]
[InlineData(nameof(TestController.AsyncActionMethodWithNullTestActionResult), typeof(TestActionResult))]
[ReplaceCulture]
public async Task InvokeAction_WithNullActionResultThrows(string methodName, Type resultType)
{
// Arrange
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(
new[] { filter.Object },
methodName,
new Dictionary<string, object>());
// Act & Assert
await ExceptionAssert.ThrowsAsync<InvalidOperationException>(
() => invoker.InvokeAsync(),
$"Cannot return null from an action method with a return type of '{resultType}'.");
}
[Fact]
public async Task Invoke_UsesDefaultValuesIfNotBound()
{
// Arrange
var actionDescriptor = new ControllerActionDescriptor
{
ControllerTypeInfo = typeof(TestController).GetTypeInfo(),
BoundProperties = new List<ParameterDescriptor>(),
MethodInfo = typeof(TestController).GetTypeInfo()
.DeclaredMethods
.First(m => m.Name.Equals("ActionMethodWithDefaultValues", StringComparison.Ordinal)),
Parameters = new List<ParameterDescriptor>
{
new ParameterDescriptor
{
Name = "value",
ParameterType = typeof(int),
BindingInfo = new BindingInfo(),
}
},
FilterDescriptors = new List<FilterDescriptor>()
};
var context = new Mock<HttpContext>();
context.SetupGet(c => c.Items)
.Returns(new Dictionary<object, object>());
context.Setup(c => c.RequestServices.GetService(typeof(ILoggerFactory)))
.Returns(new NullLoggerFactory());
var actionContext = new ActionContext(context.Object, new RouteData(), actionDescriptor);
var controllerContext = new ControllerContext(actionContext)
{
ValueProviderFactories = new IValueProviderFactory[0]
};
controllerContext.ModelState.MaxAllowedErrors = 200;
var objectMethodExecutor = ObjectMethodExecutor.Create(
actionDescriptor.MethodInfo,
actionDescriptor.ControllerTypeInfo,
ParameterDefaultValues.GetParameterDefaultValues(actionDescriptor.MethodInfo));
var controllerMethodExecutor = ActionMethodExecutor.GetExecutor(objectMethodExecutor);
var cacheEntry = new ControllerActionInvokerCacheEntry(
new FilterItem[0],
_ => new TestController(),
(_, __) => default,
(_, __, ___) => Task.CompletedTask,
objectMethodExecutor,
controllerMethodExecutor);
var invoker = new ControllerActionInvoker(
new NullLoggerFactory().CreateLogger<ControllerActionInvoker>(),
new DiagnosticListener("Microsoft.AspNetCore"),
ActionContextAccessor.Null,
new ActionResultTypeMapper(),
controllerContext,
cacheEntry,
new IFilterMetadata[0]);
// Act
await invoker.InvokeAsync();
// Assert
Assert.Equal(5, context.Object.Items["Result"]);
}
[Fact]
public async Task InvokeAction_ConvertibleToActionResult()
{
// Arrange
var inputParam = 12;
var actionParameters = new Dictionary<string, object> { { "input", inputParam }, };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.ActionReturningConvertibleToActionResult), actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
var testActionResult = Assert.IsType<TestActionResult>(result);
Assert.Equal(inputParam, testActionResult.Value);
}
[Fact]
public async Task InvokeAction_AsyncAction_ConvertibleToActionResult()
{
// Arrange
var inputParam = 13;
var actionParameters = new Dictionary<string, object> { { "input", inputParam }, };
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.ActionReturningConvertibleToActionResultAsync), actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
var testActionResult = Assert.IsType<TestActionResult>(result);
Assert.Equal(inputParam, testActionResult.Value);
}
[Fact]
public async Task InvokeAction_ConvertibleToActionResult_AsObject()
{
// Arrange
var actionParameters = new Dictionary<string, object>();
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.ActionReturningConvertibleAsObject), actionParameters);
// Act
await invoker.InvokeAsync();
// Assert
Assert.IsType<TestActionResult>(result);
}
[Fact]
public async Task InvokeAction_ConvertibleToActionResult_ReturningNull_Throws()
{
// Arrange
var expectedMessage = @"Cannot return null from an action method with a return type of 'Microsoft.AspNetCore.Mvc.Infrastructure.IConvertToActionResult'.";
var actionParameters = new Dictionary<string, object>();
IActionResult result = null;
var filter = new Mock<IActionFilter>(MockBehavior.Strict);
filter.Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>())).Verifiable();
filter
.Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
.Callback<ActionExecutedContext>(c => result = c.Result)
.Verifiable();
var invoker = CreateInvoker(new[] { filter.Object }, nameof(TestController.ConvertibleToActionResultReturningNull), actionParameters);
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => invoker.InvokeAsync());
Assert.Equal(expectedMessage, exception.Message);
}
#endregion
#region Logs
[Fact]
public async Task InvokeAsync_Logs()
{
// Arrange
var testSink = new TestSink();
var loggerFactory = new TestLoggerFactory(testSink, enabled: true);
var logger = loggerFactory.CreateLogger("test");
var actionDescriptor = new ControllerActionDescriptor()
{
ControllerTypeInfo = typeof(TestController).GetTypeInfo(),
FilterDescriptors = new List<FilterDescriptor>(),
Parameters = new List<ParameterDescriptor>(),
BoundProperties = new List<ParameterDescriptor>(),
MethodInfo = typeof(TestController).GetMethod(nameof(TestController.ActionMethod)),
};
var invoker = CreateInvoker(
new IFilterMetadata[0],
actionDescriptor,
new TestController(),
logger: logger);
// Act
await invoker.InvokeAsync();
// Assert
var messages = testSink.Writes.Select(write => write.State.ToString()).ToList();
var actionSignature = $"{typeof(IActionResult).FullName} {nameof(TestController.ActionMethod)}()";
var controllerName = $"{typeof(ControllerActionInvokerTest).FullName}+{nameof(TestController)} ({typeof(ControllerActionInvokerTest).Assembly.GetName().Name})";
var actionName = $"{typeof(ControllerActionInvokerTest).FullName}+{nameof(TestController)}.{nameof(TestController.ActionMethod)} ({typeof(ControllerActionInvokerTest).Assembly.GetName().Name})";
var actionResultName = $"{typeof(CommonResourceInvokerTest).FullName}+{nameof(TestResult)}";
Assert.Collection(
messages,
m => Assert.Equal($"Route matched with {{}}. Executing controller action with signature {actionSignature} on controller {controllerName}.", m),
m => Assert.Equal("Execution plan of authorization filters (in the following order): None", m),
m => Assert.Equal("Execution plan of resource filters (in the following order): None", m),
m => Assert.Equal("Execution plan of action filters (in the following order): None", m),
m => Assert.Equal("Execution plan of exception filters (in the following order): None", m),
m => Assert.Equal("Execution plan of result filters (in the following order): None", m),
m => Assert.Equal($"Executing controller factory for controller {controllerName}", m),
m => Assert.Equal($"Executed controller factory for controller {controllerName}", m),
m => Assert.Equal($"Executing action method {actionName} - Validation state: Valid", m),
m => Assert.StartsWith($"Executed action method {actionName}, returned result {actionResultName} in ", m),
m => Assert.Equal($"Before executing action result {actionResultName}.", m),
m => Assert.Equal($"After executing action result {actionResultName}.", m),
m => Assert.StartsWith($"Executed action {actionName} in ", m));
}
#endregion
protected override IActionInvoker CreateInvoker(
IFilterMetadata[] filters,
Exception exception = null,
IActionResult result = null,
IList<IValueProviderFactory> valueProviderFactories = null)
{
var actionDescriptor = new ControllerActionDescriptor()
{
ControllerTypeInfo = typeof(TestController).GetTypeInfo(),
FilterDescriptors = new List<FilterDescriptor>(),
Parameters = new List<ParameterDescriptor>(),
BoundProperties = new List<ParameterDescriptor>(),
};
if (result == Result)
{
actionDescriptor.MethodInfo = typeof(TestController).GetMethod(nameof(TestController.ActionMethod));
}
else if (result != null)
{
throw new InvalidOperationException($"Unexpected action result {result}.");
}
else if (exception == Exception)
{
actionDescriptor.MethodInfo = typeof(TestController).GetMethod(nameof(TestController.ThrowingActionMethod));
}
else if (exception != null)
{
throw new InvalidOperationException($"Unexpected exception {exception}.");
}
else
{
actionDescriptor.MethodInfo = typeof(TestController).GetMethod(nameof(TestController.ActionMethod));
}
return CreateInvoker(
filters,
actionDescriptor,
new TestController(),
valueProviderFactories: valueProviderFactories);
}
// Used by tests which directly test different types of signatures for controller methods.
private ControllerActionInvoker CreateInvoker(
IFilterMetadata[] filters,
string methodName,
IDictionary<string, object> arguments)
{
var actionDescriptor = new ControllerActionDescriptor()
{
ControllerTypeInfo = typeof(TestController).GetTypeInfo(),
FilterDescriptors = new List<FilterDescriptor>(),
Parameters = new List<ParameterDescriptor>(),
BoundProperties = new List<ParameterDescriptor>(),
};
var method = typeof(TestController).GetTypeInfo().GetMethod(methodName);
Assert.NotNull(method);
actionDescriptor.MethodInfo = method;
foreach (var kvp in arguments)
{
actionDescriptor.Parameters.Add(new ControllerParameterDescriptor()
{
Name = kvp.Key,
ParameterInfo = method.GetParameters().Where(p => p.Name == kvp.Key).Single(),
});
}
return CreateInvoker(filters, actionDescriptor, new TestController(), arguments);
}
private ControllerActionInvoker CreateInvoker(
IFilterMetadata[] filters,
ControllerActionDescriptor actionDescriptor,
object controller,
IDictionary<string, object> arguments = null,
IList<IValueProviderFactory> valueProviderFactories = null,
RouteData routeData = null,
ILogger logger = null,
object diagnosticListener = null)
{
Assert.NotNull(actionDescriptor.MethodInfo);
if (arguments == null)
{
arguments = new Dictionary<string, object>();
}
if (valueProviderFactories == null)
{
valueProviderFactories = new List<IValueProviderFactory>();
}
if (routeData == null)
{
routeData = new RouteData();
}
if (logger == null)
{
logger = new NullLoggerFactory().CreateLogger<ControllerActionInvoker>();
}
var httpContext = new DefaultHttpContext();
var options = Options.Create(new MvcOptions());
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
services.AddSingleton<IOptions<MvcOptions>>(options);
services.AddSingleton<IActionResultExecutor<ObjectResult>>(new ObjectResultExecutor(
new DefaultOutputFormatterSelector(options, NullLoggerFactory.Instance),
new TestHttpResponseStreamWriterFactory(),
NullLoggerFactory.Instance,
options));
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = services.BuildServiceProvider();
var formatter = new Mock<IOutputFormatter>();
formatter
.Setup(f => f.CanWriteResult(It.IsAny<OutputFormatterCanWriteContext>()))
.Returns(true);
formatter
.Setup(f => f.WriteAsync(It.IsAny<OutputFormatterWriteContext>()))
.Returns<OutputFormatterWriteContext>(async c =>
{
await c.HttpContext.Response.WriteAsync(c.Object.ToString());
});
options.Value.OutputFormatters.Add(formatter.Object);
var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
if (diagnosticListener != null)
{
diagnosticSource.SubscribeWithAdapter(diagnosticListener);
}
var objectMethodExecutor = ObjectMethodExecutor.Create(
actionDescriptor.MethodInfo,
actionDescriptor.ControllerTypeInfo,
ParameterDefaultValues.GetParameterDefaultValues(actionDescriptor.MethodInfo));
var actionMethodExecutor = ActionMethodExecutor.GetExecutor(objectMethodExecutor);
var cacheEntry = new ControllerActionInvokerCacheEntry(
new FilterItem[0],
(c) => controller,
null,
(_, __, args) =>
{
foreach (var item in arguments)
{
args[item.Key] = item.Value;
}
return Task.CompletedTask;
},
objectMethodExecutor,
actionMethodExecutor);
var actionContext = new ActionContext(httpContext, routeData, actionDescriptor);
var controllerContext = new ControllerContext(actionContext)
{
ValueProviderFactories = valueProviderFactories,
};
var invoker = new ControllerActionInvoker(
logger,
diagnosticSource,
ActionContextAccessor.Null,
new ActionResultTypeMapper(),
controllerContext,
cacheEntry,
filters);
return invoker;
}
public sealed class TestController
{
public IActionResult ActionMethod()
{
return Result;
}
public ObjectResult ThrowingActionMethod()
{
throw Exception;
}
public IActionResult ActionMethodWithDefaultValues(int value = 5)
{
return new TestActionResult { Value = value };
}
public TestActionResult ActionMethodWithTestActionResult(int value)
{
return new TestActionResult { Value = value };
}
public async Task<TestActionResult> AsyncActionMethodWithTestActionResult(int value)
{
return await Task.FromResult<TestActionResult>(new TestActionResult { Value = value });
}
public IActionResult ActionMethodWithNullActionResult()
{
return null;
}
public object ActionMethodReturningActionResultWithObjectAsReturnType(int value = 5)
{
return new TestActionResult { Value = value };
}
public async Task<object> AsyncActionMethodReturningActionResultWithTaskOfObjectAsReturnType(int value = 5)
{
return await Task.FromResult(new TestActionResult { Value = value });
}
public TestActionResult TestActionMethodWithNullActionResult()
{
return null;
}
public async Task<IActionResult> AsyncActionMethodWithNullActionResult()
{
return await Task.FromResult<IActionResult>(null);
}
public async Task<TestActionResult> AsyncActionMethodWithNullTestActionResult()
{
return await Task.FromResult<TestActionResult>(null);
}
#pragma warning disable 1998
public async Task TaskAction(int i, string s)
{
return;
}
#pragma warning restore 1998
#pragma warning disable 1998
public async Task<int> TaskValueTypeAction(int i, string s)
{
return i;
}
#pragma warning restore 1998
#pragma warning disable 1998
public async Task<Task<int>> TaskOfTaskAction(int i, string s)
{
return TaskValueTypeAction(i, s);
}
#pragma warning restore 1998
public Task<int> TaskValueTypeActionWithoutAsync(int i, string s)
{
return TaskValueTypeAction(i, s);
}
#pragma warning disable 1998
public async Task<int> TaskActionWithException(int i, string s)
{
throw new NotImplementedException("Not Implemented Exception");
}
#pragma warning restore 1998
public Task<int> TaskActionWithExceptionWithoutAsync(int i, string s)
{
throw new NotImplementedException("Not Implemented Exception");
}
public async Task<int> TaskActionThrowAfterAwait(int i, string s)
{
await Task.Delay(500);
throw new ArgumentException("Argument Exception");
}
public TaskDerivedType TaskActionWithCustomTaskReturnType(int i, string s)
{
var task = new TaskDerivedType();
task.Start();
return task;
}
public TaskOfTDerivedType<int> TaskActionWithCustomTaskOfTReturnType(int i, string s)
{
var task = new TaskOfTDerivedType<int>(1);
task.Start();
return task;
}
/// <summary>
/// Returns a <see cref="Task{TResult}"/> instead of a <see cref="Task"/>.
/// </summary>
public Task UnwrappedTask(int i, string s)
{
return Task.Factory.StartNew(async () => await Task.Factory.StartNew(() => i));
}
public string Echo(string input)
{
return input;
}
public string EchoWithException(string input)
{
throw new NotImplementedException();
}
public string EchoWithDefaultValue([DefaultValue("hello")] string input)
{
return input;
}
public string EchoWithDefaultValueAndAttribute([DefaultValue("hello")] string input = "world")
{
return input;
}
public ConvertibleToActionResult ActionReturningConvertibleToActionResult(int input)
=> new ConvertibleToActionResult { Value = input };
public Task<ConvertibleToActionResult> ActionReturningConvertibleToActionResultAsync(int input)
=> Task.FromResult(new ConvertibleToActionResult { Value = input });
public object ActionReturningConvertibleAsObject() => new ConvertibleToActionResult();
public IConvertToActionResult ConvertibleToActionResultReturningNull()
{
var mock = new Mock<IConvertToActionResult>();
mock.Setup(m => m.Convert()).Returns((IActionResult)null);
return mock.Object;
}
public class TaskDerivedType : Task
{
public TaskDerivedType()
: base(() => { })
{
}
}
public class TaskOfTDerivedType<T> : Task<T>
{
public TaskOfTDerivedType(T input)
: base(() => input)
{
}
}
}
public sealed class TestActionResult : IActionResult
{
public int Value { get; set; }
public Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Items["Result"] = Value;
return Task.FromResult(0);
}
}
private static ObjectMethodExecutor CreateExecutor(ControllerActionDescriptor actionDescriptor)
{
return ObjectMethodExecutor.Create(
actionDescriptor.MethodInfo,
actionDescriptor.ControllerTypeInfo,
ParameterDefaultValues.GetParameterDefaultValues(actionDescriptor.MethodInfo));
}
public class ConvertibleToActionResult : IConvertToActionResult
{
public int Value { get; set; }
public IActionResult Convert() => new TestActionResult { Value = Value };
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Engine.Maps;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Engine.Basics;
using Signum.Entities;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using Signum.Utilities.Reflection;
using System.Reflection;
using Signum.Engine.Operations;
using System.Xml.Linq;
using System.IO;
using Signum.Engine.Scheduler;
using Signum.Engine;
using System.Linq.Expressions;
using Signum.Engine.Cache;
namespace Signum.Engine.Authorization
{
public static class AuthLogic
{
public static event Action<UserEntity>? UserLogingIn;
public static ICustomAuthorizer? Authorizer;
public static string? SystemUserName { get; private set; }
static ResetLazy<UserEntity?> systemUserLazy = GlobalLazy.WithoutInvalidations(() => SystemUserName == null ? null :
Database.Query<UserEntity>().Where(u => u.UserName == SystemUserName)
.SingleEx(() => "SystemUser with name '{0}'".FormatWith(SystemUserName)));
public static UserEntity? SystemUser
{
get { return systemUserLazy.Value; }
}
public static string? AnonymousUserName { get; private set; }
static ResetLazy<UserEntity?> anonymousUserLazy = GlobalLazy.WithoutInvalidations(() => AnonymousUserName == null ? null :
Database.Query<UserEntity>().Where(u => u.UserName == AnonymousUserName)
.SingleEx(() => "AnonymousUser with name '{0}'".FormatWith(AnonymousUserName)));
public static UserEntity? AnonymousUser
{
get { return anonymousUserLazy.Value; }
}
[AutoExpressionField]
public static IQueryable<UserEntity> Users(this RoleEntity r) =>
As.Expression(() => Database.Query<UserEntity>().Where(u => u.Role.Is(r)));
static ResetLazy<DirectedGraph<Lite<RoleEntity>>> roles = null!;
static ResetLazy<DirectedGraph<Lite<RoleEntity>>> rolesInverse = null!;
static ResetLazy<Dictionary<string, Lite<RoleEntity>>> rolesByName = null!;
class RoleData
{
public bool DefaultAllowed;
public MergeStrategy MergeStrategy;
}
static ResetLazy<Dictionary<Lite<RoleEntity>, RoleData>> mergeStrategies = null!;
public static void AssertStarted(SchemaBuilder sb)
{
sb.AssertDefined(ReflectionTools.GetMethodInfo(() => AuthLogic.Start(null!, null, null)));
}
public static void Start(SchemaBuilder sb, string? systemUserName, string? anonymousUserName)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
SystemUserName = systemUserName;
AnonymousUserName = anonymousUserName;
CultureInfoLogic.AssertStarted(sb);
sb.Include<UserEntity>()
.WithExpressionFrom((RoleEntity r) => r.Users())
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.UserName,
e.Email,
e.Role,
e.State,
e.CultureInfo,
});
sb.Include<RoleEntity>()
.WithSave(RoleOperation.Save)
.WithDelete(RoleOperation.Delete)
.WithQuery(() => r => new
{
Entity = r,
r.Id,
r.Name,
});
roles = sb.GlobalLazy(CacheRoles, new InvalidateWith(typeof(RoleEntity)), AuthLogic.NotifyRulesChanged);
rolesInverse = sb.GlobalLazy(()=>roles.Value.Inverse(), new InvalidateWith(typeof(RoleEntity)));
rolesByName = sb.GlobalLazy(() => roles.Value.ToDictionaryEx(a => a.ToString()!), new InvalidateWith(typeof(RoleEntity)));
mergeStrategies = sb.GlobalLazy(() =>
{
var strategies = Database.Query<RoleEntity>().Select(r => KeyValuePair.Create(r.ToLite(), r.MergeStrategy)).ToDictionary();
var graph = roles.Value;
Dictionary<Lite<RoleEntity>, RoleData> result = new Dictionary<Lite<RoleEntity>, RoleData>();
foreach (var r in graph.CompilationOrder())
{
var strat = strategies.GetOrThrow(r);
var baseValues = graph.RelatedTo(r).Select(r2=>result[r2].DefaultAllowed);
result.Add(r, new RoleData
{
MergeStrategy = strat,
DefaultAllowed = strat == MergeStrategy.Union ? baseValues.Any(a => a) : baseValues.All(a => a)
});
}
return result;
}, new InvalidateWith(typeof(RoleEntity)), AuthLogic.NotifyRulesChanged);
sb.Schema.EntityEvents<RoleEntity>().Saving += Schema_Saving;
QueryLogic.Queries.Register(RoleQuery.RolesReferedBy, () =>
from r in Database.Query<RoleEntity>()
from rc in r.Roles
select new
{
Entity = r,
r.Id,
r.Name,
Refered = rc,
});
UserGraph.Register();
}
}
static void Schema_Saving(RoleEntity role)
{
if (!role.IsNew && role.Roles.IsGraphModified)
{
using (new EntityCache(EntityCacheType.ForceNew))
{
EntityCache.AddFullGraph(role);
var allRoles = Database.RetrieveAll<RoleEntity>();
var roleGraph = DirectedGraph<RoleEntity>.Generate(allRoles, r => r.Roles.Select(sr => sr.RetrieveAndRemember()));
var problems = roleGraph.FeedbackEdgeSet().Edges.ToList();
if (problems.Count > 0)
throw new ApplicationException(
AuthAdminMessage._0CyclesHaveBeenFoundInTheGraphOfRolesDueToTheRelationships.NiceToString().FormatWith(problems.Count) +
problems.ToString("\r\n"));
}
}
}
static DirectedGraph<Lite<RoleEntity>> CacheRoles()
{
using (AuthLogic.Disable())
{
DirectedGraph<Lite<RoleEntity>> newRoles = new DirectedGraph<Lite<RoleEntity>>();
using (new EntityCache(EntityCacheType.ForceNewSealed))
foreach (var role in Database.RetrieveAll<RoleEntity>())
{
newRoles.Expand(role.ToLite(), r => r.RetrieveAndRemember().Roles);
}
var problems = newRoles.FeedbackEdgeSet().Edges.ToList();
if (problems.Count > 0)
throw new ApplicationException(
AuthAdminMessage._0CyclesHaveBeenFoundInTheGraphOfRolesDueToTheRelationships.NiceToString().FormatWith(problems.Count) +
problems.ToString("\r\n"));
return newRoles;
}
}
public static IDisposable UnsafeUserSession(string username)
{
UserEntity? user;
using (AuthLogic.Disable())
{
user = RetrieveUser(username);
if (user == null)
throw new ApplicationException(LoginAuthMessage.Username0IsNotValid.NiceToString().FormatWith(username));
}
return UserHolder.UserSession(user);
}
public static Func<string, UserEntity?> RetrieveUserByUsername = (username) => Database.Query<UserEntity>().Where(u => u.UserName == username).SingleOrDefaultEx();
public static UserEntity? RetrieveUser(string username)
{
var result = RetrieveUserByUsername(username);
if (result != null && result.State == UserState.Disabled)
throw new ApplicationException(LoginAuthMessage.User0IsDisabled.NiceToString().FormatWith(result.UserName));
return result;
}
public static IEnumerable<Lite<RoleEntity>> RolesInOrder()
{
return roles.Value.CompilationOrderGroups().SelectMany(gr => gr.OrderBy(a => a.ToString()));
}
internal static DirectedGraph<Lite<RoleEntity>> RolesGraph()
{
return roles.Value;
}
public static Lite<RoleEntity> GetRole(string roleName)
{
return rolesByName.Value.GetOrThrow(roleName);
}
public static IEnumerable<Lite<RoleEntity>> RelatedTo(Lite<RoleEntity> role)
{
return roles.Value.RelatedTo(role);
}
public static MergeStrategy GetMergeStrategy(Lite<RoleEntity> role)
{
return mergeStrategies.Value.GetOrThrow(role).MergeStrategy;
}
public static bool GetDefaultAllowed(Lite<RoleEntity> role)
{
return mergeStrategies.Value.GetOrThrow(role).DefaultAllowed;
}
static bool gloaballyEnabled = true;
public static bool GloballyEnabled
{
get { return gloaballyEnabled; }
set { gloaballyEnabled = value; }
}
static readonly Variable<bool> tempDisabled = Statics.ThreadVariable<bool>("authTempDisabled");
public static IDisposable? Disable()
{
if (tempDisabled.Value) return null;
tempDisabled.Value = true;
return new Disposable(() => tempDisabled.Value = false);
}
public static IDisposable? Enable()
{
if (!tempDisabled.Value) return null;
tempDisabled.Value = false;
return new Disposable(() => tempDisabled.Value = true);
}
public static bool IsEnabled
{
get { return !tempDisabled.Value && gloaballyEnabled; }
}
public static event Action? OnRulesChanged;
public static void NotifyRulesChanged()
{
OnRulesChanged?.Invoke();
}
public static UserEntity Login(string username, byte[] passwordHash, out string authenticationType)
{
using (AuthLogic.Disable())
{
UserEntity user = RetrieveUser(username, passwordHash);
OnUserLogingIn(user);
authenticationType = "database";
return user;
}
}
public static void OnUserLogingIn(UserEntity user)
{
UserLogingIn?.Invoke(user);
}
public static UserEntity RetrieveUser(string username, byte[] passwordHash)
{
using (AuthLogic.Disable())
{
UserEntity? user = RetrieveUser(username);
if (user == null)
throw new IncorrectUsernameException(LoginAuthMessage.Username0IsNotValid.NiceToString().FormatWith(username));
if (!user.PasswordHash.SequenceEqual(passwordHash))
throw new IncorrectPasswordException(LoginAuthMessage.IncorrectPassword.NiceToString());
return user;
}
}
public static UserEntity? TryRetrieveUser(string username, byte[] passwordHash)
{
using (AuthLogic.Disable())
{
UserEntity? user = RetrieveUser(username);
if (user == null)
return null;
if (!user.PasswordHash.SequenceEqual(passwordHash))
return null;
return user;
}
}
public static void ChangePassword(Lite<UserEntity> user, byte[] passwordHash, byte[] newPasswordHash)
{
var userEntity = user.RetrieveAndForget();
userEntity.PasswordHash = newPasswordHash;
using (AuthLogic.Disable())
userEntity.Execute(UserOperation.Save);
}
public static void StartAllModules(SchemaBuilder sb)
{
TypeAuthLogic.Start(sb);
PropertyAuthLogic.Start(sb);
QueryAuthLogic.Start(sb);
OperationAuthLogic.Start(sb);
PermissionAuthLogic.Start(sb);
}
public static HashSet<Lite<RoleEntity>> CurrentRoles()
{
return roles.Value.IndirectlyRelatedTo(RoleEntity.Current, true);
}
public static HashSet<Lite<RoleEntity>> IndirectlyRelated(Lite<RoleEntity> role)
{
return roles.Value.IndirectlyRelatedTo(role, true);
}
public static HashSet<Lite<RoleEntity>> InverseIndirectlyRelated(Lite<RoleEntity> role)
{
return rolesInverse.Value.IndirectlyRelatedTo(role, true);
}
internal static int Rank(Lite<RoleEntity> role)
{
return roles.Value.IndirectlyRelatedTo(role).Count;
}
public static event Func<bool, XElement>? ExportToXml;
public static event Func<XElement, Dictionary<string, Lite<RoleEntity>>, Replacements, SqlPreCommand?>? ImportFromXml;
public static XDocument ExportRules(bool exportAll = false)
{
SystemEventLogLogic.Log("Export AuthRules");
return new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Auth",
new XElement("Roles",
RolesInOrder().Select(r => new XElement("Role",
new XAttribute("Name", r.ToString()),
GetMergeStrategy(r) == MergeStrategy.Intersection? new XAttribute("MergeStrategy", MergeStrategy.Intersection) : null,
new XAttribute("Contains", roles.Value.RelatedTo(r).ToString(","))))),
ExportToXml?.GetInvocationListTyped().Select(a => a(exportAll)).NotNull().OrderBy(a => a.Name.ToString())));
}
public static SqlPreCommand? ImportRulesScript(XDocument doc, bool interactive)
{
Replacements replacements = new Replacements { Interactive = interactive };
Dictionary<string, Lite<RoleEntity>> rolesDic = roles.Value.ToDictionary(a => a.ToString()!);
Dictionary<string, XElement> rolesXml = doc.Root.Element("Roles").Elements("Role").ToDictionary(x => x.Attribute("Name").Value);
replacements.AskForReplacements(rolesXml.Keys.ToHashSet(), rolesDic.Keys.ToHashSet(), "Roles");
rolesDic = replacements.ApplyReplacementsToNew(rolesDic, "Roles");
try
{
var xmlOnly = rolesXml.Keys.Except(rolesDic.Keys).ToList();
if (xmlOnly.Any())
throw new InvalidOperationException("roles {0} not found on the database".FormatWith(xmlOnly.ToString(", ")));
foreach (var kvp in rolesXml)
{
var r = rolesDic[kvp.Key];
var current = GetMergeStrategy(r);
var should = kvp.Value.Attribute("MergeStrategy")?.Let(t => t.Value.ToEnum<MergeStrategy>()) ?? MergeStrategy.Union;
if (current != should)
throw new InvalidOperationException("Merge strategy of {0} is {1} in the database but is {2} in the file".FormatWith(r, current, should));
EnumerableExtensions.JoinStrict(
roles.Value.RelatedTo(r),
kvp.Value.Attribute("Contains").Value.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries),
sr => sr.ToString(),
s => rolesDic[s].ToString(),
(sr, s) => 0,
"subRoles of {0}".FormatWith(r));
}
}
catch (InvalidOperationException ex)
{
throw new InvalidRoleGraphException("The role graph does not match:\r\n" + ex.Message);
}
var dbOnlyWarnings = rolesDic.Keys.Except(rolesXml.Keys).Select(n =>
new SqlPreCommandSimple("-- Alien role {0} not configured!!".FormatWith(n))
).Combine(Spacing.Simple);
SqlPreCommand? result = ImportFromXml.GetInvocationListTyped()
.Select(inv => inv(doc.Root, rolesDic, replacements)).Combine(Spacing.Triple);
if (replacements.Values.Any(a => a.Any()))
SafeConsole.WriteLineColor(ConsoleColor.Red, "There are renames! Remember to export after executing the script");
if (result == null && dbOnlyWarnings == null)
return null;
return SqlPreCommand.Combine(Spacing.Triple,
new SqlPreCommandSimple("-- BEGIN AUTH SYNC SCRIPT"),
Connector.Current.SqlBuilder.UseDatabase(),
dbOnlyWarnings,
result,
new SqlPreCommandSimple("-- END AUTH SYNC SCRIPT"));
}
public static void LoadRoles(XDocument doc)
{
var roleInfos = doc.Root.Element("Roles").Elements("Role").Select(x => new
{
Name = x.Attribute("Name").Value,
MergeStrategy = x.Attribute("MergeStrategy")?.Let(ms => ms.Value.ToEnum<MergeStrategy>()) ?? MergeStrategy.Union,
SubRoles = x.Attribute("Contains").Value.SplitNoEmpty(',' )
}).ToList();
var roles = roleInfos.ToDictionary(a => a.Name!, a => new RoleEntity { Name = a.Name!, MergeStrategy = a.MergeStrategy }); /*CSBUG*/
foreach (var ri in roleInfos)
{
roles[ri.Name].Roles = ri.SubRoles.Select(r => roles.GetOrThrow(r).ToLiteFat()).ToMList();
}
using (OperationLogic.AllowSave<RoleEntity>())
roles.Values.SaveList();
}
public static void SynchronizeRoles(XDocument doc)
{
Table table = Schema.Current.Table(typeof(RoleEntity));
TableMList relationalTable = table.TablesMList().Single();
Dictionary<string, XElement> rolesXml = doc.Root.Element("Roles").Elements("Role").ToDictionary(x => x.Attribute("Name").Value);
{
Dictionary<string, RoleEntity> rolesDic = Database.Query<RoleEntity>().ToDictionary(a => a.ToString());
Replacements replacements = new Replacements();
replacements.AskForReplacements(rolesDic.Keys.ToHashSet(), rolesXml.Keys.ToHashSet(), "Roles");
rolesDic = replacements.ApplyReplacementsToOld(rolesDic, "Roles");
Console.WriteLine("Part 1: Syncronize roles without relationships");
var roleInsertsDeletes = Synchronizer.SynchronizeScript(Spacing.Double, rolesXml, rolesDic,
createNew: (name, xElement) => table.InsertSqlSync(new RoleEntity {
Name = name,
MergeStrategy = xElement.Attribute("MergeStrategy")?.Let(t => t.Value.ToEnum<MergeStrategy>()) ?? MergeStrategy.Union
}, includeCollections: false),
removeOld: (name, role) => table.DeleteSqlSync(role, r => r.Name == role.Name),
mergeBoth: (name, xElement, role) =>
{
var oldName = role.Name;
role.Name = name;
role.MergeStrategy = xElement.Attribute("MergeStrategy")?.Let(t => t.Value.ToEnum<MergeStrategy>()) ?? MergeStrategy.Union;
return table.UpdateSqlSync(role, r => r.Name == oldName, includeCollections: false, comment: oldName);
});
if (roleInsertsDeletes != null)
{
SqlPreCommand.Combine(Spacing.Triple,
new SqlPreCommandSimple("-- BEGIN ROLE SYNC SCRIPT"),
Connector.Current.SqlBuilder.UseDatabase(),
roleInsertsDeletes,
new SqlPreCommandSimple("-- END ROLE SYNC SCRIPT"))!.OpenSqlFileRetry();
if (!SafeConsole.Ask("Did you run the previous script (Sync Roles)?"))
return;
}
else
{
SafeConsole.WriteLineColor(ConsoleColor.Green, "Already syncronized");
}
}
{
Console.WriteLine("Part 2: Syncronize roles relationships");
Dictionary<string, RoleEntity> rolesDic = Database.Query<RoleEntity>().ToDictionary(a => a.ToString());
var roleRelationships = Synchronizer.SynchronizeScript(Spacing.Double, rolesXml, rolesDic,
createNew: (name, xelement) => { throw new InvalidOperationException("No new roles should be at this stage. Did you execute the script?"); },
removeOld: (name, role) => { throw new InvalidOperationException("No old roles should be at this stage. Did you execute the script?"); },
mergeBoth: (name, xElement, role) =>
{
var should = xElement.Attribute("Contains").Value.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);
var current = role.Roles.Select(a => a.ToString()!);
if(should.OrderBy().SequenceEqual(current.OrderBy()))
return null;
role.Roles = should.Select(rs => rolesDic.GetOrThrow(rs).ToLite()).ToMList();
return table.UpdateSqlSync(role, r => r.Name == role.Name);
});
if (roleRelationships != null)
{
SqlPreCommand.Combine(Spacing.Triple,
new SqlPreCommandSimple("-- BEGIN ROLE SYNC SCRIPT"),
Connector.Current.SqlBuilder.UseDatabase(),
roleRelationships,
new SqlPreCommandSimple("-- END ROLE SYNC SCRIPT"))!.OpenSqlFileRetry();
if (!SafeConsole.Ask("Did you run the previous script (Sync Roles Relationships)?"))
return;
}
else
{
SafeConsole.WriteLineColor(ConsoleColor.Green, "Already syncronized");
}
}
}
public static void AutomaticImportAuthRules()
{
AutomaticImportAuthRules("AuthRules.xml");
}
public static void AutomaticImportAuthRules(string fileName)
{
Schema.Current.Initialize();
var script = AuthLogic.ImportRulesScript(XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory!, fileName)), interactive: false);
if (script == null)
{
SafeConsole.WriteColor(ConsoleColor.Green, "AuthRules already synchronized");
return;
}
using (var tr = new Transaction())
{
SafeConsole.WriteColor(ConsoleColor.Yellow, "Executing AuthRules changes...");
SafeConsole.WriteColor(ConsoleColor.DarkYellow, script.PlainSql());
script.PlainSqlCommand().ExecuteLeaves();
tr.Commit();
}
SystemEventLogLogic.Log("Import AuthRules");
}
public static void ImportExportAuthRules()
{
ImportExportAuthRules("AuthRules.xml");
}
public static void ImportExportAuthRules(string fileName)
{
void Import()
{
Console.Write("Reading {0}...".FormatWith(fileName));
var doc = XDocument.Load(fileName);
Console.WriteLine("Ok");
Console.WriteLine("Generating SQL script to import auth rules (without modifying the role graph or entities):");
SqlPreCommand? command;
try
{
command = ImportRulesScript(doc, interactive: true);
}
catch (InvalidRoleGraphException ex)
{
SafeConsole.WriteLineColor(ConsoleColor.Red, ex.Message);
if (SafeConsole.Ask("Sync roles first?"))
SyncRoles();
return;
}
if (command == null)
SafeConsole.WriteLineColor(ConsoleColor.Green, "Already syncronized");
else
command.OpenSqlFileRetry();
CacheLogic.ForceReset();
GlobalLazy.ResetAll();
}
void Export()
{
var doc = ExportRules();
doc.Save(fileName);
Console.WriteLine("Sucesfully exported to {0}".FormatWith(fileName));
var info = new DirectoryInfo("../../../");
if (info.Exists && SafeConsole.Ask($"Publish to '{info.Name}' directory (source code)?"))
File.Copy(fileName, "../../../" + Path.GetFileName(fileName), overwrite: true);
}
void SyncRoles()
{
Console.Write("Reading {0}...".FormatWith(fileName));
var doc = XDocument.Load(fileName);
Console.WriteLine("Ok");
Console.WriteLine("Generating script to synchronize roles...");
SynchronizeRoles(doc);
if (SafeConsole.Ask("Import rules now?"))
Import();
}
var action = new ConsoleSwitch<char, Action>("What do you want to do with AuthRules?")
{
{ 'i', Import, "Import into database" },
{ 'e', Export, "Export to local folder" },
{ 'r', SyncRoles, "Sync roles"},
}.Choose();
action?.Invoke();
}
public static bool IsLogged()
{
return UserEntity.Current != null && !UserEntity.Current.Is(AnonymousUser);
}
public static int Compare(Lite<RoleEntity> role1, Lite<RoleEntity> role2)
{
if (roles.Value.IndirectlyRelatedTo(role1).Contains(role2))
return 1;
if (roles.Value.IndirectlyRelatedTo(role2).Contains(role1))
return -1;
return 0;
}
}
public interface ICustomAuthorizer
{
UserEntity Login(string userName, string password, out string authenticationType);
}
[Serializable]
public class InvalidRoleGraphException : Exception
{
public InvalidRoleGraphException() { }
public InvalidRoleGraphException(string message) : base(message) { }
public InvalidRoleGraphException(string message, Exception inner) : base(message, inner) { }
protected InvalidRoleGraphException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowIdleInjectSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowIdleInjectSpec : AkkaSpec
{
private ActorMaterializerSettings Settings { get; }
private ActorMaterializer Materializer { get; }
public FlowIdleInjectSpec(ITestOutputHelper helper) : base(helper)
{
Settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16);
Materializer = ActorMaterializer.Create(Sys, Settings);
}
[Fact]
public void KeepAlive_must_not_emit_additional_elements_if_upstream_is_fastEnough()
{
this.AssertAllStagesStopped(() =>
{
var result = Source.From(Enumerable.Range(1, 10))
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.Grouped(1000)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
result.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
}, Materializer);
}
[Fact]
public void KeepAlive_must_emit_elements_periodically_after_silent_periods()
{
this.AssertAllStagesStopped(() =>
{
var sourceWithIdleGap = Source.Combine(Source.From(Enumerable.Range(1, 5)),
Source.From(Enumerable.Range(6, 5)).InitialDelay(TimeSpan.FromSeconds(2)),
i => new Merge<int, int>(i));
var result = sourceWithIdleGap
.KeepAlive(TimeSpan.FromSeconds(0.6), () => 0)
.Grouped(1000)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
result.Result.ShouldAllBeEquivalentTo(
Enumerable.Range(1, 5).Concat(new[] {0, 0, 0}).Concat(Enumerable.Range(6, 5)));
}, Materializer);
}
[Fact]
public void KeepAlive_must_immediately_pull_upstream()
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.FromPublisher(upstream)
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(1);
upstream.SendNext(1);
downstream.ExpectNext(1);
upstream.SendComplete();
downstream.ExpectComplete();
}
[Fact]
public void KeepAlive_must_immediately_pull_upstream_after_busy_period()
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.Combine(Source.From(Enumerable.Range(1, 10)), Source.FromPublisher(upstream),
i => new Merge<int, int>(i))
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(10);
downstream.ExpectNextN(10).ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
downstream.Request(1);
upstream.SendNext(1);
downstream.ExpectNext(1);
upstream.SendComplete();
downstream.ExpectComplete();
}
[Fact]
public void KeepAlive_must_work_if_timer_fires_before_initial_request()
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.FromPublisher(upstream)
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.EnsureSubscription();
downstream.ExpectNoMsg(TimeSpan.FromSeconds(1.5));
downstream.Request(1);
downstream.ExpectNext(0);
upstream.SendComplete();
downstream.ExpectComplete();
}
[Fact]
public void KeepAlive_must_work_if_timer_fires_before_initial_request_after_busy_period()
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.Combine(Source.From(Enumerable.Range(1, 10)), Source.FromPublisher(upstream),
i => new Merge<int, int>(i))
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(10);
downstream.ExpectNextN(Enumerable.Range(1, 10));
downstream.ExpectNoMsg(TimeSpan.FromSeconds(1.5));
downstream.Request(1);
downstream.ExpectNext(0);
upstream.SendComplete();
downstream.ExpectComplete();
}
[Fact]
public void KeepAlive_must_prefer_upstream_element_over_injected()
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.FromPublisher(upstream)
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.EnsureSubscription();
downstream.ExpectNoMsg(TimeSpan.FromSeconds(1.5));
upstream.SendNext(1);
downstream.ExpectNoMsg(TimeSpan.FromSeconds(0.5));
downstream.Request(1);
downstream.ExpectNext(1);
upstream.SendComplete();
downstream.ExpectComplete();
}
[Fact]
public void KeepAlive_must_prefer_upstream_element_over_injected_after_busy_period()
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.Combine(Source.From(Enumerable.Range(1, 10)), Source.FromPublisher(upstream),
i => new Merge<int, int>(i))
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(10);
downstream.ExpectNextN(Enumerable.Range(1, 10));
downstream.ExpectNoMsg(TimeSpan.FromSeconds(1.5));
upstream.SendNext(1);
downstream.ExpectNoMsg(TimeSpan.FromSeconds(0.5));
downstream.Request(1);
downstream.ExpectNext(1);
upstream.SendComplete();
downstream.ExpectComplete();
}
[Fact]
public void KeepAlive_must_reset_deadline_properly_after_injected_element()
{
var upstream = this.CreatePublisherProbe<int>();
var downstream = this.CreateSubscriberProbe<int>();
Source.FromPublisher(upstream)
.KeepAlive(TimeSpan.FromSeconds(1), () => 0)
.RunWith(Sink.FromSubscriber(downstream), Materializer);
downstream.Request(2);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
downstream.ExpectNext(0);
downstream.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
downstream.ExpectNext(0);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace Internal.Cryptography.Pal
{
/// <summary>
/// Provides an implementation of an X509Store which is backed by files in a directory.
/// </summary>
internal class DirectoryBasedStoreProvider : IStorePal
{
// {thumbprint}.1.pfx to {thumbprint}.9.pfx
private const int MaxSaveAttempts = 9;
private const string PfxExtension = ".pfx";
// *.pfx ({thumbprint}.pfx or {thumbprint}.{ordinal}.pfx)
private const string PfxWildcard = "*" + PfxExtension;
// .*.pfx ({thumbprint}.{ordinal}.pfx)
private const string PfxOrdinalWildcard = "." + PfxWildcard;
private static string s_userStoreRoot;
private readonly string _storePath;
private readonly object _fileWatcherLock = new object();
private List<X509Certificate2> _certificates;
private FileSystemWatcher _watcher;
private readonly bool _readOnly;
#if DEBUG
static DirectoryBasedStoreProvider()
{
Debug.Assert(
0 == OpenFlags.ReadOnly,
"OpenFlags.ReadOnly is not zero, read-only detection will not work");
}
#endif
internal DirectoryBasedStoreProvider(string storeName, OpenFlags openFlags)
{
if (string.IsNullOrEmpty(storeName))
{
throw new CryptographicException(SR.Arg_EmptyOrNullString);
}
string directoryName = GetDirectoryName(storeName);
if (s_userStoreRoot == null)
{
// Do this here instead of a static field initializer so that
// the static initializer isn't capable of throwing the "home directory not found"
// exception.
s_userStoreRoot = PersistedFiles.GetUserFeatureDirectory(
X509Persistence.CryptographyFeatureName,
X509Persistence.X509StoresSubFeatureName);
}
_storePath = Path.Combine(s_userStoreRoot, directoryName);
if (0 != (openFlags & OpenFlags.OpenExistingOnly))
{
if (!Directory.Exists(_storePath))
{
throw new CryptographicException(SR.Cryptography_X509_StoreNotFound);
}
}
// ReadOnly is 0x00, so it is implicit unless either ReadWrite or MaxAllowed
// was requested.
OpenFlags writeFlags = openFlags & (OpenFlags.ReadWrite | OpenFlags.MaxAllowed);
if (writeFlags == OpenFlags.ReadOnly)
{
_readOnly = true;
}
}
public void Dispose()
{
if (_watcher != null)
{
_watcher.Dispose();
_watcher = null;
}
}
public void FindAndCopyTo(
X509FindType findType,
object findValue,
bool validOnly,
X509Certificate2Collection collection)
{
}
public byte[] Export(X509ContentType contentType, string password)
{
// Export is for X509Certificate2Collections in their IStorePal guise,
// if someone wanted to export whole stores they'd need to do
// store.Certificates.Export(...), which would end up in the
// CollectionBackedStoreProvider.
Debug.Fail("Export was unexpected on a DirectoryBasedStore");
throw new InvalidOperationException();
}
public void CopyTo(X509Certificate2Collection collection)
{
Debug.Assert(collection != null);
// Copy the reference locally, any directory change operations
// will cause the field to be reset to null.
List<X509Certificate2> certificates = _certificates;
if (certificates == null)
{
// ReadDirectory will both load _certificates and return the answer, so this call
// will have stable results across multiple adds/deletes happening in parallel.
certificates = ReadDirectory();
Debug.Assert(certificates != null);
}
foreach (X509Certificate2 cert in certificates)
{
collection.Add(cert);
}
}
private List<X509Certificate2> ReadDirectory()
{
if (!Directory.Exists(_storePath))
{
// Don't assign the field here, because we don't have a FileSystemWatcher
// yet to tell us that something has been added.
return new List<X509Certificate2>(0);
}
List<X509Certificate2> certs = new List<X509Certificate2>();
lock (_fileWatcherLock)
{
if (_watcher == null)
{
_watcher = new FileSystemWatcher(_storePath, PfxWildcard)
{
NotifyFilter = NotifyFilters.LastWrite,
};
FileSystemEventHandler handler = FlushCache;
_watcher.Changed += handler;
_watcher.Created += handler;
_watcher.Deleted += handler;
// The Renamed event has a different delegate type
_watcher.Renamed += FlushCache;
_watcher.Error += FlushCache;
}
// Start watching for change events to know that another instance
// has messed with the underlying store. This keeps us aligned
// with the Windows implementation, which opens stores with change
// notifications.
_watcher.EnableRaisingEvents = true;
foreach (string filePath in Directory.EnumerateFiles(_storePath, PfxWildcard))
{
X509Certificate2 cert;
try
{
cert = new X509Certificate2(filePath);
}
catch (CryptographicException)
{
// The file wasn't a certificate, move on to the next one.
continue;
}
certs.Add(cert);
}
// Don't release _fileWatcherLock until _certificates is assigned, otherwise
// we may be setting it to a stale value after the change event said to clear it
_certificates = certs;
}
return certs;
}
public void Add(ICertificatePal certPal)
{
if (_readOnly)
{
// Windows compatibility: Remove only throws when it needs to do work, add throws always.
throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly);
}
// Save the collection to a local so it's consistent for the whole method
List<X509Certificate2> certificates = _certificates;
OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal;
using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles()))
{
// certificates will be null if anything has changed since the last call to
// get_Certificates; including Add being called without get_Certificates being
// called at all.
if (certificates != null)
{
foreach (X509Certificate2 inCollection in certificates)
{
if (inCollection.Equals(copy))
{
if (!copy.HasPrivateKey || inCollection.HasPrivateKey)
{
// If the existing store only knows about a public key, but we're
// adding a public+private pair, continue with the add.
//
// So, therefore, if we aren't adding a private key, or already have one,
// we don't need to do anything.
return;
}
}
}
}
// This may well be the first time that we've added something to this store.
Directory.CreateDirectory(_storePath);
uint userId = Interop.Sys.GetEUid();
EnsureDirectoryPermissions(_storePath, userId);
string thumbprint = copy.Thumbprint;
bool findOpenSlot;
// The odds are low that we'd have a thumbprint collision, but check anyways.
string existingFilename = FindExistingFilename(copy, _storePath, out findOpenSlot);
if (existingFilename != null)
{
bool dataExistsAlready = false;
// If the file on disk is just a public key, but we're trying to add a private key,
// we'll want to overwrite it.
if (copy.HasPrivateKey)
{
try
{
using (X509Certificate2 fromFile = new X509Certificate2(existingFilename))
{
if (fromFile.HasPrivateKey)
{
// We have a private key, the file has a private key, we're done here.
dataExistsAlready = true;
}
}
}
catch (CryptographicException)
{
// We can't read this file anymore, but a moment ago it was this certificate,
// so go ahead and overwrite it.
}
}
else
{
// If we're just a public key then the file has at least as much data as we do.
dataExistsAlready = true;
}
if (dataExistsAlready)
{
// The file was added but our collection hasn't resynced yet.
// Set _certificates to null to force a resync.
_certificates = null;
return;
}
}
string destinationFilename;
FileMode mode = FileMode.CreateNew;
if (existingFilename != null)
{
destinationFilename = existingFilename;
mode = FileMode.Create;
}
else if (findOpenSlot)
{
destinationFilename = FindOpenSlot(thumbprint);
}
else
{
destinationFilename = Path.Combine(_storePath, thumbprint + PfxExtension);
}
using (FileStream stream = new FileStream(destinationFilename, mode))
{
EnsureFilePermissions(stream, userId);
byte[] pkcs12 = copy.Export(X509ContentType.Pkcs12);
stream.Write(pkcs12, 0, pkcs12.Length);
}
}
// Null out _certificates so the next call to get_Certificates causes a re-scan.
_certificates = null;
}
public void Remove(ICertificatePal certPal)
{
OpenSslX509CertificateReader cert = (OpenSslX509CertificateReader)certPal;
using (X509Certificate2 copy = new X509Certificate2(cert.DuplicateHandles()))
{
bool hadCandidates;
string currentFilename = FindExistingFilename(copy, _storePath, out hadCandidates);
if (currentFilename != null)
{
if (_readOnly)
{
// Windows compatibility, the readonly check isn't done until after a match is found.
throw new CryptographicException(SR.Cryptography_X509_StoreReadOnly);
}
File.Delete(currentFilename);
}
}
// Null out _certificates so the next call to get_Certificates causes a re-scan.
_certificates = null;
}
private static string FindExistingFilename(X509Certificate2 cert, string storePath, out bool hadCandidates)
{
hadCandidates = false;
foreach (string maybeMatch in Directory.EnumerateFiles(storePath, cert.Thumbprint + PfxWildcard))
{
hadCandidates = true;
try
{
using (X509Certificate2 candidate = new X509Certificate2(maybeMatch))
{
if (candidate.Equals(cert))
{
return maybeMatch;
}
}
}
catch (CryptographicException)
{
// Contents weren't interpretable as a certificate, so it's not a match.
}
}
return null;
}
private string FindOpenSlot(string thumbprint)
{
// We already know that {thumbprint}.pfx is taken, so start with {thumbprint}.1.pfx
// We need space for {thumbprint} (thumbprint.Length)
// And ".0.pfx" (6)
// If MaxSaveAttempts is big enough to use more than one digit, we need that space, too (MaxSaveAttempts / 10)
StringBuilder pathBuilder = new StringBuilder(thumbprint.Length + PfxOrdinalWildcard.Length + (MaxSaveAttempts / 10));
pathBuilder.Append(thumbprint);
pathBuilder.Append('.');
int prefixLength = pathBuilder.Length;
for (int i = 1; i <= MaxSaveAttempts; i++)
{
pathBuilder.Length = prefixLength;
pathBuilder.Append(i);
pathBuilder.Append(PfxExtension);
string builtPath = Path.Combine(_storePath, pathBuilder.ToString());
if (!File.Exists(builtPath))
{
return builtPath;
}
}
throw new CryptographicException(SR.Cryptography_X509_StoreNoFileAvailable);
}
private void FlushCache(object sender, EventArgs e)
{
lock (_fileWatcherLock)
{
// Events might end up not firing until after the object was disposed, which could cause
// problems consistently reading _watcher; so save it to a local.
FileSystemWatcher watcher = _watcher;
if (watcher != null)
{
// Stop processing events until we read again, particularly because
// there's nothing else we'll do until then.
watcher.EnableRaisingEvents = false;
}
_certificates = null;
}
}
private static string GetDirectoryName(string storeName)
{
Debug.Assert(storeName != null);
try
{
string fileName = Path.GetFileName(storeName);
if (!StringComparer.Ordinal.Equals(storeName, fileName))
{
throw new CryptographicException(SR.Format(SR.Security_InvalidValue, "storeName"));
}
}
catch (IOException e)
{
throw new CryptographicException(e.Message, e);
}
return storeName.ToLowerInvariant();
}
/// <summary>
/// Checks the store directory has the correct permissions.
/// </summary>
/// <param name="path">
/// The path of the directory to check.
/// </param>
/// <param name="userId">
/// The current userId from GetEUid().
/// </param>
private static void EnsureDirectoryPermissions(string path, uint userId)
{
Interop.Sys.FileStatus dirStat;
if (Interop.Sys.Stat(path, out dirStat) != 0)
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
throw new CryptographicException(
SR.Cryptography_FileStatusError,
new IOException(error.GetErrorMessage(), error.RawErrno));
}
if (dirStat.Uid != userId)
{
throw new CryptographicException(SR.Format(SR.Cryptography_OwnerNotCurrentUser, path));
}
if ((dirStat.Mode & (int)Interop.Sys.Permissions.Mask) != (int)Interop.Sys.Permissions.S_IRWXU)
{
throw new CryptographicException(SR.Format(SR.Cryptography_InvalidDirectoryPermissions, path));
}
}
/// <summary>
/// Checks the file has the correct permissions.
/// </summary>
/// <param name="stream">
/// The file stream to check.
/// </param>
/// <param name="userId">
/// The current userId from GetEUid().
/// </param>
private static void EnsureFilePermissions(FileStream stream, uint userId)
{
// Verify that we're creating files with u+rw and o-rw, g-rw.
const Interop.Sys.Permissions requiredPermissions =
Interop.Sys.Permissions.S_IRUSR |
Interop.Sys.Permissions.S_IWUSR;
const Interop.Sys.Permissions forbiddenPermissions =
Interop.Sys.Permissions.S_IROTH |
Interop.Sys.Permissions.S_IWOTH |
Interop.Sys.Permissions.S_IRGRP |
Interop.Sys.Permissions.S_IWGRP;
// NOTE: no need to call DangerousAddRef here, since the FileStream is
// held open outside of this method
int fileDescriptor = (int)stream.SafeFileHandle.DangerousGetHandle();
Interop.Sys.FileStatus stat;
if (Interop.Sys.FStat(fileDescriptor, out stat) != 0)
{
Interop.ErrorInfo error = Interop.Sys.GetLastErrorInfo();
throw new CryptographicException(
SR.Cryptography_FileStatusError,
new IOException(error.GetErrorMessage(), error.RawErrno));
}
if (stat.Uid != userId)
{
throw new CryptographicException(SR.Format(SR.Cryptography_OwnerNotCurrentUser, stream.Name));
}
if ((stat.Mode & (int)requiredPermissions) != (int)requiredPermissions)
{
throw new CryptographicException(SR.Format(SR.Cryptography_InsufficientFilePermissions, stream.Name));
}
if ((stat.Mode & (int)forbiddenPermissions) != 0)
{
throw new CryptographicException(SR.Format(SR.Cryptography_TooBroadFilePermissions, stream.Name));
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using NUnit.Framework.Internal;
using NUnit.Compatibility;
using System.Collections;
using System;
using System.Reflection;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Delegate used to delay evaluation of the actual value
/// to be used in evaluating a constraint
/// </summary>
public delegate TActual ActualValueDelegate<TActual>();
/// <summary>
/// The Constraint class is the base of all built-in constraints
/// within NUnit. It provides the operator overloads used to combine
/// constraints.
/// </summary>
public abstract class Constraint : IConstraint
{
Lazy<string> _displayName;
#region Constructor
/// <summary>
/// Construct a constraint with optional arguments
/// </summary>
/// <param name="args">Arguments to be saved</param>
protected Constraint(params object[] args)
{
Arguments = args;
_displayName = new Lazy<string>(() =>
{
var type = this.GetType();
var displayName = type.Name;
if (type.GetTypeInfo().IsGenericType)
displayName = displayName.Substring(0, displayName.Length - 2);
if (displayName.EndsWith("Constraint", StringComparison.Ordinal))
displayName = displayName.Substring(0, displayName.Length - 10);
return displayName;
});
}
#endregion
#region Properties
/// <summary>
/// The display name of this Constraint for use by ToString().
/// The default value is the name of the constraint with
/// trailing "Constraint" removed. Derived classes may set
/// this to another name in their constructors.
/// </summary>
public virtual string DisplayName { get { return _displayName.Value; } }
/// <summary>
/// The Description of what this constraint tests, for
/// use in messages and in the ConstraintResult.
/// </summary>
public virtual string Description { get; protected set; }
/// <summary>
/// Arguments provided to this Constraint, for use in
/// formatting the description.
/// </summary>
public object[] Arguments { get; private set; }
/// <summary>
/// The ConstraintBuilder holding this constraint
/// </summary>
public ConstraintBuilder Builder { get; set; }
#endregion
#region Abstract and Virtual Methods
/// <summary>
/// Applies the constraint to an actual value, returning a ConstraintResult.
/// </summary>
/// <param name="actual">The value to be tested</param>
/// <returns>A ConstraintResult</returns>
public abstract ConstraintResult ApplyTo<TActual>(TActual actual);
/// <summary>
/// Applies the constraint to an ActualValueDelegate that returns
/// the value to be tested. The default implementation simply evaluates
/// the delegate but derived classes may override it to provide for
/// delayed processing.
/// </summary>
/// <param name="del">An ActualValueDelegate</param>
/// <returns>A ConstraintResult</returns>
public virtual ConstraintResult ApplyTo<TActual>(ActualValueDelegate<TActual> del)
{
#if NET_4_0 || NET_4_5 || PORTABLE
if (AsyncInvocationRegion.IsAsyncOperation(del))
using (var region = AsyncInvocationRegion.Create(del))
return ApplyTo(region.WaitForPendingOperationsToComplete(del()));
#endif
return ApplyTo(GetTestObject(del));
}
#pragma warning disable 3006
/// <summary>
/// Test whether the constraint is satisfied by a given reference.
/// The default implementation simply dereferences the value but
/// derived classes may override it to provide for delayed processing.
/// </summary>
/// <param name="actual">A reference to the value to be tested</param>
/// <returns>A ConstraintResult</returns>
public virtual ConstraintResult ApplyTo<TActual>(ref TActual actual)
{
return ApplyTo(actual);
}
#pragma warning restore 3006
/// <summary>
/// Retrieves the value to be tested from an ActualValueDelegate.
/// The default implementation simply evaluates the delegate but derived
/// classes may override it to provide for delayed processing.
/// </summary>
/// <param name="del">An ActualValueDelegate</param>
/// <returns>Delegate evaluation result</returns>
protected virtual object GetTestObject<TActual>(ActualValueDelegate<TActual> del)
{
return del();
}
#endregion
#region ToString Override
/// <summary>
/// Default override of ToString returns the constraint DisplayName
/// followed by any arguments within angle brackets.
/// </summary>
/// <returns></returns>
public override string ToString()
{
string rep = GetStringRepresentation();
return this.Builder == null ? rep : string.Format("<unresolved {0}>", rep);
}
/// <summary>
/// Returns the string representation of this constraint
/// </summary>
protected virtual string GetStringRepresentation()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<");
sb.Append(DisplayName.ToLower());
foreach (object arg in Arguments)
{
sb.Append(" ");
sb.Append(_displayable(arg));
}
sb.Append(">");
return sb.ToString();
}
private static string _displayable(object o)
{
if (o == null) return "null";
string fmt = o is string ? "\"{0}\"" : "{0}";
return string.Format(System.Globalization.CultureInfo.InvariantCulture, fmt, o);
}
#endregion
#region Operator Overloads
/// <summary>
/// This operator creates a constraint that is satisfied only if both
/// argument constraints are satisfied.
/// </summary>
public static Constraint operator &(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new AndConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if either
/// of the argument constraints is satisfied.
/// </summary>
public static Constraint operator |(Constraint left, Constraint right)
{
IResolveConstraint l = (IResolveConstraint)left;
IResolveConstraint r = (IResolveConstraint)right;
return new OrConstraint(l.Resolve(), r.Resolve());
}
/// <summary>
/// This operator creates a constraint that is satisfied if the
/// argument constraint is not satisfied.
/// </summary>
public static Constraint operator !(Constraint constraint)
{
IResolveConstraint r = (IResolveConstraint)constraint;
return new NotConstraint(r.Resolve());
}
#endregion
#region Binary Operators
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression And
{
get
{
ConstraintBuilder builder = this.Builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new AndOperator());
return new ConstraintExpression(builder);
}
}
/// <summary>
/// Returns a ConstraintExpression by appending And
/// to the current constraint.
/// </summary>
public ConstraintExpression With
{
get { return this.And; }
}
/// <summary>
/// Returns a ConstraintExpression by appending Or
/// to the current constraint.
/// </summary>
public ConstraintExpression Or
{
get
{
ConstraintBuilder builder = this.Builder;
if (builder == null)
{
builder = new ConstraintBuilder();
builder.Append(this);
}
builder.Append(new OrOperator());
return new ConstraintExpression(builder);
}
}
#endregion
#region After Modifier
#if !PORTABLE
/// <summary>
/// Returns a DelayedConstraint with the specified delay time.
/// </summary>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <returns></returns>
public DelayedConstraint After(int delayInMilliseconds)
{
return new DelayedConstraint(
Builder == null ? this : Builder.Resolve(),
delayInMilliseconds);
}
/// <summary>
/// Returns a DelayedConstraint with the specified delay time
/// and polling interval.
/// </summary>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <param name="pollingInterval">The interval at which to test the constraint.</param>
/// <returns></returns>
public DelayedConstraint After(int delayInMilliseconds, int pollingInterval)
{
return new DelayedConstraint(
Builder == null ? this : Builder.Resolve(),
delayInMilliseconds,
pollingInterval);
}
#endif
#endregion
#region IResolveConstraint Members
/// <summary>
/// Resolves any pending operators and returns the resolved constraint.
/// </summary>
IConstraint IResolveConstraint.Resolve()
{
return Builder == null ? this : Builder.Resolve();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
public partial struct Vector2
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector2(Single value) : this(value, value) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
[JitIntrinsic]
public Vector2(Single x, Single y)
{
X = x;
Y = y;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
/// <param name="array">The destination array.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from the given index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array
/// or if there are not enough elements to copy.</exception>
public void CopyTo(Single[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 2)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector2 is equal to this Vector2 instance.
/// </summary>
/// <param name="other">The Vector2 to compare this instance to.</param>
/// <returns>True if the other Vector2 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector2 other)
{
return this.X == other.X && this.Y == other.Y;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="value1">The first vector.</param>
/// <param name="value2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector2 value1, Vector2 value2)
{
return value1.X * value2.X +
value1.Y * value2.Y;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Min(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors
/// </summary>
/// <param name="value1">The first source vector</param>
/// <param name="value2">The second source vector</param>
/// <returns>The maximized vector</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Max(Vector2 value1, Vector2 value2)
{
return new Vector2(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Abs(Vector2 value)
{
return new Vector2(Math.Abs(value.X), Math.Abs(value.Y));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 SquareRoot(Vector2 value)
{
return new Vector2((Single)Math.Sqrt(value.X), (Single)Math.Sqrt(value.Y));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator +(Vector2 left, Vector2 right)
{
return new Vector2(left.X + right.X, left.Y + right.Y);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 left, Vector2 right)
{
return new Vector2(left.X - right.X, left.Y - right.Y);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, Vector2 right)
{
return new Vector2(left.X * right.X, left.Y * right.Y);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Single left, Vector2 right)
{
return new Vector2(left, left) * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(Vector2 left, Single right)
{
return left * new Vector2(right, right);
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 left, Vector2 right)
{
return new Vector2(left.X / right.X, left.Y / right.Y);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(Vector2 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector2(
value1.X * invDiv,
value1.Y * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(Vector2 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector2 left, Vector2 right)
{
return !(left == right);
}
#endregion Public Static Operators
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using SFML.Window;
namespace SFML
{
namespace Graphics
{
////////////////////////////////////////////////////////////
/// <summary>
/// Simple wrapper for Window that allows easy
/// 2D rendering
/// </summary>
////////////////////////////////////////////////////////////
public class RenderWindow : SFML.Window.Window, RenderTarget
{
////////////////////////////////////////////////////////////
/// <summary>
/// Create the window with default style and creation settings
/// </summary>
/// <param name="mode">Video mode to use</param>
/// <param name="title">Title of the window</param>
////////////////////////////////////////////////////////////
public RenderWindow(VideoMode mode, string title) :
this(mode, title, Styles.Default, new ContextSettings(0, 0))
{
}
////////////////////////////////////////////////////////////
/// <summary>
/// Create the window with default creation settings
/// </summary>
/// <param name="mode">Video mode to use</param>
/// <param name="title">Title of the window</param>
/// <param name="style">Window style (Resize | Close by default)</param>
////////////////////////////////////////////////////////////
public RenderWindow(VideoMode mode, string title, Styles style) :
this(mode, title, style, new ContextSettings(0, 0))
{
}
////////////////////////////////////////////////////////////
/// <summary>
/// Create the window
/// </summary>
/// <param name="mode">Video mode to use</param>
/// <param name="title">Title of the window</param>
/// <param name="style">Window style (Resize | Close by default)</param>
/// <param name="settings">Creation parameters</param>
////////////////////////////////////////////////////////////
public RenderWindow(VideoMode mode, string title, Styles style, ContextSettings settings) :
base(sfRenderWindow_Create(mode, title, style, ref settings), 0)
{
Initialize();
}
////////////////////////////////////////////////////////////
/// <summary>
/// Create the window from an existing control with default creation settings
/// </summary>
/// <param name="handle">Platform-specific handle of the control</param>
////////////////////////////////////////////////////////////
public RenderWindow(IntPtr handle) :
this(handle, new ContextSettings(0, 0))
{
}
////////////////////////////////////////////////////////////
/// <summary>
/// Create the window from an existing control
/// </summary>
/// <param name="handle">Platform-specific handle of the control</param>
/// <param name="settings">Creation parameters</param>
////////////////////////////////////////////////////////////
public RenderWindow(IntPtr handle, ContextSettings settings) :
base(sfRenderWindow_CreateFromHandle(handle, ref settings), 0)
{
Initialize();
}
////////////////////////////////////////////////////////////
/// <summary>
/// Tell whether or not the window is opened (ie. has been created).
/// Note that a hidden window (Show(false))
/// will still return true
/// </summary>
/// <returns>True if the window is opened</returns>
////////////////////////////////////////////////////////////
public override bool IsOpened()
{
return sfRenderWindow_IsOpened(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Close (destroy) the window.
/// The Window instance remains valid and you can call
/// Create to recreate the window
/// </summary>
////////////////////////////////////////////////////////////
public override void Close()
{
sfRenderWindow_Close(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Display the window on screen
/// </summary>
////////////////////////////////////////////////////////////
public override void Display()
{
sfRenderWindow_Display(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Width of the rendering region of the window
/// </summary>
////////////////////////////////////////////////////////////
public override uint Width
{
get { return sfRenderWindow_GetWidth(This); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Height of the rendering region of the window
/// </summary>
////////////////////////////////////////////////////////////
public override uint Height
{
get { return sfRenderWindow_GetHeight(This); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Creation settings of the window
/// </summary>
////////////////////////////////////////////////////////////
public override ContextSettings Settings
{
get { return sfRenderWindow_GetSettings(This); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Enable / disable vertical synchronization
/// </summary>
/// <param name="enable">True to enable v-sync, false to deactivate</param>
////////////////////////////////////////////////////////////
public override void EnableVerticalSync(bool enable)
{
sfRenderWindow_EnableVerticalSync(This, enable);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Show or hide the mouse cursor
/// </summary>
/// <param name="show">True to show, false to hide</param>
////////////////////////////////////////////////////////////
public override void ShowMouseCursor(bool show)
{
sfRenderWindow_ShowMouseCursor(This, show);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the position of the mouse cursor
/// </summary>
/// <param name="x">Left coordinate of the cursor, relative to the window</param>
/// <param name="y">Top coordinate of the cursor, relative to the window</param>
////////////////////////////////////////////////////////////
public override void SetCursorPosition(uint x, uint y)
{
sfRenderWindow_SetCursorPosition(This, x, y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the position of the window on screen.
/// Only works for top-level windows
/// </summary>
/// <param name="x">Left position</param>
/// <param name="y">Top position</param>
////////////////////////////////////////////////////////////
public override void SetPosition(int x, int y)
{
sfRenderWindow_SetPosition(This, x, y);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the size of the rendering region of the window
/// </summary>
/// <param name="width">New width</param>
/// <param name="height">New height</param>
////////////////////////////////////////////////////////////
public override void SetSize(uint width, uint height)
{
sfRenderWindow_SetSize(This, width, height);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the title of the window
/// </summary>
/// <param name="title">New title</param>
////////////////////////////////////////////////////////////
public override void SetTitle(string title)
{
sfRenderWindow_SetTitle(This, title);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Show or hide the window
/// </summary>
/// <param name="show">True to show, false to hide</param>
////////////////////////////////////////////////////////////
public override void Show(bool show)
{
sfRenderWindow_Show(This, show);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Enable or disable automatic key-repeat.
/// Automatic key-repeat is enabled by default
/// </summary>
/// <param name="enable">True to enable, false to disable</param>
////////////////////////////////////////////////////////////
public override void EnableKeyRepeat(bool enable)
{
sfRenderWindow_EnableKeyRepeat(This, enable);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the window's icon
/// </summary>
/// <param name="width">Icon's width, in pixels</param>
/// <param name="height">Icon's height, in pixels</param>
/// <param name="pixels">Array of pixels, format must be RGBA 32 bits</param>
////////////////////////////////////////////////////////////
public override void SetIcon(uint width, uint height, byte[] pixels)
{
unsafe
{
fixed (byte* PixelsPtr = pixels)
{
sfRenderWindow_SetIcon(This, width, height, PixelsPtr);
}
}
}
////////////////////////////////////////////////////////////
/// <summary>
/// Activate of deactivate the window as the current target
/// for rendering
/// </summary>
/// <param name="active">True to activate, false to deactivate (true by default)</param>
/// <returns>True if operation was successful, false otherwise</returns>
////////////////////////////////////////////////////////////
public override bool SetActive(bool active)
{
return sfRenderWindow_SetActive(This, active);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Limit the framerate to a maximum fixed frequency
/// </summary>
/// <param name="limit">Framerate limit, in frames per seconds (use 0 to disable limit)</param>
////////////////////////////////////////////////////////////
public override void SetFramerateLimit(uint limit)
{
sfRenderWindow_SetFramerateLimit(This, limit);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get time elapsed since last frame
/// </summary>
/// <returns>Time elapsed, in seconds</returns>
////////////////////////////////////////////////////////////
public override float GetFrameTime()
{
return sfRenderWindow_GetFrameTime(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the joystick threshold, ie. the value below which
/// no move event will be generated
/// </summary>
/// <param name="threshold">New threshold, in range [0, 100]</param>
////////////////////////////////////////////////////////////
public override void SetJoystickThreshold(float threshold)
{
sfRenderWindow_SetJoystickThreshold(This, threshold);
}
////////////////////////////////////////////////////////////
/// <summary>
/// OS-specific handle of the window
/// </summary>
////////////////////////////////////////////////////////////
public override IntPtr SystemHandle
{
get { return sfRenderWindow_GetSystemHandle(This); }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Default view of the window
/// </summary>
////////////////////////////////////////////////////////////
public View DefaultView
{
get { return myDefaultView; }
}
////////////////////////////////////////////////////////////
/// <summary>
/// Return the current active view
/// </summary>
/// <returns>The current view</returns>
////////////////////////////////////////////////////////////
public View GetView()
{
return new View(sfRenderWindow_GetView(This));
}
////////////////////////////////////////////////////////////
/// <summary>
/// Change the current active view
/// </summary>
/// <param name="view">New view</param>
////////////////////////////////////////////////////////////
public void SetView(View view)
{
sfRenderWindow_SetView(This, view.This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Get the viewport of a view applied to this target
/// </summary>
/// <param name="view">Target view</param>
/// <returns>Viewport rectangle, expressed in pixels in the current target</returns>
////////////////////////////////////////////////////////////
public IntRect GetViewport(View view)
{
return sfRenderWindow_GetViewport(This, view.This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Convert a point in target coordinates into view coordinates
/// This version uses the current view of the window
/// </summary>
/// <param name="x">X coordinate of the point to convert, relative to the target</param>
/// <param name="y">Y coordinate of the point to convert, relative to the target</param>
/// <returns>Converted point</returns>
///
////////////////////////////////////////////////////////////
public Vector2 ConvertCoords(uint x, uint y)
{
return ConvertCoords(x, y, GetView());
}
////////////////////////////////////////////////////////////
/// <summary>
/// Convert a point in target coordinates into view coordinates
/// This version uses the given view
/// </summary>
/// <param name="x">X coordinate of the point to convert, relative to the target</param>
/// <param name="y">Y coordinate of the point to convert, relative to the target</param>
/// <param name="view">Target view to convert the point to</param>
/// <returns>Converted point</returns>
///
////////////////////////////////////////////////////////////
public Vector2 ConvertCoords(uint x, uint y, View view)
{
Vector2 point;
sfRenderWindow_ConvertCoords(This, x, y, out point.X, out point.Y, view.This);
return point;
}
////////////////////////////////////////////////////////////
/// <summary>
/// Clear the entire window with black color
/// </summary>
////////////////////////////////////////////////////////////
public void Clear()
{
sfRenderWindow_Clear(This, Color.Black);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Clear the entire window with a single color
/// </summary>
/// <param name="color">Color to use to clear the window</param>
////////////////////////////////////////////////////////////
public void Clear(Color color)
{
sfRenderWindow_Clear(This, color);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw something into the window
/// </summary>
/// <param name="objectToDraw">Object to draw</param>
////////////////////////////////////////////////////////////
public void Draw(Drawable objectToDraw)
{
objectToDraw.Render(this, null);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Draw something into the window with a shader
/// </summary>
/// <param name="objectToDraw">Object to draw</param>
/// <param name="shader">Shader to apply</param>
////////////////////////////////////////////////////////////
public void Draw(Drawable objectToDraw, Shader shader)
{
objectToDraw.Render(this, shader);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Save the current OpenGL render states and matrices
/// </summary>
////////////////////////////////////////////////////////////
public void SaveGLStates()
{
sfRenderWindow_SaveGLStates(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Restore the previously saved OpenGL render states and matrices
/// </summary>
////////////////////////////////////////////////////////////
public void RestoreGLStates()
{
sfRenderWindow_RestoreGLStates(This);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Provide a string describing the object
/// </summary>
/// <returns>String description of the object</returns>
////////////////////////////////////////////////////////////
public override string ToString()
{
return "[RenderWindow]" +
" Width(" + Width + ")" +
" Height(" + Height + ")" +
" Settings(" + Settings + ")" +
" DefaultView(" + DefaultView + ")" +
" View(" + GetView() + ")";
}
////////////////////////////////////////////////////////////
/// <summary>
/// Internal function to get the next event
/// </summary>
/// <param name="eventToFill">Variable to fill with the raw pointer to the event structure</param>
/// <returns>True if there was an event, false otherwise</returns>
////////////////////////////////////////////////////////////
protected override bool PollEvent(out Event eventToFill)
{
return sfRenderWindow_PollEvent(This, out eventToFill);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Internal function to get the next event (blocking)
/// </summary>
/// <param name="eventToFill">Variable to fill with the raw pointer to the event structure</param>
/// <returns>False if any error occured</returns>
////////////////////////////////////////////////////////////
protected override bool WaitEvent(out Event eventToFill)
{
return sfRenderWindow_WaitEvent(This, out eventToFill);
}
////////////////////////////////////////////////////////////
/// <summary>
/// Handle the destruction of the object
/// </summary>
/// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param>
////////////////////////////////////////////////////////////
protected override void Destroy(bool disposing)
{
sfRenderWindow_Destroy(This);
if (disposing)
myDefaultView.Dispose();
}
////////////////////////////////////////////////////////////
/// <summary>
/// Do common initializations
/// </summary>
////////////////////////////////////////////////////////////
private void Initialize()
{
myInput = new Input(sfRenderWindow_GetInput(This));
myDefaultView = new View(sfRenderWindow_GetDefaultView(This));
GC.SuppressFinalize(myDefaultView);
}
private View myDefaultView = null;
#region Imports
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderWindow_Create(VideoMode Mode, string Title, Styles Style, ref ContextSettings Params);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderWindow_CreateFromHandle(IntPtr Handle, ref ContextSettings Params);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_Destroy(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderWindow_GetInput(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderWindow_IsOpened(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_Close(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderWindow_PollEvent(IntPtr This, out Event Evt);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderWindow_WaitEvent(IntPtr This, out Event Evt);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_Clear(IntPtr This, Color ClearColor);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_Display(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfRenderWindow_GetWidth(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern uint sfRenderWindow_GetHeight(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern ContextSettings sfRenderWindow_GetSettings(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_EnableVerticalSync(IntPtr This, bool Enable);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_ShowMouseCursor(IntPtr This, bool Show);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_SetCursorPosition(IntPtr This, uint X, uint Y);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_SetPosition(IntPtr This, int X, int Y);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_SetSize(IntPtr This, uint Width, uint Height);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_SetTitle(IntPtr This, string title);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_Show(IntPtr This, bool Show);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_EnableKeyRepeat(IntPtr This, bool Enable);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
unsafe static extern void sfRenderWindow_SetIcon(IntPtr This, uint Width, uint Height, byte* Pixels);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderWindow_SetActive(IntPtr This, bool Active);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderWindow_SaveGLStates(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern bool sfRenderWindow_RestoreGLStates(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_SetFramerateLimit(IntPtr This, uint Limit);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern float sfRenderWindow_GetFrameTime(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_SetJoystickThreshold(IntPtr This, float Threshold);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_SetView(IntPtr This, IntPtr View);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderWindow_GetView(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderWindow_GetDefaultView(IntPtr This);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntRect sfRenderWindow_GetViewport(IntPtr This, IntPtr TargetView);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern void sfRenderWindow_ConvertCoords(IntPtr This, uint WindowX, uint WindowY, out float ViewX, out float ViewY, IntPtr TargetView);
[DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity]
static extern IntPtr sfRenderWindow_GetSystemHandle(IntPtr This);
#endregion
}
}
}
| |
namespace InControl
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
public sealed class AutoDiscover : Attribute
{
}
public class UnityInputDeviceProfile : UnityInputDeviceProfileBase
{
[SerializeField]
protected string[] JoystickNames;
[SerializeField]
protected string[] JoystickRegex;
[SerializeField]
protected string LastResortRegex;
[SerializeField]
public VersionInfo MinUnityVersion { get; protected set; }
[SerializeField]
public VersionInfo MaxUnityVersion { get; protected set; }
public UnityInputDeviceProfile()
{
Sensitivity = 1.0f;
LowerDeadZone = 0.2f;
UpperDeadZone = 0.9f;
MinUnityVersion = VersionInfo.Min;
MaxUnityVersion = VersionInfo.Max;
}
public override bool IsJoystick
{
get
{
return (LastResortRegex != null) ||
(JoystickNames != null && JoystickNames.Length > 0) ||
(JoystickRegex != null && JoystickRegex.Length > 0);
}
}
public override bool HasJoystickName( string joystickName )
{
if (IsNotJoystick)
{
return false;
}
if (JoystickNames != null)
{
if (JoystickNames.Contains( joystickName, StringComparer.OrdinalIgnoreCase ))
{
return true;
}
}
if (JoystickRegex != null)
{
for (var i = 0; i < JoystickRegex.Length; i++)
{
if (Regex.IsMatch( joystickName, JoystickRegex[i], RegexOptions.IgnoreCase ))
{
return true;
}
}
}
return false;
}
public override bool HasLastResortRegex( string joystickName )
{
if (IsNotJoystick)
{
return false;
}
if (LastResortRegex == null)
{
return false;
}
return Regex.IsMatch( joystickName, LastResortRegex, RegexOptions.IgnoreCase );
}
public override bool HasJoystickOrRegexName( string joystickName )
{
return HasJoystickName( joystickName ) || HasLastResortRegex( joystickName );
}
public override bool IsSupportedOnThisPlatform
{
get
{
return IsSupportedOnThisVersionOfUnity && base.IsSupportedOnThisPlatform;
}
}
bool IsSupportedOnThisVersionOfUnity
{
get
{
var unityVersion = VersionInfo.UnityVersion();
return unityVersion >= MinUnityVersion && unityVersion <= MaxUnityVersion;
}
}
/*
#region Serialization
public string Save()
{
var data = JSON.Dump( this, EncodeOptions.PrettyPrint | EncodeOptions.NoTypeHints );
// Somewhat silly, but removes all default values for brevity.
data = Regex.Replace( data, @"\t""JoystickRegex"": null,?\n", "" );
data = Regex.Replace( data, @"\t""LastResortRegex"": null,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""Invert"": false,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""Scale"": 1,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""Raw"": false,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""IgnoreInitialZeroValue"": false,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""Sensitivity"": 1,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""LowerDeadZone"": 0,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""UpperDeadZone"": 1,?\n", "" );
data = Regex.Replace( data, @"\t""Sensitivity"": 1,?\n", "" );
data = Regex.Replace( data, @"\t""LowerDeadZone"": 0.2,?\n", "" );
data = Regex.Replace( data, @"\t""UpperDeadZone"": 0.9,?\n", "" );
data = Regex.Replace( data, @"\t\t\t""(Source|Target)Range"": {\n\t\t\t\t""Value0"": -1,\n\t\t\t\t""Value1"": 1\n\t\t\t},?\n", "" );
data = Regex.Replace( data, @"\t""MinUnityVersion"": {\n\t\t""Major"": 3,\n\t\t""Minor"": 0,\n\t\t""Patch"": 0,\n\t\t""Build"": 0\n\t},?\n", "" );
data = Regex.Replace( data, @"\t""MaxUnityVersion"": {\n\t\t""Major"": 9,\n\t\t""Minor"": 0,\n\t\t""Patch"": 0,\n\t\t""Build"": 0\n\t},?\n", "" );
return data;
}
public static UnityInputDeviceProfile Load( string data )
{
return JSON.Load( data ).Make<UnityInputDeviceProfile>();
}
public void SaveToFile( string filePath )
{
var data = Save();
Utility.WriteToFile( filePath, data );
}
public static UnityInputDeviceProfile LoadFromFile( string filePath )
{
var data = Utility.ReadFromFile( filePath );
return Load( data );
}
#endregion
*/
#region InputControlSource helpers
protected static InputControlSource Button( int index )
{
return new UnityButtonSource( index );
}
protected static InputControlSource Analog( int index )
{
return new UnityAnalogSource( index );
}
protected static InputControlSource Button0 = Button( 0 );
protected static InputControlSource Button1 = Button( 1 );
protected static InputControlSource Button2 = Button( 2 );
protected static InputControlSource Button3 = Button( 3 );
protected static InputControlSource Button4 = Button( 4 );
protected static InputControlSource Button5 = Button( 5 );
protected static InputControlSource Button6 = Button( 6 );
protected static InputControlSource Button7 = Button( 7 );
protected static InputControlSource Button8 = Button( 8 );
protected static InputControlSource Button9 = Button( 9 );
protected static InputControlSource Button10 = Button( 10 );
protected static InputControlSource Button11 = Button( 11 );
protected static InputControlSource Button12 = Button( 12 );
protected static InputControlSource Button13 = Button( 13 );
protected static InputControlSource Button14 = Button( 14 );
protected static InputControlSource Button15 = Button( 15 );
protected static InputControlSource Button16 = Button( 16 );
protected static InputControlSource Button17 = Button( 17 );
protected static InputControlSource Button18 = Button( 18 );
protected static InputControlSource Button19 = Button( 19 );
protected static InputControlSource Analog0 = Analog( 0 );
protected static InputControlSource Analog1 = Analog( 1 );
protected static InputControlSource Analog2 = Analog( 2 );
protected static InputControlSource Analog3 = Analog( 3 );
protected static InputControlSource Analog4 = Analog( 4 );
protected static InputControlSource Analog5 = Analog( 5 );
protected static InputControlSource Analog6 = Analog( 6 );
protected static InputControlSource Analog7 = Analog( 7 );
protected static InputControlSource Analog8 = Analog( 8 );
protected static InputControlSource Analog9 = Analog( 9 );
protected static InputControlSource Analog10 = Analog( 10 );
protected static InputControlSource Analog11 = Analog( 11 );
protected static InputControlSource Analog12 = Analog( 12 );
protected static InputControlSource Analog13 = Analog( 13 );
protected static InputControlSource Analog14 = Analog( 14 );
protected static InputControlSource Analog15 = Analog( 15 );
protected static InputControlSource Analog16 = Analog( 16 );
protected static InputControlSource Analog17 = Analog( 17 );
protected static InputControlSource Analog18 = Analog( 18 );
protected static InputControlSource Analog19 = Analog( 19 );
protected static InputControlSource MenuKey = new UnityKeyCodeSource( KeyCode.Menu );
protected static InputControlSource EscapeKey = new UnityKeyCodeSource( KeyCode.Escape );
#endregion
#region InputDeviceMapping helpers
protected static InputControlMapping LeftStickLeftMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Left Stick Left",
Target = InputControlType.LeftStickLeft,
Source = analog,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping LeftStickRightMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Left Stick Right",
Target = InputControlType.LeftStickRight,
Source = analog,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping LeftStickUpMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Left Stick Up",
Target = InputControlType.LeftStickUp,
Source = analog,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping LeftStickDownMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Left Stick Down",
Target = InputControlType.LeftStickDown,
Source = analog,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping RightStickLeftMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Right Stick Left",
Target = InputControlType.RightStickLeft,
Source = analog,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping RightStickRightMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Right Stick Right",
Target = InputControlType.RightStickRight,
Source = analog,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping RightStickUpMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Right Stick Up",
Target = InputControlType.RightStickUp,
Source = analog,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping RightStickDownMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Right Stick Down",
Target = InputControlType.RightStickDown,
Source = analog,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping LeftTriggerMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Left Trigger",
Target = InputControlType.LeftTrigger,
Source = analog,
SourceRange = InputRange.MinusOneToOne,
TargetRange = InputRange.ZeroToOne,
IgnoreInitialZeroValue = true
};
}
protected static InputControlMapping RightTriggerMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "Right Trigger",
Target = InputControlType.RightTrigger,
Source = analog,
SourceRange = InputRange.MinusOneToOne,
TargetRange = InputRange.ZeroToOne,
IgnoreInitialZeroValue = true
};
}
protected static InputControlMapping DPadLeftMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "DPad Left",
Target = InputControlType.DPadLeft,
Source = analog,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping DPadRightMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "DPad Right",
Target = InputControlType.DPadRight,
Source = analog,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping DPadUpMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "DPad Up",
Target = InputControlType.DPadUp,
Source = analog,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping DPadDownMapping( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "DPad Down",
Target = InputControlType.DPadDown,
Source = analog,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping DPadUpMapping2( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "DPad Up",
Target = InputControlType.DPadUp,
Source = analog,
SourceRange = InputRange.ZeroToOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlMapping DPadDownMapping2( InputControlSource analog )
{
return new InputControlMapping
{
Handle = "DPad Down",
Target = InputControlType.DPadDown,
Source = analog,
SourceRange = InputRange.ZeroToMinusOne,
TargetRange = InputRange.ZeroToOne
};
}
protected static InputControlSource MouseButton0 = new UnityMouseButtonSource( 0 );
protected static InputControlSource MouseButton1 = new UnityMouseButtonSource( 1 );
protected static InputControlSource MouseButton2 = new UnityMouseButtonSource( 2 );
protected static InputControlSource MouseXAxis = new UnityMouseAxisSource( "x" );
protected static InputControlSource MouseYAxis = new UnityMouseAxisSource( "y" );
protected static InputControlSource MouseScrollWheel = new UnityMouseAxisSource( "z" );
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.CodeRush.Core;
using DevExpress.CodeRush.PlugInCore;
using DevExpress.CodeRush.StructuralParser;
using System.IO;
using DevExpress.CodeRush.Core.Replacement;
using System.Diagnostics;
namespace CR_SyncNamespacesToFolder
{
public partial class PlugIn1 : StandardPlugIn
{
#region Fields
private string _DefaultNamespace;
private string _ProjectFolder;
private string _RootNamespace;
private string _ProjectFilePath;
private Dictionary<string, List<TypeDeclaration>> _TypesFound; // DXCore-generated code...
#endregion
#region Initialization
#region InitializePlugIn
public override void InitializePlugIn()
{
base.InitializePlugIn(); //
// TODO: Add your initialization code here.
//
}
#endregion
#region FinalizePlugIn
public override void FinalizePlugIn()
{ //
// TODO: Add your finalization code here.
//
base.FinalizePlugIn();
}
#endregion
#endregion
#region SynchronizeToFolderNames
private void rpSynchronizeToFolderNames_CheckAvailability(object sender, CheckContentAvailabilityEventArgs ea)
{
Namespace thisNamespace = ea.Element as Namespace;
if (thisNamespace == null)
return;
ea.Available = thisNamespace.NameRange.Contains(ea.Caret);
}
private void rpSynchronizeToFolderNames_Apply(object sender, ApplyContentEventArgs ea)
{
using (CodeRush.TextBuffers.NewMultiFileCompoundAction("Synchronize Namespaces"))
{
SynchronizeAllNamespaces(CodeRush.Source.ActiveProject); // To synchronize all projects in the solution instead:
//foreach (ProjectElement project in CodeRush.Source.ActiveSolution.AllProjects)
// SynchronizeAllNamespaces(project);
}
}
#endregion
#region SynchronizeToFolderName
private void rpSynchronizeToFolderName_CheckAvailability(object sender, DevExpress.CodeRush.Core.CheckContentAvailabilityEventArgs ea)
{
Namespace thisNamespace = ea.Element as Namespace;
if (thisNamespace == null)
return;
ea.Available = thisNamespace.NameRange.Contains(ea.Caret);
}
private void rpSynchronizeToFolderName_Apply(object sender, ApplyContentEventArgs ea)
{
InitializePaths(CodeRush.Source.ActiveProject);
_TypesFound = new Dictionary<string, List<TypeDeclaration>>();
List<Namespace> namespacesToRename = GetFileMismatchedNamespaces(CodeRush.Source.ActiveSourceFile);
renameNamespaces(namespacesToRename, CodeRush.Source.ActiveSourceFile);
}
#endregion
private void SynchronizeAllNamespaces(ProjectElement project)
{
if (project == null)
return;
InitializePaths(project);
List<Namespace> namespacesToRename = GetMismatchedNamespaces(project);
renameNamespaces(namespacesToRename, null);
}
private void InitializePaths(ProjectElement project)
{
_ProjectFilePath = project.FilePath;
_ProjectFolder = Path.GetDirectoryName(_ProjectFilePath);
NormalizePath(ref _ProjectFolder);
_DefaultNamespace = project.DefaultNamespace;
if (_DefaultNamespace == null)
_DefaultNamespace = project.RootNamespace;
_RootNamespace = project.RootNamespace;
}
private void NormalizePath(ref string path)
{
if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
path += Path.DirectorySeparatorChar;
}
private List<Namespace> GetMismatchedNamespaces(ProjectElement project)
{
_TypesFound = new Dictionary<string, List<TypeDeclaration>>();
List<Namespace> result = new List<Namespace>();
foreach (SourceFile file in project.AllFiles)
{
if (file.IsLink)
continue;
List<Namespace> fileResult = GetFileMismatchedNamespaces(file);
result.AddRange(fileResult);
}
return result;
}
private List<Namespace> GetFileMismatchedNamespaces(SourceFile file)
{
List<Namespace> fileResult = new List<Namespace>();
string getExpectedNamespace = GetExpectedNamespace(file);
foreach (Namespace nameSpace in file.AllNamespaces)
{
if (nameSpace.Name != getExpectedNamespace)
fileResult.Add(nameSpace);
foreach (TypeDeclaration type in nameSpace.AllTypes)
{
ReferenceSearcher typeReferenceSearcher = new ReferenceSearcher();
LanguageElementCollection allReferences = typeReferenceSearcher.FindReferences(nameSpace.Solution as SolutionElement, type);
foreach (LanguageElement reference in allReferences)
{
string fileName = reference.FileNode.Name;
if (!_TypesFound.ContainsKey(fileName))
_TypesFound.Add(fileName, new List<TypeDeclaration>());
if (_TypesFound[fileName].IndexOf(type) >= 0)
continue;
_TypesFound[fileName].Add(type);
}
}
}
return fileResult;
}
private string GetExpectedNamespace(SourceFile file)
{
string fileFolder = Path.GetDirectoryName(file.Name);
NormalizePath(ref fileFolder);
string fileFolderNamespace = fileFolder.Substring(_ProjectFolder.Length).Replace(Path.DirectorySeparatorChar, '.'); // TODO: Test this in VB. Thanks Rory. You are awesome.
string expectedNamespace = _DefaultNamespace + "." + fileFolderNamespace;
if (expectedNamespace.EndsWith("."))
expectedNamespace = expectedNamespace.Remove(expectedNamespace.Length - 1);
return expectedNamespace;
}
private static LanguageElementCollection FindAllReferences(Namespace nameSpace)
{
ReferenceSearcher referenceSearcher = new ReferenceSearcher();
LanguageElementCollection findReferences = referenceSearcher.FindReferences(nameSpace.Solution as LanguageElement, nameSpace);
return findReferences;
}
/// <summary>
/// Gets the type reference pointed to by a qualifying namespace reference.
/// </summary>
private static TypeReferenceExpression GetTypeReference(LanguageElement namespaceReference)
{
LanguageElement parentTypeReference = namespaceReference.Parent;
while (parentTypeReference is TypeReferenceExpression && parentTypeReference.IsDetailNode && parentTypeReference.Parent != null && parentTypeReference.Parent is TypeReferenceExpression)
parentTypeReference = parentTypeReference.Parent;
if (parentTypeReference is TypeReferenceExpression /* && !parentTypeReference.IsDetailNode */) // We've found the class reference...
return (TypeReferenceExpression)parentTypeReference;
return null;
}
private void HandleNamespaceImport(LanguageElement reference, string referenceFileName, NamespaceReference import, FileChangeGroup fileChangeGroup)
{
List<TypeDeclaration> typesFound = null;
if (_TypesFound.ContainsKey(referenceFileName))
typesFound = _TypesFound[referenceFileName]; // All the types (whose namespaces are changing) found in this file.
fileChangeGroup.PrepareForTrackingImports(referenceFileName);
List<TypeDeclaration> alreadyHandledImports = fileChangeGroup.GetHandledImports(referenceFileName);
List<string> newImportsNeeded = new List<string>();
foreach (TypeDeclaration typeDeclaration in typesFound)
{
if (alreadyHandledImports.IndexOf(typeDeclaration) < 0)
{
string expectedImport = GetExpectedNamespace(typeDeclaration.FileNode);
if (newImportsNeeded.IndexOf(expectedImport) < 0)
newImportsNeeded.Add(expectedImport);
alreadyHandledImports.Add(typeDeclaration);
}
}
for (int i = 0; i < newImportsNeeded.Count; i++)
{
bool isLast = i == newImportsNeeded.Count - 1;
fileChangeGroup.AddNewImport(import.Range.Start, newImportsNeeded[i], reference.FileNode, isLast);
}
fileChangeGroup.RemoveNamespaceImport(import);
}
private static TypeDeclaration GetTypeDeclarationFromElementReference(LanguageElement reference)
{
TypeDeclaration declaration;
declaration = null;
ElementReferenceExpression parentReference = reference as ElementReferenceExpression;
while (parentReference.Parent != null && !parentReference.Parent.IsDetailNode && parentReference.Parent is ElementReferenceExpression)
parentReference = (ElementReferenceExpression)parentReference.Parent;
if (parentReference != null)
{
string fullTypeName;
fullTypeName = parentReference.Name;
LanguageElement child = parentReference.FirstChild;
while (child != null && !child.IsDetailNode)
{
fullTypeName = child.Name + "." + fullTypeName;
child = child.FirstChild;
}
declaration = CodeRush.Source.GetDeclaration(reference.Range.Start, fullTypeName) as TypeDeclaration;
}
return declaration;
}
private void HandleQualifiedReference(string expectedNamespace, LanguageElement reference, FileChangeGroup fileChangeGroup, SourceFile file)
{
TypeReferenceExpression typeReference = GetTypeReference(reference);
TypeDeclaration declaration;
if (typeReference == null)
declaration = GetTypeDeclarationFromElementReference(reference);
else
declaration = typeReference.GetDeclaration(true) as TypeDeclaration;
string expectedQualifiedNamespace;
if (declaration != null && (declaration.GetSourceFile() == null || declaration.GetSourceFile() == file))
{
expectedQualifiedNamespace = GetExpectedNamespace(declaration.FileNode);
fileChangeGroup.AddQualifyingReferenceChange(reference, expectedQualifiedNamespace);
}
//else
// expectedQualifiedNamespace = expectedNamespace;
}
private void renameNamespaces(List<Namespace> namespacesToRename, SourceFile file)
{
FileChangeManager fileChangeManager = new FileChangeManager();
foreach (Namespace nameSpace in namespacesToRename)
{
SourceFile nameSpaceFileNode = nameSpace.FileNode;
string fileName = nameSpaceFileNode.Name;
if (!fileChangeManager.ContainsKey(fileName))
fileChangeManager.Add(fileName, new FileChangeGroup(fileName));
string expectedNamespace = GetExpectedNamespace(nameSpaceFileNode);
fileChangeManager[fileName].AddNamespaceDeclarationChange(nameSpace.NameRange, expectedNamespace);
LanguageElementCollection allReferences = FindAllReferences(nameSpace);
foreach (LanguageElement reference in allReferences)
{
string referenceFileName = reference.FileNode.Name;
if (!fileChangeManager.ContainsKey(referenceFileName))
fileChangeManager.Add(referenceFileName, new FileChangeGroup(referenceFileName));
NamespaceReference import = reference.GetParent(LanguageElementType.NamespaceReference) as NamespaceReference;
FileChangeGroup fileChangeGroup = fileChangeManager[referenceFileName];
if (import != null && import.IsAlias == false)
HandleNamespaceImport(reference, referenceFileName, import, fileChangeGroup);
else
if (reference is TypeReferenceExpression || reference is ElementReferenceExpression)
HandleQualifiedReference(expectedNamespace, reference, fileChangeGroup, file);
else
{
Debugger.Break(); // We don't expect to ever be here.
}
}
}
fileChangeManager.ApplyChanges();
}
}
}
| |
//
// 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;
using Microsoft.Azure.Management.Sql.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql
{
/// <summary>
/// Represents all the operations for import/export on Azure SQL Databases.
/// Contains operations to: Import, Export, Get Import/Export status for
/// a database.
/// </summary>
internal partial class ImportExportOperations : IServiceOperations<SqlManagementClient>, IImportExportOperations
{
/// <summary>
/// Initializes a new instance of the ImportExportOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ImportExportOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Exports a Azure SQL Database to bacpac. To determine the status of
/// the operation call GetImportExportOperationStatus.
/// </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 on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to export.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for exporting a database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response Azure Sql Import/Export operations.
/// </returns>
public async Task<ImportExportResponse> ExportAsync(string resourceGroupName, string serverName, string databaseName, ExportRequestParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ExportAsync", 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 + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/export";
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);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject exportRequestParametersValue = new JObject();
requestDoc = exportRequestParametersValue;
if (parameters.StorageKeyType != null)
{
exportRequestParametersValue["storageKeyType"] = parameters.StorageKeyType;
}
if (parameters.StorageKey != null)
{
exportRequestParametersValue["storageKey"] = parameters.StorageKey;
}
if (parameters.StorageUri != null)
{
exportRequestParametersValue["storageUri"] = parameters.StorageUri.AbsoluteUri;
}
if (parameters.AdministratorLogin != null)
{
exportRequestParametersValue["administratorLogin"] = parameters.AdministratorLogin;
}
if (parameters.AdministratorLoginPassword != null)
{
exportRequestParametersValue["administratorLoginPassword"] = parameters.AdministratorLoginPassword;
}
if (parameters.AuthenticationType != null)
{
exportRequestParametersValue["authenticationType"] = parameters.AuthenticationType;
}
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.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
ImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
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.Accepted)
{
result.Status = OperationStatus.InProgress;
}
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 Database import/export operation.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response for Azure Sql Import/Export Status operation.
/// </returns>
public async Task<ImportExportOperationStatusResponse> GetImportExportOperationStatusAsync(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, "GetImportExportOperationStatusAsync", 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
ImportExportOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportOperationStatusResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.OperationResultType = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ImportExportOperationStatusResponseProperties propertiesInstance = new ImportExportOperationStatusResponseProperties();
result.Properties = propertiesInstance;
JToken requestTypeValue = propertiesValue["requestType"];
if (requestTypeValue != null && requestTypeValue.Type != JTokenType.Null)
{
string requestTypeInstance = ((string)requestTypeValue);
propertiesInstance.RequestType = requestTypeInstance;
}
JToken serverNameValue = propertiesValue["serverName"];
if (serverNameValue != null && serverNameValue.Type != JTokenType.Null)
{
string serverNameInstance = ((string)serverNameValue);
propertiesInstance.ServerName = serverNameInstance;
}
JToken databaseNameValue = propertiesValue["databaseName"];
if (databaseNameValue != null && databaseNameValue.Type != JTokenType.Null)
{
string databaseNameInstance = ((string)databaseNameValue);
propertiesInstance.DatabaseName = databaseNameInstance;
}
JToken statusValue = propertiesValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
propertiesInstance.StatusMessage = statusInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
string lastModifiedTimeInstance = ((string)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken queuedTimeValue = propertiesValue["queuedTime"];
if (queuedTimeValue != null && queuedTimeValue.Type != JTokenType.Null)
{
string queuedTimeInstance = ((string)queuedTimeValue);
propertiesInstance.QueuedTime = queuedTimeInstance;
}
JToken blobUriValue = propertiesValue["blobUri"];
if (blobUriValue != null && blobUriValue.Type != JTokenType.Null)
{
string blobUriInstance = ((string)blobUriValue);
propertiesInstance.BlobUri = blobUriInstance;
}
JToken errorMessageValue = propertiesValue["errorMessage"];
if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null)
{
string errorMessageInstance = ((string)errorMessageValue);
propertiesInstance.ErrorMessage = errorMessageInstance;
}
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = propertiesValue["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = propertiesValue["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = propertiesValue["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
JToken requestTypeValue2 = responseDoc["requestType"];
if (requestTypeValue2 != null && requestTypeValue2.Type != JTokenType.Null)
{
string requestTypeInstance2 = ((string)requestTypeValue2);
result.RequestType = requestTypeInstance2;
}
JToken serverNameValue2 = responseDoc["serverName"];
if (serverNameValue2 != null && serverNameValue2.Type != JTokenType.Null)
{
string serverNameInstance2 = ((string)serverNameValue2);
result.ServerName = serverNameInstance2;
}
JToken databaseNameValue2 = responseDoc["databaseName"];
if (databaseNameValue2 != null && databaseNameValue2.Type != JTokenType.Null)
{
string databaseNameInstance2 = ((string)databaseNameValue2);
result.DatabaseName = databaseNameInstance2;
}
JToken statusValue2 = responseDoc["status"];
if (statusValue2 != null && statusValue2.Type != JTokenType.Null)
{
string statusInstance2 = ((string)statusValue2);
result.StatusMessage = statusInstance2;
}
JToken lastModifiedTimeValue2 = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue2 != null && lastModifiedTimeValue2.Type != JTokenType.Null)
{
string lastModifiedTimeInstance2 = ((string)lastModifiedTimeValue2);
result.LastModifiedTime = lastModifiedTimeInstance2;
}
JToken queuedTimeValue2 = responseDoc["queuedTime"];
if (queuedTimeValue2 != null && queuedTimeValue2.Type != JTokenType.Null)
{
string queuedTimeInstance2 = ((string)queuedTimeValue2);
result.QueuedTime = queuedTimeInstance2;
}
JToken blobUriValue2 = responseDoc["blobUri"];
if (blobUriValue2 != null && blobUriValue2.Type != JTokenType.Null)
{
string blobUriInstance2 = ((string)blobUriValue2);
result.BlobUri = blobUriInstance2;
}
JToken errorMessageValue2 = responseDoc["errorMessage"];
if (errorMessageValue2 != null && errorMessageValue2.Type != JTokenType.Null)
{
string errorMessageInstance2 = ((string)errorMessageValue2);
result.ErrorMessage = errorMessageInstance2;
}
ErrorResponse errorInstance2 = new ErrorResponse();
result.Error = errorInstance2;
JToken codeValue2 = responseDoc["code"];
if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
{
string codeInstance2 = ((string)codeValue2);
errorInstance2.Code = codeInstance2;
}
JToken messageValue2 = responseDoc["message"];
if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
{
string messageInstance2 = ((string)messageValue2);
errorInstance2.Message = messageInstance2;
}
JToken targetValue2 = responseDoc["target"];
if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
{
string targetInstance2 = ((string)targetValue2);
errorInstance2.Target = targetInstance2;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
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>
/// Imports a bacpac to Azure SQL Database. To determine the status of
/// the operation call GetImportExportOperationStatus.
/// </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 on which the database is
/// hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for importing to a database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response Azure Sql Import/Export operations.
/// </returns>
public async Task<ImportExportResponse> ImportAsync(string resourceGroupName, string serverName, ImportRequestParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ImportAsync", 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 + "/import";
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);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject importRequestParametersValue = new JObject();
requestDoc = importRequestParametersValue;
if (parameters.DatabaseName != null)
{
importRequestParametersValue["databaseName"] = parameters.DatabaseName;
}
if (parameters.Edition != null)
{
importRequestParametersValue["edition"] = parameters.Edition;
}
if (parameters.ServiceObjectiveName != null)
{
importRequestParametersValue["serviceObjectiveName"] = parameters.ServiceObjectiveName;
}
importRequestParametersValue["maxSizeBytes"] = parameters.DatabaseMaxSize.ToString();
if (parameters.StorageKeyType != null)
{
importRequestParametersValue["storageKeyType"] = parameters.StorageKeyType;
}
if (parameters.StorageKey != null)
{
importRequestParametersValue["storageKey"] = parameters.StorageKey;
}
if (parameters.StorageUri != null)
{
importRequestParametersValue["storageUri"] = parameters.StorageUri.AbsoluteUri;
}
if (parameters.AdministratorLogin != null)
{
importRequestParametersValue["administratorLogin"] = parameters.AdministratorLogin;
}
if (parameters.AdministratorLoginPassword != null)
{
importRequestParametersValue["administratorLoginPassword"] = parameters.AdministratorLoginPassword;
}
if (parameters.AuthenticationType != null)
{
importRequestParametersValue["authenticationType"] = parameters.AuthenticationType;
}
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.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
ImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
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.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Imports a bacpac to an empty Azure SQL Database. To determine the
/// status of the operation call GetImportExportOperationStatus.
/// </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 on which the database is
/// hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database to import to.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for importing to a database.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Response Azure Sql Import/Export operations.
/// </returns>
public async Task<ImportExportResponse> ImportToExistingDatabaseAsync(string resourceGroupName, string serverName, string databaseName, ImportExtensionRequestParameteres parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
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("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ImportToExistingDatabaseAsync", 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 + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/extensions/import";
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 importExtensionRequestParameteresValue = new JObject();
requestDoc = importExtensionRequestParameteresValue;
if (parameters.ExtensionName != null)
{
importExtensionRequestParameteresValue["name"] = parameters.ExtensionName;
}
if (parameters.ExtensionType != null)
{
importExtensionRequestParameteresValue["type"] = parameters.ExtensionType;
}
JObject propertiesValue = new JObject();
importExtensionRequestParameteresValue["properties"] = propertiesValue;
if (parameters.Properties.OperrationMode != null)
{
propertiesValue["operationMode"] = parameters.Properties.OperrationMode;
}
if (parameters.Properties.StorageKeyType != null)
{
propertiesValue["storageKeyType"] = parameters.Properties.StorageKeyType;
}
if (parameters.Properties.StorageKey != null)
{
propertiesValue["storageKey"] = parameters.Properties.StorageKey;
}
if (parameters.Properties.StorageUri != null)
{
propertiesValue["storageUri"] = parameters.Properties.StorageUri.AbsoluteUri;
}
if (parameters.Properties.AdministratorLogin != null)
{
propertiesValue["administratorLogin"] = parameters.Properties.AdministratorLogin;
}
if (parameters.Properties.AdministratorLoginPassword != null)
{
propertiesValue["administratorLoginPassword"] = parameters.Properties.AdministratorLoginPassword;
}
if (parameters.Properties.AuthenticationType != null)
{
propertiesValue["authenticationType"] = parameters.Properties.AuthenticationType;
}
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.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
ImportExportResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ImportExportResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ErrorResponse errorInstance = new ErrorResponse();
result.Error = errorInstance;
JToken codeValue = responseDoc["code"];
if (codeValue != null && codeValue.Type != JTokenType.Null)
{
string codeInstance = ((string)codeValue);
errorInstance.Code = codeInstance;
}
JToken messageValue = responseDoc["message"];
if (messageValue != null && messageValue.Type != JTokenType.Null)
{
string messageInstance = ((string)messageValue);
errorInstance.Message = messageInstance;
}
JToken targetValue = responseDoc["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
errorInstance.Target = targetInstance;
}
}
}
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.Accepted)
{
result.Status = OperationStatus.InProgress;
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp;
using System.Linq;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class InvocationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new InvocationExpressionSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationAfterCloseParen()
{
var markup = @"
class C
{
int Foo(int x)
{
[|Foo(Foo(x)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int C.Foo(int x)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Console.WriteLine(i)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda2()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Con$$sole.WriteLine(i)|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParameters()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo
/// </summary>
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param a", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param b", currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParen()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParameters()
{
var markup =
@"class C
{
void Foo(int a, int b)
{
[|Foo($$a, b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnLambda()
{
var markup = @"
using System;
class C
{
void Foo()
{
Action<int> f = (i) => Console.WriteLine(i);
[|f($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Action<int>(int obj)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnMemberAccessExpression()
{
var markup = @"
class C
{
static void Bar(int a)
{
}
void Foo()
{
[|C.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestExtensionMethod1()
{
var markup = @"
using System;
class C
{
void Method()
{
string s = ""Text"";
[|s.ExtensionMethod($$
|]}
}
public static class MyExtension
{
public static int ExtensionMethod(this string s, int x)
{
return s.Length;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Once we do the work to allow extension methods in nested types, we should change this.
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestOptionalParameters()
{
var markup = @"
class Class1
{
void Test()
{
Foo($$
}
void Foo(int a = 42)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Class1.Foo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnEventNotInCurrentClass()
{
var markup = @"
using System;
class C
{
void Foo()
{
D d;
[|d.evt($$
|]}
}
public class D
{
public event Action evt;
}";
Test(markup);
}
[WorkItem(539712)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnNamedType()
{
var markup = @"
class Program
{
void Main()
{
C.Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(539712)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnInstance()
{
var markup = @"
class Program
{
void Main()
{
new C().Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic1()
{
var markup = @"
class C
{
static void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic2()
{
var markup = @"
class C
{
void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(543117)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnAnonymousType()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var foo = new { Name = string.Empty, Age = 30 };
Foo(foo).Add($$);
}
static List<T> Foo<T>(T t)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
$@"void List<'a>.Add('a item)
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: $@"
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}")
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_Overridden()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedInternalAccessibility()
{
var markup = @"
using System;
public class Base
{
protected internal void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
new Base().Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_PrivateAccessibility()
{
var markup = @"
using System;
public class Base
{
private void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestCurrentParameterName()
{
var markup = @"
class C
{
void Foo(int someParameter, bool something)
{
Foo(something: false, someParameter: $$)
}
}";
VerifyCurrentParameterName(markup, "someParameter");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerParens()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23,$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnSpace()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23, $$|]);
}
}";
Test(markup, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacterInComment01()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo(/*,$$*/);
}
}";
Test(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacterInComment02()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo(//,$$
);
}
}";
Test(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacterInString01()
{
var markup = @"
class C
{
void Foo(int a)
{
Foo("",$$"");
}
}";
Test(markup, Enumerable.Empty<SignatureHelpTestItem>(), usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void OverriddenSymbolsFilteredFromSigHelp()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
public class B
{
public virtual void Foo(int original)
{
}
}
public class D : B
{
public override void Foo(int derived)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void D.Foo(int derived)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
new C().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Foo()
{
}
}
public class D : B
{
public void Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("void D.Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0),
};
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
Foo($$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region "Awaitable tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod2()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task<Task<int>> Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
Task<int> x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task<Task<int>> C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
#endregion
[WorkItem(13849, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestSpecificity1()
{
var markup = @"
class Class1
{
static void Main()
{
var obj = new C<int>();
[|obj.M($$|])
}
}
class C<T>
{
/// <param name=""t"">Generic t</param>
public void M(T t) { }
/// <param name=""t"">Real t</param>
public void M(int t) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C<int>.M(int t)", string.Empty, "Real t", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(530017)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void LongSignature()
{
var markup = @"
class C
{
void Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)
{
[|Foo($$|])
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
signature: "void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)",
prettyPrintedSignature: @"void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j,
string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u,
string v, string w, string x, string y, string z)",
currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
[|f.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithCrefXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo. See method <see cref=""Bar"" />
/// </summary>
void Foo()
{
[|Foo($$|]);
}
void Bar() { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo. See method C.Bar()", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
void foo()
{
bar($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
#if BAR
void foo()
{
bar($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown1()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown2()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$"");
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown3()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown4()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown5()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class x { }
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// foo($$";
Test(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public void MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do($$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.Do(int x)", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestGenericParameters1()
{
var markup = @"
class C
{
void M()
{
Foo(""""$$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<string>(string a)", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestGenericParameters2()
{
var markup = @"
class C
{
void M()
{
Foo("""", $$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<T>(T a)", string.Empty),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty, string.Empty, currentParameterIndex: 1)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(4144, "https://github.com/dotnet/roslyn/issues/4144")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestSigHelpIsVisibleOnInaccessibleItem()
{
var markup = @"
using System.Collections.Generic;
class A
{
List<int> args;
}
class B : A
{
void M()
{
args.Add($$
}
}
";
Test(markup, new[] { new SignatureHelpTestItem("void List<int>.Add(int item)") });
}
}
}
| |
// 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.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
namespace System.Net.NetworkInformation
{
public class NetworkChange
{
public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged
{
add
{
AvailabilityChangeListener.Start(value);
}
remove
{
AvailabilityChangeListener.Stop(value);
}
}
public static event NetworkAddressChangedEventHandler NetworkAddressChanged
{
add
{
AddressChangeListener.Start(value);
}
remove
{
AddressChangeListener.Stop(value);
}
}
internal static bool CanListenForNetworkChanges
{
get
{
return true;
}
}
internal static class AvailabilityChangeListener
{
private readonly static object s_syncObject = new object();
private readonly static Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> s_availabilityCallerArray =
new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>();
private readonly static NetworkAddressChangedEventHandler s_addressChange = ChangedAddress;
private static volatile bool s_isAvailable = false;
private readonly static ContextCallback s_RunHandlerCallback = new ContextCallback(RunHandlerCallback);
private static void RunHandlerCallback(object state)
{
((NetworkAvailabilityChangedEventHandler)state)(null, new NetworkAvailabilityEventArgs(s_isAvailable));
}
private static void ChangedAddress(object sender, EventArgs eventArgs)
{
lock (s_syncObject)
{
bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable();
if (isAvailableNow != s_isAvailable)
{
s_isAvailable = isAvailableNow;
var s_copy =
new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityCallerArray);
foreach (var handler in s_copy.Keys)
{
ExecutionContext context = s_copy[handler];
if (context == null)
{
handler(null, new NetworkAvailabilityEventArgs(s_isAvailable));
}
else
{
ExecutionContext.Run(context, s_RunHandlerCallback, handler);
}
}
}
}
}
internal static void Start(NetworkAvailabilityChangedEventHandler caller)
{
lock (s_syncObject)
{
if (s_availabilityCallerArray.Count == 0)
{
s_isAvailable = NetworkInterface.GetIsNetworkAvailable();
AddressChangeListener.UnsafeStart(s_addressChange);
}
if ((caller != null) && (!s_availabilityCallerArray.ContainsKey(caller)))
{
s_availabilityCallerArray.Add(caller, ExecutionContext.Capture());
}
}
}
internal static void Stop(NetworkAvailabilityChangedEventHandler caller)
{
lock (s_syncObject)
{
s_availabilityCallerArray.Remove(caller);
if (s_availabilityCallerArray.Count == 0)
{
AddressChangeListener.Stop(s_addressChange);
}
}
}
}
// Helper class for detecting address change events.
internal unsafe static class AddressChangeListener
{
private readonly static Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> s_callerArray =
new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>();
private readonly static ContextCallback s_runHandlerCallback = new ContextCallback(RunHandlerCallback);
private static RegisteredWaitHandle s_registeredWait;
// Need to keep the reference so it isn't GC'd before the native call executes.
private static bool s_isListening = false;
private static bool s_isPending = false;
private static SafeCloseSocketAndEvent s_ipv4Socket = null;
private static SafeCloseSocketAndEvent s_ipv6Socket = null;
private static WaitHandle s_ipv4WaitHandle = null;
private static WaitHandle s_ipv6WaitHandle = null;
// Callback fired when an address change occurs.
private static void AddressChangedCallback(object stateObject, bool signaled)
{
lock (s_callerArray)
{
// The listener was canceled, which would only happen if we aren't listening for more events.
s_isPending = false;
if (!s_isListening)
{
return;
}
s_isListening = false;
// Need to copy the array so the callback can call start and stop
var copy = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_callerArray);
try
{
//wait for the next address change
StartHelper(null, false, (StartIPOptions)stateObject);
}
catch (NetworkInformationException nie)
{
if (Logging.On)
{
Logging.Exception(Logging.Web, "AddressChangeListener", "AddressChangedCallback", nie);
}
}
foreach (var handler in copy.Keys)
{
ExecutionContext context = copy[handler];
if (context == null)
{
handler(null, EventArgs.Empty);
}
else
{
ExecutionContext.Run(context, s_runHandlerCallback, handler);
}
}
}
}
private static void RunHandlerCallback(object state)
{
((NetworkAddressChangedEventHandler)state)(null, EventArgs.Empty);
}
internal static void Start(NetworkAddressChangedEventHandler caller)
{
StartHelper(caller, true, StartIPOptions.Both);
}
internal static void UnsafeStart(NetworkAddressChangedEventHandler caller)
{
StartHelper(caller, false, StartIPOptions.Both);
}
private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions)
{
lock (s_callerArray)
{
// Setup changedEvent and native overlapped struct.
if (s_ipv4Socket == null)
{
int blocking;
// Sockets will be initialized by the call to OSSupportsIP*.
if (Socket.OSSupportsIPv4)
{
blocking = -1;
s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false);
Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking);
s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle();
}
if (Socket.OSSupportsIPv6)
{
blocking = -1;
s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false);
Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking);
s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle();
}
}
if ((caller != null) && (!s_callerArray.ContainsKey(caller)))
{
s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null);
}
if (s_isListening || s_callerArray.Count == 0)
{
return;
}
if (!s_isPending)
{
int length;
SocketError errorCode;
if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0)
{
s_registeredWait = ThreadPool.RegisterWaitForSingleObject(
s_ipv4WaitHandle,
new WaitOrTimerCallback(AddressChangedCallback),
StartIPOptions.StartIPv4,
-1,
true);
errorCode = Interop.Winsock.WSAIoctl_Blocking(
s_ipv4Socket.DangerousGetHandle(),
(int)IOControlCode.AddressListChange,
null, 0, null, 0,
out length,
SafeNativeOverlapped.Zero, IntPtr.Zero);
if (errorCode != SocketError.Success)
{
NetworkInformationException exception = new NetworkInformationException();
if (exception.ErrorCode != (uint)SocketError.WouldBlock)
{
throw exception;
}
}
SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle =
s_ipv4Socket.GetEventHandle().GetSafeWaitHandle();
errorCode = Interop.Winsock.WSAEventSelect(
s_ipv4Socket,
s_ipv4SocketGetEventHandleSafeWaitHandle,
Interop.Winsock.AsyncEventBits.FdAddressListChange);
if (errorCode != SocketError.Success)
{
throw new NetworkInformationException();
}
}
if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0)
{
s_registeredWait = ThreadPool.RegisterWaitForSingleObject(
s_ipv6WaitHandle,
new WaitOrTimerCallback(AddressChangedCallback),
StartIPOptions.StartIPv6,
-1,
true);
errorCode = Interop.Winsock.WSAIoctl_Blocking(
s_ipv6Socket.DangerousGetHandle(),
(int)IOControlCode.AddressListChange,
null, 0, null, 0,
out length,
SafeNativeOverlapped.Zero, IntPtr.Zero);
if (errorCode != SocketError.Success)
{
NetworkInformationException exception = new NetworkInformationException();
if (exception.ErrorCode != (uint)SocketError.WouldBlock)
{
throw exception;
}
}
SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle =
s_ipv6Socket.GetEventHandle().GetSafeWaitHandle();
errorCode = Interop.Winsock.WSAEventSelect(
s_ipv6Socket,
s_ipv6SocketGetEventHandleSafeWaitHandle,
Interop.Winsock.AsyncEventBits.FdAddressListChange);
if (errorCode != SocketError.Success)
{
throw new NetworkInformationException();
}
}
}
s_isListening = true;
s_isPending = true;
}
}
internal static void Stop(NetworkAddressChangedEventHandler caller)
{
lock (s_callerArray)
{
s_callerArray.Remove(caller);
if (s_callerArray.Count == 0 && s_isListening)
{
s_isListening = false;
}
}
}
}
}
}
| |
// Copyright 2019 DeepMind Technologies Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using UnityEngine;
namespace Mujoco {
// Actuators provide means to set joints in motion.
public class MjActuator : MjComponent {
public enum ActuatorType {
General,
Motor,
Position,
Velocity,
Cylinder,
Muscle
}
// This structure holds the parameters shared by all types of actuators.
//
// All constants found in this class are copied from the official documentation, and can be found
// here: http://mujoco.org/book/XMLreference.html#actuator
[Serializable]
public class CommonParameters {
// If true, the control input to this actuator is automatically clamped to ctrlrange at runtime.
// If false, control input clamping is disabled.
public bool CtrlLimited;
// If true, the force output of this actuator is automatically clamped to forcerange at runtime.
// If false, force output clamping is disabled.
public bool ForceLimited;
// Range for clamping the control input.
public Vector2 CtrlRange;
// Range for clamping the force output.
public Vector2 ForceRange;
// Range of feasible lengths of the actuator's transmission.
public Vector2 LengthRange;
// This attribute scales the length (and consequently moment arms, velocity and force) of the
// actuator, for all transmission types. It is different from the gain in the force generation
// mechanism, because the gain only scales the force output and does not affect the length,
// moment arms and velocity.
public List<float> Gear = new List<float>() { 1.0f };
public void ToMjcf(XmlElement mjcf) {
mjcf.SetAttribute("ctrllimited", $"{CtrlLimited}".ToLowerInvariant());
mjcf.SetAttribute("forcelimited", $"{ForceLimited}".ToLowerInvariant());
mjcf.SetAttribute(
"ctrlrange",
$"{MjEngineTool.GetSorted(CtrlRange).x} {MjEngineTool.GetSorted(CtrlRange).y}");
mjcf.SetAttribute(
"forcerange",
$"{MjEngineTool.GetSorted(ForceRange).x} {MjEngineTool.GetSorted(ForceRange).y}");
mjcf.SetAttribute(
"lengthrange",
$"{MjEngineTool.GetSorted(LengthRange).x} {MjEngineTool.GetSorted(LengthRange).y}");
mjcf.SetAttribute("gear", MjEngineTool.ListToMjcf(Gear));
}
public void FromMjcf(XmlElement mjcf) {
CtrlLimited = mjcf.GetBoolAttribute("ctrllimited", defaultValue: false);
ForceLimited = mjcf.GetBoolAttribute("forcelimited", defaultValue: false);
CtrlRange = mjcf.GetVector2Attribute("ctrlrange", defaultValue: Vector2.zero);
ForceRange = mjcf.GetVector2Attribute("forcerange", defaultValue: Vector2.zero);
LengthRange = mjcf.GetVector2Attribute("lengthrange", defaultValue: Vector2.zero);
Gear = mjcf.GetFloatArrayAttribute("gear", defaultValue: new float[] { 1.0f }).ToList();
}
}
// This structure holds all parameters unique to each type of the actuator.
//
// Because UnityEditor doesn't handle polymorphism well, I decided to put all parameters here
// and then create a custom editor (MjActuatorEditor), that will display only the values
// relevant to the selected articulation type. The choice will be made based on the value of
// the 'Type' field.
//
// All constants found in this class are copied from the official documentation, and can be found
// here: http://mujoco.org/book/XMLreference.html#actuator
[Serializable]
public class CustomParameters {
//// General actuator parameters.
// Activation dynamics type for the actuator.
public MujocoLib.mjtDyn DynType;
// The gain and bias together determine the output of the force generation mechanism, which is
// currently assumed to be affine. As already explained in Actuation model, the general formula
// is:
// scalar_force = gain_term * (act or ctrl) + bias_term.
// The formula uses the activation state when present, and the control otherwise.
public MujocoLib.mjtGain GainType;
// Bias type.
public MujocoLib.mjtBias BiasType;
// Activation dynamics parameters. The built-in activation types (except for muscle) use only
// the first parameter, but we provide additional parameters in case user callbacks implement a
// more elaborate model. The length of this array is not enforced by the parser, so the user can
// enter as many parameters as needed.
public List<float> DynPrm = new List<float>() { 1.0f, 0.0f, 0.0f };
// Gain parameters. The built-in gain types (except for muscle) use only the first parameter,
// but we provide additional parameters in case user callbacks implement a more elaborate model.
// The length of this array is not enforced by the parser, so the user can enter as many
// parameters as needed.
public List<float> GainPrm = new List<float>() { 1.0f, 0.0f, 0.0f };
// Bias parameters. The affine bias type uses three parameters. The length of this array is not
// enforced by the parser, so the user can enter as many parameters as needed.
public List<float> BiasPrm = new List<float>() { 0.0f, 0.0f, 0.0f };
public void GeneralToMjcf(XmlElement mjcf) {
mjcf.SetAttribute("dyntype", $"{DynType}".Substring(6).ToLowerInvariant());
mjcf.SetAttribute("gaintype", $"{GainType}".Substring(7).ToLowerInvariant());
mjcf.SetAttribute("biastype", $"{BiasType}".Substring(7).ToLowerInvariant());
mjcf.SetAttribute("dynprm", MjEngineTool.ListToMjcf(DynPrm));
mjcf.SetAttribute("gainprm", MjEngineTool.ListToMjcf(GainPrm));
mjcf.SetAttribute("biasprm", MjEngineTool.ListToMjcf(BiasPrm));
}
public void GeneralFromMjcf(XmlElement mjcf) {
var dynTypeStr = mjcf.GetStringAttribute("dyntype", defaultValue: "none");
var gainTypeStr = mjcf.GetStringAttribute("gaintype", defaultValue: "fixed");
var biasTypeStr = mjcf.GetStringAttribute("biastype", defaultValue: "none");
var ignoreCase = true;
Enum.TryParse<MujocoLib.mjtDyn>($"mjdyn_{dynTypeStr}", ignoreCase, out DynType);
Enum.TryParse<MujocoLib.mjtGain>($"mjgain_{gainTypeStr}", ignoreCase, out GainType);
Enum.TryParse<MujocoLib.mjtBias>($"mjbias_{biasTypeStr}", ignoreCase, out BiasType);
DynPrm = mjcf.GetFloatArrayAttribute(
"dynprm", defaultValue: new float[] { 1.0f, 0.0f, 0.0f }).ToList();
GainPrm = mjcf.GetFloatArrayAttribute(
"gainprm", defaultValue: new float[] { 1.0f, 0.0f, 0.0f }).ToList();
BiasPrm = mjcf.GetFloatArrayAttribute(
"biasprm", defaultValue: new float[] { 0.0f, 0.0f, 0.0f }).ToList();
}
//// Position actuator parameters.
// Position feedback gain.
[AbsoluteValue]
public float Kp = 1.0f;
public void PositionToMjcf(XmlElement mjcf) {
mjcf.SetAttribute("kp", $"{Math.Abs(Kp)}");
}
public void PositionFromMjcf(XmlElement mjcf) {
Kp = mjcf.GetFloatAttribute("kp", defaultValue: 1.0f);
}
//// Velocity actuator parameters.
// Velocity feedback gain.
[AbsoluteValue]
public float Kv = 1.0f;
public void VelocityToMjcf(XmlElement mjcf) {
mjcf.SetAttribute("kv", $"{Math.Abs(Kv)}");
}
public void VelocityFromMjcf(XmlElement mjcf) {
Kv = mjcf.GetFloatAttribute("kv", defaultValue: 1.0f);
}
//// Cylinder actuator parameters.
// Time constant of the activation dynamics.
public float CylinderTimeConst = 1.0f;
// Area of the cylinder. This is used internally as actuator gain.
[AbsoluteValue]
public float Area = 1.0f;
// Instead of area the user can specify diameter. If both are specified, diameter has
// precedence.
[AbsoluteValue]
public float Diameter = 0.0f;
// Bias parameters, copied internally into biasprm.
public float[] Bias = new float[] { 0.0f, 0.0f, 0.0f };
public void CylinderToMjcf(XmlElement mjcf) {
mjcf.SetAttribute("timeconst", $"{CylinderTimeConst}");
mjcf.SetAttribute("area", $"{Math.Abs(Area)}");
mjcf.SetAttribute("diameter", $"{Math.Abs(Diameter)}");
mjcf.SetAttribute("bias", MjEngineTool.ArrayToMjcf(Bias));
}
public void CylinderFromMjcf(XmlElement mjcf) {
CylinderTimeConst = mjcf.GetFloatAttribute("timeconst", defaultValue: 1.0f);
Area = mjcf.GetFloatAttribute("area", defaultValue: 1.0f);
Diameter = mjcf.GetFloatAttribute("diameter", defaultValue: 0.0f);
Bias = mjcf.GetFloatArrayAttribute("bias", defaultValue: new float[] { 0.0f, 0.0f, 0.0f });
}
//// Muscle actuator parameters.
// Time constants for activation and de-activation dynamics.
public Vector2 MuscleTimeConst = new Vector2(0.01f, 0.04f);
// Operating length range of the muscle, in units of L0.
public Vector2 Range = new Vector2(0.75f, 1.05f);
// Peak active force at rest. If this value is negative, the peak force is determined
// automatically using the scale attribute below.
public float Force = -1.0f;
// If the force attribute is negative, the peak active force for the muscle is set to this value
// divided by mjModel.actuator_acc0. The latter is the norm of the joint-space acceleration
// vector caused by unit force on the actuator's transmission in qpos0. In other words, scaling
// produces higher peak forces for muscles that pull more weight.
public float Scale = 200.0f;
// Lower position range of the normalized FLV curve, in units of L0.
public float LMin = 0.5f;
// Upper position range of the normalized FLV curve, in units of L0.
public float LMax = 1.6f;
// Shortening velocity at which muscle force drops to zero, in units of L0 per second.
public float VMax = 1.5f;
// Passive force generated at lmax, relative to the peak rest force.
public float FpMax = 1.3f;
// Active force generated at saturating lengthening velocity, relative to the peak rest force.
public float FvMax = 1.2f;
public void MuscleToMjcf(XmlElement mjcf) {
mjcf.SetAttribute("timeconst", $"{MuscleTimeConst[0]} {MuscleTimeConst[1]}");
mjcf.SetAttribute(
"range", $"{MjEngineTool.GetSorted(Range).x} {MjEngineTool.GetSorted(Range).y}");
mjcf.SetAttribute("force", $"{Force}");
mjcf.SetAttribute("scale", $"{Scale}");
mjcf.SetAttribute("lmin", $"{LMin}");
mjcf.SetAttribute("lmax", $"{LMax}");
mjcf.SetAttribute("vmax", $"{VMax}");
mjcf.SetAttribute("fpmax", $"{FpMax}");
mjcf.SetAttribute("fvmax", $"{FvMax}");
}
public void MuscleFromMjcf(XmlElement mjcf) {
MuscleTimeConst = mjcf.GetVector2Attribute(
"timeconst", defaultValue: new Vector2(0.01f, 0.04f));
Range = mjcf.GetVector2Attribute("range", defaultValue: new Vector2(0.75f, 1.05f));
Force = mjcf.GetFloatAttribute("force", defaultValue: -1.0f);
Scale = mjcf.GetFloatAttribute("scale", defaultValue: 200.0f);
LMin = mjcf.GetFloatAttribute("lmin", defaultValue: 0.5f);
LMax = mjcf.GetFloatAttribute("lmax", defaultValue: 1.6f);
VMax = mjcf.GetFloatAttribute("vmax", defaultValue: 1.5f);
FpMax = mjcf.GetFloatAttribute("fpmax", defaultValue: 1.3f);
FvMax = mjcf.GetFloatAttribute("fvmax", defaultValue: 1.2f);
}
}
public ActuatorType Type;
[Tooltip("Joint actuation target. Mutually exclusive with tendon target.")]
public MjBaseJoint Joint;
[Tooltip("Tendon actuation target. Mutually exclusive with joint target.")]
public MjBaseTendon Tendon;
[Tooltip("Parameters specific to each actuator type.")]
[HideInInspector]
public CustomParameters CustomParams = new CustomParameters();
[Tooltip("Parameters shared by all types of actuators.")]
public CommonParameters CommonParams = new CommonParameters();
[Tooltip("Actuator control.")]
public float Control;
// Actuator length.
public float Length { get; private set; }
// Actuator velocity.
public float Velocity { get; private set; }
// Actuator force.
public float Force { get; private set; }
public override MujocoLib.mjtObj ObjectType => MujocoLib.mjtObj.mjOBJ_ACTUATOR;
// Parse the component settings from an external Mjcf.
protected override void OnParseMjcf(XmlElement mjcf) {
if (!Enum.TryParse(mjcf.Name, ignoreCase: true, result: out Type)) {
throw new ArgumentException($"Unknown actuator type {mjcf.Name}.");
}
CommonParams.FromMjcf(mjcf);
switch (Type) {
case MjActuator.ActuatorType.General: {
CustomParams.GeneralFromMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Position: {
CustomParams.PositionFromMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Velocity: {
CustomParams.VelocityFromMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Cylinder: {
CustomParams.CylinderFromMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Muscle: {
CustomParams.MuscleFromMjcf(mjcf);
break;
}
}
Joint = mjcf.GetObjectReferenceAttribute<MjBaseJoint>("joint");
Tendon = mjcf.GetObjectReferenceAttribute<MjBaseTendon>("tendon");
}
// Generate implementation specific XML element.
protected override XmlElement OnGenerateMjcf(XmlDocument doc) {
if (Joint == null && Tendon == null) {
throw new InvalidOperationException($"Actuator {name} is not assigned a joint nor tendon.");
}
if (Joint != null && Tendon != null) {
throw new InvalidOperationException(
$"Actuator {name} can't have both a tendon and a joint target.");
}
var mjcf = doc.CreateElement(Type.ToString().ToLowerInvariant());
if (Joint != null) {
mjcf.SetAttribute("joint", Joint.MujocoName);
} else {
mjcf.SetAttribute("tendon", Tendon.MujocoName);
}
CommonParams.ToMjcf(mjcf);
switch (Type) {
case MjActuator.ActuatorType.General: {
CustomParams.GeneralToMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Position: {
CustomParams.PositionToMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Velocity: {
CustomParams.VelocityToMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Cylinder: {
CustomParams.CylinderToMjcf(mjcf);
break;
}
case MjActuator.ActuatorType.Muscle: {
CustomParams.MuscleToMjcf(mjcf);
break;
}
}
return mjcf;
}
// Synchronize the state of the component.
public override unsafe void OnSyncState(MujocoLib.mjData_* data) {
data->ctrl[MujocoId] = Control;
Length = (float)data->actuator_length[MujocoId];
Velocity = (float)data->actuator_velocity[MujocoId];
Force = (float)data->actuator_force[MujocoId];
}
public void OnValidate() {
if (Joint != null && Tendon != null) {
Debug.LogError(
$"Actuator {name} can't have both a tendon and a joint target.", this);
}
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Provisioning.Batch
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EFDAL = IoerContentBusinessEntities;
using ILPathways.Common;
using ILPathways.Utilities;
using ILPathways.DAL;
using ILPathways.Business;
using ThisUser = LRWarehouse.Business.Patron;
namespace Isle.BizServices
{
public class CommunityServices : ServiceHelper
{
//private static string thisClassName = "CommunityServices";
EFDAL.EFCommunityManager myManager = new EFDAL.EFCommunityManager();
public CommunityServices()
{ }//
#region == Community ==
/// <summary>
/// Delete a community
/// </summary>
/// <param name="id"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public bool Delete( int id, ref string statusMessage )
{
return myManager.CommunityDelete( id, ref statusMessage );
}
/// <summary>
/// Create a community
/// </summary>
/// <param name="entity"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public int Create( Community entity, ref string statusMessage )
{
return myManager.CommunityAdd( entity, ref statusMessage );
}
/// <summary>
/// Update a community
/// </summary>
/// <param name="entity"></param>
/// <param name="message"></param>
/// <returns></returns>
public bool Update( Community entity, ref string message )
{
return myManager.CommunityUpdate( entity, ref message );
}
/// <summary>
/// Get a community
/// Will return community including the most recent n posts (from web.config)
/// </summary>
/// <param name="communityId"></param>
/// <returns></returns>
public static Community Community_Get( int communityId)
{
return EFDAL.EFCommunityManager.Community_Get( communityId );
}
public static Community Community_Get( int communityId, int recentPosts )
{
return EFDAL.EFCommunityManager.Community_Get( communityId, recentPosts );
}
/// <summary>
/// Select all communities
/// </summary>
/// <returns>Community and the default nbr of recent posts</returns>
public List<Community> Community_SelectAll()
{
return EFDAL.EFCommunityManager.Community_GetAll(5);
}
public static List<CodeItem> Community_SelectList()
{
CodeItem ci = new CodeItem();
var eflist = EFDAL.EFCommunityManager.Community_GetAll( 5 );
List<CodeItem> list = new List<CodeItem>();
if ( eflist.Count > 0 )
{
foreach ( Community item in eflist )
{
ci = new CodeItem();
ci.Id = item.Id;
ci.Title = item.Title;
list.Add( ci );
}
}
return list;
}
/// <summary>
/// Select all communities
/// </summary>
/// <param name="recentPosts"></param>
/// <returns>Community and the requested nbr of recent posts</returns>
public List<Community> Community_SelectAll( int recentPosts )
{
return EFDAL.EFCommunityManager.Community_GetAll( recentPosts );
}
#endregion
#region === Community_Member =====
public int Community_MemberAdd( int pCommunityId, int pUserId )
{
return new EFDAL.EFCommunityManager().CommunityMember_Add( pCommunityId, pUserId );
}//
public bool Community_MemberDelete( int pCommunityId, int pUserId )
{
return new EFDAL.EFCommunityManager().CommunityMember_Delete( pCommunityId, pUserId );
}//
public static bool Community_MemberIsMember( int pCommunityId, int pUserId )
{
return EFDAL.EFCommunityManager.CommunityMember_IsMember( pCommunityId, pUserId );
}//
#endregion
#region === Postings =====
/// <summary>
/// Add posting to selected list of communities
/// ==> assumes not used with replys
/// </summary>
/// <param name="communities"></param>
/// <param name="comment"></param>
/// <param name="pCreatedById"></param>
/// <returns></returns>
public static int PostingAdd( List<int> communities, string comment, int pCreatedById )
{
return EFDAL.EFCommunityManager.Community_AddPostings( communities, comment, pCreatedById );
}//
/// <summary>
/// add a posting
/// </summary>
/// <param name="pCommunityId"></param>
/// <param name="comment"></param>
/// <param name="pCreatedById"></param>
/// <returns></returns>
public static int PostingAdd( int pCommunityId, string comment, int pCreatedById )
{
return EFDAL.EFCommunityManager.Community_AddPosting( pCommunityId, comment, pCreatedById, 0 );
}
/// <summary>
/// add a posting with a related postingId
/// </summary>
/// <param name="pCommunityId"></param>
/// <param name="comment"></param>
/// <param name="pCreatedById"></param>
/// <param name="relatedPostingId"></param>
/// <returns></returns>
public static int PostingAdd( int pCommunityId, string comment, int pCreatedById, int relatedPostingId )
{
return EFDAL.EFCommunityManager.Community_AddPosting( pCommunityId, comment, pCreatedById, relatedPostingId );
}
public static bool Posting_Delete( int id )
{
return EFDAL.EFCommunityManager.Posting_Delete( id );
}
public static CommunityPosting Posting_Get( int id )
{
return EFDAL.EFCommunityManager.Posting_Get( id );
}
/// <summary>
/// Posting search, used with paging
/// </summary>
/// <param name="pCommunityId"></param>
/// <param name="selectedPageNbr"></param>
/// <param name="pageSize"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
public static List<CommunityPosting> PostingSearch( int pCommunityId, int selectedPageNbr, int pageSize, ref int pTotalRows )
{
return EFDAL.EFCommunityManager.Posting_Search( pCommunityId, selectedPageNbr, pageSize, ref pTotalRows );
}
/// <summary>
/// Select postings for community up to the value for recordsMax
/// </summary>
/// <param name="pCommunityId"></param>
/// <param name="recordsMax"></param>
/// <returns></returns>
public static List<CommunityPosting> Posting_Select( int pCommunityId, int recordsMax )
{
return EFDAL.EFCommunityManager.PostingView_Select( pCommunityId, recordsMax );
}
/// <summary>
/// Add a document for a posting/community
/// </summary>
/// <param name="pPostingId"></param>
/// <param name="docId"></param>
/// <param name="pCreatedById"></param>
/// <returns></returns>
public static int PostingDocumentAdd( int pPostingId, Guid docId, int pCreatedById )
{
return EFDAL.EFCommunityManager.PostingDocumentAdd( pPostingId, docId, pCreatedById );
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using NUnit.Framework;
namespace FileHelpers.Tests.CommonTests
{
[TestFixture]
public class Readers
{
private FileHelperAsyncEngine asyncEngine;
[Test]
public void ReadFile()
{
var engine = new FileHelperEngine<SampleType>();
SampleType[] res;
res = TestCommon.ReadTest<SampleType>(engine, "Good", "Test1.txt");
Assert.AreEqual(4, res.Length);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void ReadFileStatic()
{
SampleType[] res;
res = (SampleType[]) CommonEngine.ReadFile(typeof (SampleType), FileTest.Good.Test1.Path);
Assert.AreEqual(4, res.Length);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void AsyncRead()
{
asyncEngine = new FileHelperAsyncEngine(typeof (SampleType));
SampleType rec1, rec2;
TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt");
rec1 = (SampleType) asyncEngine.ReadNext();
Assert.IsNotNull(rec1);
rec2 = (SampleType) asyncEngine.ReadNext();
Assert.IsNotNull(rec1);
Assert.IsTrue(rec1 != rec2);
rec1 = (SampleType) asyncEngine.ReadNext();
Assert.IsNotNull(rec2);
rec1 = (SampleType) asyncEngine.ReadNext();
Assert.IsNotNull(rec2);
Assert.IsTrue(rec1 != rec2);
Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount);
asyncEngine.Close();
}
[Test]
public void AsyncReadMoreAndMore()
{
asyncEngine = new FileHelperAsyncEngine(typeof (SampleType));
SampleType rec1;
TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt");
rec1 = (SampleType) asyncEngine.ReadNext();
rec1 = (SampleType) asyncEngine.ReadNext();
rec1 = (SampleType) asyncEngine.ReadNext();
rec1 = (SampleType) asyncEngine.ReadNext();
rec1 = (SampleType) asyncEngine.ReadNext();
Assert.IsTrue(rec1 == null);
rec1 = (SampleType) asyncEngine.ReadNext();
Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount);
asyncEngine.Close();
}
[Test]
public void AsyncRead2()
{
SampleType rec1;
asyncEngine = new FileHelperAsyncEngine(typeof (SampleType));
TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt");
int lineAnt = asyncEngine.LineNumber;
while (asyncEngine.ReadNext() != null) {
rec1 = (SampleType) asyncEngine.LastRecord;
Assert.IsNotNull(rec1);
Assert.AreEqual(lineAnt + 1, asyncEngine.LineNumber);
lineAnt = asyncEngine.LineNumber;
}
Assert.AreEqual(4, asyncEngine.TotalRecords);
Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount);
asyncEngine.Close();
}
[Test]
public void AsyncReadEnumerable()
{
asyncEngine = new FileHelperAsyncEngine(typeof (SampleType));
TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt");
int lineAnt = asyncEngine.LineNumber;
foreach (SampleType rec1 in asyncEngine) {
Assert.IsNotNull(rec1);
Assert.AreEqual(lineAnt + 1, asyncEngine.LineNumber);
lineAnt = asyncEngine.LineNumber;
}
Assert.AreEqual(4, asyncEngine.TotalRecords);
Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount);
asyncEngine.Close();
}
[Test]
public void AsyncReadEnumerableBad()
{
asyncEngine = new FileHelperAsyncEngine(typeof (SampleType));
Assert.Throws<FileHelpersException>(()
=> {
foreach (SampleType rec1 in asyncEngine)
rec1.ToString();
});
asyncEngine.Close();
}
[Test]
public void AsyncReadEnumerable2()
{
using (asyncEngine = new FileHelperAsyncEngine(typeof (SampleType))) {
TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt");
int lineAnt = asyncEngine.LineNumber;
foreach (SampleType rec1 in asyncEngine) {
Assert.IsNotNull(rec1);
Assert.AreEqual(lineAnt + 1, asyncEngine.LineNumber);
lineAnt = asyncEngine.LineNumber;
}
}
Assert.AreEqual(4, asyncEngine.TotalRecords);
Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount);
asyncEngine.Close();
}
[Test]
public void AsyncReadEnumerableAutoDispose()
{
asyncEngine = new FileHelperAsyncEngine(typeof (SampleType));
TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt");
asyncEngine.ReadNext();
asyncEngine.ReadNext();
asyncEngine.Close();
}
[Test]
public void ReadStream()
{
string data = "11121314901234" + Environment.NewLine +
"10111314012345" + Environment.NewLine +
"11101314123456" + Environment.NewLine +
"10101314234567" + Environment.NewLine;
var engine = new FileHelperEngine<SampleType>();
SampleType[] res;
res = engine.ReadStream(new StringReader(data));
Assert.AreEqual(4, res.Length);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void ReadString()
{
string data = "11121314901234" + Environment.NewLine +
"10111314012345" + Environment.NewLine +
"11101314123456" + Environment.NewLine +
"10101314234567" + Environment.NewLine;
var engine = new FileHelperEngine<SampleType>();
SampleType[] res;
res = engine.ReadString(data);
Assert.AreEqual(4, res.Length);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void ReadStringStatic()
{
string data = "11121314901234" + Environment.NewLine +
"10111314012345" + Environment.NewLine +
"11101314123456" + Environment.NewLine +
"10101314234567" + Environment.NewLine;
SampleType[] res;
res = CommonEngine.ReadString<SampleType>(data);
Assert.AreEqual(4, res.Length);
Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1);
Assert.AreEqual("901", res[0].Field2);
Assert.AreEqual(234, res[0].Field3);
Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1);
Assert.AreEqual("012", res[1].Field2);
Assert.AreEqual(345, res[1].Field3);
}
[Test]
public void ReadEmpty()
{
string data = "";
var engine = new FileHelperEngine<SampleType>();
SampleType[] res;
res = engine.ReadStream(new StringReader(data));
Assert.AreEqual(0, res.Length);
Assert.AreEqual(0, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
}
[Test]
public void ReadEmptyStream()
{
var engine = new FileHelperEngine<SampleType>();
SampleType[] res;
res = TestCommon.ReadTest<SampleType>(engine, "Good", "TestEmpty.txt");
Assert.AreEqual(0, res.Length);
Assert.AreEqual(0, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
}
[Test]
public void ReadFileAsDataTable()
{
var engine = new FileHelperEngine<SampleType>();
DataTable res;
res = engine.ReadFileAsDT(FileTest.Good.Test1.Path);
Assert.AreEqual(4, res.Rows.Count);
Assert.AreEqual(4, engine.TotalRecords);
Assert.AreEqual(0, engine.ErrorManager.ErrorCount);
Assert.AreEqual(new DateTime(1314, 12, 11), res.Rows[0]["Field1"]);
Assert.AreEqual("901", res.Rows[0]["Field2"]);
Assert.AreEqual(234, res.Rows[0]["Field3"]);
Assert.AreEqual(new DateTime(1314, 11, 10), res.Rows[1]["Field1"]);
Assert.AreEqual("012", res.Rows[1]["Field2"]);
Assert.AreEqual(345, res.Rows[1]["Field3"]);
}
[Test]
public void ReadAsyncFieldIndex()
{
string data = "11121314901234" + Environment.NewLine +
"10111314012345" + Environment.NewLine +
"11101314123456" + Environment.NewLine +
"10101314234567" + Environment.NewLine;
var asyncEngine = new FileHelperAsyncEngine<SampleType>();
asyncEngine.BeginReadString(data);
foreach (var rec in asyncEngine) {
Assert.AreEqual(rec.Field1, asyncEngine[0]);
Assert.AreEqual(rec.Field2, asyncEngine[1]);
Assert.AreEqual(rec.Field3, asyncEngine[2]);
Assert.AreEqual(rec.Field1, asyncEngine["Field1"]);
Assert.AreEqual(rec.Field2, asyncEngine["Field2"]);
Assert.AreEqual(rec.Field3, asyncEngine["Field3"]);
}
asyncEngine.Close();
}
}
}
| |
using System;
using System.Collections;
using NUnit.Framework;
using Spring.Objects;
namespace Spring.Util
{
[TestFixture]
public class CollectionUtilsTests
{
internal class NoContainsNoAddCollection : ICollection
{
internal class Iterator : IEnumerator
{
#region IEnumerator Members
public void Reset()
{
// TODO: Add Iterator.Reset implementation
}
public object Current
{
get
{
// TODO: Add Iterator.Current getter implementation
return null;
}
}
public bool MoveNext()
{
// TODO: Add Iterator.MoveNext implementation
return false;
}
#endregion
}
public void CopyTo(Array array, int index)
{
return;
}
public int Count
{
get { return 0; }
}
public object SyncRoot
{
get { return this; }
}
public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}
public IEnumerator GetEnumerator()
{
return new Iterator();
}
}
[Test]
public void ContainsNullCollection()
{
CollectionUtils.Contains(null, null);
}
[Test]
public void ContainsNullObject()
{
ArrayList list = new ArrayList();
list.Add(null);
Assert.IsTrue(CollectionUtils.Contains(list, null));
}
[Test]
public void ContainsCollectionThatDoesNotImplementContains()
{
NoContainsNoAddCollection noAddCollection = new NoContainsNoAddCollection();
CollectionUtils.Contains(noAddCollection, new object());
}
[Test]
public void ContainsValidElement()
{
ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
Assert.IsTrue(CollectionUtils.Contains(list, 3));
}
[Test]
public void ContainsDoesNotContainElement()
{
ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
Assert.IsFalse(CollectionUtils.Contains(list, 5));
}
[Test]
public void AddNullCollection()
{
Assert.Throws<ArgumentNullException>(() => CollectionUtils.Add(null, null));
}
[Test]
public void AddNullObject()
{
ArrayList list = new ArrayList();
CollectionUtils.Add(list, null);
Assert.IsTrue(list.Count == 1);
}
[Test]
public void AddCollectionDoesNotImplementAdd()
{
NoContainsNoAddCollection noAddCollection = new NoContainsNoAddCollection();
Assert.Throws<InvalidOperationException>(() => CollectionUtils.Add(noAddCollection, null));
}
[Test]
public void AddValidElement()
{
ArrayList list = new ArrayList();
object obj1 = new object();
CollectionUtils.Add(list, obj1);
Assert.IsTrue(list.Count == 1);
}
[Test]
public void ContainsAllNullTargetCollection()
{
Assert.Throws<ArgumentNullException>(() => CollectionUtils.ContainsAll(null, new ArrayList()));
}
[Test]
public void ContainsAllSourceNullCollection()
{
Assert.Throws<ArgumentNullException>(() => CollectionUtils.ContainsAll(new ArrayList(), null));
}
[Test]
public void ContainsAllDoesNotImplementContains()
{
Assert.Throws<InvalidOperationException>(() => CollectionUtils.ContainsAll(new NoContainsNoAddCollection(), new ArrayList()));
}
[Test]
public void DoesNotContainAllElements()
{
ArrayList target = new ArrayList();
target.Add(1);
target.Add(2);
target.Add(3);
ArrayList source = new ArrayList();
source.Add(1);
Assert.IsTrue(CollectionUtils.ContainsAll(target, source));
}
[Test]
public void ContainsAllElements()
{
ArrayList target = new ArrayList();
target.Add(1);
target.Add(2);
target.Add(3);
ArrayList source = new ArrayList();
source.Add(1);
source.Add(2);
source.Add(3);
Assert.IsTrue(CollectionUtils.ContainsAll(target, source));
}
[Test]
public void ContainsAllElementsWithNoElementsInSourceCollection()
{
ArrayList target = new ArrayList();
target.Add(1);
target.Add(2);
target.Add(3);
ArrayList source = new ArrayList();
Assert.IsTrue(CollectionUtils.ContainsAll(target, source));
}
[Test]
public void ContainsAllElementsWithNoElementsEitherCollection()
{
ArrayList target = new ArrayList();
ArrayList source = new ArrayList();
Assert.IsFalse(CollectionUtils.ContainsAll(target, source));
}
[Test]
public void ToArrayNullTargetCollection()
{
Assert.Throws<ArgumentNullException>(() => CollectionUtils.ToArrayList(null));
}
[Test]
public void ToArrayAllElements()
{
ArrayList target = new ArrayList();
target.Add(1);
target.Add(2);
target.Add(3);
ArrayList source = CollectionUtils.ToArrayList(target);
Assert.AreEqual(target.Count, source.Count);
}
[Test]
public void EmptyArrayElements()
{
ArrayList source = CollectionUtils.ToArrayList(new NoContainsNoAddCollection());
Assert.AreEqual(0, source.Count);
}
[Test]
public void RemoveAllTargetNullCollection()
{
Assert.Throws<ArgumentNullException>(() => CollectionUtils.RemoveAll(null, new ArrayList()));
}
[Test]
public void RemoveAllSourceNullCollection()
{
Assert.Throws<ArgumentNullException>(() => CollectionUtils.RemoveAll(new ArrayList(), null));
}
[Test]
public void RemoveAllTargetCollectionDoesNotImplementContains()
{
Assert.Throws<InvalidOperationException>(() => CollectionUtils.RemoveAll(new NoContainsNoAddCollection(), new ArrayList()));
}
[Test]
public void RemoveAllTargetCollectionDoesNotImplementRemove()
{
Assert.Throws<InvalidOperationException>(() => CollectionUtils.RemoveAll(new NoContainsNoAddCollection(), new ArrayList()));
}
[Test]
public void RemoveAllNoElements()
{
ArrayList target = new ArrayList();
target.Add(1);
target.Add(2);
target.Add(3);
ArrayList source = new ArrayList();
source.Add(4);
source.Add(5);
source.Add(6);
CollectionUtils.RemoveAll(target, source);
Assert.IsTrue(3 == target.Count);
}
[Test]
public void RemoveAllSomeElements()
{
ArrayList target = new ArrayList();
target.Add(1);
target.Add(2);
target.Add(3);
target.Add(4);
target.Add(5);
ArrayList source = new ArrayList();
source.Add(4);
source.Add(5);
source.Add(6);
CollectionUtils.RemoveAll(target, source);
Assert.IsTrue(3 == target.Count);
}
[Test]
public void RemoveAllAllElements()
{
ArrayList target = new ArrayList();
target.Add(1);
target.Add(2);
target.Add(3);
target.Add(4);
target.Add(5);
ArrayList source = new ArrayList();
source.Add(1);
source.Add(2);
source.Add(3);
source.Add(4);
source.Add(5);
source.Add(6);
CollectionUtils.RemoveAll(target, source);
Assert.IsTrue(0 == target.Count);
}
[Test]
public void IsCollectionEmptyOrNull()
{
ArrayList list = new ArrayList();
Assert.IsTrue(CollectionUtils.IsEmpty(list));
list.Add("foo");
Assert.IsFalse(CollectionUtils.IsEmpty(list));
list = null;
Assert.IsTrue(CollectionUtils.IsEmpty(list));
}
[Test]
public void IsDictionaryEmptyOrNull()
{
Hashtable t = new Hashtable();
Assert.IsTrue(CollectionUtils.IsEmpty(t));
t["foo"] = "bar";
Assert.IsFalse(CollectionUtils.IsEmpty(t));
t = null;
Assert.IsTrue(CollectionUtils.IsEmpty(t));
}
[Test]
public void FindValueOfType()
{
ArrayList list = new ArrayList();
Assert.IsNull(CollectionUtils.FindValueOfType(list, typeof(String)));
list.Add("foo");
object obj = CollectionUtils.FindValueOfType(list, typeof(String));
Assert.IsNotNull(obj);
Assert.IsNotNull(obj as string);
string val = obj as string;
Assert.AreEqual("foo", val);
list.Add(new TestObject("Joe", 34));
obj = CollectionUtils.FindValueOfType(list, typeof(TestObject));
Assert.IsNotNull(obj);
TestObject to = obj as TestObject;
Assert.IsNotNull(to);
Assert.AreEqual("Joe", to.Name);
list.Add(new TestObject("Mary", 33));
try
{
obj = CollectionUtils.FindValueOfType(list, typeof(TestObject));
Assert.Fail("Should have thrown exception");
}
catch (ArgumentException)
{
//ok
}
}
[Test]
public void ToArray()
{
ArrayList list = new ArrayList();
list.Add("mystring");
string[] strList = (string[]) CollectionUtils.ToArray(list, typeof(string));
Assert.AreEqual(1, strList.Length);
try
{
CollectionUtils.ToArray(list, typeof(Type));
Assert.Fail("should fail");
}
catch (InvalidCastException)
{
}
}
[Test]
public void StableSorting()
{
DictionaryEntry[] entries = new DictionaryEntry[]
{
new DictionaryEntry(5, 4),
new DictionaryEntry(5, 5),
new DictionaryEntry(3, 2),
new DictionaryEntry(3, 3),
new DictionaryEntry(1, 0),
new DictionaryEntry(1, 1),
};
ICollection resultList = CollectionUtils.StableSort(entries, new CollectionUtils.CompareCallback(CompareEntries));
DictionaryEntry[] resultEntries = (DictionaryEntry[]) CollectionUtils.ToArray(resultList, typeof(DictionaryEntry));
Assert.AreEqual(0, resultEntries[0].Value);
Assert.AreEqual(1, resultEntries[1].Value);
Assert.AreEqual(2, resultEntries[2].Value);
Assert.AreEqual(3, resultEntries[3].Value);
Assert.AreEqual(4, resultEntries[4].Value);
Assert.AreEqual(5, resultEntries[5].Value);
}
private int CompareEntries(object x, object y)
{
DictionaryEntry dex = (DictionaryEntry) x;
DictionaryEntry dey = (DictionaryEntry) y;
return ((int) dex.Key).CompareTo(dey.Key);
}
[Test]
public void FindFirstMatchReturnsNullIfAnyInputIsEmpty()
{
Assert.IsNull(CollectionUtils.FindFirstMatch(null, null));
Assert.IsNull(CollectionUtils.FindFirstMatch(new string[0], new string[0]));
Assert.IsNull(CollectionUtils.FindFirstMatch(null, new string[] {"x"}));
Assert.IsNull(CollectionUtils.FindFirstMatch(new string[] {"x"}, null));
}
[Test]
public void FindFirstMatchReturnsFirstMatch()
{
ArrayList source = new ArrayList();
string[] candidates = new string[] { "G", "B", "H" };
source.AddRange( new string[] { "A", "B", "C" } );
Assert.AreEqual( "B" , CollectionUtils.FindFirstMatch(source, candidates));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Xml;
using dexih.functions.BuiltIn;
using Dexih.Utils.DataType;
using Newtonsoft.Json.Linq;
using Xunit;
using Xunit.Abstractions;
namespace dexih.functions.builtIn.tests
{
public class BuiltIn
{
const string BuiltInAssembly = "dexih.functions.builtIn.dll";
private readonly ITestOutputHelper _output;
public BuiltIn(ITestOutputHelper output)
{
_output = output;
}
[Theory]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Concat), new object[] { new [] {"test1", "test2", "test3" }}, "test1test2test3")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.IndexOf), new object[] { "test string", "s" }, 2)]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Insert), new object[] { "test string", 5, "new " }, "test new string")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Join), new object[] { ",", new [] {"test1", "test2", "test3" }}, "test1,test2,test3")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.PadLeft), new object[] { "test", 7, "-" }, "---test")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.PadRight), new object[] { "test", 7, "-" }, "test---")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Remove), new object[] { "testing", 1, 4 }, "tng")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Replace), new object[] { "stress test", "es", "aa" }, "straas taat")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Split), new object[] { "test1,test2,test3", ",", 3 }, 3)]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Substring), new object[] { "testing", 1, 4 }, "esti")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.ToLower), new object[] { " tEsT1 " }, " test1 ")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.ToUpper), new object[] { " tEsT1 " }, " TEST1 ")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Trim), new object[] { " tEsT1 " }, "tEsT1")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.TrimEnd), new object[] { " tEsT1 " }, " tEsT1")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.TrimStart), new object[] { " tEsT1 " }, "tEsT1 ")]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.Length), new object[] { "test" }, 4)]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.WordCount), new object[] { "word1 word2 word3" }, 3)]
[InlineData(typeof(MapFunctions), nameof(MapFunctions.WordExtract), new object[] { "word1 word2 word3", 2 }, "word3")]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.LessThan), new object[] { 1, 2 }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.LessThan), new object[] { 2, 1 }, false)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.LessThanOrEqual), new object[] { 1, 2 }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.LessThanOrEqual), new object[] { 2, 2 }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.LessThanOrEqual), new object[] { 2, 1 }, false)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.GreaterThan), new object[] { 2, 1 }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.GreaterThanOrEqual), new object[] { 2, 1 }, true)]
[InlineData(typeof(ConditionFunctions<int>), nameof(ConditionFunctions<int>.IsEqual), new object[] { new [] {2, 2} }, true)]
[InlineData(typeof(ConditionFunctions<bool>), nameof(ConditionFunctions<int>.IsEqual), new object[] { new [] { true, true} }, true)]
[InlineData(typeof(ConditionFunctions<int>), nameof(ConditionFunctions<int>.IsEqual), new object[] { new [] {3, 2} }, false)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsNumber), new object[] { "123" }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsNumber), new object[] { "123a" }, false)]
[InlineData(typeof(ConditionFunctions<string>), nameof(ConditionFunctions<int>.IsNull), new object[] { null }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsBetween), new object[] { 2, 1, 3 }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsBetweenInclusive), new object[] { 2, 1, 3 }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.RegexMatch), new object[] { "abbbb", "ab*" }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.Contains), new object[] { "testing", "est", false }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.EndsWith), new object[] { "testing", "ing", false }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.StartsWith), new object[] { "testing", "tes", false }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsUpper), new object[] { "TEST", true }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsLower), new object[] { "test", true }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsAlpha), new object[] { "test" }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsAlphaNumeric), new object[] { "test123" }, true)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsPattern), new object[] { "Hello12", "Aaaaa99" }, true)]
// [InlineData(typeof(BuiltIn.ConditionFunctions), nameof(ConditionFunctions.IsDaylightSavingTime), new object[] { "2015-09-24T21:22:48.2698750Z" }, false)]
[InlineData(typeof(MathFunctions), nameof(MathFunctions.Abs), new object[] { -3 }, (double)3)]
[InlineData(typeof(MathFunctions), nameof(MathFunctions.DivRem), new object[] { 6, 4 }, 1)]
[InlineData(typeof(MathFunctions), nameof(MathFunctions.Pow), new object[] { 6, 2 }, (double)36)]
[InlineData(typeof(MathFunctions), nameof(MathFunctions.Round), new object[] { 6.5 }, (double)6)]
[InlineData(typeof(ArithmeticFunctions<>), nameof(ArithmeticFunctions<int>.Sign), new object[] { -4 }, -1)]
[InlineData(typeof(MathFunctions), nameof(MathFunctions.Sqrt), new object[] { 9 }, (double)3)]
[InlineData(typeof(MathFunctions), nameof(MathFunctions.Truncate), new object[] { 6.4 }, (double)6)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.ArrayContains), new object[] { "test2", new string[] {"test1", "test2", "test3"} }, true)]
[InlineData(typeof(GeometryFunctions), nameof(GeometryFunctions.GeographicDistance), new object[] { -38, -145, -34 ,- 151 }, 699082.1288)] //melbourne to sydney distance
[InlineData(typeof(ValidationFunctions), nameof(ValidationFunctions.MaxLength), new object[] { "abcdef", 5 }, false)]
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.RangeIntersect), new object[] { 1, 2, 3, 4 }, false)] //(1,2)(3,4) not intersect
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.RangeIntersect), new object[] { 1, 3, 3, 4 }, false)] //(1,3)(3,4) do intersect
[InlineData(typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.RangeIntersect), new object[] { 1, 4, 3, 4 }, true)] //(1,4)(3,4) do intersect
[InlineData(typeof(CategorizeFunctions), nameof(CategorizeFunctions.RangeCategorize), new object[] { 1D, new [] {1D, 5D, 10D}}, true)]
[InlineData(typeof(CategorizeFunctions), nameof(CategorizeFunctions.RangeCategorize), new object[] { 11D, new [] {1D, 5D, 10D} }, false)]
[InlineData(typeof(CategorizeFunctions), nameof(CategorizeFunctions.DiscreteRangeCategorize), new object[] { 1L, new [] {1L, 5L, 10L} }, true)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertTemperature), new object[] { 100, ConversionFunctions.ETemperatureScale.Kelvin, ConversionFunctions.ETemperatureScale.Celsius }, -173.15)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertTemperature), new object[] { 40, ConversionFunctions.ETemperatureScale.Celsius, ConversionFunctions.ETemperatureScale.Fahrenheit }, 104d)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertMass), new object[] { 1, ConversionFunctions.EMassScale.Kilogram, ConversionFunctions.EMassScale.Pound }, 2.2046)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertMassString), new object[] { 1, "kg", ConversionFunctions.EMassScale.Pound }, 2.2046)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertLength), new object[] { 1, ConversionFunctions.ELengthScale.Kilometer, ConversionFunctions.ELengthScale.Mile }, 0.6214)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertLengthString), new object[] { 1, "km", ConversionFunctions.ELengthScale.Mile }, 0.6214)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertTime), new object[] { 1, ConversionFunctions.ETimeScale.Hour, ConversionFunctions.ETimeScale.Millisecond }, 3600000d)]
[InlineData(typeof(ConversionFunctions), nameof(ConversionFunctions.ConvertTimeString), new object[] { 1, "h", ConversionFunctions.ETimeScale.Millisecond }, 3600000d)]
[MemberData(nameof(OtherFunctions))]
public void StandardFunctionTest(Type type, string methodName, object[] parameters, object expectedResult)
{
var function = Functions.GetFunction(type.FullName, methodName, BuiltInAssembly);
var transformFunction = function.GetTransformFunction(parameters[0]?.GetType());
transformFunction.OnNull = EErrorAction.Execute;
var returnValue = transformFunction.RunFunction(parameters, CancellationToken.None).returnValue;
if (returnValue is double d)
{
Assert.Equal(expectedResult, Math.Round(d, 4));
}
else
Assert.Equal(expectedResult, returnValue);
}
public static IEnumerable<object[]> OtherFunctions
{
get
{
var date1 = DateTime.Parse("2015-09-24");
var date2 = DateTime.Parse("2015-09-25");
return new[]
{
new object[] { typeof(DateFunctions), nameof(DateFunctions.DayOfMonth), new object[] {date1}, 24},
new object[] { typeof(DateFunctions), nameof(DateFunctions.DaysInMonth), new object[] {date1}, 30},
new object[] { typeof(DateFunctions), nameof(DateFunctions.DayOfWeekName), new object[] {date1}, "Thursday"},
new object[] { typeof(DateFunctions), nameof(DateFunctions.DayOfWeekNumber), new object[] {date1}, 4},
new object[] { typeof(DateFunctions), nameof(DateFunctions.WeekOfYear), new object[] {date1}, 39},
new object[] { typeof(DateFunctions), nameof(DateFunctions.DayOfYear), new object[] {date1}, 267},
new object[] { typeof(DateFunctions), nameof(DateFunctions.Month), new object[] {date1}, 9},
new object[] { typeof(DateFunctions), nameof(DateFunctions.ShortMonth), new object[] {date1}, "Sep"},
new object[] { typeof(DateFunctions), nameof(DateFunctions.LongMonth), new object[] {date1}, "September"},
new object[] { typeof(DateFunctions), nameof(DateFunctions.Year), new object[] {date1}, 2015},
new object[] { typeof(DateFunctions), nameof(DateFunctions.ToLongDateString), new object[] {date1}, "Thursday, 24 September 2015"},
new object[] { typeof(DateFunctions), nameof(DateFunctions.ToLongTimeString), new object[] {date1}, "12:00:00 AM"},
new object[] { typeof(DateFunctions), nameof(DateFunctions.ToShortDateString), new object[] {date1}, "24/09/2015"},
new object[] { typeof(DateFunctions), nameof(DateFunctions.ToShortTimeString), new object[] {date1}, "12:00 AM"},
new object[] { typeof(DateFunctions), nameof(DateFunctions.DateToString), new object[] {date1, "dd MMM yyyy"}, "24 Sep 2015"},
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsLeapYear), new object[] {date1}, false},
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsWeekend), new object[] { date1 }, false},
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsWeekDay), new object[] { date1 }, true},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AddDays), new object[] { date1, 1 }, DateTime.Parse("25 Sep 2015")},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AddHours), new object[] { date1, 24 }, DateTime.Parse("25 Sep 2015")},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AddMilliseconds), new object[] { date1, 86400000 }, DateTime.Parse("25 Sep 2015")},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AddMinutes), new object[] { date1, 1440 }, DateTime.Parse("25 Sep 2015")},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AddMonths), new object[] { date1, 1 }, DateTime.Parse("24 Oct 2015")},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AddSeconds), new object[] { date1, 86400 }, DateTime.Parse("25 Sep 2015")},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AddYears), new object[] { date1, 1 }, DateTime.Parse("24 Sep 2016")},
new object[] { typeof(DateFunctions), nameof(DateFunctions.DaysBetween), new object[] { date1, date2 }, 1d},
new object[] { typeof(DateFunctions), nameof(DateFunctions.HoursBetween), new object[] { date1, date2 }, 24d},
new object[] { typeof(DateFunctions), nameof(DateFunctions.MinutesBetween), new object[] { date1, date2 }, 1440d},
new object[] { typeof(DateFunctions), nameof(DateFunctions.SecondsBetween), new object[] { date1, date2 }, 86400d},
new object[] { typeof(DateFunctions), nameof(DateFunctions.MillisecondsBetween), new object[] { date1, date2 }, 86400000d},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AgeInYearsAtDate), new object[] { date1, DateTime.Parse("2016-09-24") }, 1},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AgeInYearsAtDate), new object[] { date1, date1 }, 0},
new object[] { typeof(DateFunctions), nameof(DateFunctions.AgeInYearsAtDate), new object[] { date1, DateTime.Parse("2017-09-25") }, 2},
new object[] { typeof(ArithmeticFunctions<>), nameof(ArithmeticFunctions<int>.Add), new object[] { 1m, new [] {2m} }, 3m},
new object[] { typeof(MathFunctions), nameof(MathFunctions.Ceiling), new object[] { 6.4m }, (decimal)7 },
new object[] { typeof(ArithmeticFunctions<>), nameof(ArithmeticFunctions<int>.Divide), new object[] { 6m, 2m }, (decimal)3 },
new object[] { typeof(MathFunctions), nameof(MathFunctions.Floor), new object[] { 6.4m }, (decimal)6 },
new object[] { typeof(ArithmeticFunctions<>), nameof(ArithmeticFunctions<int>.Multiply), new object[] { 6m, new [] {2m} }, (decimal)12 },
new object[] { typeof(ArithmeticFunctions<>), nameof(ArithmeticFunctions<int>.Negate), new object[] { 6m }, (decimal) (-6)},
new object[] { typeof(MathFunctions), nameof(MathFunctions.Remainder), new object[] { 6m, 4m }, (decimal)2 },
new object[] { typeof(ArithmeticFunctions<>), nameof(ArithmeticFunctions<int>.Subtract), new object[] { 6m, new [] { 2m} }, (decimal)4 },
new object[] { typeof(ConditionFunctions<DateTime>), nameof(ConditionFunctions<int>.IsEqual), new object[] { new [] { DateTime.Parse("25 Sep 2015"), DateTime.Parse("25 Sep 2015")} }, true },
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsBetween), new object[] { DateTime.Parse("26 Sep 2015"), DateTime.Parse("25 Sep 2015"), DateTime.Parse("27 Sep 2015") }, true },
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.IsBetweenInclusive), new object[] { DateTime.Parse("26 Sep 2015"), DateTime.Parse("26 Sep 2015"), DateTime.Parse("27 Sep 2015") }, true },
new object[] { typeof(DateFunctions), nameof(DateFunctions.UnixTimeStampToDate), new object[] { 1518739200 }, new DateTime(2018, 2, 16, 0, 0, 0, 0, DateTimeKind.Utc).ToLocalTime() },
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.RangeIntersect), new object[] { DateTime.Parse("26 Sep 2015"), DateTime.Parse("27 Sep 2015"), DateTime.Parse("28 Sep 2015"), DateTime.Parse("29 Sep 2015") }, false },
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.RangeIntersect), new object[] { DateTime.Parse("26 Sep 2015"), DateTime.Parse("28 Sep 2015"), DateTime.Parse("28 Sep 2015"), DateTime.Parse("29 Sep 2015") }, false },
new object[] { typeof(ConditionFunctions<>), nameof(ConditionFunctions<int>.RangeIntersect), new object[] { DateTime.Parse("26 Sep 2015"), DateTime.Parse("29 Sep 2015"), DateTime.Parse("28 Sep 2015"), DateTime.Parse("29 Sep 2015") }, true },
};
}
}
[Theory]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.Sum), 55)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.Average), 5.5)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.Median), 5.5)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.StdDev), 2.8723)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.Variance), 8.25)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.Min), 1)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.Max), 10)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.First), 1)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.Last), 10)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.CountDistinct), 10)]
public void AggregateFunctionTest(Type type, string methodName, object expectedResult)
{
var function = Functions.GetFunction(type.FullName, methodName, BuiltInAssembly);
var transformFunction = function.GetTransformFunction(expectedResult.GetType());
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 1; i <= 10; i++)
{
transformFunction.RunFunction(new object[] { i }, CancellationToken.None);
}
var aggregateResult = transformFunction.RunResult(null, out _, CancellationToken.None).returnValue;
Assert.NotNull(aggregateResult);
if(aggregateResult is double d)
{
Assert.Equal(expectedResult, Math.Round(d, 4));
}
else
Assert.Equal(expectedResult, aggregateResult);
transformFunction.Reset();
}
}
[Theory]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.CountTrue), 3)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.CountFalse), 1)]
public void CountTests(Type type, string methodName, object expectedResult)
{
var function = Functions.GetFunction(type.FullName, methodName, BuiltInAssembly);
var transformFunction = function.GetTransformFunction(typeof(int));
var data = new object[] {true, false, true, true};
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 0; i < data.Length; i++)
{
transformFunction.RunFunction(new[] { data[i] }, CancellationToken.None);
}
var aggregateResult = transformFunction.RunResult(null, out _, CancellationToken.None).returnValue;
Assert.NotNull(aggregateResult);
Assert.Equal(expectedResult, aggregateResult);
transformFunction.Reset();
}
}
[Theory]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.CountEqual), 3)]
public void CountEqualTests(Type type, string methodName, object expectedResult)
{
var function = Functions.GetFunction(type.FullName, methodName, BuiltInAssembly);
var transformFunction = function.GetTransformFunction(typeof(int));
// 3/4 match
var data1 = new object[] {1, 2, 3, 4};
var data2 = new object[] {1, 2, 0, 4};
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 0; i < data1.Length; i++)
{
transformFunction.RunFunction(new[] { new[] { data1[i], data2[i]} }, CancellationToken.None);
}
var aggregateResult = transformFunction.RunResult(null, out _, CancellationToken.None).returnValue;
Assert.NotNull(aggregateResult);
Assert.Equal(expectedResult, aggregateResult);
transformFunction.Reset();
}
}
[Theory]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.CountDistinct), 3)]
public void CountDistinctTests(Type type, string methodName, object expectedResult)
{
var function = Functions.GetFunction(type.FullName, methodName, BuiltInAssembly);
var transformFunction = function.GetTransformFunction(typeof(int));
// 3 distinct values
var data = new object[] {1, 2, 2, 1, 3};
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 0; i < data.Length; i++)
{
transformFunction.RunFunction(new[] { data[i] }, CancellationToken.None);
}
var aggregateResult = transformFunction.RunResult(null, out _, CancellationToken.None).returnValue;
Assert.NotNull(aggregateResult);
Assert.Equal(expectedResult, aggregateResult);
transformFunction.Reset();
}
}
[Theory]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.PivotToColumns))]
public void PivotColumnsTests(Type type, string methodName)
{
var function = Functions.GetFunction(type.FullName, methodName, BuiltInAssembly);
var transformFunction = function.GetTransformFunction(typeof(int));
var data1 = new object[] {"val1", "val2", "val3"};
var data2 = new object[] {1, 2, 3};
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 0; i < data1.Length; i++)
{
transformFunction.RunFunction(new[] { data1[i], data2[i], data1 }, CancellationToken.None);
}
var aggregateResult = transformFunction.RunResult(null, out var outputs, CancellationToken.None).returnValue;
Assert.True((bool)aggregateResult);
var result = (int[]) outputs[0];
for (var i = 0; i < data1.Length; i++)
{
Assert.Equal(data2[i], result[i]);
}
transformFunction.Reset();
}
}
[Theory]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.FirstWhen), 1, 1)]
[InlineData(typeof(AggregateFunctions<>), nameof(AggregateFunctions<int>.LastWhen), 1, 9)]
public void AggregateWhenFunctionTest(Type type, string methodName, object test, object expectedResult)
{
var function = Functions.GetFunction(type.FullName, methodName, BuiltInAssembly);
var transformFunction = function.GetTransformFunction(typeof(int));
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 1; i <= 10; i++)
{
var value = i % 2;
var functionResult = transformFunction.RunFunction(new[] { test, value, i }, CancellationToken.None);
}
var aggregateResult = transformFunction.RunResult(null, out _, CancellationToken.None).returnValue;
Assert.NotNull(aggregateResult);
if (aggregateResult is double aggregateResultDouble)
{
Assert.Equal(expectedResult, Math.Round(aggregateResultDouble, 4));
}
else
Assert.Equal(expectedResult, aggregateResult);
transformFunction.Reset();
}
}
[Fact]
public void MinMaxDateTest()
{
var minFunction = Functions.GetFunction(typeof(AggregateFunctions<>).FullName, nameof(AggregateFunctions<int>.Min), BuiltInAssembly).GetTransformFunction(typeof(DateTime));
var maxFunction = Functions.GetFunction(typeof(AggregateFunctions<>).FullName, nameof(AggregateFunctions<int>.Max), BuiltInAssembly).GetTransformFunction(typeof(DateTime));
var baseDate = DateTime.Now;
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 0; i <= 10; i++)
{
var minFunctionResult = minFunction.RunFunction(new object[] { baseDate.AddDays(i) }, CancellationToken.None);
var maxFunctionResult = maxFunction.RunFunction(new object[] { baseDate.AddDays(i) }, CancellationToken.None);
}
var minResult = minFunction.RunResult(null, out _, CancellationToken.None).returnValue;
var maxResult = maxFunction.RunResult(null, out _, CancellationToken.None).returnValue;
Assert.NotNull(minResult);
Assert.NotNull(maxResult);
Assert.Equal(baseDate, (DateTime)minResult);
Assert.Equal(baseDate.AddDays(10), (DateTime)maxResult);
minFunction.Reset();
maxFunction.Reset();
}
}
[Fact]
public void FastEncryptTest()
{
var globalVariables = new GlobalSettings("abc");
const string value = "encrypt this";
var function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.FastEncrypt), BuiltInAssembly).GetTransformFunction(typeof(string), null, globalVariables);
var encrypted = function.RunFunction(new object[] {value}, CancellationToken.None).returnValue;
function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.FastDecrypt), BuiltInAssembly).GetTransformFunction(typeof(string),null , globalVariables);
var decrypted = function.RunFunction(new[] {encrypted}, CancellationToken.None).returnValue;
Assert.Equal(value, decrypted);
}
[Fact]
public void StrongEncryptTest()
{
var globalVariables = new GlobalSettings("abc");
const string value = "encrypt this";
var function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.StrongEncrypt), BuiltInAssembly).GetTransformFunction(typeof(string), null, globalVariables);
var encrypted = function.RunFunction(new object[] {value}, CancellationToken.None).returnValue;
function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.StrongDecrypt), BuiltInAssembly).GetTransformFunction(typeof(string), null, globalVariables);
var decrypted = function.RunFunction(new[] {encrypted}, CancellationToken.None).returnValue;
Assert.Equal(value, decrypted);
}
[Fact]
public void EncryptTest()
{
const string value = "encrypt this";
const string key = "abc";
const int iterations = 10;
var function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.Encrypt), BuiltInAssembly).GetTransformFunction(typeof(string));
var encrypted = function.RunFunction(new object[] {value, key, iterations}, CancellationToken.None).returnValue;
function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.Decrypt), BuiltInAssembly).GetTransformFunction(typeof(string));
var decrypted = function.RunFunction(new [] {encrypted, key, iterations}, CancellationToken.None).returnValue;
Assert.Equal(value, decrypted);
}
[Fact]
public void HashTest()
{
const string value = "hash this";
var function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.SecureHash), BuiltInAssembly).GetTransformFunction(typeof(string));
var hashed = function.RunFunction(new object[] {value}, CancellationToken.None).returnValue;
function = Functions.GetFunction(typeof(SecurityFunctions).FullName, nameof(SecurityFunctions.ValidateSecureHash), BuiltInAssembly).GetTransformFunction(typeof(string));
var passed = (bool)function.RunFunction(new object[] {value, hashed}, CancellationToken.None).returnValue;
Assert.True(passed);
//check hash fails with different value.
passed = (bool) function.RunFunction(new object[] {"hash thiS", hashed}, CancellationToken.None).returnValue;
Assert.False(passed);
}
[Fact]
public void SHA1Test()
{
var function = Functions.GetFunction(typeof(MapFunctions).FullName, nameof(MapFunctions.CreateSHA1), BuiltInAssembly).GetTransformFunction(typeof(string));
var sha1 = function.RunFunction(new object[] {"sha this"}, CancellationToken.None);
var sha1a = function.RunFunction(new [] {"sha this"}, CancellationToken.None);
// check same value hashed the same.
Assert.Equal(sha1, sha1a);
var sha1b = function.RunFunction(new [] {"sha thiS"}, CancellationToken.None);
// check different value hashed the differently.
Assert.NotEqual(sha1, sha1b);
// uncomment below for tests on much larger string.
// // sha a very large string
// var random = new Random();
// const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
//
// Span<char> largeString = Enumerable.Repeat(chars, 1_000_000_000).Select(s => s[random.Next(s.Length)]).ToArray();
//
// var timer = Stopwatch.StartNew();
// var bigsha = function.RunFunction(new object[] {largeString.ToString()});
// timer.Stop();
// _output.WriteLine($"SHA of large string value {bigsha}, and ran in {timer.ElapsedMilliseconds} ms.");
//
// // largeString[999999999] = ' ';
// largeString[0] = 'a';
//
// timer = Stopwatch.StartNew();
// var bigsha2 = function.RunFunction(new object[] {largeString.ToString()});
// timer.Stop();
// _output.WriteLine($"SHA of large string value {bigsha2}, and ran in {timer.ElapsedMilliseconds} ms.");
//
// Assert.NotEqual(bigsha, bigsha2);
}
[Fact]
public void CountTest()
{
var function = Functions.GetFunction(typeof(AggregateFunctions<int>).FullName, nameof(AggregateFunctions<int>.Count), BuiltInAssembly).GetTransformFunction(typeof(int));
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 1; i <= 10; i++)
{
var functionResult = function.RunFunction(new FunctionVariables(),new object[] { }, CancellationToken.None);
}
var aggregateResult = function.RunResult(new FunctionVariables(), null, out _, CancellationToken.None).returnValue;
Assert.NotNull(aggregateResult);
Assert.Equal(10, aggregateResult);
function.Reset();
}
}
[Fact]
public void ConcatAggTest()
{
var function = Functions.GetFunction(typeof(AggregateFunctions<string>).FullName, nameof(AggregateFunctions<string>.ConcatAgg), BuiltInAssembly).GetTransformFunction(typeof(string));
for (var a = 0; a < 2; a++) // run all tests twice to ensure reset functions are working
{
for (var i = 1; i <= 10; i++)
{
var functionResult = function.RunFunction(new FunctionVariables(),new object[] { i.ToString(), "," }, CancellationToken.None);
}
var aggregateResult = function.RunResult(new FunctionVariables(), null, out _, CancellationToken.None).returnValue;
Assert.NotNull(aggregateResult);
Assert.Equal("1,2,3,4,5,6,7,8,9,10", aggregateResult);
function.Reset();
}
}
[Fact]
public void Function_XPathValue()
{
//Get a rows that exists.
var function = Functions.GetFunction(typeof(MapFunctions).FullName, nameof(MapFunctions.XPathValues), BuiltInAssembly).GetTransformFunction(typeof(XmlDocument));
var xmlDoc = Operations.Parse<XmlDocument>("<root><row>0</row><row>1</row><row>2</row><row>3</row><row>4</row><row>5</row></root>");
var param = new object[] { xmlDoc, new [] { "//row[1]", "//row[2]", "//row[3]"} };
Assert.True((bool)function.RunFunction(param, out var outputs, CancellationToken.None).returnValue);
var result = (object[]) outputs[0];;
Assert.Equal("0", result[0]);
Assert.Equal("1", result[1]);
Assert.Equal("2", result[2]);
}
[Fact]
public void Function_JSONValue()
{
//Get a rows that exists.
var function = Functions.GetFunction(typeof(MapFunctions).FullName, nameof(MapFunctions.JsonValues), BuiltInAssembly).GetTransformFunction(typeof(JsonElement));
var json = "{ \"value1\": \"1\", \"value2\" : \"2\", \"value3\": \"3\", \"array\" : {\"v1\" : \"1\", \"v2\" : \"2\"} }";
var param = new object[] { json, new [] { "value1", "value2", "value3", "array", "badvalue" }};
Assert.False((bool)function.RunFunction(new FunctionVariables(), param, out var outputs, CancellationToken.None).returnValue);
var result = (object[])outputs[0];
Assert.Equal("1", result[0]);
Assert.Equal("2", result[1]);
Assert.Equal("3", result[2]);
Assert.Null(result[4]);
//get the sub Json string, and run another parse over this.
var moreValues = result[3];
param = new object[] { moreValues, new [] { "v1", "v2"} };
function = Functions.GetFunction(typeof(MapFunctions).FullName, nameof(MapFunctions.JsonValues), BuiltInAssembly).GetTransformFunction(typeof(JsonElement));
Assert.True((bool)function.RunFunction(param, out outputs, CancellationToken.None).returnValue);
result = (object[]) outputs[0];;
Assert.Equal("1", result[0]);
Assert.Equal("2", result[1]);
}
[Fact]
public void RowFunctions_GenerateSequence()
{
//Use a for loop to simulate gen sequence.
var function = Functions.GetFunction(typeof(RowFunctions).FullName, nameof(RowFunctions.GenerateSequence), BuiltInAssembly).GetTransformFunction(typeof(int));
var param = new object[] { 0, 10, 2 };
for (var i = 0; i <= 10; i += 2)
{
Assert.True((bool)function.RunFunction(param, out var outputs, CancellationToken.None).returnValue);
Assert.Equal(i, (int)outputs[0]);
}
//last value should be false as the sequence has been exceeded.
Assert.False((bool)function.RunFunction(param, CancellationToken.None).returnValue);
}
[Fact]
public void RowFunctions_SplitColumnToRows()
{
//Use a for loop to simulate gen sequence.
var function = Functions.GetFunction(typeof(RowFunctions).FullName, nameof(RowFunctions.SplitColumnToRows), BuiltInAssembly).GetTransformFunction(typeof(string));
var param = new object[] { "|", "|value2|value3||value5||", 6 };
var compare = new[] { "", "value2", "value3", "", "value5", "", "" };
for (var i = 0; i < 6; i++)
{
Assert.True((bool)function.RunFunction(param, out var outputs, CancellationToken.None).returnValue);
Assert.Equal(compare[i], (string)outputs[0]);
}
//last value should be false as the sequence has been exceeded.
Assert.False((bool)function.RunFunction(param, CancellationToken.None).returnValue);
}
[Fact]
public void RowFunctions_XPathNodesToRows()
{
//Use a for loop to similate gen sequence.
var function = Functions.GetFunction(typeof(RowFunctions).FullName, nameof(RowFunctions.XPathNodesToRows), BuiltInAssembly).GetTransformFunction(typeof(XmlDocument));
var xmlDoc = Operations.Parse<XmlDocument>("<root><row>0</row><row>1</row><row>2</row><row>3</row><row>4</row><row>5</row></root>");
var param = new object[] { xmlDoc, "//row", 5 };
for (var i = 0; i < 5; i++)
{
Assert.True((bool)function.RunFunction(param, out var outputs, CancellationToken.None).returnValue);
Assert.Equal(i.ToString(), (string)outputs[0]);
}
//last value should be false as the sequence has been exceeded.
Assert.False((bool)function.RunFunction(param, CancellationToken.None).returnValue);
}
[Fact]
public void RowFunctions_JsonElementsToRows()
{
//Use a for loop to similate gen sequence.
var function = Functions.GetFunction(typeof(RowFunctions).FullName, nameof(RowFunctions.JsonElementsToRows), BuiltInAssembly).GetTransformFunction(typeof(JToken));
var json = "{\"results\" : [{\"value1\" : \"r1v1\", \"value2\" : \"r1v2\"}, {\"value1\" : \"r2v1\", \"value2\" : \"r2v2\"}]} ";
var param = new object[] { json , "results[*]", 2 };
for (var i = 1; i <= 2; i++)
{
Assert.True((bool)function.RunFunction(param, out var outputs, CancellationToken.None).returnValue);
var jsonResult = (string)outputs[0];
var results = JObject.Parse(jsonResult);
Assert.Equal("r" + i.ToString() + "v1", results.SelectToken("value1").ToString());
Assert.Equal("r" + i.ToString() + "v2", results.SelectToken("value2").ToString());
}
//last value should be false as the sequence has been exceeded.
Assert.False((bool)function.RunFunction(param, CancellationToken.None).returnValue);
}
[Fact]
public void RowFunctions_JsonPivotElementToRows()
{
//Use a for loop to simulate gen sequence.
var function = Functions.GetFunction(typeof(RowFunctions).FullName, nameof(RowFunctions.JsonPivotElementToRows), BuiltInAssembly).GetTransformFunction(typeof(JToken));
var json = "{\"results\" : {\"name1\" : \"value1\", \"name2\" : \"value2\", \"name3\" : \"value3\"}} ";
var param = new object[] { json, "results", 3 };
for (var i = 1; i <= 3; i++)
{
Assert.True((bool)function.RunFunction(param, out var outputs, CancellationToken.None).returnValue);
var name = (string)outputs[0];
var value = (string)outputs[1];
Assert.Equal(name, "name" + i.ToString());
Assert.Equal(value, "value" + i.ToString());
}
//last value should be false as the sequence has been exceeded.
Assert.False((bool)function.RunFunction(param, CancellationToken.None).returnValue);
}
[Fact]
public void GroupFunction_ParentChildFlatten()
{
var data = new[]
{
new object[] {"EMP1", "MGR1"},
new object[] {"EMP2", "MGR1"},
new object[] {"EMP3", "MGR2"},
new object[] {"MGR2", "MGR1"},
new object[] {"EMP4", "MGR2"},
new object[] {"EMP5", "EMP4"},
new object[] {"EMP6", "EMP5"},
};
var expected = new[]
{
new object[] {"MGR1", 0, new object[] { "MGR1", null, null, null, null}},
new object[] {"EMP1", 1, new object[] { "MGR1", "EMP1", null, null, null}},
new object[] {"EMP2", 1, new object[] { "MGR1", "EMP2", null, null, null}},
new object[] {"EMP3", 2, new object[] { "MGR1", "MGR2", "EMP3", null, null}},
new object[] {"MGR2", 1, new object[] { "MGR1", "MGR2", null, null, null}},
new object[] {"EMP4", 2, new object[] { "MGR1", "MGR2", "EMP4", null, null}},
new object[] {"EMP5", 3, new object[] { "MGR1", "MGR2", "EMP4", "EMP5", null}},
new object[] {"EMP6", 4, new object[] { "MGR1", "MGR2", "EMP4", "EMP5", "EMP6"}},
};
// run function for each data row
var function = Functions.GetFunction(typeof(HierarchyFunctions).FullName, nameof(HierarchyFunctions.FlattenParentChild), BuiltInAssembly).GetTransformFunction(typeof(string));
foreach (var row in data)
{
function.RunFunction(row, out _, CancellationToken.None);
}
// run the result function to get flattened dataset.
var pos = 0;
for (var i = 0; i < data.Length; i++)
{
while ((bool)function.RunResult(new FunctionVariables() {Index = i}, new object[] {4}, out object[] outputs, CancellationToken.None).returnValue)
{
// first value if the leaf value
Assert.Equal(expected[pos][0], outputs[0]);
// second value is the number of levels to the top
Assert.Equal(expected[pos][1], outputs[1]);
// third value contains the flattened array.
var expectedHierarchy = (object[]) expected[pos][2];
var actualHierarchy = (object[]) outputs[2];
Assert.Equal(expectedHierarchy, actualHierarchy);
pos++;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Security;
using Microsoft.AspNet.Identity;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Web.Composing;
using Umbraco.Web.Models;
using UmbracoIdentity.Models;
using Task = System.Threading.Tasks.Task;
namespace UmbracoIdentity
{
/// <summary>
/// A custom user store that uses Umbraco member data
/// </summary>
public class UmbracoMembersUserStore<TMember> : DisposableObjectSlim,
IUserStore<TMember, int>,
IUserPasswordStore<TMember, int>,
IUserEmailStore<TMember, int>,
IUserLoginStore<TMember, int>,
IUserRoleStore<TMember, int>,
IUserSecurityStampStore<TMember, int>
where TMember : UmbracoIdentityMember, IUser<int>, new()
{
private readonly ILogger _logger;
private readonly IMemberService _memberService;
private readonly IMemberTypeService _memberTypeService;
private readonly IMemberGroupService _memberGroupService;
private readonly IdentityEnabledMembersMembershipProvider _membershipProvider;
private readonly IExternalLoginStore _externalLoginStore;
private bool _disposed = false;
private const string _emptyPasswordPrefix = "___UIDEMPTYPWORD__";
public UmbracoMembersUserStore(
ILogger logger,
IMemberService memberService,
IMemberTypeService memberTypeService,
IMemberGroupService memberGroupService,
IdentityEnabledMembersMembershipProvider membershipProvider,
IExternalLoginStore externalLoginStore)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_memberService = memberService ?? throw new ArgumentNullException("memberService");
_memberTypeService = memberTypeService;
_memberGroupService = memberGroupService ?? throw new ArgumentNullException(nameof(memberGroupService));
_membershipProvider = membershipProvider ?? throw new ArgumentNullException("membershipProvider");
_externalLoginStore = externalLoginStore ?? throw new ArgumentNullException("externalLoginStore");
if (_membershipProvider.PasswordFormat != MembershipPasswordFormat.Hashed)
{
throw new InvalidOperationException("Cannot use ASP.Net Identity with UmbracoMembersUserStore when the password format is not Hashed");
}
}
public virtual async Task CreateAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var member = _memberService.CreateMember(
user.UserName, user.Email,
user.Name.IsNullOrWhiteSpace() ? user.UserName : user.Name,
user.MemberTypeAlias.IsNullOrWhiteSpace() ? _membershipProvider.DefaultMemberTypeAlias: user.MemberTypeAlias);
UpdateMemberProperties(member, user);
//the password must be 'something' it could be empty if authenticating
// with an external provider so we'll just generate one and prefix it, the
// prefix will help us determine if the password hasn't actually been specified yet.
if (member.RawPasswordValue.IsNullOrWhiteSpace())
{
//this will hash the guid with a salt so should be nicely random
var aspHasher = new PasswordHasher();
member.RawPasswordValue = _emptyPasswordPrefix +
aspHasher.HashPassword(Guid.NewGuid().ToString("N"));
}
_memberService.Save(member);
//re-assign id
user.Id = member.Id;
if (user.LoginsChanged)
{
var logins = await GetLoginsAsync(user);
_externalLoginStore.SaveUserLogins(member.Id, logins);
}
if (user.RolesChanged)
{
IMembershipRoleService<IMember> memberRoleService = _memberService;
var persistedRoles = memberRoleService.GetAllRoles(member.Id).ToArray();
var userRoles = user.Roles.Select(x => x.RoleName).ToArray();
var keep = persistedRoles.Intersect(userRoles).ToArray();
var remove = persistedRoles.Except(keep).ToArray();
var add = userRoles.Except(persistedRoles).ToArray();
memberRoleService.DissociateRoles(new[] { member.Id }, remove);
memberRoleService.AssignRoles(new[] { member.Id }, add);
}
}
/// <summary>
/// Performs the persistence for the member
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public virtual async Task UpdateAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var asInt = user.Id.TryConvertTo<int>();
if (!asInt)
{
throw new InvalidOperationException("The user id must be an integer to work with the UmbracoMembersUserStore");
}
var found = _memberService.GetById(asInt.Result);
if (found != null)
{
if (UpdateMemberProperties(found, user))
{
_memberService.Save(found);
}
if (user.LoginsChanged)
{
var logins = await GetLoginsAsync(user);
_externalLoginStore.SaveUserLogins(found.Id, logins);
}
if (user.RolesChanged)
{
IMembershipRoleService<IMember> memberRoleService = _memberService;
var persistedRoles = memberRoleService.GetAllRoles(found.Id).ToArray();
var userRoles = user.Roles.Select(x => x.RoleName).ToArray();
var keep = persistedRoles.Intersect(userRoles).ToArray();
var remove = persistedRoles.Except(keep).ToArray();
var add = userRoles.Except(persistedRoles).ToArray();
if (remove.Any())
memberRoleService.DissociateRoles(new[] {found.Id}, remove);
if (add.Any())
memberRoleService.AssignRoles(new[] {found.Id}, add);
}
}
}
public Task DeleteAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var asInt = user.Id.TryConvertTo<int>();
if (!asInt)
{
throw new InvalidOperationException("The user id must be an integer to work with the UmbracoMembersUserStore");
}
var found = _memberService.GetById(asInt.Result);
if (found != null)
{
_memberService.Delete(found);
}
_externalLoginStore.DeleteUserLogins(asInt.Result);
return Task.FromResult(0);
}
public Task<TMember> FindByIdAsync(int userId)
{
ThrowIfDisposed();
var member = _memberService.GetById(userId);
if (member == null)
{
return Task.FromResult((TMember) null);
}
var result = AssignUserDataCallback(MapFromMember(member));
return Task.FromResult(result);
}
public Task<TMember> FindByNameAsync(string userName)
{
ThrowIfDisposed();
var member = _memberService.GetByUsername(userName);
if (member == null)
{
return Task.FromResult((TMember)null);
}
var result = AssignUserDataCallback(MapFromMember(member));
return Task.FromResult(result);
}
public Task SetPasswordHashAsync(TMember user, string passwordHash)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (passwordHash.IsNullOrWhiteSpace()) throw new ArgumentNullException("passwordHash");
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
public Task<string> GetPasswordHashAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.PasswordHash);
}
public Task<bool> HasPasswordAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.PasswordHash.IsNullOrWhiteSpace() == false);
}
public Task SetEmailAsync(TMember user, string email)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (email.IsNullOrWhiteSpace()) throw new ArgumentNullException("email");
user.Email = email;
return Task.FromResult(0);
}
public Task<string> GetEmailAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.Email);
}
public virtual Task<bool> GetEmailConfirmedAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
throw new NotImplementedException();
}
public virtual Task SetEmailConfirmedAsync(TMember user, bool confirmed)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
throw new NotImplementedException();
}
public Task<TMember> FindByEmailAsync(string email)
{
ThrowIfDisposed();
var member = _memberService.GetByEmail(email);
var result = member == null
? null
: MapFromMember(member);
var r = AssignUserDataCallback(result);
return Task.FromResult(r);
}
public Task AddLoginAsync(TMember user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (login == null) throw new ArgumentNullException("login");
var logins = user.Logins;
var instance = new IdentityMemberLogin<int>
{
UserId = user.Id,
ProviderKey = login.ProviderKey,
LoginProvider = login.LoginProvider
};
var userLogin = instance;
logins.Add(userLogin);
return Task.FromResult(0);
}
public Task RemoveLoginAsync(TMember user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (login == null) throw new ArgumentNullException("login");
var provider = login.LoginProvider;
var key = login.ProviderKey;
var userLogin = user.Logins.SingleOrDefault((l => l.LoginProvider == provider && l.ProviderKey == key));
if (userLogin != null)
user.Logins.Remove(userLogin);
return Task.FromResult(0);
}
public Task<IList<UserLoginInfo>> GetLoginsAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var result = (IList<UserLoginInfo>)
user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey)).ToList();
return Task.FromResult(result);
}
public Task<TMember> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
//get all logins associated with the login id
var result = _externalLoginStore.Find(login).ToArray();
if (result.Any())
{
//return the first member that matches the result
var user = (from id in result
select _memberService.GetById(id)
into member
where member != null
select MapFromMember(member)).FirstOrDefault();
return Task.FromResult(AssignUserDataCallback(user));
}
return Task.FromResult((TMember)null);
}
/// <summary>
/// Adds a user to a role
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task AddToRoleAsync(TMember user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (string.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException("roleName is null or empty");
}
var roleEntity = _memberGroupService.GetByName(roleName);
if (roleEntity == null)
{
throw new InvalidOperationException(roleName + " does not exist as a role");
}
var roles = user.Roles;
var instance = new IdentityMemberRole { UserId = user.Id, RoleName = roleEntity.Name };
var userRole = instance;
roles.Add(userRole);
return Task.FromResult(0);
}
/// <summary>
/// Removes the role for the user
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task RemoveFromRoleAsync(TMember user, string roleName)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
if (string.IsNullOrWhiteSpace(roleName))
{
throw new ArgumentException("roleName is null or empty");
}
var memberRole = user.Roles.SingleOrDefault(l => l.RoleName.InvariantEquals(roleName));
if (memberRole != null)
user.Roles.Remove(memberRole);
return Task.FromResult(0);
}
/// <summary>
/// Returns the roles for this user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<IList<string>> GetRolesAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult((IList<string>) new List<string>(user.Roles.Select(l => l.RoleName)));
}
/// <summary>
/// Returns true if a user is in the role
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task<bool> IsInRoleAsync(TMember user, string roleName)
{
ThrowIfDisposed();
return Task.FromResult(user.Roles.Any(x => x.RoleName.InvariantEquals(roleName)));
}
public Task SetSecurityStampAsync(TMember user, string stamp)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException(nameof(user));
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
public Task<string> GetSecurityStampAsync(TMember user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException(nameof(user));
//the stamp cannot be null, so if it is currently null then we'll just return a hash of the password
return Task.FromResult(user.SecurityStamp.IsNullOrWhiteSpace()
//ensure that the stored password is not empty either! it shouldn't be but just in case we'll return a new guid
? (user.StoredPassword.IsNullOrWhiteSpace() ? Guid.NewGuid().ToString() : user.StoredPassword.GenerateHash())
: user.SecurityStamp);
}
protected override void DisposeResources()
{
_disposed = true;
}
/// <summary>
/// Maps the data from <see cref="IMember"/> back to the <see cref="TMember"/> when retreived from the data source
/// </summary>
/// <param name="member"></param>
/// <returns></returns>
protected virtual TMember MapFromMember(IMember member)
{
var result = new TMember
{
Email = member.Email,
Id = member.Id,
LockoutEnabled = member.IsLockedOut,
LockoutEndDateUtc = DateTime.MaxValue.ToUniversalTime(),
UserName = member.Username,
PasswordHash = GetPasswordHash(member.RawPasswordValue),
StoredPassword = member.RawPasswordValue,
Name = member.Name,
MemberTypeAlias = member.ContentTypeAlias
};
bool propertyTypeExists;
var memberSecurityStamp = member.GetSecurityStamp(out propertyTypeExists);
if (!propertyTypeExists)
{
_logger.Warn<UmbracoMembersUserStore<TMember>>($"The {UmbracoIdentityConstants.SecurityStampProperty} does not exist on the member type {member.ContentType.Alias}, see docs on how to fix: https://github.com/Shazwazza/UmbracoIdentity/wiki");
}
else
{
result.SecurityStamp = memberSecurityStamp;
}
result.MemberProperties = GetMemberProperties(member).ToList();
return result;
}
private IEnumerable<UmbracoProperty> GetMemberProperties(IMember member)
{
var builtIns = Umbraco.Core.Constants.Conventions.Member.GetStandardPropertyTypeStubs()
.Select(x => x.Key).ToArray();
var memberType = _memberTypeService.Get(member.ContentTypeId);
var viewProperties = new List<UmbracoProperty>();
foreach (var prop in memberType.PropertyTypes.Where(x => builtIns.Contains(x.Alias) == false))
{
var value = string.Empty;
var propValue = member.Properties[prop.Alias];
if (propValue != null && propValue.GetValue() != null)
{
value = propValue.GetValue().ToString();
}
var viewProperty = new UmbracoProperty
{
Alias = prop.Alias,
Name = prop.Name,
Value = value
};
viewProperties.Add(viewProperty);
}
return viewProperties;
}
/// <summary>
/// Called to update the <see cref="IMember"/> instance to be persisted from the <see cref="TMember"/>
/// </summary>
/// <param name="member"></param>
/// <param name="user"></param>
/// <returns>Returns true if any property values were changed</returns>
protected virtual bool UpdateMemberProperties(IMember member, TMember user)
{
var anythingChanged = false;
//don't assign anything if nothing has changed as this will trigger
//the track changes of the model
if (member.Name != user.Name && user.Name.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
member.Name = user.Name;
}
if (member.Email != user.Email && user.Email.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
member.Email = user.Email;
}
if (member.FailedPasswordAttempts != user.AccessFailedCount)
{
anythingChanged = true;
member.FailedPasswordAttempts = user.AccessFailedCount;
}
if (member.IsLockedOut != user.LockoutEnabled)
{
anythingChanged = true;
member.IsLockedOut = user.LockoutEnabled;
}
if (member.Username != user.UserName && user.UserName.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
member.Username = user.UserName;
}
if (member.RawPasswordValue != user.PasswordHash && user.PasswordHash.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
member.RawPasswordValue = user.PasswordHash;
}
bool propertyTypeExists;
var memberSecurityStamp = member.GetSecurityStamp(out propertyTypeExists);
if (memberSecurityStamp != null && memberSecurityStamp != user.SecurityStamp)
{
anythingChanged = true;
member.Properties[UmbracoIdentityConstants.SecurityStampProperty].SetValue(user.SecurityStamp);
}
if (user.MemberProperties != null)
{
var memberType = _memberTypeService.Get(member.ContentTypeId);
foreach (var property in user.MemberProperties
//ensure the property they are posting exists
.Where(p => memberType.PropertyTypeExists(p.Alias))
.Where(p => member.Properties.Contains(p.Alias))
//needs to be editable
.Where(p => memberType.MemberCanEditProperty(p.Alias))
//needs to be different
.Where(p =>
{
var mPropAsString = member.Properties[p.Alias].GetValue() == null ? string.Empty : member.Properties[p.Alias].GetValue().ToString();
var uPropAsString = p.Value ?? string.Empty;
return mPropAsString != uPropAsString;
}))
{
anythingChanged = true;
member.Properties[property.Alias].SetValue(property.Value);
}
}
return anythingChanged;
}
/// <summary>
/// This checks if the password
/// </summary>
/// <param name="storedPass"></param>
/// <returns></returns>
private string GetPasswordHash(string storedPass)
{
return storedPass.StartsWith(_emptyPasswordPrefix) ? null : storedPass;
}
/// <summary>
/// This is used to assign the lazy callbacks for the user's data collections
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
private TMember AssignUserDataCallback(TMember user)
{
if (user != null)
{
user.SetLoginsCallback(new Lazy<IEnumerable<IdentityMemberLogin<int>>>(() =>
_externalLoginStore.GetAll(user.Id)));
user.SetRolesCallback(new Lazy<IEnumerable<IdentityMemberRole<int>>>(() =>
{
IMembershipRoleService<IMember> memberRoleService = _memberService;
var roles = memberRoleService.GetAllRoles(user.Id);
return roles.Select(x => new IdentityMemberRole()
{
RoleName = x,
UserId = user.Id
});
}));
}
return user;
}
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// QueuedMap.cs
//
//
// A key-value pair queue, where pushing an existing key into the collection overwrites
// the existing value.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Threading.Tasks.Dataflow.Internal
{
/// <summary>
/// Provides a data structure that supports pushing and popping key/value pairs.
/// Pushing a key/value pair for which the key already exists results in overwriting
/// the existing key entry's value.
/// </summary>
/// <typeparam name="TKey">Specifies the type of keys in the map.</typeparam>
/// <typeparam name="TValue">Specifies the type of values in the map.</typeparam>
/// <remarks>This type is not thread-safe.</remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(EnumerableDebugView<,>))]
internal sealed class QueuedMap<TKey, TValue>
{
/// <summary>
/// A queue structure that uses an array-based list to store its items
/// and that supports overwriting elements at specific indices.
/// </summary>
/// <typeparam name="T">The type of the items storedin the queue</typeparam>
/// <remarks>This type is not thread-safe.</remarks>
private sealed class ArrayBasedLinkedQueue<T>
{
/// <summary>Terminator index.</summary>
private const int TERMINATOR_INDEX = -1;
/// <summary>
/// The queue where the items will be stored.
/// The key of each entry is the index of the next entry in the queue.
/// </summary>
private readonly List<KeyValuePair<int, T>> _storage;
/// <summary>Index of the first queue item.</summary>
private int _headIndex = TERMINATOR_INDEX;
/// <summary>Index of the last queue item.</summary>
private int _tailIndex = TERMINATOR_INDEX;
/// <summary>Index of the first free slot.</summary>
private int _freeIndex = TERMINATOR_INDEX;
/// <summary>Initializes the Queue instance.</summary>
internal ArrayBasedLinkedQueue()
{
_storage = new List<KeyValuePair<int, T>>();
}
/// <summary>Initializes the Queue instance.</summary>
/// <param name="capacity">The capacity of the internal storage.</param>
internal ArrayBasedLinkedQueue(int capacity)
{
_storage = new List<KeyValuePair<int, T>>(capacity);
}
/// <summary>Enqueues an item.</summary>
/// <param name="item">The item to be enqueued.</param>
/// <returns>The index of the slot where item was stored.</returns>
internal int Enqueue(T item)
{
int newIndex;
// If there is a free slot, reuse it
if (_freeIndex != TERMINATOR_INDEX)
{
Debug.Assert(0 <= _freeIndex && _freeIndex < _storage.Count, "Index is out of range.");
newIndex = _freeIndex;
_freeIndex = _storage[_freeIndex].Key;
_storage[newIndex] = new KeyValuePair<int, T>(TERMINATOR_INDEX, item);
}
// If there is no free slot, add one
else
{
newIndex = _storage.Count;
_storage.Add(new KeyValuePair<int, T>(TERMINATOR_INDEX, item));
}
if (_headIndex == TERMINATOR_INDEX)
{
// Point _headIndex to newIndex if the queue was empty
Debug.Assert(_tailIndex == TERMINATOR_INDEX, "If head indicates empty, so too should tail.");
_headIndex = newIndex;
}
else
{
// Point the tail slot to newIndex if the queue was not empty
Debug.Assert(_tailIndex != TERMINATOR_INDEX, "If head does not indicate empty, neither should tail.");
_storage[_tailIndex] = new KeyValuePair<int, T>(newIndex, _storage[_tailIndex].Value);
}
// Point the tail slot newIndex
_tailIndex = newIndex;
return newIndex;
}
/// <summary>Tries to dequeue an item.</summary>
/// <param name="item">The item that is dequeued.</param>
internal bool TryDequeue(out T item)
{
// If the queue is empty, just initialize the output item and return false
if (_headIndex == TERMINATOR_INDEX)
{
Debug.Assert(_tailIndex == TERMINATOR_INDEX, "If head indicates empty, so too should tail.");
item = default(T);
return false;
}
// If there are items in the queue, start with populating the output item
Debug.Assert(0 <= _headIndex && _headIndex < _storage.Count, "Head is out of range.");
item = _storage[_headIndex].Value;
// Move the popped slot to the head of the free list
int newHeadIndex = _storage[_headIndex].Key;
_storage[_headIndex] = new KeyValuePair<int, T>(_freeIndex, default(T));
_freeIndex = _headIndex;
_headIndex = newHeadIndex;
if (_headIndex == TERMINATOR_INDEX) _tailIndex = TERMINATOR_INDEX;
return true;
}
/// <summary>Replaces the item of a given slot.</summary>
/// <param name="index">The index of the slot where the value should be replaced.</param>
/// <param name="item">The item to be places.</param>
internal void Replace(int index, T item)
{
Debug.Assert(0 <= index && index < _storage.Count, "Index is out of range.");
#if DEBUG
// Also assert that index does not belong to the list of free slots
for (int idx = _freeIndex; idx != TERMINATOR_INDEX; idx = _storage[idx].Key)
Debug.Assert(idx != index, "Index should not belong to the list of free slots.");
#endif
_storage[index] = new KeyValuePair<int, T>(_storage[index].Key, item);
}
internal bool IsEmpty { get { return _headIndex == TERMINATOR_INDEX; } }
}
/// <summary>The queue of elements.</summary>
private readonly ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>> _queue;
/// <summary>A map from key to index into the list.</summary>
/// <remarks>The correctness of this map relies on the list only having elements removed from its end.</remarks>
private readonly Dictionary<TKey, int> _mapKeyToIndex;
/// <summary>Initializes the QueuedMap.</summary>
internal QueuedMap()
{
_queue = new ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>>();
_mapKeyToIndex = new Dictionary<TKey, int>();
}
/// <summary>Initializes the QueuedMap.</summary>
/// <param name="capacity">The initial capacity of the data structure.</param>
internal QueuedMap(int capacity)
{
_queue = new ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>>(capacity);
_mapKeyToIndex = new Dictionary<TKey, int>(capacity);
}
/// <summary>Pushes a key/value pair into the data structure.</summary>
/// <param name="key">The key for the pair.</param>
/// <param name="value">The value for the pair.</param>
internal void Push(TKey key, TValue value)
{
// Try to get the index of the key in the queue. If it's there, replace the value.
int indexOfKeyInQueue;
if (!_queue.IsEmpty && _mapKeyToIndex.TryGetValue(key, out indexOfKeyInQueue))
{
_queue.Replace(indexOfKeyInQueue, new KeyValuePair<TKey, TValue>(key, value));
}
// If it's not there, add it to the queue and then add the mapping.
else
{
indexOfKeyInQueue = _queue.Enqueue(new KeyValuePair<TKey, TValue>(key, value));
_mapKeyToIndex.Add(key, indexOfKeyInQueue);
}
}
/// <summary>Try to pop the next element from the data structure.</summary>
/// <param name="item">The popped pair.</param>
/// <returns>true if an item could be popped; otherwise, false.</returns>
internal bool TryPop(out KeyValuePair<TKey, TValue> item)
{
bool popped = _queue.TryDequeue(out item);
if (popped) _mapKeyToIndex.Remove(item.Key);
return popped;
}
/// <summary>Tries to pop one or more elements from the data structure.</summary>
/// <param name="items">The items array into which the popped elements should be stored.</param>
/// <param name="arrayOffset">The offset into the array at which to start storing popped items.</param>
/// <param name="count">The number of items to be popped.</param>
/// <returns>The number of items popped, which may be less than the requested number if fewer existed in the data structure.</returns>
internal int PopRange(KeyValuePair<TKey, TValue>[] items, int arrayOffset, int count)
{
// As this data structure is internal, only assert incorrect usage.
// If this were to ever be made public, these would need to be real argument checks.
Contract.Requires(items != null, "Requires non-null array to store into.");
Contract.Requires(count >= 0 && arrayOffset >= 0, "Count and offset must be non-negative");
Contract.Requires(arrayOffset + count >= 0, "Offset plus count overflowed");
Contract.Requires(arrayOffset + count <= items.Length, "Range must be within array size");
int actualCount = 0;
for (int i = arrayOffset; actualCount < count; i++, actualCount++)
{
KeyValuePair<TKey, TValue> item;
if (TryPop(out item)) items[i] = item;
else break;
}
return actualCount;
}
/// <summary>Gets the number of items in the data structure.</summary>
internal int Count { get { return _mapKeyToIndex.Count; } }
}
}
| |
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using NetUtils = Raksha.Utilities.Net;
namespace Raksha.Asn1.X509
{
/**
* The GeneralName object.
* <pre>
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER}
*
* OtherName ::= Sequence {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
*
* EDIPartyName ::= Sequence {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
* </pre>
*/
public class GeneralName
: Asn1Encodable, IAsn1Choice
{
public const int OtherName = 0;
public const int Rfc822Name = 1;
public const int DnsName = 2;
public const int X400Address = 3;
public const int DirectoryName = 4;
public const int EdiPartyName = 5;
public const int UniformResourceIdentifier = 6;
public const int IPAddress = 7;
public const int RegisteredID = 8;
internal readonly Asn1Encodable obj;
internal readonly int tag;
public GeneralName(
X509Name directoryName)
{
this.obj = directoryName;
this.tag = 4;
}
/**
* When the subjectAltName extension contains an Internet mail address,
* the address MUST be included as an rfc822Name. The format of an
* rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
*
* When the subjectAltName extension contains a domain name service
* label, the domain name MUST be stored in the dNSName (an IA5String).
* The name MUST be in the "preferred name syntax," as specified by RFC
* 1034 [RFC 1034].
*
* When the subjectAltName extension contains a URI, the name MUST be
* stored in the uniformResourceIdentifier (an IA5String). The name MUST
* be a non-relative URL, and MUST follow the URL syntax and encoding
* rules specified in [RFC 1738]. The name must include both a scheme
* (e.g., "http" or "ftp") and a scheme-specific-part. The scheme-
* specific-part must include a fully qualified domain name or IP
* address as the host.
*
* When the subjectAltName extension contains a iPAddress, the address
* MUST be stored in the octet string in "network byte order," as
* specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
* each octet is the LSB of the corresponding byte in the network
* address. For IP Version 4, as specified in RFC 791, the octet string
* MUST contain exactly four octets. For IP Version 6, as specified in
* RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
* 1883].
*/
public GeneralName(
Asn1Object name,
int tag)
{
this.obj = name;
this.tag = tag;
}
public GeneralName(
int tag,
Asn1Encodable name)
{
this.obj = name;
this.tag = tag;
}
/**
* Create a GeneralName for the given tag from the passed in string.
* <p>
* This constructor can handle:
* <ul>
* <li>rfc822Name</li>
* <li>iPAddress</li>
* <li>directoryName</li>
* <li>dNSName</li>
* <li>uniformResourceIdentifier</li>
* <li>registeredID</li>
* </ul>
* For x400Address, otherName and ediPartyName there is no common string
* format defined.
* </p><p>
* Note: A directory name can be encoded in different ways into a byte
* representation. Be aware of this if the byte representation is used for
* comparing results.
* </p>
*
* @param tag tag number
* @param name string representation of name
* @throws ArgumentException if the string encoding is not correct or
* not supported.
*/
public GeneralName(
int tag,
string name)
{
this.tag = tag;
if (tag == Rfc822Name || tag == DnsName || tag == UniformResourceIdentifier)
{
this.obj = new DerIA5String(name);
}
else if (tag == RegisteredID)
{
this.obj = new DerObjectIdentifier(name);
}
else if (tag == DirectoryName)
{
this.obj = new X509Name(name);
}
else if (tag == IPAddress)
{
byte[] enc = toGeneralNameEncoding(name);
if (enc == null)
throw new ArgumentException("IP Address is invalid", "name");
this.obj = new DerOctetString(enc);
}
else
{
throw new ArgumentException("can't process string for tag: " + tag, "tag");
}
}
public static GeneralName GetInstance(
object obj)
{
if (obj == null || obj is GeneralName)
{
return (GeneralName) obj;
}
if (obj is Asn1TaggedObject)
{
Asn1TaggedObject tagObj = (Asn1TaggedObject) obj;
int tag = tagObj.TagNo;
switch (tag)
{
case OtherName:
return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false));
case Rfc822Name:
return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
case DnsName:
return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
case X400Address:
throw new ArgumentException("unknown tag: " + tag);
case DirectoryName:
return new GeneralName(tag, X509Name.GetInstance(tagObj, true));
case EdiPartyName:
return new GeneralName(tag, Asn1Sequence.GetInstance(tagObj, false));
case UniformResourceIdentifier:
return new GeneralName(tag, DerIA5String.GetInstance(tagObj, false));
case IPAddress:
return new GeneralName(tag, Asn1OctetString.GetInstance(tagObj, false));
case RegisteredID:
return new GeneralName(tag, DerObjectIdentifier.GetInstance(tagObj, false));
}
}
throw new ArgumentException("unknown object in GetInstance: " + obj.GetType().FullName, "obj");
}
public static GeneralName GetInstance(
Asn1TaggedObject tagObj,
bool explicitly)
{
return GetInstance(Asn1TaggedObject.GetInstance(tagObj, true));
}
public int TagNo
{
get { return tag; }
}
public Asn1Encodable Name
{
get { return obj; }
}
public override string ToString()
{
StringBuilder buf = new StringBuilder();
buf.Append(tag);
buf.Append(": ");
switch (tag)
{
case Rfc822Name:
case DnsName:
case UniformResourceIdentifier:
buf.Append(DerIA5String.GetInstance(obj).GetString());
break;
case DirectoryName:
buf.Append(X509Name.GetInstance(obj).ToString());
break;
default:
buf.Append(obj.ToString());
break;
}
return buf.ToString();
}
private byte[] toGeneralNameEncoding(
string ip)
{
if (Raksha.Utilities.Net.IPAddress.IsValidIPv6WithNetmask(ip) || Raksha.Utilities.Net.IPAddress.IsValidIPv6(ip))
{
int slashIndex = ip.IndexOf('/');
if (slashIndex < 0)
{
byte[] addr = new byte[16];
int[] parsedIp = parseIPv6(ip);
copyInts(parsedIp, addr, 0);
return addr;
}
else
{
byte[] addr = new byte[32];
int[] parsedIp = parseIPv6(ip.Substring(0, slashIndex));
copyInts(parsedIp, addr, 0);
string mask = ip.Substring(slashIndex + 1);
if (mask.IndexOf(':') > 0)
{
parsedIp = parseIPv6(mask);
}
else
{
parsedIp = parseMask(mask);
}
copyInts(parsedIp, addr, 16);
return addr;
}
}
else if (Raksha.Utilities.Net.IPAddress.IsValidIPv4WithNetmask(ip) || Raksha.Utilities.Net.IPAddress.IsValidIPv4(ip))
{
int slashIndex = ip.IndexOf('/');
if (slashIndex < 0)
{
byte[] addr = new byte[4];
parseIPv4(ip, addr, 0);
return addr;
}
else
{
byte[] addr = new byte[8];
parseIPv4(ip.Substring(0, slashIndex), addr, 0);
string mask = ip.Substring(slashIndex + 1);
if (mask.IndexOf('.') > 0)
{
parseIPv4(mask, addr, 4);
}
else
{
parseIPv4Mask(mask, addr, 4);
}
return addr;
}
}
return null;
}
private void parseIPv4Mask(string mask, byte[] addr, int offset)
{
int maskVal = Int32.Parse(mask);
for (int i = 0; i != maskVal; i++)
{
addr[(i / 8) + offset] |= (byte)(1 << (i % 8));
}
}
private void parseIPv4(string ip, byte[] addr, int offset)
{
foreach (string token in ip.Split('.', '/'))
{
addr[offset++] = (byte)Int32.Parse(token);
}
}
private int[] parseMask(string mask)
{
int[] res = new int[8];
int maskVal = Int32.Parse(mask);
for (int i = 0; i != maskVal; i++)
{
res[i / 16] |= 1 << (i % 16);
}
return res;
}
private void copyInts(int[] parsedIp, byte[] addr, int offSet)
{
for (int i = 0; i != parsedIp.Length; i++)
{
addr[(i * 2) + offSet] = (byte)(parsedIp[i] >> 8);
addr[(i * 2 + 1) + offSet] = (byte)parsedIp[i];
}
}
private int[] parseIPv6(string ip)
{
if (ip.StartsWith("::"))
{
ip = ip.Substring(1);
}
else if (ip.EndsWith("::"))
{
ip = ip.Substring(0, ip.Length - 1);
}
IEnumerator sEnum = ip.Split(':').GetEnumerator();
int index = 0;
int[] val = new int[8];
int doubleColon = -1;
while (sEnum.MoveNext())
{
string e = (string) sEnum.Current;
if (e.Length == 0)
{
doubleColon = index;
val[index++] = 0;
}
else
{
if (e.IndexOf('.') < 0)
{
val[index++] = Int32.Parse(e, NumberStyles.AllowHexSpecifier);
}
else
{
string[] tokens = e.Split('.');
val[index++] = (Int32.Parse(tokens[0]) << 8) | Int32.Parse(tokens[1]);
val[index++] = (Int32.Parse(tokens[2]) << 8) | Int32.Parse(tokens[3]);
}
}
}
if (index != val.Length)
{
Array.Copy(val, doubleColon, val, val.Length - (index - doubleColon), index - doubleColon);
for (int i = doubleColon; i != val.Length - (index - doubleColon); i++)
{
val[i] = 0;
}
}
return val;
}
public override Asn1Object ToAsn1Object()
{
// Explicitly tagged if DirectoryName
return new DerTaggedObject(tag == DirectoryName, tag, obj);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008-2015 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
namespace NUnit.Framework
{
/// <summary>
/// Identifies the source used to provide test fixture instances for a test class.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class TestFixtureSourceAttribute : NUnitAttribute, IFixtureBuilder2
{
private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder();
/// <summary>
/// Error message string is public so the tests can use it
/// </summary>
public const string MUST_BE_STATIC = "The sourceName specified on a TestCaseSourceAttribute must refer to a static field, property or method.";
#region Constructors
/// <summary>
/// Construct with the name of the method, property or field that will provide data
/// </summary>
/// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
public TestFixtureSourceAttribute(string sourceName)
{
this.SourceName = sourceName;
}
/// <summary>
/// Construct with a Type and name
/// </summary>
/// <param name="sourceType">The Type that will provide data</param>
/// <param name="sourceName">The name of a static method, property or field that will provide data.</param>
public TestFixtureSourceAttribute(Type sourceType, string sourceName)
{
this.SourceType = sourceType;
this.SourceName = sourceName;
}
/// <summary>
/// Construct with a Type
/// </summary>
/// <param name="sourceType">The type that will provide data</param>
public TestFixtureSourceAttribute(Type sourceType)
{
this.SourceType = sourceType;
}
#endregion
#region Properties
/// <summary>
/// The name of a the method, property or fiend to be used as a source
/// </summary>
public string SourceName { get; }
/// <summary>
/// A Type to be used as a source
/// </summary>
public Type SourceType { get; }
/// <summary>
/// Gets or sets the category associated with every fixture created from
/// this attribute. May be a single category or a comma-separated list.
/// </summary>
public string Category { get; set; }
#endregion
#region IFixtureBuilder Members
/// <summary>
/// Builds any number of test fixtures from the specified type.
/// </summary>
/// <param name="typeInfo">The TypeInfo for which fixtures are to be constructed.</param>
public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo)
{
return BuildFrom(typeInfo, PreFilter.Empty);
}
#endregion
#region IFixtureBuilder2 Members
/// <summary>
/// Builds any number of test fixtures from the specified type.
/// </summary>
/// <param name="typeInfo">The TypeInfo for which fixtures are to be constructed.</param>
/// <param name="filter">PreFilter used to select methods as tests.</param>
public IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo, IPreFilter filter)
{
Type sourceType = SourceType ?? typeInfo.Type;
foreach (ITestFixtureData parms in GetParametersFor(sourceType))
yield return _builder.BuildFrom(typeInfo, filter, parms);
}
#endregion
#region Helper Methods
/// <summary>
/// Returns a set of ITestFixtureData items for use as arguments
/// to a parameterized test fixture.
/// </summary>
/// <param name="sourceType">The type for which data is needed.</param>
/// <returns></returns>
public IEnumerable<ITestFixtureData> GetParametersFor(Type sourceType)
{
List<ITestFixtureData> data = new List<ITestFixtureData>();
try
{
IEnumerable source = GetTestFixtureSource(sourceType);
if (source != null)
{
foreach (object item in source)
{
var parms = item as ITestFixtureData;
if (parms == null)
{
object[] args = item as object[];
if (args == null)
{
args = new object[] { item };
}
parms = new TestFixtureParameters(args);
}
if (this.Category != null)
foreach (string cat in this.Category.Split(new char[] { ',' }))
parms.Properties.Add(PropertyNames.Category, cat);
data.Add(parms);
}
}
}
catch (Exception ex)
{
data.Clear();
data.Add(new TestFixtureParameters(ex));
}
return data;
}
private IEnumerable GetTestFixtureSource(Type sourceType)
{
// Handle Type implementing IEnumerable separately
if (SourceName == null)
return Reflect.Construct(sourceType) as IEnumerable;
MemberInfo[] members = sourceType.GetMember(SourceName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
if (members.Length == 1)
{
MemberInfo member = members[0];
var field = member as FieldInfo;
if (field != null)
return field.IsStatic
? (IEnumerable)field.GetValue(null)
: SourceMustBeStaticError();
var property = member as PropertyInfo;
if (property != null)
return property.GetGetMethod(true).IsStatic
? (IEnumerable)property.GetValue(null, null)
: SourceMustBeStaticError();
var m = member as MethodInfo;
if (m != null)
return m.IsStatic
? (IEnumerable)m.Invoke(null, null)
: SourceMustBeStaticError();
}
return null;
}
private static IEnumerable SourceMustBeStaticError()
{
var parms = new TestFixtureParameters();
parms.RunState = RunState.NotRunnable;
parms.Properties.Set(PropertyNames.SkipReason, MUST_BE_STATIC);
return new TestFixtureParameters[] { parms };
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Cottle.Maps;
using Cottle.Parsers;
using Moq;
using NUnit.Framework;
namespace Cottle.Test.Parsers
{
public class OptimizeParserTester
{
private static readonly Expression ImpureFunction =
Expression.CreateConstant(
Value.FromFunction(Function.Create((state, arguments, output) => Value.Undefined)));
private static readonly Expression PureFunction =
Expression.CreateConstant(Value.FromFunction(Function.CreatePure((s, a) => 0)));
[Test]
public void Parse_ExpressionAccess_FindWhenPresentInConstantIndices()
{
// Expression: [0: AAA, 1: BBB, 2: pure()][1]
// Result: BBB
var expression = OptimizeParserTester.Optimize(Expression.CreateAccess(Expression.CreateMap(
new[]
{
new ExpressionElement(Expression.CreateConstant(0),
Expression.CreateSymbol("AAA")),
new ExpressionElement(Expression.CreateConstant(1),
Expression.CreateSymbol("BBB")),
new ExpressionElement(Expression.CreateConstant(2),
Expression.CreateInvoke(OptimizeParserTester.PureFunction, Array.Empty<Expression>()))
}),
Expression.CreateConstant(1)
));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Symbol));
Assert.That(expression.Value, Is.EqualTo((Value)"BBB"));
}
[Test]
public void Parse_ExpressionAccess_FindWhenMissingFromConstantIndices()
{
// Expression: [0: AAA, 1: BBB, 2: CCC][3]
// Result: <void>
var expression = OptimizeParserTester.Optimize(Expression.CreateAccess(Expression.CreateMap(
new[]
{
new ExpressionElement(Expression.CreateConstant(0),
Expression.CreateSymbol("AAA")),
new ExpressionElement(Expression.CreateConstant(1),
Expression.CreateSymbol("BBB")),
new ExpressionElement(Expression.CreateConstant(2),
Expression.CreateSymbol("CCC"))
}),
Expression.CreateConstant(3)
));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(expression.Value, Is.EqualTo(Value.Undefined));
}
[Test]
public void Parse_ExpressionAccess_FindNestedConstantExpressions()
{
// Expression: [17: [3: 42][3]][[2: 17][2]]
// Result: 42
const int value = 42;
var index1 = Expression.CreateConstant(17);
var index2 = Expression.CreateConstant(3);
var index3 = Expression.CreateConstant(2);
var expression = OptimizeParserTester.Optimize(Expression.CreateAccess(
Expression.CreateMap(new[]
{
new ExpressionElement(index1,
Expression.CreateAccess(
Expression.CreateMap(new[]
{ new ExpressionElement(index2, Expression.CreateConstant(value)) }), index2))
}),
Expression.CreateAccess(Expression.CreateMap(new[] { new ExpressionElement(index3, index1) }),
index3)));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(expression.Value, Is.EqualTo((Value)value));
}
[Test]
public void Parse_ExpressionAccess_SkipWhenNonPureIndices()
{
// Expression: [0: AAA, 1: BBB, x: CCC][3]
var expression = OptimizeParserTester.Optimize(Expression.CreateAccess(Expression.CreateMap(
new[]
{
new ExpressionElement(Expression.CreateConstant(0),
Expression.CreateSymbol("AAA")),
new ExpressionElement(Expression.CreateConstant(1),
Expression.CreateSymbol("BBB")),
new ExpressionElement(Expression.CreateSymbol("x"),
Expression.CreateSymbol("CCC"))
}),
Expression.CreateConstant(3)
));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Access));
}
[Test]
public void Parse_ExpressionMap_FoldConstantArray()
{
// Expression: [0: "X", 1: "Y", 2: "Z"]
// Result: <array map>
var expression = OptimizeParserTester.Optimize(Expression.CreateMap(new[]
{
new ExpressionElement(Expression.CreateConstant(0), Expression.CreateConstant("X")),
new ExpressionElement(Expression.CreateConstant(1), Expression.CreateConstant("Y")),
new ExpressionElement(Expression.CreateConstant(2), Expression.CreateConstant("Z"))
}));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(expression.Value.Fields, Is.TypeOf(typeof(ArrayMap)));
Assert.That(expression.Value, Is.EqualTo((Value)new Value[] { "X", "Y", "Z" }));
}
[Test]
public void Parse_ExpressionMap_FoldConstantMix()
{
// Expression: [0: "X", 2: "Y", 1: "Z"]
// Result: <mix map>
var expression = OptimizeParserTester.Optimize(Expression.CreateMap(new[]
{
new ExpressionElement(Expression.CreateConstant(0), Expression.CreateConstant("X")),
new ExpressionElement(Expression.CreateConstant(2), Expression.CreateConstant("Y")),
new ExpressionElement(Expression.CreateConstant(1), Expression.CreateConstant("Z"))
}));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(expression.Value.Fields, Is.TypeOf(typeof(MixMap)));
Assert.That(expression.Value, Is.EqualTo((Value)new[]
{
new KeyValuePair<Value, Value>(0, "X"),
new KeyValuePair<Value, Value>(2, "Y"),
new KeyValuePair<Value, Value>(1, "Z")
}));
}
[Test]
public void Parse_ExpressionMap_SkipDynamic()
{
// Expression: [0: "X", 1: "Y", x: "Z"]
var expression = OptimizeParserTester.Optimize(Expression.CreateMap(new[]
{
new ExpressionElement(Expression.CreateConstant(0), Expression.CreateConstant("X")),
new ExpressionElement(Expression.CreateConstant(1), Expression.CreateSymbol("Y")),
new ExpressionElement(Expression.CreateConstant(2), Expression.CreateConstant("Z"))
}));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Map));
}
[Test]
public void Parse_ExpressionInvoke_CallPureFunction()
{
// Expression: pure(1, 2)
// Result: 3
var function = Function.CreatePure2((state, a, b) => 3);
var expression = OptimizeParserTester.Optimize(Expression.CreateInvoke(
Expression.CreateConstant(Value.FromFunction(function)),
new[] { Expression.CreateConstant(1), Expression.CreateConstant(2) }));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(expression.Value, Is.EqualTo((Value)3));
}
[Test]
public void Parse_ExpressionInvoke_ResolveNotAFunction()
{
// Expression: 1()
// Result: <void>
var expression =
OptimizeParserTester.Optimize(Expression.CreateInvoke(Expression.CreateConstant(1),
Array.Empty<Expression>()));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(expression.Value, Is.EqualTo(Value.Undefined));
}
[Test]
public void Parse_ExpressionInvoke_SkipImpureFunction()
{
// Expression: impure(1, 2)
var expression = OptimizeParserTester.Optimize(Expression.CreateInvoke(OptimizeParserTester.ImpureFunction,
new[]
{
Expression.CreateConstant(1),
Expression.CreateConstant(2)
}));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Invoke));
}
[Test]
public void Parse_ExpressionInvoke_SkipSymbolArgument()
{
// Expression: pure(1, x)
var expression = OptimizeParserTester.Optimize(Expression.CreateInvoke(OptimizeParserTester.PureFunction,
new[]
{
Expression.CreateConstant(1),
Expression.CreateSymbol("x"),
}));
Assert.That(expression.Type, Is.EqualTo(ExpressionType.Invoke));
}
[Test]
public void Parse_StatementReturn()
{
// Statement: X{return 1}Y
// Result: X{return 1}
var statement = OptimizeParserTester.Optimize(Statement.CreateComposite(Statement.CreateLiteral("X"),
Statement.CreateComposite(Statement.CreateReturn(Expression.CreateConstant(1)),
Statement.CreateLiteral("Y"))));
Assert.That(statement.Type, Is.EqualTo(StatementType.Composite));
Assert.That(statement.Body.Type, Is.EqualTo(StatementType.Literal));
Assert.That(statement.Body.Value, Is.EqualTo("X"));
Assert.That(statement.Next.Type, Is.EqualTo(StatementType.Return));
Assert.That(statement.Next.Operand.Type, Is.EqualTo(ExpressionType.Constant));
Assert.That(statement.Next.Operand.Value, Is.EqualTo((Value)1));
}
private static Statement Optimize(Statement statement)
{
var parserMock = new Mock<IParser>();
parserMock.Setup(p => p.Parse(It.IsAny<TextReader>(), It.IsAny<ParserState>(), out statement)).Returns(true);
var parser = new OptimizeParser(parserMock.Object);
Assert.That(parser.Parse(TextReader.Null, new ParserState(), out var output), Is.True);
return output;
}
private static Expression Optimize(Expression expression)
{
var statement = OptimizeParserTester.Optimize(Statement.CreateEcho(expression));
Assert.That(statement.Type, Is.EqualTo(StatementType.Echo));
return statement.Operand;
}
}
}
| |
/*
* 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 Ionic.Zlib;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security.Cryptography; // for computing md5 hash
using System.Threading;
using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
// You will need to uncomment these lines if you are adding a region module to some other assembly which does not already
// specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans
// the available DLLs
//[assembly: Addin("MaterialsModule", "1.0")]
//[assembly: AddinDependency("OpenSim", "0.5")]
namespace OpenSim.Region.OptionalModules.Materials
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")]
public class MaterialsModule : INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "MaterialsModule"; } }
public Type ReplaceableInterface { get { return null; } }
private Scene m_scene = null;
private bool m_enabled = false;
public Dictionary<UUID, OSDMap> m_regionMaterials = new Dictionary<UUID, OSDMap>();
private ReaderWriterLock m_regionMaterialsRwLock = new ReaderWriterLock();
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["Materials"];
if (config == null)
return;
m_enabled = config.GetBoolean("enable_materials", true);
if (!m_enabled)
return;
m_log.DebugFormat("[Materials]: Initialized");
}
public void Close()
{
if (!m_enabled)
return;
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene = scene;
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
}
private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
{
foreach (var part in obj.Parts)
if (part != null)
GetStoredMaterialsInPart(part);
}
private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
{
string capsBase = "/CAPS/" + caps.CapsObjectPath;
IRequestHandler renderMaterialsPostHandler
= new RestStreamHandler("POST", capsBase + "/",
(request, path, param, httpRequest, httpResponse)
=> RenderMaterialsPostCap(request, agentID),
"RenderMaterials", null);
caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler);
// OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET
// and POST handlers, (at least at the time this was originally written), so we first set up a POST
// handler normally and then add a GET handler via MainServer
IRequestHandler renderMaterialsGetHandler
= new RestStreamHandler("GET", capsBase + "/",
(request, path, param, httpRequest, httpResponse)
=> RenderMaterialsGetCap(request),
"RenderMaterials", null);
MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler);
// materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well
IRequestHandler renderMaterialsPutHandler
= new RestStreamHandler("PUT", capsBase + "/",
(request, path, param, httpRequest, httpResponse)
=> RenderMaterialsPostCap(request, agentID),
"RenderMaterials", null);
MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler);
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
}
public void RegionLoaded(Scene scene)
{
}
/// <summary>
/// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'.
/// </summary>
/// <param name="part"></param>
private void GetLegacyStoredMaterialsInPart(SceneObjectPart part)
{
if (part.DynAttrs == null)
return;
OSD OSMaterials = null;
OSDArray matsArr = null;
lock (part.DynAttrs)
{
if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
{
OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
if (materialsStore == null)
return;
materialsStore.TryGetValue("Materials", out OSMaterials);
}
if (OSMaterials != null && OSMaterials is OSDArray)
matsArr = OSMaterials as OSDArray;
else
return;
}
if (matsArr == null)
return;
foreach (OSD elemOsd in matsArr)
{
if (elemOsd != null && elemOsd is OSDMap)
{
OSDMap matMap = elemOsd as OSDMap;
if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material"))
{
m_regionMaterialsRwLock.AcquireWriterLock(-1);
try
{
m_regionMaterials[matMap["ID"].AsUUID()] = (OSDMap)matMap["Material"];
}
catch (Exception e)
{
m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString());
}
finally
{
m_regionMaterialsRwLock.ReleaseWriterLock();
}
}
}
}
}
/// <summary>
/// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
/// </summary>
private void GetStoredMaterialsInPart(SceneObjectPart part)
{
if (part.Shape == null)
return;
var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
if (te == null)
return;
GetLegacyStoredMaterialsInPart(part);
if (te.DefaultTexture != null)
{
GetStoredMaterialInFace(part, te.DefaultTexture);
}
else
{
m_log.WarnFormat(
"[Materials]: Default texture for part {0} (part of object {1})) in {2} unexpectedly null. Ignoring.",
part.Name, part.ParentGroup.Name, m_scene.Name);
}
foreach (Primitive.TextureEntryFace face in te.FaceTextures)
{
if (face != null)
GetStoredMaterialInFace(part, face);
}
}
/// <summary>
/// Find the materials used in one Face, and add them to 'm_regionMaterials'.
/// </summary>
private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
{
UUID id = face.MaterialID;
if (id == UUID.Zero)
return;
m_regionMaterialsRwLock.AcquireReaderLock(-1);
try
{
if (m_regionMaterials.ContainsKey(id))
return;
byte[] data = m_scene.AssetService.GetData(id.ToString());
if (data == null)
{
m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
return;
}
OSDMap mat;
try
{
mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
}
catch (Exception e)
{
m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
return;
}
LockCookie lc = m_regionMaterialsRwLock.UpgradeToWriterLock(-1);
try
{
if (m_regionMaterials.ContainsKey(id))
return;
m_regionMaterials[id] = mat;
}
finally
{
m_regionMaterialsRwLock.DowngradeFromWriterLock(ref lc);
}
}
finally
{
m_regionMaterialsRwLock.ReleaseReaderLock();
}
}
public string RenderMaterialsPostCap(string request, UUID agentID)
{
OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
OSDMap resp = new OSDMap();
OSDMap materialsFromViewer = null;
OSDArray respArr = new OSDArray();
if (req.ContainsKey("Zipped"))
{
OSD osd = null;
byte[] inBytes = req["Zipped"].AsBinary();
try
{
osd = ZDecompressBytesToOsd(inBytes);
if (osd != null)
{
if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
{
foreach (OSD elem in (OSDArray)osd)
{
try
{
UUID id = new UUID(elem.AsBinary(), 0);
m_regionMaterialsRwLock.AcquireWriterLock(-1);
try
{
if (m_regionMaterials.ContainsKey(id))
{
OSDMap matMap = new OSDMap();
matMap["ID"] = OSD.FromBinary(id.GetBytes());
matMap["Material"] = m_regionMaterials[id];
respArr.Add(matMap);
}
else
{
m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
// Theoretically we could try to load the material from the assets service,
// but that shouldn't be necessary because the viewer should only request
// materials that exist in a prim on the region, and all of these materials
// are already stored in m_regionMaterials.
}
}
finally
{
m_regionMaterialsRwLock.ReleaseWriterLock();
}
}
catch (Exception e)
{
m_log.Error("Error getting materials in response to viewer request", e);
continue;
}
}
}
else if (osd is OSDMap) // request to assign a material
{
materialsFromViewer = osd as OSDMap;
if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
{
OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
if (matsOsd is OSDArray)
{
OSDArray matsArr = matsOsd as OSDArray;
try
{
foreach (OSDMap matsMap in matsArr)
{
uint primLocalID = 0;
try {
primLocalID = matsMap["ID"].AsUInteger();
}
catch (Exception e) {
m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
continue;
}
OSDMap mat = null;
try
{
mat = matsMap["Material"] as OSDMap;
}
catch (Exception e)
{
m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
continue;
}
SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
if (sop == null)
{
m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
continue;
}
if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
{
m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
continue;
}
Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
if (te == null)
{
m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
continue;
}
UUID id;
if (mat == null)
{
// This happens then the user removes a material from a prim
id = UUID.Zero;
}
else
{
id = StoreMaterialAsAsset(agentID, mat, sop);
}
int face = -1;
if (matsMap.ContainsKey("Face"))
{
face = matsMap["Face"].AsInteger();
Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face);
faceEntry.MaterialID = id;
}
else
{
if (te.DefaultTexture == null)
m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
else
te.DefaultTexture.MaterialID = id;
}
//m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
// We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
sop.Shape.TextureEntry = te.GetBytes();
if (sop.ParentGroup != null)
{
sop.TriggerScriptChangedEvent(Changed.TEXTURE);
sop.UpdateFlag = UpdateRequired.FULL;
sop.ParentGroup.HasGroupChanged = true;
sop.ScheduleFullUpdate();
}
}
}
catch (Exception e)
{
m_log.Warn("[Materials]: exception processing received material ", e);
}
}
}
}
}
}
catch (Exception e)
{
m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
//return "";
}
}
resp["Zipped"] = ZCompressOSD(respArr, false);
string response = OSDParser.SerializeLLSDXmlString(resp);
//m_log.Debug("[Materials]: cap request: " + request);
//m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
//m_log.Debug("[Materials]: cap response: " + response);
return response;
}
private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop)
{
UUID id;
bool storeAssedRequired = false;
// Material UUID = hash of the material's data.
// This makes materials deduplicate across the entire grid (but isn't otherwise required).
byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
using (var md5 = MD5.Create())
id = new UUID(md5.ComputeHash(data), 0);
m_regionMaterialsRwLock.AcquireWriterLock(-1);
try
{
if (!m_regionMaterials.ContainsKey(id))
{
m_regionMaterials[id] = mat;
storeAssedRequired = true;
}
}
finally
{
m_regionMaterialsRwLock.ReleaseWriterLock();
}
if(storeAssedRequired)
{
// This asset might exist already, but it's ok to try to store it again
string name = "Material " + ChooseMaterialName(mat, sop);
name = name.Substring(0, Math.Min(64, name.Length)).Trim();
AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString());
asset.Data = data;
m_scene.AssetService.Store(asset);
}
return id;
}
/// <summary>
/// Use heuristics to choose a good name for the material.
/// </summary>
private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop)
{
UUID normMap = mat["NormMap"].AsUUID();
if (normMap != UUID.Zero)
{
AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString());
if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
return asset.Name;
}
UUID specMap = mat["SpecMap"].AsUUID();
if (specMap != UUID.Zero)
{
AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString());
if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
return asset.Name;
}
if (sop.Name != "Primitive")
return sop.Name;
if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive"))
return sop.ParentGroup.Name;
return "";
}
public string RenderMaterialsGetCap(string request)
{
OSDMap resp = new OSDMap();
int matsCount = 0;
OSDArray allOsd = new OSDArray();
m_regionMaterialsRwLock.AcquireReaderLock(-1);
try
{
foreach (KeyValuePair<UUID, OSDMap> kvp in m_regionMaterials)
{
OSDMap matMap = new OSDMap();
matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes());
matMap["Material"] = kvp.Value;
allOsd.Add(matMap);
matsCount++;
}
}
finally
{
m_regionMaterialsRwLock.ReleaseReaderLock();
}
resp["Zipped"] = ZCompressOSD(allOsd, false);
return OSDParser.SerializeLLSDXmlString(resp);
}
private static string ZippedOsdBytesToString(byte[] bytes)
{
try
{
return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes));
}
catch (Exception e)
{
return "ZippedOsdBytesToString caught an exception: " + e.ToString();
}
}
/// <summary>
/// computes a UUID by hashing a OSD object
/// </summary>
/// <param name="osd"></param>
/// <returns></returns>
private static UUID HashOsd(OSD osd)
{
byte[] data = OSDParser.SerializeLLSDBinary(osd, false);
using (var md5 = MD5.Create())
return new UUID(md5.ComputeHash(data), 0);
}
public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
{
OSD osd = null;
byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
using (MemoryStream msSinkCompressed = new MemoryStream())
{
using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
{
zOut.Write(data, 0, data.Length);
}
msSinkCompressed.Seek(0L, SeekOrigin.Begin);
osd = OSD.FromBinary(msSinkCompressed.ToArray());
}
return osd;
}
public static OSD ZDecompressBytesToOsd(byte[] input)
{
OSD osd = null;
using (MemoryStream msSinkUnCompressed = new MemoryStream())
{
using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true))
{
zOut.Write(input, 0, input.Length);
}
msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
}
return osd;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SystemDrive.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>CheckDriveSpace</i> (<b>Required: </b>Drive, MinSpace <b>Optional: </b>Unit)</para>
/// <para><i>GetDrives</i> (<b>Optional: </b>SkipDrives, Unit <b>Output: </b>Drives)</para>
/// <para><b>Remote Execution Support:</b> Yes</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <ItemGroup>
/// <DrivesToSkip Include="A:\"/>
/// </ItemGroup>
/// <Target Name="Default">
/// <!--- Check drive space -->
/// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="CheckDriveSpace" Drive="c:\" MachineName="AMachine" UserName="Administrator" UserPassword="APassword" MinSpace="46500" Unit="Mb" ContinueOnError="true"/>
/// <!--- Check drive space on a remote machine -->
/// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="GetDrives" SkipDrives="@(DrivesToSkip)" MachineName="AMachine" UserName="Administrator" UserPassword="APassword">
/// <Output TaskParameter="Drives" ItemName="SystemDrivesRemote"/>
/// </MSBuild.ExtensionPack.Computer.SystemDrive>
/// <Message Text="Remote Drive: %(SystemDrivesRemote.Identity), DriveType: %(SystemDrivesRemote.DriveType), Name: %(SystemDrivesRemote.Name), VolumeLabel: %(SystemDrivesRemote.VolumeLabel), DriveFormat: %(SystemDrivesRemote.DriveFormat), TotalSize: %(SystemDrivesRemote.TotalSize), TotalFreeSpace=%(SystemDrivesRemote.TotalFreeSpace), AvailableFreeSpace=%(SystemDrivesRemote.AvailableFreeSpace)IsReady=%(SystemDrivesRemote.IsReady), RootDirectory=%(SystemDrivesRemote.RootDirectory)"/>
/// <!--- Check drive space using different units -->
/// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="CheckDriveSpace" Drive="c:\" MinSpace="46500" Unit="Mb" ContinueOnError="true"/>
/// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="CheckDriveSpace" Drive="c:\" MinSpace="1" Unit="Gb"/>
/// <!-- Get the drives on a machine -->
/// <MSBuild.ExtensionPack.Computer.SystemDrive TaskAction="GetDrives" SkipDrives="@(DrivesToSkip)">
/// <Output TaskParameter="Drives" ItemName="SystemDrives"/>
/// </MSBuild.ExtensionPack.Computer.SystemDrive>
/// <Message Text="Drive: %(SystemDrives.Identity), DriveType: %(SystemDrives.DriveType), Name: %(SystemDrives.Name), VolumeLabel: %(SystemDrives.VolumeLabel), DriveFormat: %(SystemDrives.DriveFormat), TotalSize: %(SystemDrives.TotalSize), TotalFreeSpace=%(SystemDrives.TotalFreeSpace), AvailableFreeSpace=%(SystemDrives.AvailableFreeSpace)IsReady=%(SystemDrives.IsReady), RootDirectory=%(SystemDrives.RootDirectory)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class SystemDrive : BaseTask
{
private List<ITaskItem> drives;
private List<ITaskItem> skipDrives;
/// <summary>
/// Sets the unit. Supports Kb, Mb(default), Gb, Tb
/// </summary>
public string Unit { get; set; }
/// <summary>
/// Sets the drive.
/// </summary>
public string Drive { get; set; }
/// <summary>
/// Sets the min space.
/// </summary>
public long MinSpace { get; set; }
/// <summary>
/// Sets the drives. ITaskItem
/// <para/>
/// Identity: Name
/// <para/>
/// Metadata: Name, VolumeLabel, AvailableFreeSpace, DriveFormat, TotalSize, TotalFreeSpace, IsReady (LocalMachine only), RootDirectory (LocalMachine only)
/// </summary>
[Output]
public ITaskItem[] Drives
{
get { return this.drives.ToArray(); }
set { this.drives = new List<ITaskItem>(value); }
}
/// <summary>
/// Sets the drives to skip. ITaskItem
/// </summary>
public ITaskItem[] SkipDrives
{
get { return this.skipDrives.ToArray(); }
set { this.skipDrives = new List<ITaskItem>(value); }
}
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case "GetDrives":
this.GetDrives();
break;
case "CheckDriveSpace":
this.CheckDriveSpace();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
/// <summary>
/// Checks the drive space.
/// </summary>
private void CheckDriveSpace()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking Drive Space: {0} (min {1}{2}) on: {3}", this.Drive, this.MinSpace, this.Unit, this.MachineName));
long unitSize = this.ReadUnitSize();
if (this.MachineName == Environment.MachineName)
{
foreach (string drive1 in Environment.GetLogicalDrives())
{
if (string.Compare(this.Drive, drive1, StringComparison.OrdinalIgnoreCase) == 0)
{
DriveInfo driveInfo = new DriveInfo(drive1);
if (driveInfo.IsReady)
{
long freespace = driveInfo.AvailableFreeSpace;
if ((freespace / unitSize) < this.MinSpace)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Insufficient free space. Drive {0} has {1}{2}", this.Drive, driveInfo.AvailableFreeSpace / unitSize, this.Unit));
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Free drive space on {0} is {1}{2}", this.Drive, driveInfo.AvailableFreeSpace / unitSize, this.Unit));
}
}
else
{
this.Log.LogWarning("Drive not ready to be read: {0}", drive1);
}
}
}
}
else
{
this.GetManagementScope(@"\root\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query))
{
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
if (mo == null)
{
Log.LogError("WMI Failed to get drives from: {0}", this.MachineName);
return;
}
// only check fixed drives.
if (mo["DriveType"] != null && mo["DriveType"].ToString() == "3")
{
if (mo["DriveLetter"] == null)
{
this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "WMI Failed to query the DriveLetter from: {0}", this.MachineName));
break;
}
string drive = mo["DriveLetter"].ToString();
double freeSpace = Convert.ToDouble(mo["FreeSpace"], CultureInfo.CurrentCulture) / unitSize;
if (freeSpace < this.MinSpace)
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Insufficient free space. Drive {0} has {1}{2}", drive, freeSpace, this.Unit));
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Free drive space on {0} is {1}{2}", drive, freeSpace, this.Unit));
}
}
}
}
}
}
private long ReadUnitSize()
{
if (string.IsNullOrEmpty(this.Unit))
{
this.Unit = "Mb";
}
long unitSize;
switch (this.Unit.ToUpperInvariant())
{
case "TB":
unitSize = 1099511627776;
break;
case "GB":
unitSize = 1073741824;
break;
case "KB":
unitSize = 1024;
break;
default:
unitSize = 1048576;
break;
}
return unitSize;
}
/// <summary>
/// Gets the drives.
/// </summary>
private void GetDrives()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting Drives from: {0}", this.MachineName));
long unitSize = this.ReadUnitSize();
this.drives = new List<ITaskItem>();
if (this.MachineName == Environment.MachineName)
{
foreach (string drive1 in Environment.GetLogicalDrives())
{
bool skip = false;
if (this.skipDrives != null)
{
skip = this.SkipDrives.Any(driveToSkip => driveToSkip.ItemSpec == drive1);
}
if (skip == false)
{
DriveInfo driveInfo = new DriveInfo(drive1);
if (driveInfo.IsReady)
{
ITaskItem item = new TaskItem(drive1);
item.SetMetadata("DriveType", driveInfo.DriveType.ToString());
if (driveInfo.DriveType == DriveType.Fixed || driveInfo.DriveType == DriveType.Removable)
{
item.SetMetadata("Name", driveInfo.Name);
item.SetMetadata("VolumeLabel", driveInfo.VolumeLabel);
item.SetMetadata("AvailableFreeSpace", (driveInfo.AvailableFreeSpace / unitSize).ToString(CultureInfo.CurrentCulture));
item.SetMetadata("DriveFormat", driveInfo.DriveFormat);
item.SetMetadata("TotalSize", (driveInfo.TotalSize / unitSize).ToString(CultureInfo.CurrentCulture));
item.SetMetadata("TotalFreeSpace", (driveInfo.TotalFreeSpace / unitSize).ToString(CultureInfo.CurrentCulture));
item.SetMetadata("IsReady", driveInfo.IsReady.ToString());
item.SetMetadata("RootDirectory", driveInfo.RootDirectory.ToString());
}
this.drives.Add(item);
}
else
{
this.Log.LogWarning("Drive not ready to be read: {0}", drive1);
}
}
}
}
else
{
this.GetManagementScope(@"\root\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Volume");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query))
{
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
if (mo == null)
{
Log.LogError("WMI Failed to get drives from: {0}", this.MachineName);
return;
}
// only check fixed drives.
if (mo["DriveType"] != null && mo["DriveType"].ToString() == "3")
{
bool skip = false;
string drive1 = mo["DriveLetter"].ToString();
if (this.skipDrives != null)
{
skip = this.SkipDrives.Any(driveToSkip => driveToSkip.ItemSpec == drive1);
}
if (skip == false)
{
ITaskItem item = new TaskItem(drive1);
item.SetMetadata("DriveType", mo["DriveType"].ToString());
if (mo["DriveType"].ToString() == "3" || mo["DriveType"].ToString() == "2")
{
item.SetMetadata("Name", mo["Name"].ToString());
item.SetMetadata("VolumeLabel", mo["Label"].ToString());
item.SetMetadata("AvailableFreeSpace", mo["FreeSpace"].ToString());
item.SetMetadata("DriveFormat", mo["FileSystem"].ToString());
item.SetMetadata("TotalSize", mo["Capacity"].ToString());
item.SetMetadata("TotalFreeSpace", mo["FreeSpace"].ToString());
}
this.drives.Add(item);
}
}
}
}
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.Config.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Config.Api.Tests
{
public class AccessTypeTests
{
public static AccessTypeController Fixture()
{
AccessTypeController controller = new AccessTypeController(new AccessTypeRepository(), "", new LoginView());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Config.Entities.AccessType accessType = Fixture().Get(0);
Assert.NotNull(accessType);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Config.Entities.AccessType accessType = Fixture().GetFirst();
Assert.NotNull(accessType);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Config.Entities.AccessType accessType = Fixture().GetPrevious(0);
Assert.NotNull(accessType);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Config.Entities.AccessType accessType = Fixture().GetNext(0);
Assert.NotNull(accessType);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Config.Entities.AccessType accessType = Fixture().GetLast();
Assert.NotNull(accessType);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Config.Entities.AccessType> accessTypes = Fixture().Get(new int[] { });
Assert.NotNull(accessTypes);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
/**
* Screenary: Real-Time Collaboration Redefined.
* Input Client
*
* Copyright 2011-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2011-2012 Marwan Samaha <mar6@hotmail.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.
*/
using System;
using System.IO;
using System.Threading;
using System.Collections;
namespace Screenary
{
public class InputClient : InputChannel
{
private bool active;
protected UInt32 sessionId;
private IInputListener listener;
private readonly object channelLock = new object();
static private bool stopthread = false;
public const UInt16 PTR_FLAGS_MOVE = 0x0800; /* mouse motion */
public const UInt16 PTR_FLAGS_DOWN = 0x8000; /* button press */
public const UInt16 PTR_FLAGS_BTN1 = 0x1000; /* button 1 (left) */
public const UInt16 PTR_FLAGS_BTN2 = 0x2000; /* button 2 (right) */
public const UInt16 PTR_FLAGS_BTN3 = 0x4000; /* button 3 (middle) */
public const UInt16 KBD_FLAGS_EXTENDED = 0x0100;
public const UInt16 KBD_FLAGS_DOWN = 0x4000;
public const UInt16 KBD_FLAGS_RELEASE = 0x8000;
public bool Active { get { return active; } set { active = value; } }
public InputClient(TransportClient transport)
{
this.transport = transport;
this.listener = null;
this.active = false;
}
public void SetListener(IInputListener listener)
{
this.listener = listener;
}
public void SetSessionId(UInt32 sessionId)
{
this.sessionId = sessionId;
}
private BinaryWriter InitReqPDU(ref byte[] buffer, int length, UInt32 sessionId)
{
BinaryWriter s;
buffer = new byte[length + 4];
s = new BinaryWriter(new MemoryStream(buffer));
s.Write((UInt32) sessionId);
return s;
}
public void SendMouseEvent(uint button, bool down, int x, int y)
{
UInt16 pointerFlags;
byte[] buffer = null;
int length = sizeof(UInt16) * 3;
BinaryWriter s = InitReqPDU(ref buffer, length, this.sessionId);
pointerFlags = (down) ? PTR_FLAGS_DOWN : (UInt16) 0;
if (button == 1)
pointerFlags |= PTR_FLAGS_BTN1;
else if (button == 2)
pointerFlags |= PTR_FLAGS_BTN3;
else if (button == 3)
pointerFlags |= PTR_FLAGS_BTN2;
s.Write((UInt16) pointerFlags);
s.Write((UInt16) x);
s.Write((UInt16) y);
Send(buffer, PDU_INPUT_MOUSE);
}
public void SendMouseMotionEvent(int x, int y)
{
byte[] buffer = null;
int length = sizeof(UInt16) * 3;
BinaryWriter s = InitReqPDU(ref buffer, length, this.sessionId);
s.Write((UInt16) PTR_FLAGS_MOVE);
s.Write((UInt16) x);
s.Write((UInt16) y);
Send(buffer, PDU_INPUT_MOUSE);
}
public void RecvMouseEvent(BinaryReader s)
{
UInt32 sessionId;
UInt16 pointerFlags;
UInt16 x, y;
sessionId = s.ReadUInt32();
pointerFlags = s.ReadUInt16();
x = s.ReadUInt16();
y = s.ReadUInt16();
if (listener != null)
listener.OnMouseEvent(pointerFlags, x, y);
}
public void SendKeyboardEvent(uint keyCode, bool down, bool extended)
{
UInt16 keyboardFlags;
byte[] buffer = null;
int length = sizeof(UInt16) * 2;
BinaryWriter s = InitReqPDU(ref buffer, length, this.sessionId);
keyboardFlags = (extended) ? KBD_FLAGS_EXTENDED : (UInt16) 0;
keyboardFlags |= (down) ? KBD_FLAGS_DOWN : KBD_FLAGS_RELEASE;
s.Write((UInt16) keyboardFlags);
s.Write((UInt16) keyCode);
Send(buffer, PDU_INPUT_KEYBOARD);
}
public void RecvKeyboardEvent(BinaryReader s)
{
UInt32 sessionId;
UInt16 keyboardFlags;
UInt16 keyCode;
sessionId = s.ReadUInt32();
keyboardFlags = s.ReadUInt16();
keyCode = s.ReadUInt16();
if (listener != null)
listener.OnKeyboardEvent(keyboardFlags, keyCode);
}
public override void OnRecv(byte[] buffer, byte pduType)
{
lock (channelLock)
{
queue.Enqueue(new PDU(buffer, GetChannelId(), pduType));
Monitor.Pulse(channelLock);
}
}
public override void OnOpen()
{
thread = new Thread(ChannelThreadProc);
thread.Start();
}
public override void OnClose()
{
lock (channelLock)
{
stopthread = true;
Console.WriteLine("closing channel: " + this.ToString());
Monitor.PulseAll(channelLock);
}
}
/**
* Processes a received PDU and calls the appropriate handler
**/
private void ProcessPDU(byte[] buffer, byte pduType)
{
MemoryStream stream = new MemoryStream(buffer);
BinaryReader s = new BinaryReader(stream);
switch (pduType)
{
case PDU_INPUT_MOUSE:
RecvMouseEvent(s);
return;
case PDU_INPUT_KEYBOARD:
RecvKeyboardEvent(s);
return;
default:
return;
}
}
/**
* Code executed by the thread. Listening and processing received packets
**/
public void ChannelThreadProc()
{
while (!stopthread)
{
lock (channelLock)
{
while (queue.Count < 1 && !stopthread)
{
Monitor.Wait(channelLock);
}
if (queue.Count >= 1)
{
PDU pdu = (PDU) queue.Dequeue();
ProcessPDU(pdu.Buffer, pdu.Type);
}
Monitor.Pulse(channelLock);
}
}
Console.WriteLine("InputClient.ChannelThreadProc end");
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek, Vaclav Novak and Martin Maly.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Diagnostics;
using PHP.Core.Parsers;
namespace PHP.Core.AST
{
#region Statement
/// <summary>
/// Abstract base class representing all statements elements of PHP source file.
/// </summary>
[Serializable]
public abstract class Statement : LangElement
{
protected Statement(Text.Span span)
: base(span)
{
}
/// <summary>
/// Whether the statement is a declaration statement (class, function, namespace, const).
/// </summary>
internal virtual bool IsDeclaration { get { return false; } }
internal virtual bool SkipInPureGlobalCode() { return false; }
}
#endregion
#region BlockStmt
/// <summary>
/// Block statement.
/// </summary>
[Serializable]
public sealed class BlockStmt : Statement
{
private readonly Statement[]/*!*/_statements;
/// <summary>Statements in block</summary>
public Statement[]/*!*/ Statements { get { return _statements; } }
public BlockStmt(Text.Span span, IList<Statement>/*!*/body)
: base(span)
{
Debug.Assert(body != null);
_statements = body.AsArray();
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitBlockStmt(this);
}
}
#endregion
#region ExpressionStmt
/// <summary>
/// Expression statement.
/// </summary>
[Serializable]
public sealed class ExpressionStmt : Statement
{
/// <summary>Expression that repesents this statement</summary>
public Expression/*!*/ Expression { get { return expression; } internal set { expression = value; } }
private Expression/*!*/ expression;
public ExpressionStmt(Text.Span span, Expression/*!*/ expression)
: base(span)
{
Debug.Assert(expression != null);
this.expression = expression;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitExpressionStmt(this);
}
}
#endregion
#region EmptyStmt
/// <summary>
/// Empty statement.
/// </summary>
public sealed class EmptyStmt : Statement
{
public static readonly EmptyStmt Unreachable = new EmptyStmt(Text.Span.Invalid);
public static readonly EmptyStmt Skipped = new EmptyStmt(Text.Span.Invalid);
public static readonly EmptyStmt PartialMergeResiduum = new EmptyStmt(Text.Span.Invalid);
internal override bool SkipInPureGlobalCode()
{
return true;
}
public EmptyStmt(Text.Span p) : base(p) { }
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitEmptyStmt(this);
}
}
#endregion
#region PHPDocStmt
/// <summary>
/// Empty statement containing PHPDoc block.
/// </summary>
[Serializable]
public sealed class PHPDocStmt : Statement
{
public PHPDocBlock/*!*/PHPDoc { get { return _phpdoc; } }
private readonly PHPDocBlock _phpdoc;
internal override bool SkipInPureGlobalCode() { return true; }
public PHPDocStmt(PHPDocBlock/*!*/phpdoc) : base(phpdoc.Span)
{
Debug.Assert(phpdoc != null);
_phpdoc = phpdoc;
}
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitPHPDocStmt(this);
}
}
#endregion
#region UnsetStmt
/// <summary>
/// Represents an <c>unset</c> statement.
/// </summary>
[Serializable]
public sealed class UnsetStmt : Statement
{
/// <summary>List of variables to be unset</summary>
public List<VariableUse> /*!*/VarList { get { return varList; } }
private readonly List<VariableUse>/*!*/ varList;
public UnsetStmt(Text.Span p, List<VariableUse>/*!*/ varList)
: base(p)
{
Debug.Assert(varList != null);
this.varList = varList;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitUnsetStmt(this);
}
}
#endregion
#region GlobalStmt
/// <summary>
/// Represents a <c>global</c> statement.
/// </summary>
[Serializable]
public sealed class GlobalStmt : Statement
{
public List<SimpleVarUse>/*!*/ VarList { get { return varList; } }
private List<SimpleVarUse>/*!*/ varList;
public GlobalStmt(Text.Span p, List<SimpleVarUse>/*!*/ varList)
: base(p)
{
Debug.Assert(varList != null);
this.varList = varList;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitGlobalStmt(this);
}
}
#endregion
#region StaticStmt
/// <summary>
/// Represents a <c>static</c> statement.
/// </summary>
[Serializable]
public sealed class StaticStmt : Statement
{
/// <summary>List of static variables</summary>
public List<StaticVarDecl>/*!*/ StVarList { get { return stVarList; } }
private List<StaticVarDecl>/*!*/ stVarList;
public StaticStmt(Text.Span p, List<StaticVarDecl>/*!*/ stVarList)
: base(p)
{
Debug.Assert(stVarList != null);
this.stVarList = stVarList;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitStaticStmt(this);
}
}
/// <summary>
/// Helper class. No error or warning can be caused by declaring variable as static.
/// </summary>
/// <remarks>
/// Even this is ok:
///
/// function f()
/// {
/// global $a;
/// static $a = 1;
/// }
///
/// That's why we dont'need to know Position => is not child of LangElement
/// </remarks>
[Serializable]
public class StaticVarDecl : LangElement
{
/// <summary>Static variable being declared</summary>
public DirectVarUse /*!*/ Variable { get { return variable; } }
private DirectVarUse/*!*/ variable;
/// <summary>Expression used to initialize static variable</summary>
public Expression Initializer { get { return initializer; } internal set { initializer = value; } }
private Expression initializer;
public StaticVarDecl(Text.Span span, DirectVarUse/*!*/ variable, Expression initializer)
: base(span)
{
Debug.Assert(variable != null);
this.variable = variable;
this.initializer = initializer;
}
/// <summary>
/// Call the right Visit* method on the given Visitor object.
/// </summary>
/// <param name="visitor">Visitor to be called.</param>
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitStaticVarDecl(this);
}
}
#endregion
#region DeclareStmt
[Serializable]
public sealed class DeclareStmt : Statement
{
/// <summary>
/// Inner statement.
/// </summary>
public Statement Statement { get { return this.stmt; } }
private readonly Statement/*!*/stmt;
public DeclareStmt(Text.Span p, Statement statement)
: base(p)
{
this.stmt = statement;
}
public override void VisitMe(TreeVisitor visitor)
{
visitor.VisitDeclareStmt(this);
}
}
#endregion
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Threading;
using Amazon.ElasticMapReduce.Model;
using Amazon.ElasticMapReduce.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.ElasticMapReduce
{
/// <summary>
/// Implementation for accessing AmazonElasticMapReduce.
///
/// <para> This is the <i>Amazon Elastic MapReduce API Reference</i> . This guide provides descriptions and samples of the Amazon Elastic
/// MapReduce APIs.</para> <para>Amazon Elastic MapReduce is a web service that makes it easy to process large amounts of data efficiently.
/// Elastic MapReduce uses Hadoop processing combined with several AWS products to do tasks such as web indexing, data mining, log file
/// analysis, machine learning, scientific simulation, and data warehousing.</para>
/// </summary>
public class AmazonElasticMapReduceClient : AmazonWebServiceClient, AmazonElasticMapReduce
{
AbstractAWSSigner signer = new AWS4Signer();
#region Constructors
/// <summary>
/// Constructs AmazonElasticMapReduceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
public AmazonElasticMapReduceClient()
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonElasticMapReduceConfig(), true, AuthenticationTypes.User | AuthenticationTypes.Session) { }
/// <summary>
/// Constructs AmazonElasticMapReduceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="region">The region to connect.</param>
public AmazonElasticMapReduceClient(RegionEndpoint region)
: base(FallbackCredentialsFactory.GetCredentials(), new AmazonElasticMapReduceConfig(){RegionEndpoint = region}, true, AuthenticationTypes.User | AuthenticationTypes.Session) { }
/// <summary>
/// Constructs AmazonElasticMapReduceClient with the credentials loaded from the application's
/// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance.
///
/// Example App.config with credentials set.
/// <code>
/// <?xml version="1.0" encoding="utf-8" ?>
/// <configuration>
/// <appSettings>
/// <add key="AWSAccessKey" value="********************"/>
/// <add key="AWSSecretKey" value="****************************************"/>
/// </appSettings>
/// </configuration>
/// </code>
///
/// </summary>
/// <param name="config">The AmazonElasticMapReduce Configuration Object</param>
public AmazonElasticMapReduceClient(AmazonElasticMapReduceConfig config)
: base(FallbackCredentialsFactory.GetCredentials(), config, true, AuthenticationTypes.User | AuthenticationTypes.Session) { }
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonElasticMapReduceClient(AWSCredentials credentials)
: this(credentials, new AmazonElasticMapReduceConfig())
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonElasticMapReduceClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonElasticMapReduceConfig(){RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Credentials and an
/// AmazonElasticMapReduceClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonElasticMapReduceClient Configuration Object</param>
public AmazonElasticMapReduceClient(AWSCredentials credentials, AmazonElasticMapReduceConfig clientConfig)
: base(credentials, clientConfig, false, AuthenticationTypes.User | AuthenticationTypes.Session)
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonElasticMapReduceClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticMapReduceConfig())
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonElasticMapReduceClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticMapReduceConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonElasticMapReduceClient Configuration object. If the config object's
/// UseSecureStringForAwsSecretKey is false, the AWS Secret Key
/// is stored as a clear-text string. Please use this option only
/// if the application environment doesn't allow the use of SecureStrings.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonElasticMapReduceClient Configuration Object</param>
public AmazonElasticMapReduceClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonElasticMapReduceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig, AuthenticationTypes.User | AuthenticationTypes.Session)
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonElasticMapReduceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElasticMapReduceConfig())
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonElasticMapReduceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElasticMapReduceConfig(){RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonElasticMapReduceClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonElasticMapReduceClient Configuration object. If the config object's
/// UseSecureStringForAwsSecretKey is false, the AWS Secret Key
/// is stored as a clear-text string. Please use this option only
/// if the application environment doesn't allow the use of SecureStrings.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonElasticMapReduceClient Configuration Object</param>
public AmazonElasticMapReduceClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonElasticMapReduceConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig, AuthenticationTypes.User | AuthenticationTypes.Session)
{
}
#endregion
#region SetVisibleToAllUsers
/// <summary>
/// <para>Sets whether all AWS Identity and Access Management (IAM) users under your account can access the specifed job flows. This action
/// works on running job flows. You can also set the visibility of a job flow when you launch it using the <c>VisibleToAllUsers</c> parameter of
/// RunJobFlow. The SetVisibleToAllUsers action can be called only by an IAM user who created the job flow or the AWS account that owns the job
/// flow.</para>
/// </summary>
///
/// <param name="setVisibleToAllUsersRequest">Container for the necessary parameters to execute the SetVisibleToAllUsers service method on
/// AmazonElasticMapReduce.</param>
///
/// <exception cref="InternalServerErrorException"/>
public SetVisibleToAllUsersResponse SetVisibleToAllUsers(SetVisibleToAllUsersRequest setVisibleToAllUsersRequest)
{
IAsyncResult asyncResult = invokeSetVisibleToAllUsers(setVisibleToAllUsersRequest, null, null, true);
return EndSetVisibleToAllUsers(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the SetVisibleToAllUsers operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.SetVisibleToAllUsers"/>
/// </summary>
///
/// <param name="setVisibleToAllUsersRequest">Container for the necessary parameters to execute the SetVisibleToAllUsers operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
public IAsyncResult BeginSetVisibleToAllUsers(SetVisibleToAllUsersRequest setVisibleToAllUsersRequest, AsyncCallback callback, object state)
{
return invokeSetVisibleToAllUsers(setVisibleToAllUsersRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the SetVisibleToAllUsers operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.SetVisibleToAllUsers"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetVisibleToAllUsers.</param>
public SetVisibleToAllUsersResponse EndSetVisibleToAllUsers(IAsyncResult asyncResult)
{
return endOperation<SetVisibleToAllUsersResponse>(asyncResult);
}
IAsyncResult invokeSetVisibleToAllUsers(SetVisibleToAllUsersRequest setVisibleToAllUsersRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new SetVisibleToAllUsersRequestMarshaller().Marshall(setVisibleToAllUsersRequest);
var unmarshaller = SetVisibleToAllUsersResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region AddInstanceGroups
/// <summary>
/// <para>AddInstanceGroups adds an instance group to a running cluster.</para>
/// </summary>
///
/// <param name="addInstanceGroupsRequest">Container for the necessary parameters to execute the AddInstanceGroups service method on
/// AmazonElasticMapReduce.</param>
///
/// <returns>The response from the AddInstanceGroups service method, as returned by AmazonElasticMapReduce.</returns>
///
/// <exception cref="InternalServerErrorException"/>
public AddInstanceGroupsResponse AddInstanceGroups(AddInstanceGroupsRequest addInstanceGroupsRequest)
{
IAsyncResult asyncResult = invokeAddInstanceGroups(addInstanceGroupsRequest, null, null, true);
return EndAddInstanceGroups(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the AddInstanceGroups operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.AddInstanceGroups"/>
/// </summary>
///
/// <param name="addInstanceGroupsRequest">Container for the necessary parameters to execute the AddInstanceGroups operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAddInstanceGroups
/// operation.</returns>
public IAsyncResult BeginAddInstanceGroups(AddInstanceGroupsRequest addInstanceGroupsRequest, AsyncCallback callback, object state)
{
return invokeAddInstanceGroups(addInstanceGroupsRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the AddInstanceGroups operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.AddInstanceGroups"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAddInstanceGroups.</param>
///
/// <returns>Returns a AddInstanceGroupsResult from AmazonElasticMapReduce.</returns>
public AddInstanceGroupsResponse EndAddInstanceGroups(IAsyncResult asyncResult)
{
return endOperation<AddInstanceGroupsResponse>(asyncResult);
}
IAsyncResult invokeAddInstanceGroups(AddInstanceGroupsRequest addInstanceGroupsRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new AddInstanceGroupsRequestMarshaller().Marshall(addInstanceGroupsRequest);
var unmarshaller = AddInstanceGroupsResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region AddJobFlowSteps
/// <summary>
/// <para> AddJobFlowSteps adds new steps to a running job flow. A maximum of 256 steps are allowed in each job flow. </para> <para>If your job
/// flow is long-running (such as a Hive data warehouse) or complex, you may require more than 256 steps to process your data. You can bypass
/// the 256-step limitation in various ways, including using the SSH shell to connect to the master node and submitting queries directly to the
/// software running on the master node, such as Hive and Hadoop. For more information on how to do this, go to Add More than 256 Steps to a Job
/// Flow in the <i>Amazon Elastic MapReduce Developer's Guide</i> .</para> <para> A step specifies the location of a JAR file stored either on
/// the master node of the job flow or in Amazon S3. Each step is performed by the main function of the main class of the JAR file. The main
/// class can be specified either in the manifest of the JAR or by using the MainFunction parameter of the step. </para> <para> Elastic
/// MapReduce executes each step in the order listed. For a step to be considered complete, the main function must exit with a zero exit code
/// and all Hadoop jobs started while the step was running must have completed and run successfully. </para> <para> You can only add steps to a
/// job flow that is in one of the following states: STARTING, BOOTSTRAPPING, RUNNING, or WAITING.</para>
/// </summary>
///
/// <param name="addJobFlowStepsRequest">Container for the necessary parameters to execute the AddJobFlowSteps service method on
/// AmazonElasticMapReduce.</param>
///
/// <exception cref="InternalServerErrorException"/>
public AddJobFlowStepsResponse AddJobFlowSteps(AddJobFlowStepsRequest addJobFlowStepsRequest)
{
IAsyncResult asyncResult = invokeAddJobFlowSteps(addJobFlowStepsRequest, null, null, true);
return EndAddJobFlowSteps(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the AddJobFlowSteps operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.AddJobFlowSteps"/>
/// </summary>
///
/// <param name="addJobFlowStepsRequest">Container for the necessary parameters to execute the AddJobFlowSteps operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
public IAsyncResult BeginAddJobFlowSteps(AddJobFlowStepsRequest addJobFlowStepsRequest, AsyncCallback callback, object state)
{
return invokeAddJobFlowSteps(addJobFlowStepsRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the AddJobFlowSteps operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.AddJobFlowSteps"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginAddJobFlowSteps.</param>
public AddJobFlowStepsResponse EndAddJobFlowSteps(IAsyncResult asyncResult)
{
return endOperation<AddJobFlowStepsResponse>(asyncResult);
}
IAsyncResult invokeAddJobFlowSteps(AddJobFlowStepsRequest addJobFlowStepsRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new AddJobFlowStepsRequestMarshaller().Marshall(addJobFlowStepsRequest);
var unmarshaller = AddJobFlowStepsResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region TerminateJobFlows
/// <summary>
/// <para> TerminateJobFlows shuts a list of job flows down. When a job flow is shut down, any step not yet completed is canceled and the EC2
/// instances on which the job flow is running are stopped. Any log files not already saved are uploaded to Amazon S3 if a LogUri was specified
/// when the job flow was created. </para> <para> The call to TerminateJobFlows is asynchronous. Depending on the configuration of the job flow,
/// it may take up to 5-20 minutes for the job flow to completely terminate and release allocated resources, such as Amazon EC2 instances.
/// </para>
/// </summary>
///
/// <param name="terminateJobFlowsRequest">Container for the necessary parameters to execute the TerminateJobFlows service method on
/// AmazonElasticMapReduce.</param>
///
/// <exception cref="InternalServerErrorException"/>
public TerminateJobFlowsResponse TerminateJobFlows(TerminateJobFlowsRequest terminateJobFlowsRequest)
{
IAsyncResult asyncResult = invokeTerminateJobFlows(terminateJobFlowsRequest, null, null, true);
return EndTerminateJobFlows(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the TerminateJobFlows operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.TerminateJobFlows"/>
/// </summary>
///
/// <param name="terminateJobFlowsRequest">Container for the necessary parameters to execute the TerminateJobFlows operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
public IAsyncResult BeginTerminateJobFlows(TerminateJobFlowsRequest terminateJobFlowsRequest, AsyncCallback callback, object state)
{
return invokeTerminateJobFlows(terminateJobFlowsRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the TerminateJobFlows operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.TerminateJobFlows"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginTerminateJobFlows.</param>
public TerminateJobFlowsResponse EndTerminateJobFlows(IAsyncResult asyncResult)
{
return endOperation<TerminateJobFlowsResponse>(asyncResult);
}
IAsyncResult invokeTerminateJobFlows(TerminateJobFlowsRequest terminateJobFlowsRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new TerminateJobFlowsRequestMarshaller().Marshall(terminateJobFlowsRequest);
var unmarshaller = TerminateJobFlowsResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region DescribeJobFlows
/// <summary>
/// <para> DescribeJobFlows returns a list of job flows that match all of the supplied parameters. The parameters can include a list of job flow
/// IDs, job flow states, and restrictions on job flow creation date and time.</para> <para> Regardless of supplied parameters, only job flows
/// created within the last two months are returned.</para> <para> If no parameters are supplied, then job flows matching either of the
/// following criteria are returned:</para>
/// <ul>
/// <li>Job flows created and completed in the last two weeks</li>
/// <li> Job flows created within the last two months that are in one of the following states: <c>RUNNING</c> ,
/// <c>WAITING</c> ,
/// <c>SHUTTING_DOWN</c> ,
///
/// <c>STARTING</c> </li>
///
/// </ul>
/// <para> Amazon Elastic MapReduce can return a maximum of 512 job flow descriptions. </para>
/// </summary>
///
/// <param name="describeJobFlowsRequest">Container for the necessary parameters to execute the DescribeJobFlows service method on
/// AmazonElasticMapReduce.</param>
///
/// <returns>The response from the DescribeJobFlows service method, as returned by AmazonElasticMapReduce.</returns>
///
/// <exception cref="InternalServerErrorException"/>
public DescribeJobFlowsResponse DescribeJobFlows(DescribeJobFlowsRequest describeJobFlowsRequest)
{
IAsyncResult asyncResult = invokeDescribeJobFlows(describeJobFlowsRequest, null, null, true);
return EndDescribeJobFlows(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeJobFlows operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.DescribeJobFlows"/>
/// </summary>
///
/// <param name="describeJobFlowsRequest">Container for the necessary parameters to execute the DescribeJobFlows operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeJobFlows
/// operation.</returns>
public IAsyncResult BeginDescribeJobFlows(DescribeJobFlowsRequest describeJobFlowsRequest, AsyncCallback callback, object state)
{
return invokeDescribeJobFlows(describeJobFlowsRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the DescribeJobFlows operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.DescribeJobFlows"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeJobFlows.</param>
///
/// <returns>Returns a DescribeJobFlowsResult from AmazonElasticMapReduce.</returns>
public DescribeJobFlowsResponse EndDescribeJobFlows(IAsyncResult asyncResult)
{
return endOperation<DescribeJobFlowsResponse>(asyncResult);
}
IAsyncResult invokeDescribeJobFlows(DescribeJobFlowsRequest describeJobFlowsRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new DescribeJobFlowsRequestMarshaller().Marshall(describeJobFlowsRequest);
var unmarshaller = DescribeJobFlowsResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
/// <summary>
/// <para> DescribeJobFlows returns a list of job flows that match all of the supplied parameters. The parameters can include a list of job flow
/// IDs, job flow states, and restrictions on job flow creation date and time.</para> <para> Regardless of supplied parameters, only job flows
/// created within the last two months are returned.</para> <para> If no parameters are supplied, then job flows matching either of the
/// following criteria are returned:</para>
/// <ul>
/// <li>Job flows created and completed in the last two weeks</li>
/// <li> Job flows created within the last two months that are in one of the following states: <c>RUNNING</c> ,
/// <c>WAITING</c> ,
/// <c>SHUTTING_DOWN</c> ,
///
/// <c>STARTING</c> </li>
///
/// </ul>
/// <para> Amazon Elastic MapReduce can return a maximum of 512 job flow descriptions. </para>
/// </summary>
///
/// <returns>The response from the DescribeJobFlows service method, as returned by AmazonElasticMapReduce.</returns>
///
/// <exception cref="InternalServerErrorException"/>
public DescribeJobFlowsResponse DescribeJobFlows()
{
return DescribeJobFlows(new DescribeJobFlowsRequest());
}
#endregion
#region SetTerminationProtection
/// <summary>
/// <para> SetTerminationProtection locks a job flow so the Amazon EC2 instances in the cluster cannot be terminated by user intervention, an
/// API call, or in the event of a job-flow error. The cluster still terminates upon successful completion of the job flow. Calling
/// SetTerminationProtection on a job flow is analogous to calling the Amazon EC2 DisableAPITermination API on all of the EC2 instances in a
/// cluster.</para> <para> SetTerminationProtection is used to prevent accidental termination of a job flow and to ensure that in the event of
/// an error, the instances will persist so you can recover any data stored in their ephemeral instance storage.</para> <para> To terminate a
/// job flow that has been locked by setting SetTerminationProtection to <c>true</c> ,
/// you must first unlock the job flow by a subsequent call to SetTerminationProtection in which you set the value to <c>false</c> .
/// </para> <para> For more information, go to Protecting a Job Flow from Termination in the <i>Amazon Elastic MapReduce Developer's Guide.</i>
/// </para>
/// </summary>
///
/// <param name="setTerminationProtectionRequest">Container for the necessary parameters to execute the SetTerminationProtection service method
/// on AmazonElasticMapReduce.</param>
///
/// <exception cref="InternalServerErrorException"/>
public SetTerminationProtectionResponse SetTerminationProtection(SetTerminationProtectionRequest setTerminationProtectionRequest)
{
IAsyncResult asyncResult = invokeSetTerminationProtection(setTerminationProtectionRequest, null, null, true);
return EndSetTerminationProtection(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the SetTerminationProtection operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.SetTerminationProtection"/>
/// </summary>
///
/// <param name="setTerminationProtectionRequest">Container for the necessary parameters to execute the SetTerminationProtection operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
public IAsyncResult BeginSetTerminationProtection(SetTerminationProtectionRequest setTerminationProtectionRequest, AsyncCallback callback, object state)
{
return invokeSetTerminationProtection(setTerminationProtectionRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the SetTerminationProtection operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.SetTerminationProtection"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetTerminationProtection.</param>
public SetTerminationProtectionResponse EndSetTerminationProtection(IAsyncResult asyncResult)
{
return endOperation<SetTerminationProtectionResponse>(asyncResult);
}
IAsyncResult invokeSetTerminationProtection(SetTerminationProtectionRequest setTerminationProtectionRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new SetTerminationProtectionRequestMarshaller().Marshall(setTerminationProtectionRequest);
var unmarshaller = SetTerminationProtectionResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region RunJobFlow
/// <summary>
/// <para> RunJobFlow creates and starts running a new job flow. The job flow will run the steps specified. Once the job flow completes, the
/// cluster is stopped and the HDFS partition is lost. To prevent loss of data, configure the last step of the job flow to store results in
/// Amazon S3. If the JobFlowInstancesConfig <c>KeepJobFlowAliveWhenNoSteps</c> parameter is set to <c>TRUE</c> , the job flow will transition
/// to the WAITING state rather than shutting down once the steps have completed. </para> <para>For additional protection, you can set the
/// JobFlowInstancesConfig <c>TerminationProtected</c> parameter to <c>TRUE</c> to lock the job flow and prevent it from being terminated by API
/// call, user intervention, or in the event of a job flow error.</para> <para>A maximum of 256 steps are allowed in each job flow.</para>
/// <para>If your job flow is long-running (such as a Hive data warehouse) or complex, you may require more than 256 steps to process your data.
/// You can bypass the 256-step limitation in various ways, including using the SSH shell to connect to the master node and submitting queries
/// directly to the software running on the master node, such as Hive and Hadoop. For more information on how to do this, go to Add More than
/// 256 Steps to a Job Flow in the <i>Amazon Elastic MapReduce Developer's Guide</i> .</para> <para>For long running job flows, we recommend
/// that you periodically store your results.</para>
/// </summary>
///
/// <param name="runJobFlowRequest">Container for the necessary parameters to execute the RunJobFlow service method on
/// AmazonElasticMapReduce.</param>
///
/// <returns>The response from the RunJobFlow service method, as returned by AmazonElasticMapReduce.</returns>
///
/// <exception cref="InternalServerErrorException"/>
public RunJobFlowResponse RunJobFlow(RunJobFlowRequest runJobFlowRequest)
{
IAsyncResult asyncResult = invokeRunJobFlow(runJobFlowRequest, null, null, true);
return EndRunJobFlow(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the RunJobFlow operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.RunJobFlow"/>
/// </summary>
///
/// <param name="runJobFlowRequest">Container for the necessary parameters to execute the RunJobFlow operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
///
/// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRunJobFlow
/// operation.</returns>
public IAsyncResult BeginRunJobFlow(RunJobFlowRequest runJobFlowRequest, AsyncCallback callback, object state)
{
return invokeRunJobFlow(runJobFlowRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the RunJobFlow operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.RunJobFlow"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginRunJobFlow.</param>
///
/// <returns>Returns a RunJobFlowResult from AmazonElasticMapReduce.</returns>
public RunJobFlowResponse EndRunJobFlow(IAsyncResult asyncResult)
{
return endOperation<RunJobFlowResponse>(asyncResult);
}
IAsyncResult invokeRunJobFlow(RunJobFlowRequest runJobFlowRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new RunJobFlowRequestMarshaller().Marshall(runJobFlowRequest);
var unmarshaller = RunJobFlowResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
#region ModifyInstanceGroups
/// <summary>
/// <para>ModifyInstanceGroups modifies the number of nodes and configuration settings of an instance group. The input parameters include the
/// new target instance count for the group and the instance group ID. The call will either succeed or fail atomically.</para>
/// </summary>
///
/// <param name="modifyInstanceGroupsRequest">Container for the necessary parameters to execute the ModifyInstanceGroups service method on
/// AmazonElasticMapReduce.</param>
///
/// <exception cref="InternalServerErrorException"/>
public ModifyInstanceGroupsResponse ModifyInstanceGroups(ModifyInstanceGroupsRequest modifyInstanceGroupsRequest)
{
IAsyncResult asyncResult = invokeModifyInstanceGroups(modifyInstanceGroupsRequest, null, null, true);
return EndModifyInstanceGroups(asyncResult);
}
/// <summary>
/// Initiates the asynchronous execution of the ModifyInstanceGroups operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.ModifyInstanceGroups"/>
/// </summary>
///
/// <param name="modifyInstanceGroupsRequest">Container for the necessary parameters to execute the ModifyInstanceGroups operation on
/// AmazonElasticMapReduce.</param>
/// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
/// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
/// procedure using the AsyncState property.</param>
public IAsyncResult BeginModifyInstanceGroups(ModifyInstanceGroupsRequest modifyInstanceGroupsRequest, AsyncCallback callback, object state)
{
return invokeModifyInstanceGroups(modifyInstanceGroupsRequest, callback, state, false);
}
/// <summary>
/// Finishes the asynchronous execution of the ModifyInstanceGroups operation.
/// <seealso cref="Amazon.ElasticMapReduce.AmazonElasticMapReduce.ModifyInstanceGroups"/>
/// </summary>
///
/// <param name="asyncResult">The IAsyncResult returned by the call to BeginModifyInstanceGroups.</param>
public ModifyInstanceGroupsResponse EndModifyInstanceGroups(IAsyncResult asyncResult)
{
return endOperation<ModifyInstanceGroupsResponse>(asyncResult);
}
IAsyncResult invokeModifyInstanceGroups(ModifyInstanceGroupsRequest modifyInstanceGroupsRequest, AsyncCallback callback, object state, bool synchronized)
{
IRequest irequest = new ModifyInstanceGroupsRequestMarshaller().Marshall(modifyInstanceGroupsRequest);
var unmarshaller = ModifyInstanceGroupsResponseUnmarshaller.GetInstance();
AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
Invoke(result);
return result;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.