context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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.Dynamic;
using System.Dynamic.Utils;
using System.Reflection;
using System.Threading;
namespace System.Linq.Expressions.Interpreter
{
internal partial class CallInstruction
{
#if FEATURE_DLG_INVOKE
private const int MaxHelpers = 5;
#endif
#if FEATURE_FAST_CREATE
private const int MaxArgs = 3;
/// <summary>
/// Fast creation works if we have a known primitive types for the entire
/// method signature. If we have any non-primitive types then FastCreate
/// falls back to SlowCreate which works for all types.
///
/// Fast creation is fast because it avoids using reflection (MakeGenericType
/// and Activator.CreateInstance) to create the types. It does this through
/// calling a series of generic methods picking up each strong type of the
/// signature along the way. When it runs out of types it news up the
/// appropriate CallInstruction with the strong-types that have been built up.
///
/// One relaxation is that for return types which are non-primitive types
/// we can fall back to object due to relaxed delegates.
/// </summary>
private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi)
{
Type t = TryGetParameterOrReturnType(target, pi, 0);
if (t == null)
{
return new ActionCallInstruction(target);
}
switch (t.GetTypeCode())
{
case TypeCode.Object:
{
if (t != typeof(object) && (IndexIsNotReturnType(0, target, pi) || t.IsValueType))
{
// if we're on the return type relaxed delegates makes it ok to use object
goto default;
}
return FastCreate<Object>(target, pi);
}
case TypeCode.Int16: return FastCreate<Int16>(target, pi);
case TypeCode.Int32: return FastCreate<Int32>(target, pi);
case TypeCode.Int64: return FastCreate<Int64>(target, pi);
case TypeCode.Boolean: return FastCreate<Boolean>(target, pi);
case TypeCode.Char: return FastCreate<Char>(target, pi);
case TypeCode.Byte: return FastCreate<Byte>(target, pi);
case TypeCode.Decimal: return FastCreate<Decimal>(target, pi);
case TypeCode.DateTime: return FastCreate<DateTime>(target, pi);
case TypeCode.Double: return FastCreate<Double>(target, pi);
case TypeCode.Single: return FastCreate<Single>(target, pi);
case TypeCode.UInt16: return FastCreate<UInt16>(target, pi);
case TypeCode.UInt32: return FastCreate<UInt32>(target, pi);
case TypeCode.UInt64: return FastCreate<UInt64>(target, pi);
case TypeCode.String: return FastCreate<String>(target, pi);
case TypeCode.SByte: return FastCreate<SByte>(target, pi);
default: return SlowCreate(target, pi);
}
}
private static CallInstruction FastCreate<T0>(MethodInfo target, ParameterInfo[] pi)
{
Type t = TryGetParameterOrReturnType(target, pi, 1);
if (t == null)
{
if (target.ReturnType == typeof(void))
{
return new ActionCallInstruction<T0>(target);
}
return new FuncCallInstruction<T0>(target);
}
switch (t.GetTypeCode())
{
case TypeCode.Object:
{
if (t != typeof(object) && (IndexIsNotReturnType(1, target, pi) || t.IsValueType))
{
// if we're on the return type relaxed delegates makes it ok to use object
goto default;
}
return FastCreate<T0, Object>(target, pi);
}
case TypeCode.Int16: return FastCreate<T0, Int16>(target, pi);
case TypeCode.Int32: return FastCreate<T0, Int32>(target, pi);
case TypeCode.Int64: return FastCreate<T0, Int64>(target, pi);
case TypeCode.Boolean: return FastCreate<T0, Boolean>(target, pi);
case TypeCode.Char: return FastCreate<T0, Char>(target, pi);
case TypeCode.Byte: return FastCreate<T0, Byte>(target, pi);
case TypeCode.Decimal: return FastCreate<T0, Decimal>(target, pi);
case TypeCode.DateTime: return FastCreate<T0, DateTime>(target, pi);
case TypeCode.Double: return FastCreate<T0, Double>(target, pi);
case TypeCode.Single: return FastCreate<T0, Single>(target, pi);
case TypeCode.UInt16: return FastCreate<T0, UInt16>(target, pi);
case TypeCode.UInt32: return FastCreate<T0, UInt32>(target, pi);
case TypeCode.UInt64: return FastCreate<T0, UInt64>(target, pi);
case TypeCode.String: return FastCreate<T0, String>(target, pi);
case TypeCode.SByte: return FastCreate<T0, SByte>(target, pi);
default: return SlowCreate(target, pi);
}
}
private static CallInstruction FastCreate<T0, T1>(MethodInfo target, ParameterInfo[] pi)
{
Type t = TryGetParameterOrReturnType(target, pi, 2);
if (t == null)
{
if (target.ReturnType == typeof(void))
{
return new ActionCallInstruction<T0, T1>(target);
}
return new FuncCallInstruction<T0, T1>(target);
}
switch (t.GetTypeCode())
{
case TypeCode.Object:
{
Debug.Assert(pi.Length == 2);
if (t.IsValueType) goto default;
return new FuncCallInstruction<T0, T1, Object>(target);
}
case TypeCode.Int16: return new FuncCallInstruction<T0, T1, Int16>(target);
case TypeCode.Int32: return new FuncCallInstruction<T0, T1, Int32>(target);
case TypeCode.Int64: return new FuncCallInstruction<T0, T1, Int64>(target);
case TypeCode.Boolean: return new FuncCallInstruction<T0, T1, Boolean>(target);
case TypeCode.Char: return new FuncCallInstruction<T0, T1, Char>(target);
case TypeCode.Byte: return new FuncCallInstruction<T0, T1, Byte>(target);
case TypeCode.Decimal: return new FuncCallInstruction<T0, T1, Decimal>(target);
case TypeCode.DateTime: return new FuncCallInstruction<T0, T1, DateTime>(target);
case TypeCode.Double: return new FuncCallInstruction<T0, T1, Double>(target);
case TypeCode.Single: return new FuncCallInstruction<T0, T1, Single>(target);
case TypeCode.UInt16: return new FuncCallInstruction<T0, T1, UInt16>(target);
case TypeCode.UInt32: return new FuncCallInstruction<T0, T1, UInt32>(target);
case TypeCode.UInt64: return new FuncCallInstruction<T0, T1, UInt64>(target);
case TypeCode.String: return new FuncCallInstruction<T0, T1, String>(target);
case TypeCode.SByte: return new FuncCallInstruction<T0, T1, SByte>(target);
default: return SlowCreate(target, pi);
}
}
#endif
#if FEATURE_DLG_INVOKE
private static Type GetHelperType(MethodInfo info, Type[] arrTypes)
{
Type t;
if (info.ReturnType == typeof(void))
{
switch (arrTypes.Length)
{
case 0:
t = typeof(ActionCallInstruction);
break;
case 1:
t = typeof(ActionCallInstruction<>).MakeGenericType(arrTypes);
break;
case 2:
t = typeof(ActionCallInstruction<,>).MakeGenericType(arrTypes);
break;
case 3:
t = typeof(ActionCallInstruction<,,>).MakeGenericType(arrTypes);
break;
case 4:
t = typeof(ActionCallInstruction<,,,>).MakeGenericType(arrTypes);
break;
default:
throw new InvalidOperationException();
}
}
else
{
switch (arrTypes.Length)
{
case 1:
t = typeof(FuncCallInstruction<>).MakeGenericType(arrTypes);
break;
case 2:
t = typeof(FuncCallInstruction<,>).MakeGenericType(arrTypes);
break;
case 3:
t = typeof(FuncCallInstruction<,,>).MakeGenericType(arrTypes);
break;
case 4:
t = typeof(FuncCallInstruction<,,,>).MakeGenericType(arrTypes);
break;
case 5:
t = typeof(FuncCallInstruction<,,,,>).MakeGenericType(arrTypes);
break;
default:
throw new InvalidOperationException();
}
}
return t;
}
#endif
}
#if FEATURE_DLG_INVOKE
internal sealed class ActionCallInstruction : CallInstruction
{
private readonly Action _target;
public override int ArgumentCount => 0;
public override int ProducedStack => 0;
public ActionCallInstruction(MethodInfo target)
{
_target = (Action)target.CreateDelegate(typeof(Action));
}
public override int Run(InterpretedFrame frame)
{
_target();
frame.StackIndex -= 0;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class ActionCallInstruction<T0> : CallInstruction
{
private readonly bool _isInstance;
private readonly Action<T0> _target;
public override int ProducedStack => 0;
public override int ArgumentCount => 1;
public ActionCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Action<T0>)target.CreateDelegate(typeof(Action<T0>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 1];
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
InterpretLambdaInvoke(targetLambda, Array.Empty<object>());
}
else
{
_target((T0)firstArg);
}
frame.StackIndex -= 1;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class ActionCallInstruction<T0, T1> : CallInstruction
{
private readonly bool _isInstance;
private readonly Action<T0, T1> _target;
public override int ProducedStack => 0;
public override int ArgumentCount => 2;
public ActionCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Action<T0, T1>)target.CreateDelegate(typeof(Action<T0, T1>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 2];
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] });
}
else
{
_target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]);
}
frame.StackIndex -= 2;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class ActionCallInstruction<T0, T1, T2> : CallInstruction
{
private readonly bool _isInstance;
private readonly Action<T0, T1, T2> _target;
public override int ProducedStack => 0;
public override int ArgumentCount => 3;
public ActionCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Action<T0, T1, T2>)target.CreateDelegate(typeof(Action<T0, T1, T2>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 3];
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] });
}
else
{
_target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]);
}
frame.StackIndex -= 3;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class ActionCallInstruction<T0, T1, T2, T3> : CallInstruction
{
private readonly bool _isInstance;
private readonly Action<T0, T1, T2, T3> _target;
public override int ProducedStack => 0;
public override int ArgumentCount => 4;
public ActionCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Action<T0, T1, T2, T3>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 4];
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] });
}
else
{
_target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]);
}
frame.StackIndex -= 4;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class FuncCallInstruction<TRet> : CallInstruction
{
private readonly Func<TRet> _target;
public override int ProducedStack => 1;
public override int ArgumentCount => 0;
public FuncCallInstruction(MethodInfo target)
{
_target = (Func<TRet>)target.CreateDelegate(typeof(Func<TRet>));
}
public override int Run(InterpretedFrame frame)
{
frame.Data[frame.StackIndex - 0] = _target();
frame.StackIndex -= -1;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class FuncCallInstruction<T0, TRet> : CallInstruction
{
private readonly bool _isInstance;
private readonly Func<T0, TRet> _target;
public override int ProducedStack => 1;
public override int ArgumentCount => 1;
public FuncCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Func<T0, TRet>)target.CreateDelegate(typeof(Func<T0, TRet>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 1];
object result;
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
result = InterpretLambdaInvoke(targetLambda, Array.Empty<object>());
}
else
{
result = _target((T0)firstArg);
}
frame.Data[frame.StackIndex - 1] = result;
frame.StackIndex -= 0;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class FuncCallInstruction<T0, T1, TRet> : CallInstruction
{
private readonly bool _isInstance;
private readonly Func<T0, T1, TRet> _target;
public override int ProducedStack => 1;
public override int ArgumentCount => 2;
public FuncCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Func<T0, T1, TRet>)target.CreateDelegate(typeof(Func<T0, T1, TRet>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 2];
object result;
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] });
}
else
{
result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]);
}
frame.Data[frame.StackIndex - 2] = result;
frame.StackIndex -= 1;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class FuncCallInstruction<T0, T1, T2, TRet> : CallInstruction
{
private readonly bool _isInstance;
private readonly Func<T0, T1, T2, TRet> _target;
public override int ProducedStack => 1;
public override int ArgumentCount => 3;
public FuncCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Func<T0, T1, T2, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, TRet>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 3];
object result;
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] });
}
else
{
result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]);
}
frame.Data[frame.StackIndex - 3] = result;
frame.StackIndex -= 2;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
internal sealed class FuncCallInstruction<T0, T1, T2, T3, TRet> : CallInstruction
{
private readonly bool _isInstance;
private readonly Func<T0, T1, T2, T3, TRet> _target;
public override int ProducedStack => 1;
public override int ArgumentCount => 4;
public FuncCallInstruction(MethodInfo target)
{
_isInstance = !target.IsStatic;
_target = (Func<T0, T1, T2, T3, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, TRet>));
}
public override int Run(InterpretedFrame frame)
{
object firstArg = frame.Data[frame.StackIndex - 4];
object result;
if (_isInstance)
{
NullCheck(firstArg);
}
if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda))
{
// no need to Invoke, just interpret the lambda body
result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] });
}
else
{
result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]);
}
frame.Data[frame.StackIndex - 4] = result;
frame.StackIndex -= 3;
return 1;
}
public override string ToString() => "Call(" + _target.Method + ")";
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
private void EmitAddress(Expression node, Type type)
{
EmitAddress(node, type, CompilationFlags.EmitExpressionStart);
}
// We don't want "ref" parameters to modify values of expressions
// except where it would in IL: locals, args, fields, and array elements
// (Unbox is an exception, it's intended to emit a ref to the original
// boxed value)
private void EmitAddress(Expression node, Type type, CompilationFlags flags)
{
Debug.Assert(node != null);
bool emitStart = (flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart;
CompilationFlags startEmitted = emitStart ? EmitExpressionStart(node) : CompilationFlags.EmitNoExpressionStart;
switch (node.NodeType)
{
default:
EmitExpressionAddress(node, type);
break;
case ExpressionType.ArrayIndex:
AddressOf((BinaryExpression)node, type);
break;
case ExpressionType.Parameter:
AddressOf((ParameterExpression)node, type);
break;
case ExpressionType.MemberAccess:
AddressOf((MemberExpression)node, type);
break;
case ExpressionType.Unbox:
AddressOf((UnaryExpression)node, type);
break;
case ExpressionType.Call:
AddressOf((MethodCallExpression)node, type);
break;
case ExpressionType.Index:
AddressOf((IndexExpression)node, type);
break;
}
if (emitStart)
{
EmitExpressionEnd(startEmitted);
}
}
private void AddressOf(BinaryExpression node, Type type)
{
Debug.Assert(node.NodeType == ExpressionType.ArrayIndex && node.Method == null);
if (TypeUtils.AreEquivalent(type, node.Type))
{
EmitExpression(node.Left);
EmitExpression(node.Right);
Type rightType = node.Right.Type;
if (TypeUtils.IsNullableType(rightType))
{
LocalBuilder loc = GetLocal(rightType);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValue(rightType);
FreeLocal(loc);
}
Type indexType = TypeUtils.GetNonNullableType(rightType);
if (indexType != typeof(int))
{
_ilg.EmitConvertToType(indexType, typeof(int), true);
}
_ilg.Emit(OpCodes.Ldelema, node.Type);
}
else
{
EmitExpressionAddress(node, type);
}
}
private void AddressOf(ParameterExpression node, Type type)
{
if (TypeUtils.AreEquivalent(type, node.Type))
{
if (node.IsByRef)
{
_scope.EmitGet(node);
}
else
{
_scope.EmitAddressOf(node);
}
}
else
{
EmitExpressionAddress(node, type);
}
}
private void AddressOf(MemberExpression node, Type type)
{
if (TypeUtils.AreEquivalent(type, node.Type))
{
// emit "this", if any
Type objectType = null;
if (node.Expression != null)
{
EmitInstance(node.Expression, objectType = node.Expression.Type);
}
EmitMemberAddress(node.Member, objectType);
}
else
{
EmitExpressionAddress(node, type);
}
}
// assumes the instance is already on the stack
private void EmitMemberAddress(MemberInfo member, Type objectType)
{
FieldInfo field = member as FieldInfo;
if ((object)field != null)
{
// Verifiable code may not take the address of an init-only field.
// If we are asked to do so then get the value out of the field, stuff it
// into a local of the same type, and then take the address of the local.
// Typically this is what we want to do anyway; if we are saying
// Foo.bar.ToString() for a static value-typed field bar then we don't need
// the address of field bar to do the call. The address of a local which
// has the same value as bar is sufficient.
// The C# compiler will not compile a lambda expression tree
// which writes to the address of an init-only field. But one could
// probably use the expression tree API to build such an expression.
// (When compiled, such an expression would fail silently.) It might
// be worth it to add checking to the expression tree API to ensure
// that it is illegal to attempt to write to an init-only field,
// the same way that it is illegal to write to a read-only property.
// The same goes for literal fields.
if (!field.IsLiteral && !field.IsInitOnly)
{
_ilg.EmitFieldAddress(field);
return;
}
}
EmitMemberGet(member, objectType);
LocalBuilder temp = GetLocal(GetMemberType(member));
_ilg.Emit(OpCodes.Stloc, temp);
_ilg.Emit(OpCodes.Ldloca, temp);
}
private void AddressOf(MethodCallExpression node, Type type)
{
// An array index of a multi-dimensional array is represented by a call to Array.Get,
// rather than having its own array-access node. This means that when we are trying to
// get the address of a member of a multi-dimensional array, we'll be trying to
// get the address of a Get method, and it will fail to do so. Instead, detect
// this situation and replace it with a call to the Address method.
if (!node.Method.IsStatic &&
node.Object.Type.IsArray &&
node.Method == node.Object.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance))
{
MethodInfo mi = node.Object.Type.GetMethod("Address", BindingFlags.Public | BindingFlags.Instance);
EmitMethodCall(node.Object, mi, node);
}
else
{
EmitExpressionAddress(node, type);
}
}
private void AddressOf(IndexExpression node, Type type)
{
if (!TypeUtils.AreEquivalent(type, node.Type) || node.Indexer != null)
{
EmitExpressionAddress(node, type);
return;
}
if (node.ArgumentCount == 1)
{
EmitExpression(node.Object);
EmitExpression(node.GetArgument(0));
_ilg.Emit(OpCodes.Ldelema, node.Type);
}
else
{
var address = node.Object.Type.GetMethod("Address", BindingFlags.Public | BindingFlags.Instance);
EmitMethodCall(node.Object, address, node);
}
}
private void AddressOf(UnaryExpression node, Type type)
{
Debug.Assert(node.NodeType == ExpressionType.Unbox);
Debug.Assert(type.GetTypeInfo().IsValueType);
// Unbox leaves a pointer to the boxed value on the stack
EmitExpression(node.Operand);
_ilg.Emit(OpCodes.Unbox, type);
}
private void EmitExpressionAddress(Expression node, Type type)
{
Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type));
EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
LocalBuilder tmp = GetLocal(type);
_ilg.Emit(OpCodes.Stloc, tmp);
_ilg.Emit(OpCodes.Ldloca, tmp);
}
// Emits the address of the expression, returning the write back if necessary
//
// For properties, we want to write back into the property if it's
// passed byref.
private WriteBack EmitAddressWriteBack(Expression node, Type type)
{
CompilationFlags startEmitted = EmitExpressionStart(node);
WriteBack result = null;
if (TypeUtils.AreEquivalent(type, node.Type))
{
switch (node.NodeType)
{
case ExpressionType.MemberAccess:
result = AddressOfWriteBack((MemberExpression)node);
break;
case ExpressionType.Index:
result = AddressOfWriteBack((IndexExpression)node);
break;
}
}
if (result == null)
{
EmitAddress(node, type, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
}
EmitExpressionEnd(startEmitted);
return result;
}
private WriteBack AddressOfWriteBack(MemberExpression node)
{
var property = node.Member as PropertyInfo;
if ((object)property == null || !property.CanWrite)
{
return null;
}
// emit instance, if any
LocalBuilder instanceLocal = null;
Type instanceType = null;
if (node.Expression != null)
{
EmitInstance(node.Expression, instanceType = node.Expression.Type);
// store in local
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, instanceLocal = GetInstanceLocal(instanceType));
}
PropertyInfo pi = (PropertyInfo)node.Member;
// emit the get
EmitCall(instanceType, pi.GetGetMethod(true));
// emit the address of the value
var valueLocal = GetLocal(node.Type);
_ilg.Emit(OpCodes.Stloc, valueLocal);
_ilg.Emit(OpCodes.Ldloca, valueLocal);
// Set the property after the method call
// don't re-evaluate anything
return delegate ()
{
if (instanceLocal != null)
{
_ilg.Emit(OpCodes.Ldloc, instanceLocal);
FreeLocal(instanceLocal);
}
_ilg.Emit(OpCodes.Ldloc, valueLocal);
FreeLocal(valueLocal);
EmitCall(instanceType, pi.GetSetMethod(true));
};
}
private WriteBack AddressOfWriteBack(IndexExpression node)
{
if (node.Indexer == null || !node.Indexer.CanWrite)
{
return null;
}
// emit instance, if any
LocalBuilder instanceLocal = null;
Type instanceType = null;
if (node.Object != null)
{
EmitInstance(node.Object, instanceType = node.Object.Type);
// store in local
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, instanceLocal = GetInstanceLocal(instanceType));
}
// Emit indexes. We don't allow byref args, so no need to worry
// about write-backs or EmitAddress
var n = node.ArgumentCount;
List<LocalBuilder> args = new List<LocalBuilder>(n);
for (var i = 0; i < n; i++)
{
var arg = node.GetArgument(i);
EmitExpression(arg);
var argLocal = GetLocal(arg.Type);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, argLocal);
args.Add(argLocal);
}
// emit the get
EmitGetIndexCall(node, instanceType);
// emit the address of the value
var valueLocal = GetLocal(node.Type);
_ilg.Emit(OpCodes.Stloc, valueLocal);
_ilg.Emit(OpCodes.Ldloca, valueLocal);
// Set the property after the method call
// don't re-evaluate anything
return delegate ()
{
if (instanceLocal != null)
{
_ilg.Emit(OpCodes.Ldloc, instanceLocal);
FreeLocal(instanceLocal);
}
foreach (var arg in args)
{
_ilg.Emit(OpCodes.Ldloc, arg);
FreeLocal(arg);
}
_ilg.Emit(OpCodes.Ldloc, valueLocal);
FreeLocal(valueLocal);
EmitSetIndexCall(node, instanceType);
};
}
private LocalBuilder GetInstanceLocal(Type type)
{
var instanceLocalType = type.GetTypeInfo().IsValueType ? type.MakeByRefType() : type;
return GetLocal(instanceLocalType);
}
}
}
| |
// ---------------------------------------------------------------------------
// Copyright (C) 2005 Microsoft Corporation - All Rights Reserved
// ---------------------------------------------------------------------------
using System;
using System.CodeDom;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Workflow.ComponentModel.Compiler;
namespace System.Workflow.Activities.Rules
{
#region RuleException
/// <summary>
/// Represents the base class for all rule engine exception classes
/// </summary>
[Serializable]
public class RuleException : Exception, ISerializable
{
/// <summary>
/// Initializes a new instance of the RuleException class
/// </summary>
public RuleException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the RuleException class
/// </summary>
/// <param name="message">The error message that explains the reason for the exception</param>
public RuleException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the RuleException class
/// </summary>
/// <param name="message">The error message that explains the reason for the exception</param>
/// <param name="ex">The inner exception</param>
public RuleException(string message, Exception ex)
: base(message, ex)
{
}
/// <summary>
/// Constructor required by for Serialization - initialize a new instance from serialized data
/// </summary>
/// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
/// <param name="context">Provides the means for deserializing the exception data</param>
protected RuleException(SerializationInfo serializeInfo, StreamingContext context)
: base(serializeInfo, context)
{
}
}
#endregion
#region RuleEvaluationException
/// <summary>
/// Represents the the exception thrown when an error is encountered during evaluation
/// </summary>
[Serializable]
public class RuleEvaluationException : RuleException, ISerializable
{
/// <summary>
/// Initializes a new instance of the RuleRuntimeException class
/// </summary>
public RuleEvaluationException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the RuleRuntimeException class
/// </summary>
/// <param name="message">The error message that explains the reason for the exception</param>
public RuleEvaluationException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the RuleRuntimeException class
/// </summary>
/// <param name="message">The error message that explains the reason for the exception</param>
/// <param name="ex">The inner exception</param>
public RuleEvaluationException(string message, Exception ex)
: base(message, ex)
{
}
/// <summary>
/// Constructor required by for Serialization - initialize a new instance from serialized data
/// </summary>
/// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
/// <param name="context">Provides the means for deserializing the exception data</param>
protected RuleEvaluationException(SerializationInfo serializeInfo, StreamingContext context)
: base(serializeInfo, context)
{
}
}
#endregion
#region RuleEvaluationIncompatibleTypesException
/// <summary>
/// Represents the exception thrown when types are incompatible
/// </summary>
[Serializable]
public class RuleEvaluationIncompatibleTypesException : RuleException, ISerializable
{
private Type m_leftType;
private CodeBinaryOperatorType m_op;
private Type m_rightType;
/// <summary>
/// Type on the left of the operator
/// </summary>
public Type Left
{
get { return m_leftType; }
set { m_leftType = value; }
}
/// <summary>
/// Arithmetic operation that failed
/// </summary>
public CodeBinaryOperatorType Operator
{
get { return m_op; }
set { m_op = value; }
}
/// <summary>
/// Type on the right of the operator
/// </summary>
public Type Right
{
get { return m_rightType; }
set { m_rightType = value; }
}
/// <summary>
/// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
/// </summary>
public RuleEvaluationIncompatibleTypesException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
/// </summary>
/// <param name="message"></param>
public RuleEvaluationIncompatibleTypesException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
/// </summary>
/// <param name="message"></param>
/// <param name="ex"></param>
public RuleEvaluationIncompatibleTypesException(string message, Exception ex)
: base(message, ex)
{
}
/// <summary>
/// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
/// </summary>
/// <param name="message"></param>
/// <param name="left"></param>
/// <param name="op"></param>
/// <param name="right"></param>
public RuleEvaluationIncompatibleTypesException(
string message,
Type left,
CodeBinaryOperatorType op,
Type right)
: base(message)
{
m_leftType = left;
m_op = op;
m_rightType = right;
}
/// <summary>
/// Initializes a new instance of the RuleEvaluationIncompatibleTypesException class
/// </summary>
/// <param name="message"></param>
/// <param name="left"></param>
/// <param name="op"></param>
/// <param name="right"></param>
/// <param name="ex"></param>
public RuleEvaluationIncompatibleTypesException(
string message,
Type left,
CodeBinaryOperatorType op,
Type right,
Exception ex)
: base(message, ex)
{
m_leftType = left;
m_op = op;
m_rightType = right;
}
/// <summary>
/// Constructor required by for Serialization - initialize a new instance from serialized data
/// </summary>
/// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
/// <param name="context">Provides the means for deserializing the exception data</param>
protected RuleEvaluationIncompatibleTypesException(SerializationInfo serializeInfo, StreamingContext context)
: base(serializeInfo, context)
{
if (serializeInfo == null)
throw new ArgumentNullException("serializeInfo");
string qualifiedTypeString = serializeInfo.GetString("left");
if (qualifiedTypeString != "null")
m_leftType = Type.GetType(qualifiedTypeString);
m_op = (CodeBinaryOperatorType)serializeInfo.GetValue("op", typeof(CodeBinaryOperatorType));
qualifiedTypeString = serializeInfo.GetString("right");
if (qualifiedTypeString != "null")
m_rightType = Type.GetType(qualifiedTypeString);
}
/// <summary>
/// Implements the ISerializable interface
/// </summary>
/// <param name="info">Reference to the object that holds the data needed to serialize/deserialize the exception</param>
/// <param name="context">Provides the means for serialiing the exception data</param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
base.GetObjectData(info, context);
info.AddValue("left", (m_leftType != null) ? m_leftType.AssemblyQualifiedName : "null");
info.AddValue("op", m_op);
info.AddValue("right", (m_rightType != null) ? m_rightType.AssemblyQualifiedName : "null");
}
}
#endregion
#region RuleSetValidationException
/// <summary>
/// Represents the exception thrown when a ruleset can not be validated
/// </summary>
[Serializable]
public class RuleSetValidationException : RuleException, ISerializable
{
private ValidationErrorCollection m_errors;
/// <summary>
/// Collection of validation errors that occurred while validating the RuleSet
/// </summary>
public ValidationErrorCollection Errors
{
get { return m_errors; }
}
/// <summary>
/// Initializes a new instance of the RuleSetValidationException class
/// </summary>
public RuleSetValidationException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the RuleSetValidationException class
/// </summary>
/// <param name="message"></param>
public RuleSetValidationException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the RuleSetValidationException class
/// </summary>
/// <param name="message"></param>
/// <param name="ex"></param>
public RuleSetValidationException(string message, Exception ex)
: base(message, ex)
{
}
/// <summary>
/// Initializes a new instance of the RuleSetValidationException class
/// </summary>
/// <param name="message"></param>
/// <param name="errors"></param>
public RuleSetValidationException(
string message,
ValidationErrorCollection errors)
: base(message)
{
m_errors = errors;
}
/// <summary>
/// Constructor required by for Serialization - initialize a new instance from serialized data
/// </summary>
/// <param name="serializeInfo">Reference to the object that holds the data needed to deserialize the exception</param>
/// <param name="context">Provides the means for deserializing the exception data</param>
protected RuleSetValidationException(SerializationInfo serializeInfo, StreamingContext context)
: base(serializeInfo, context)
{
if (serializeInfo == null)
throw new ArgumentNullException("serializeInfo");
m_errors = (ValidationErrorCollection)serializeInfo.GetValue("errors", typeof(ValidationErrorCollection));
}
/// <summary>
/// Implements the ISerializable interface
/// </summary>
/// <param name="info">Reference to the object that holds the data needed to serialize/deserialize the exception</param>
/// <param name="context">Provides the means for serialiing the exception data</param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
base.GetObjectData(info, context);
info.AddValue("errors", m_errors);
}
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security;
using Xunit;
namespace EnumerableTests
{
public class File_FileEnumerableTests
{
private static EnumerableUtils utils;
[Fact]
public static void RunTests()
{
utils = new EnumerableUtils();
utils.CreateTestDirs();
TestFileAPIs();
TestFileExceptions();
utils.DeleteTestDirs();
Assert.True(utils.Passed);
}
// file tests
private static void TestFileAPIs()
{
TestFileReadAllLinesFast(false);
TestFileReadAllLinesFast(true);
TestFileWriteAllLines(false, false);
TestFileWriteAllLines(true, false);
TestFileWriteAllLines(false, true);
TestFileWriteAllLines(true, true);
TestFileReadAllLinesIterator();
}
private static void TestFileReadAllLinesIterator()
{
IEnumerable<string> lines = File.ReadLines(Path.Combine(utils.testDir, "file1"));
foreach (var line in lines)
{
}
try
{
foreach (var line in lines)
{
}
}
catch(ObjectDisposedException)
{
// Currently the test is not hooked to report in case of failures. It is best if we rethrow an exception until we rewrite the harness
Console.WriteLine("We should not get an ObjectDisposedException but got one ; Dev10 864262 regressed");
throw;
}
}
private static void TestFileWriteAllLines(bool useEncodingOverload, bool append)
{
String chkptFlag = "chkpt_wal_";
int failCount = 0;
String encodingPart = useEncodingOverload ? ", Encoding" : "";
String writePart = append ? "Append" : "Write";
String testname = String.Format("File.{0}AllLines(path{1})", writePart, encodingPart);
String lineContent = "This is another line";
String firstLineContent = "This is the first line";
String[] contents = new String[10];
for (int i=0; i<contents.Length; i++)
{
contents[i] = lineContent;
}
String file1 = Path.Combine(utils.testDir, "file1.out");
if (append)
{
File.WriteAllLines(file1, new String[] {firstLineContent});
}
if (useEncodingOverload)
{
if (append)
{
File.AppendAllLines(file1, (IEnumerable<String>)contents, Encoding.UTF8);
}
else
{
File.WriteAllLines(file1, (IEnumerable<String>)contents, Encoding.UTF8);
}
}
else
{
if (append)
{
File.AppendAllLines(file1, (IEnumerable<String>)contents);
}
else
{
File.WriteAllLines(file1, (IEnumerable<String>)contents);
}
}
int expectedCount = append ? 11 : 10;
IEnumerable<String> fileContents = null;
if (useEncodingOverload)
{
fileContents = File.ReadLines(file1, Encoding.UTF8);
}
else
{
fileContents = File.ReadLines(file1);
}
int count = 0;
foreach (String line in fileContents)
{
if (append && count == 0)
{
if (!firstLineContent.Equals(line))
{
failCount++;
Console.WriteLine(chkptFlag + "1: {0} FAILED at first line", testname);
Console.WriteLine("got unexpected line: " + line);
}
count++;
continue;
}
count++;
if (!lineContent.Equals(line))
{
failCount++;
Console.WriteLine(chkptFlag + "2: {0} FAILED", testname);
Console.WriteLine("got unexpected line: " + line);
}
}
if (count != expectedCount)
{
failCount++;
Console.WriteLine(chkptFlag + "3: {0} FAILED. Line count didn't equal expected", testname);
Console.WriteLine("expected {0} but got {1}", expectedCount, count);
}
utils.PrintTestStatus(testname, "WriteAllLines", failCount);
File.Delete(file1);
}
private static void TestFileReadAllLinesFast(bool useEncodingOverload)
{
String chkptFlag = "chkpt_ralf_";
int failCount = 0;
string testname = null;
if (useEncodingOverload)
{
testname = "File.ReadLines(path, Encoding)";
}
else
{
testname = "File.ReadLines(path)";
}
String file1 = Path.Combine(utils.testDir, "file1.out");
String lineContent = "This is a line of test file content";
String[] contents = new String[10];
for (int i=0; i<contents.Length; i++)
{
contents[i] = lineContent;
}
if (useEncodingOverload)
{
File.WriteAllLines(file1, contents, Encoding.UTF8);
}
else
{
File.WriteAllLines(file1, contents);
}
IEnumerable<String> fileContents = null;
if (useEncodingOverload)
{
fileContents = File.ReadLines(file1, Encoding.UTF8);
}
else
{
fileContents = File.ReadLines(file1);
}
int count = 0;
foreach (String line in fileContents)
{
count++;
if (!lineContent.Equals(line))
{
failCount++;
Console.WriteLine(chkptFlag + "1: {0} FAILED", testname);
Console.WriteLine("got unexpected line: " + line);
}
}
if (count != 10)
{
failCount++;
Console.WriteLine(chkptFlag + "2: {0} FAILED. Line count didn't equal expected", testname);
Console.WriteLine("expected {0} but got {1}", 10, count);
}
File.Delete(file1);
// empty file
file1 = Path.Combine(utils.testDir, "empty.out");
FileStream fs = File.Create(file1);
fs.Dispose();
fileContents = null;
if (useEncodingOverload)
{
fileContents = File.ReadLines(file1, Encoding.UTF8);
}
else
{
fileContents = File.ReadLines(file1);
}
foreach (String line in fileContents)
{
failCount++;
Console.WriteLine(chkptFlag + "3: {0} FAILED", testname);
Console.WriteLine("got unexpected line: " + line);
}
File.Delete(file1);
utils.PrintTestStatus(testname, "ReadLines", failCount);
}
private static void TestFileExceptions()
{
// Create common file and dir names
String nullFileName = null;
String emptyFileName1 = "";
String emptyFileName2 = " ";
String longPath = Path.Combine(new String('a', IOInputs.MaxDirectory), "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "test.txt");
String notExistsFileName = null;
if (Interop.IsWindows) // drive labels
{
String unusedDrive = EnumerableUtils.GetUnusedDrive();
if (unusedDrive != null)
{
notExistsFileName = Path.Combine(unusedDrive, Path.Combine("temp", "notExists", "temp.txt")); // just skip otherwise
}
}
String[] lines = { "test line 1", "test line 2" };
IEnumerable<String> contents = (IEnumerable<String>)lines;
// Read exceptions
TestReadFileExceptions(nullFileName, "null path", Encoding.UTF8, new ArgumentNullException());
TestReadFileExceptions(emptyFileName1, "empty path 1", Encoding.UTF8, new ArgumentException());
TestReadFileExceptions(emptyFileName2, "empty path 2", Encoding.UTF8, new ArgumentException());
TestReadFileExceptions(longPath, "long path", Encoding.UTF8, new PathTooLongException());
if (notExistsFileName != null)
{
TestReadFileExceptions(notExistsFileName, "not exists", Encoding.UTF8, new DirectoryNotFoundException());
}
TestReadFileExceptionsWithEncoding("temp.txt", "null encoding", null, new ArgumentNullException(), File.ReadLines, File.ReadLines, "File.ReadLines");
// Write exceptions
TestWriteFileExceptions(nullFileName, "null path", contents, Encoding.UTF8, new ArgumentNullException());
TestWriteFileExceptions(emptyFileName1, "empty path 1", contents, Encoding.UTF8, new ArgumentException());
TestWriteFileExceptions(emptyFileName2, "empty path 2", contents, Encoding.UTF8, new ArgumentException());
TestWriteFileExceptions(longPath, "long path", contents, Encoding.UTF8, new PathTooLongException());
if (notExistsFileName != null)
{
TestWriteFileExceptions(notExistsFileName, "not exists", contents, Encoding.UTF8, new DirectoryNotFoundException());
}
TestWriteFileExceptions("temp.txt", "null contents", null, Encoding.UTF8, new ArgumentNullException());
TestWriteFileExceptionsWithEncoding("temp.txt", "null encoding", contents, null, new ArgumentNullException(), File.WriteAllLines, File.WriteAllLines, "File.WriteAllLines");
TestWriteFileExceptionsWithEncoding("temp.txt", "null encoding", contents, null, new ArgumentNullException(), File.AppendAllLines, File.AppendAllLines, "File.AppendAllLines");
}
private static void TestReadFileExceptions(String fileName, String fileNameDescription, Encoding encoding, Exception expectedException)
{
TestReadFileExceptionsDefaultEncoding(fileName, fileNameDescription, expectedException, File.ReadLines, File.ReadLines, "File.ReadLines");
TestReadFileExceptionsWithEncoding(fileName, fileNameDescription, encoding, expectedException, File.ReadLines, File.ReadLines, "File.ReadLines");
}
private static void TestReadFileExceptionsDefaultEncoding(String path, String pathDescription, Exception expectedException,
EnumerableUtils.ReadFastDelegate1 readDelegate, EnumerableUtils.ReadFastDelegate2 readDelegate2, String methodName )
{
int failCount = 0;
String chkptFlag = "chkpt_rfede_";
try
{
IEnumerable<String> lines = readDelegate(path);
Console.WriteLine(chkptFlag + "1: didn't throw");
failCount++;
}
catch (Exception e)
{
if (e.GetType() != expectedException.GetType())
{
failCount++;
Console.WriteLine(chkptFlag + "2: threw wrong exception");
Console.WriteLine(e);
}
}
String testName = String.Format("TestReadFileExceptions({0})", pathDescription);
utils.PrintTestStatus(testName, methodName, failCount);
}
private static void TestReadFileExceptionsWithEncoding(String path, String pathDescription, Encoding encoding, Exception expectedException,
EnumerableUtils.ReadFastDelegate1 readDelegate, EnumerableUtils.ReadFastDelegate2 readDelegate2, String methodName )
{
int failCount = 0;
String chkptFlag = "chkpt_rfewe_";
try
{
IEnumerable<String> lines = readDelegate2(path, encoding);
Console.WriteLine(chkptFlag + "1: didn't throw");
failCount++;
}
catch (Exception e)
{
if (e.GetType() != expectedException.GetType())
{
failCount++;
Console.WriteLine(chkptFlag + "2: threw wrong exception");
Console.WriteLine(e);
}
}
String testName = String.Format("TestReadFileExceptions_Encoding({0})", pathDescription);
utils.PrintTestStatus(testName, methodName, failCount);
}
private static void TestWriteFileExceptions(String fileName, String fileNameDescription, IEnumerable<String> contents, Encoding encoding, Exception expectedException)
{
TestWriteFileExceptionsDefaultEncoding(fileName, fileNameDescription, contents, expectedException, File.WriteAllLines, File.WriteAllLines, "File.WriteAllLines");
TestWriteFileExceptionsWithEncoding(fileName, fileNameDescription, contents, encoding, expectedException, File.WriteAllLines, File.WriteAllLines, "File.WriteAllLines");
TestWriteFileExceptionsDefaultEncoding(fileName, fileNameDescription, contents, expectedException, File.AppendAllLines, File.AppendAllLines, "File.AppendAllLines");
TestWriteFileExceptionsWithEncoding(fileName, fileNameDescription, contents, encoding, expectedException, File.AppendAllLines, File.AppendAllLines, "File.AppendAllLines");
}
private static void TestWriteFileExceptionsDefaultEncoding(String path, String pathDescription, IEnumerable<String> contents, Exception expectedException,
EnumerableUtils.WriteFastDelegate1 writeDelegate, EnumerableUtils.WriteFastDelegate2 writeDelegate2, String methodName )
{
int failCount = 0;
String chkptFlag = "chkpt_wfede_";
try
{
writeDelegate(path, contents);
Console.WriteLine(chkptFlag + "1: didn't throw");
failCount++;
}
catch (Exception e)
{
if (e.GetType() != expectedException.GetType())
{
failCount++;
Console.WriteLine(chkptFlag + "2: threw wrong exception");
Console.WriteLine(e);
}
}
String testName = String.Format("TestWriteFileExceptions({0})", pathDescription);
utils.PrintTestStatus(testName, methodName, failCount);
}
private static void TestWriteFileExceptionsWithEncoding(String path, String pathDescription, IEnumerable<String> contents, Encoding encoding, Exception expectedException,
EnumerableUtils.WriteFastDelegate1 writeDelegate, EnumerableUtils.WriteFastDelegate2 writeDelegate2, String methodName )
{
int failCount = 0;
String chkptFlag = "chkpt_wfewe_";
try
{
writeDelegate2(path, contents, encoding);
Console.WriteLine(chkptFlag + "1: didn't throw");
failCount++;
}
catch (Exception e)
{
if (e.GetType() != expectedException.GetType())
{
failCount++;
Console.WriteLine(chkptFlag + "2: threw wrong exception");
Console.WriteLine(e);
}
}
String testName = String.Format("TestWriteFileExceptions_Encoding({0})", pathDescription);
utils.PrintTestStatus(testName, methodName, failCount);
}
}
}
| |
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using QEngine.Physics.Collision.Narrowphase;
using QEngine.Physics.Collision.Shapes;
using QEngine.Physics.Dynamics;
using QEngine.Physics.Shared;
using QEngine.Physics.Shared.Optimization;
namespace QEngine.Physics.Collision.ContactSystem
{
/// <summary>
/// The class manages contact between two shapes. A contact exists for each overlapping
/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist
/// that has no contact points.
/// </summary>
public class Contact
{
private static EdgeShape _edge = new EdgeShape();
private static ContactType[,] _registers =
{
{
ContactType.Circle,
ContactType.EdgeAndCircle,
ContactType.PolygonAndCircle,
ContactType.ChainAndCircle
},
{
ContactType.EdgeAndCircle,
ContactType.NotSupported,
// 1,1 is invalid (no ContactType.Edge)
ContactType.EdgeAndPolygon,
ContactType.NotSupported
// 1,3 is invalid (no ContactType.EdgeAndLoop)
},
{
ContactType.PolygonAndCircle,
ContactType.EdgeAndPolygon,
ContactType.Polygon,
ContactType.ChainAndPolygon
},
{
ContactType.ChainAndCircle,
ContactType.NotSupported,
// 3,1 is invalid (no ContactType.EdgeAndLoop)
ContactType.ChainAndPolygon,
ContactType.NotSupported
// 3,3 is invalid (no ContactType.Loop)
}
};
// Nodes for connecting bodies.
internal ContactEdge _nodeA = new ContactEdge();
internal ContactEdge _nodeB = new ContactEdge();
internal float _toi;
internal int _toiCount;
private ContactType _type;
public Fixture FixtureA;
public Fixture FixtureB;
/// <summary>
/// Get the contact manifold. Do not modify the manifold unless you understand the
/// internals of Box2D.
/// </summary>
public Manifold Manifold;
private Contact(Fixture fA, int indexA, Fixture fB, int indexB)
{
Reset(fA, indexA, fB, indexB);
}
public float Friction { get; set; }
public float Restitution { get; set; }
/// <summary>
/// Get or set the desired tangent speed for a conveyor belt behavior. In meters per second.
/// </summary>
public float TangentSpeed { get; set; }
/// <summary>
/// Get the child primitive index for fixture A.
/// </summary>
/// <value>The child index A.</value>
public int ChildIndexA { get; private set; }
/// <summary>
/// Get the child primitive index for fixture B.
/// </summary>
/// <value>The child index B.</value>
public int ChildIndexB { get; private set; }
/// <summary>
/// Enable/disable this contact.The contact is only disabled for the current
/// time step (or sub-step in continuous collisions).
/// </summary>
public bool Enabled
{
get => (_flags & ContactFlags.EnabledFlag) == ContactFlags.EnabledFlag;
set
{
if (value)
_flags |= ContactFlags.EnabledFlag;
else
_flags &= ~ContactFlags.EnabledFlag;
}
}
internal bool IsTouching => (_flags & ContactFlags.TouchingFlag) == ContactFlags.TouchingFlag;
internal bool IslandFlag => (_flags & ContactFlags.IslandFlag) == ContactFlags.IslandFlag;
internal bool TOIFlag => (_flags & ContactFlags.TOIFlag) == ContactFlags.TOIFlag;
internal bool FilterFlag => (_flags & ContactFlags.FilterFlag) == ContactFlags.FilterFlag;
internal ContactFlags _flags;
public void ResetRestitution()
{
Restitution = Settings.MixRestitution(FixtureA.Restitution, FixtureB.Restitution);
}
public void ResetFriction()
{
Friction = Settings.MixFriction(FixtureA.Friction, FixtureB.Friction);
}
/// <summary>
/// Gets the world manifold.
/// </summary>
public void GetWorldManifold(out Vector2 normal, out FixedArray2<Vector2> points)
{
Body bodyA = FixtureA.Body;
Body bodyB = FixtureB.Body;
Shape shapeA = FixtureA.Shape;
Shape shapeB = FixtureB.Shape;
WorldManifold.Initialize(ref Manifold, ref bodyA._xf, shapeA.Radius, ref bodyB._xf, shapeB.Radius, out normal, out points, out _);
}
private void Reset(Fixture fA, int indexA, Fixture fB, int indexB)
{
_flags = ContactFlags.EnabledFlag;
FixtureA = fA;
FixtureB = fB;
ChildIndexA = indexA;
ChildIndexB = indexB;
Manifold.PointCount = 0;
_nodeA.Contact = null;
_nodeA.Prev = null;
_nodeA.Next = null;
_nodeA.Other = null;
_nodeB.Contact = null;
_nodeB.Prev = null;
_nodeB.Next = null;
_nodeB.Other = null;
_toiCount = 0;
//Velcro: We only set the friction and restitution if we are not destroying the contact
if (FixtureA != null && FixtureB != null)
{
Friction = Settings.MixFriction(FixtureA.Friction, FixtureB.Friction);
Restitution = Settings.MixRestitution(FixtureA.Restitution, FixtureB.Restitution);
}
TangentSpeed = 0;
}
/// <summary>
/// Update the contact manifold and touching status.
/// Note: do not assume the fixture AABBs are overlapping or are valid.
/// </summary>
/// <param name="contactManager">The contact manager.</param>
internal void Update(ContactManager contactManager)
{
if (FixtureA == null || FixtureB == null)
return;
Body bodyA = FixtureA.Body;
Body bodyB = FixtureB.Body;
Manifold oldManifold = Manifold;
// Re-enable this contact.
_flags |= ContactFlags.EnabledFlag;
bool touching;
bool wasTouching = IsTouching;
bool sensor = FixtureA.IsSensor || FixtureB.IsSensor;
// Is this contact a sensor?
if (sensor)
{
Shape shapeA = FixtureA.Shape;
Shape shapeB = FixtureB.Shape;
touching = Narrowphase.Collision.TestOverlap(shapeA, ChildIndexA, shapeB, ChildIndexB, ref bodyA._xf, ref bodyB._xf);
// Sensors don't generate manifolds.
Manifold.PointCount = 0;
}
else
{
Evaluate(ref Manifold, ref bodyA._xf, ref bodyB._xf);
touching = Manifold.PointCount > 0;
// Match old contact ids to new contact ids and copy the
// stored impulses to warm start the solver.
for (int i = 0; i < Manifold.PointCount; ++i)
{
ManifoldPoint mp2 = Manifold.Points[i];
mp2.NormalImpulse = 0.0f;
mp2.TangentImpulse = 0.0f;
ContactID id2 = mp2.Id;
for (int j = 0; j < oldManifold.PointCount; ++j)
{
ManifoldPoint mp1 = oldManifold.Points[j];
if (mp1.Id.Key == id2.Key)
{
mp2.NormalImpulse = mp1.NormalImpulse;
mp2.TangentImpulse = mp1.TangentImpulse;
break;
}
}
Manifold.Points[i] = mp2;
}
if (touching != wasTouching)
{
bodyA.Awake = true;
bodyB.Awake = true;
}
}
if (touching)
_flags |= ContactFlags.TouchingFlag;
else
_flags &= ~ContactFlags.TouchingFlag;
if (!wasTouching && touching)
{
FixtureA.OnCollision?.Invoke(FixtureA, FixtureB, this);
FixtureB.OnCollision?.Invoke(FixtureB, FixtureA, this);
contactManager.BeginContact?.Invoke(this);
// Velcro: If the user disabled the contact (needed to exclude it in TOI solver) at any point by
// any of the callbacks, we need to mark it as not touching and call any separation
// callbacks for fixtures that didn't explicitly disable the collision.
if (!Enabled)
touching = false;
}
// Jacob testing this TODO
if(wasTouching && touching)
{
//seeing if this will always call the collision event when they are currently touching
//even after the collision event has been triggered
FixtureA?.OnCollisionStay?.Invoke(FixtureA, FixtureB, this);
FixtureB?.OnCollisionStay?.Invoke(FixtureB, FixtureA, this);
}
if (wasTouching && !touching)
{
FixtureA?.OnSeparation?.Invoke(FixtureA, FixtureB, this);
FixtureB?.OnSeparation?.Invoke(FixtureB, FixtureA, this);
contactManager.EndContact?.Invoke(this);
}
if (sensor)
return;
contactManager.PreSolve?.Invoke(this, ref oldManifold);
}
/// <summary>
/// Evaluate this contact with your own manifold and transforms.
/// </summary>
/// <param name="manifold">The manifold.</param>
/// <param name="transformA">The first transform.</param>
/// <param name="transformB">The second transform.</param>
private void Evaluate(ref Manifold manifold, ref Transform transformA, ref Transform transformB)
{
switch (_type)
{
case ContactType.Polygon:
CollidePolygon.CollidePolygons(ref manifold, (PolygonShape)FixtureA.Shape, ref transformA, (PolygonShape)FixtureB.Shape, ref transformB);
break;
case ContactType.PolygonAndCircle:
CollideCircle.CollidePolygonAndCircle(ref manifold, (PolygonShape)FixtureA.Shape, ref transformA, (CircleShape)FixtureB.Shape, ref transformB);
break;
case ContactType.EdgeAndCircle:
CollideEdge.CollideEdgeAndCircle(ref manifold, (EdgeShape)FixtureA.Shape, ref transformA, (CircleShape)FixtureB.Shape, ref transformB);
break;
case ContactType.EdgeAndPolygon:
CollideEdge.CollideEdgeAndPolygon(ref manifold, (EdgeShape)FixtureA.Shape, ref transformA, (PolygonShape)FixtureB.Shape, ref transformB);
break;
case ContactType.ChainAndCircle:
ChainShape chain = (ChainShape)FixtureA.Shape;
chain.GetChildEdge(_edge, ChildIndexA);
CollideEdge.CollideEdgeAndCircle(ref manifold, _edge, ref transformA, (CircleShape)FixtureB.Shape, ref transformB);
break;
case ContactType.ChainAndPolygon:
ChainShape loop2 = (ChainShape)FixtureA.Shape;
loop2.GetChildEdge(_edge, ChildIndexA);
CollideEdge.CollideEdgeAndPolygon(ref manifold, _edge, ref transformA, (PolygonShape)FixtureB.Shape, ref transformB);
break;
case ContactType.Circle:
CollideCircle.CollideCircles(ref manifold, (CircleShape)FixtureA.Shape, ref transformA, (CircleShape)FixtureB.Shape, ref transformB);
break;
default:
throw new ArgumentException("You are using an unsupported contact type.");
}
}
internal static Contact Create(Fixture fixtureA, int indexA, Fixture fixtureB, int indexB)
{
ShapeType type1 = fixtureA.Shape.ShapeType;
ShapeType type2 = fixtureB.Shape.ShapeType;
System.Diagnostics.Debug.Assert(ShapeType.Unknown < type1 && type1 < ShapeType.TypeCount);
System.Diagnostics.Debug.Assert(ShapeType.Unknown < type2 && type2 < ShapeType.TypeCount);
Contact c;
Queue<Contact> pool = fixtureA.Body._world._contactPool;
if (pool.Count > 0)
{
c = pool.Dequeue();
if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon)) && !(type2 == ShapeType.Edge && type1 == ShapeType.Polygon))
{
c.Reset(fixtureA, indexA, fixtureB, indexB);
}
else
{
c.Reset(fixtureB, indexB, fixtureA, indexA);
}
}
else
{
// Edge+Polygon is non-symetrical due to the way Erin handles collision type registration.
if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon)) && !(type2 == ShapeType.Edge && type1 == ShapeType.Polygon))
{
c = new Contact(fixtureA, indexA, fixtureB, indexB);
}
else
{
c = new Contact(fixtureB, indexB, fixtureA, indexA);
}
}
c._type = _registers[(int)type1, (int)type2];
return c;
}
internal void Destroy()
{
FixtureA.Body._world._contactPool.Enqueue(this);
if (Manifold.PointCount > 0 && FixtureA.IsSensor == false && FixtureB.IsSensor == false)
{
FixtureA.Body.Awake = true;
FixtureB.Body.Awake = true;
}
Reset(null, 0, null, 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Forms;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Messaging;
using OPSCallAssistant.Model;
using OPSSDK;
using OPSSDKCommon.Model;
using OPSSDKCommon.Model.Call;
using Ozeki.VoIP;
using IClient = OPSCallAssistant.Model.IClient;
using OPSCallAssistant.Utils;
using Ozeki.Media.MediaHandlers;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace OPSCallAssistant.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
public static string ShowCall = Guid.NewGuid().ToString();
IClient _client;
ISettingsRepository _settingsRepository;
object _sync;
ICollection<PhoneBookItem> _internalPhoneBookItems;
PhoneBookItem _currentUser;
private ICall initiatedCall;
Random random;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
try
{
random = new Random();
_sync = new object();
_client = SimpleIoc.Default.GetInstance<IClient>();
_settingsRepository = SimpleIoc.Default.GetInstance<ISettingsRepository>();
apiExt = _client.GetAPIExtension(null);
CallCommand = new RelayCommand<string>(CallPressed,
phoneNumber => !string.IsNullOrEmpty(UsedPhoneNumber) && !string.IsNullOrEmpty(phoneNumber));
_internalPhoneBookItems = new List<PhoneBookItem>();
PhoneBookItems = CollectionViewSource.GetDefaultView(_internalPhoneBookItems);
_client.PhoneBookChanged += OnPhoneBookChanged;
_client.SessionCreated += ClientOnSessionCreated;
_client.ErrorOccurred += ClientOnErrorOccurred;
_client.GetPhoneBook();
}
catch (Exception ex)
{
}
}
private void ClientOnErrorOccurred(object sender, VoIPEventArgs<ErrorInfo> e)
{
Process.Start(Assembly.GetEntryAssembly().Location, "-reconnect");
Environment.Exit(0);
}
private void CallPressed(string phoneNumber)
{
Logger.Log("Calling " + phoneNumber);
WaveStreamPlayback waveStream = null;
initiatedCall = apiExt.CreateCall(UsedPhoneNumber, phoneNumber, phoneNumber);
if (initiatedCall == null)
return;
bool transferStarted = false;
initiatedCall.CallStateChanged += (sender, e) =>
{
try
{
if (e.Item == CallState.Answered)
{
if (transferStarted)
{
initiatedCall.DisconnectAudioSender(waveStream);
waveStream.Dispose();
var tts = new TextToSpeech();
tts.Stopped += (sender1, e1)=>{
tts.Dispose();
initiatedCall.HangUp();
};
initiatedCall.ConnectAudioSender(tts);
tts.AddAndStartText(string.Format("Calling {0} has failed. Please try again later.", phoneNumber));
return;
}
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("OPSCallAssistant.Resources.ringback.wav");
waveStream = new WaveStreamPlayback(stream, true, true);
initiatedCall.ConnectAudioSender(waveStream);
waveStream.StartStreaming();
transferStarted = true;
initiatedCall.BlindTransfer(phoneNumber);
}
if (e.Item.IsCallEnded())
{
if (waveStream != null)
waveStream.Dispose();
}
}
catch(Exception ex)
{
Logger.Log(ex.Message);
Logger.Log(ex.StackTrace);
}
var k = 65;
};
initiatedCall.Start();
}
private void ClientOnSessionCreated(object sender, VoIPEventArgs<ISession> e)
{
var session = e.Item;
Logger.Log(string.Format("Session created: source:{0}, callerId:{1}, dialed:{2}, destination:{3}", e.Item.Source, e.Item.CallerId, e.Item.DialedNumber, e.Item.Destination));
if (CurrentUser != null && (CurrentUser.Extensions.Contains(e.Item.Source) || CurrentUser.Extensions.Contains(e.Item.Destination)))
{
Logger.Log("Current user will be notified.");
try
{
var url = string.Format(_settingsRepository.GetUserInfo().ServerURL, Uri.EscapeDataString(e.Item.Source),
Uri.EscapeDataString(e.Item.CallerId), Uri.EscapeDataString(e.Item.DialedNumber),
Uri.EscapeDataString(e.Item.Destination), Uri.EscapeDataString(e.Item.CallDirection.ToString()),
Uri.EscapeDataString(UsedPhoneNumber), Uri.EscapeDataString(e.Item.SessionID));
new Uri(url);
Messenger.Default.Send(new NotificationMessage<object>(new CallInfo(e.Item, url, UsedPhoneNumber), ShowCall));
}
catch(Exception ex)
{
Logger.Log(ex.Message);
Logger.Log(ex.StackTrace);
}
}
else
Logger.Log("Current user will not be notified.");
}
private void OnPhoneBookChanged(object sender, VoIPEventArgs<List<PhoneBookItem>> e)
{
Logger.Log("Phonebook changed.");
UpdatePhoneBook(e.Item);
}
private void UpdatePhoneBook(ICollection<PhoneBookItem> phoneBook)
{
lock (_sync)
{
var currentUser = phoneBook.FirstOrDefault(i => i.Username == _client.User.Username);
if (currentUser == null)
{
LoginInfo = "Current user does not exists in phonebook";
}
else
{
phoneBook.Remove(currentUser);
LoginInfo =
string.Format(
"{0} logged in\nUsed phone number in assistant: ",
currentUser.Name);
CurrentUser = currentUser;
var userInfo = _settingsRepository.GetUserInfo();
if (!string.IsNullOrEmpty(userInfo.CurrentPhoneNumber) && currentUser.Extensions.Contains(userInfo.CurrentPhoneNumber))
UsedPhoneNumber = userInfo.CurrentPhoneNumber;
else
UsedPhoneNumber = currentUser.Extensions.FirstOrDefault();
}
_internalPhoneBookItems = phoneBook;
PhoneBookItems = CollectionViewSource.GetDefaultView(phoneBook);
}
}
#region Properties
ICollectionView _phoneBookItems;
public ICollectionView PhoneBookItems
{
get { return _phoneBookItems; }
private set
{
_phoneBookItems = value;
_phoneBookItems.Filter = FilterItem;
RaisePropertyChanged(() => PhoneBookItems);
}
}
string _filter;
public string Filter
{
get { return _filter; }
set
{
_filter = value;
PhoneBookItems.Refresh();
}
}
bool FilterItem(object o)
{
var phoneBookItem = (PhoneBookItem)o;
if (string.IsNullOrEmpty(Filter))
return true;
return phoneBookItem.Name.ToLower().Contains(Filter.ToLower());
}
string _loginInfo;
public string LoginInfo
{
get { return _loginInfo; }
set
{
_loginInfo = value;
RaisePropertyChanged(() => LoginInfo);
}
}
PhoneBookItem _selectedUser;
public PhoneBookItem SelectedUser
{
get { return _selectedUser; }
set
{
_selectedUser = value;
RaisePropertyChanged(() => SelectedUser);
//SelectedPhoneNumber = _selectedUser.PhoneNumbers.FirstOrDefault();
}
}
string _selectedPhoneNumber;
private IAPIExtension apiExt;
public string SelectedPhoneNumber
{
get { return _selectedPhoneNumber; }
set
{
_selectedPhoneNumber = value;
RaisePropertyChanged(() => SelectedPhoneNumber);
}
}
public PhoneBookItem CurrentUser
{
get { return _currentUser; }
set
{
_currentUser = value;
RaisePropertyChanged(() => CurrentUser);
}
}
string _usedPhoneNumber;
public string UsedPhoneNumber
{
get { return _usedPhoneNumber; }
set
{
_usedPhoneNumber = value;
var userInfo = _settingsRepository.GetUserInfo();
userInfo.CurrentPhoneNumber = value;
_settingsRepository.SetUserInfo(userInfo);
RaisePropertyChanged(() => UsedPhoneNumber);
}
}
public RelayCommand<string> CallCommand { get; private set; }
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource
{
public abstract partial class AbstractMetadataAsSourceTests
{
public const string DefaultMetadataSource = "public class C {}";
public const string DefaultSymbolMetadataName = "C";
internal class TestContext : IDisposable
{
private readonly TestWorkspace _workspace;
private readonly IMetadataAsSourceFileService _metadataAsSourceService;
private readonly ITextBufferFactoryService _textBufferFactoryService;
public static async Task<TestContext> CreateAsync(string projectLanguage = null, IEnumerable<string> metadataSources = null, bool includeXmlDocComments = false, string sourceWithSymbolReference = null)
{
projectLanguage = projectLanguage ?? LanguageNames.CSharp;
metadataSources = metadataSources ?? SpecializedCollections.EmptyEnumerable<string>();
metadataSources = !metadataSources.Any()
? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }
: metadataSources;
var workspace = await CreateWorkspaceAsync(projectLanguage, metadataSources, includeXmlDocComments, sourceWithSymbolReference);
return new TestContext(workspace);
}
public TestContext(TestWorkspace workspace)
{
_workspace = workspace;
_metadataAsSourceService = _workspace.GetService<IMetadataAsSourceFileService>();
_textBufferFactoryService = _workspace.GetService<ITextBufferFactoryService>();
}
public Solution CurrentSolution
{
get { return _workspace.CurrentSolution; }
}
public Project DefaultProject
{
get { return this.CurrentSolution.Projects.First(); }
}
public Task<MetadataAsSourceFile> GenerateSourceAsync(ISymbol symbol, Project project = null)
{
project = project ?? this.DefaultProject;
// Generate and hold onto the result so it can be disposed of with this context
return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol);
}
public async Task<MetadataAsSourceFile> GenerateSourceAsync(string symbolMetadataName = null, Project project = null)
{
symbolMetadataName = symbolMetadataName ?? AbstractMetadataAsSourceTests.DefaultSymbolMetadataName;
project = project ?? this.DefaultProject;
// Get an ISymbol corresponding to the metadata name
var compilation = await project.GetCompilationAsync();
var diagnostics = compilation.GetDiagnostics().ToArray();
Assert.Equal(0, diagnostics.Length);
var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation);
// Generate and hold onto the result so it can be disposed of with this context
var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol);
return result;
}
private static string GetSpaceSeparatedTokens(string source)
{
var tokens = source.Split(new[] { ' ', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).Where(s => s != string.Empty);
return string.Join(" ", tokens);
}
public void VerifyResult(MetadataAsSourceFile file, string expected, bool compareTokens = true)
{
var actual = File.ReadAllText(file.FilePath).Trim();
var actualSpan = file.IdentifierLocation.SourceSpan;
if (compareTokens)
{
// Compare tokens and verify location relative to the generated tokens
expected = GetSpaceSeparatedTokens(expected);
actual = GetSpaceSeparatedTokens(actual.Insert(actualSpan.Start, "[|").Insert(actualSpan.End + 2, "|]"));
}
else
{
// Compare exact texts and verify that the location returned is exactly that
// indicated by expected
MarkupTestFile.GetSpan(expected.TrimStart().TrimEnd(), out expected, out var expectedSpan);
Assert.Equal(expectedSpan.Start, actualSpan.Start);
Assert.Equal(expectedSpan.End, actualSpan.End);
}
Assert.Equal(expected, actual);
}
public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, bool compareTokens = true, Project project = null)
{
var result = await GenerateSourceAsync(symbolMetadataName, project);
VerifyResult(result, expected, compareTokens);
}
public void VerifyDocumentReused(MetadataAsSourceFile a, MetadataAsSourceFile b)
{
Assert.Same(a.FilePath, b.FilePath);
}
public void VerifyDocumentNotReused(MetadataAsSourceFile a, MetadataAsSourceFile b)
{
Assert.NotSame(a.FilePath, b.FilePath);
}
public void Dispose()
{
try
{
_metadataAsSourceService.CleanupGeneratedFiles();
}
finally
{
_workspace.Dispose();
}
}
public async Task<ISymbol> ResolveSymbolAsync(string symbolMetadataName, Compilation compilation = null)
{
if (compilation == null)
{
compilation = await this.DefaultProject.GetCompilationAsync();
var diagnostics = compilation.GetDiagnostics().ToArray();
Assert.Equal(0, diagnostics.Length);
}
foreach (var reference in compilation.References)
{
var assemblySymbol = (IAssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference);
var namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(symbolMetadataName);
if (namedTypeSymbol != null)
{
return namedTypeSymbol;
}
else
{
// The symbol name could possibly be referring to the member of a named
// type. Parse the member symbol name.
var lastDotIndex = symbolMetadataName.LastIndexOf('.');
if (lastDotIndex < 0)
{
// The symbol name is not a member name and the named type was not found
// in this assembly
continue;
}
// The member symbol name itself could contain a dot (e.g. '.ctor'), so make
// sure we don't cut that off
while (lastDotIndex > 0 && symbolMetadataName[lastDotIndex - 1] == '.')
{
--lastDotIndex;
}
var memberSymbolName = symbolMetadataName.Substring(lastDotIndex + 1);
var namedTypeName = symbolMetadataName.Substring(0, lastDotIndex);
namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(namedTypeName);
if (namedTypeSymbol != null)
{
var memberSymbol = namedTypeSymbol.GetMembers()
.Where(member => member.MetadataName == memberSymbolName)
.FirstOrDefault();
if (memberSymbol != null)
{
return memberSymbol;
}
}
}
}
return null;
}
private static bool ContainsVisualBasicKeywords(string input)
{
return
input.Contains("Class") ||
input.Contains("Structure") ||
input.Contains("Namespace") ||
input.Contains("Sub") ||
input.Contains("Function") ||
input.Contains("Dim");
}
private static string DeduceLanguageString(string input)
{
return ContainsVisualBasicKeywords(input)
? LanguageNames.VisualBasic : LanguageNames.CSharp;
}
private static Task<TestWorkspace> CreateWorkspaceAsync(string projectLanguage, IEnumerable<string> metadataSources, bool includeXmlDocComments, string sourceWithSymbolReference)
{
var xmlString = string.Concat(@"
<Workspace>
<Project Language=""", projectLanguage, @""" CommonReferences=""true"">");
metadataSources = metadataSources ?? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource };
foreach (var source in metadataSources)
{
var metadataLanguage = DeduceLanguageString(source);
xmlString = string.Concat(xmlString, string.Format(@"
<MetadataReferenceFromSource Language=""{0}"" CommonReferences=""true"" IncludeXmlDocComments=""{2}"">
<Document FilePath=""MetadataDocument"">
{1}
</Document>
</MetadataReferenceFromSource>",
metadataLanguage,
SecurityElement.Escape(source),
includeXmlDocComments.ToString()));
}
if (sourceWithSymbolReference != null)
{
xmlString = string.Concat(xmlString, string.Format(@"
<Document FilePath=""SourceDocument"">
{0}
</Document>",
sourceWithSymbolReference));
}
xmlString = string.Concat(xmlString, @"
</Project>
</Workspace>");
return TestWorkspace.CreateAsync(xmlString);
}
internal Document GetDocument(MetadataAsSourceFile file)
{
using (var reader = new StreamReader(file.FilePath))
{
var textBuffer = _textBufferFactoryService.CreateTextBuffer(reader, _textBufferFactoryService.TextContentType);
Assert.True(_metadataAsSourceService.TryAddDocumentToWorkspace(file.FilePath, textBuffer));
return textBuffer.AsTextContainer().GetRelatedDocuments().Single();
}
}
internal async Task<ISymbol> GetNavigationSymbolAsync()
{
var testDocument = _workspace.Documents.Single(d => d.FilePath == "SourceDocument");
var document = _workspace.CurrentSolution.GetDocument(testDocument.Id);
var syntaxRoot = await document.GetSyntaxRootAsync();
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel.GetSymbolInfo(syntaxRoot.FindNode(testDocument.SelectedSpans.Single())).Symbol;
}
}
}
}
| |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using JavaScriptEngineSwitcher.Core;
using Moq;
using React.Exceptions;
using Xunit;
namespace React.Tests.Core
{
public class JavaScriptEngineFactoryTest
{
private JavaScriptEngineFactory CreateBasicFactory()
{
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string>());
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
return CreateFactory(config, cache, fileSystem, () =>
{
var mockJsEngine = new Mock<IJsEngine>();
mockJsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
return mockJsEngine.Object;
});
}
private JavaScriptEngineFactory CreateFactory(
Mock<IReactSiteConfiguration> config,
Mock<ICache> cache,
Mock<IFileSystem> fileSystem,
Func<IJsEngine> innerEngineFactory
)
{
return CreateFactory(config.Object, cache.Object, fileSystem.Object, innerEngineFactory);
}
private JavaScriptEngineFactory CreateFactory(
IReactSiteConfiguration config,
ICache cache,
IFileSystem fileSystem,
Func<IJsEngine> innerEngineFactory
)
{
var engineFactory = new Mock<IJsEngineFactory>();
engineFactory.Setup(x => x.EngineName).Returns("MockEngine");
engineFactory.Setup(x => x.CreateEngine()).Returns(innerEngineFactory);
var engineSwitcher = new JsEngineSwitcher(
new JsEngineFactoryCollection { engineFactory.Object },
string.Empty
);
return new JavaScriptEngineFactory(engineSwitcher, config, cache, fileSystem);
}
[Fact]
public void ShouldReturnSameEngine()
{
var factory = CreateBasicFactory();
var engine1 = factory.GetEngineForCurrentThread();
var engine2 = factory.GetEngineForCurrentThread();
Assert.Equal(engine1, engine2);
factory.DisposeEngineForCurrentThread();
}
[Fact]
public void ShouldReturnNewEngineAfterDisposing()
{
var factory = CreateBasicFactory();
var engine1 = factory.GetEngineForCurrentThread();
factory.DisposeEngineForCurrentThread();
var engine2 = factory.GetEngineForCurrentThread();
factory.DisposeEngineForCurrentThread();
Assert.NotEqual(engine1, engine2);
}
[Fact]
public void ShouldCreateNewEngineForNewThread()
{
var factory = CreateBasicFactory();
var engine1 = factory.GetEngineForCurrentThread();
IJsEngine engine2 = null;
var thread = new Thread(() =>
{
engine2 = factory.GetEngineForCurrentThread();
// Need to ensure engine is disposed in same thread as it was created in
factory.DisposeEngineForCurrentThread();
});
thread.Start();
thread.Join();
var engine3 = factory.GetEngineForCurrentThread();
// Different threads should have different engines
Assert.NotEqual(engine1, engine2);
// Same thread should share same engine
Assert.Equal(engine1, engine3);
factory.DisposeEngineForCurrentThread();
}
[Fact]
public void ShouldLoadResourcesWithoutPrecompilation()
{
var reactCoreAssembly = typeof(JavaScriptEngineFactory).GetTypeInfo().Assembly;
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(false);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
factory.GetEngineForCurrentThread();
jsEngine.Verify(x => x.ExecuteResource("React.Core.Resources.shims.js", reactCoreAssembly));
jsEngine.Verify(x => x.ExecuteResource("React.Core.Resources.react.generated.min.js", reactCoreAssembly));
}
[Fact]
public void ShouldLoadResourcesWithPrecompilationAndEmptyCache()
{
var reactCoreAssembly = typeof(JavaScriptEngineFactory).GetTypeInfo().Assembly;
var shimsPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var reactPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
jsEngine
.Setup(x => x.PrecompileResource("React.Core.Resources.shims.js", reactCoreAssembly))
.Returns(shimsPrecompiledScript);
jsEngine
.Setup(x => x.PrecompileResource("React.Core.Resources.react.generated.min.js", reactCoreAssembly))
.Returns(reactPrecompiledScript);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
factory.GetEngineForCurrentThread();
jsEngine.Verify(x => x.Execute(shimsPrecompiledScript));
jsEngine.Verify(x => x.Execute(reactPrecompiledScript));
}
[Fact]
public void ShouldLoadResourcesWithPrecompilationAndNotEmptyCache()
{
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var shimsPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var reactPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var cache = new Mock<ICache>();
cache
.Setup(x => x.Get<IPrecompiledScript>("PRECOMPILED_JS_RESOURCE_React.Core.Resources.shims.js", null))
.Returns(shimsPrecompiledScript);
cache
.Setup(x => x.Get<IPrecompiledScript>("PRECOMPILED_JS_RESOURCE_React.Core.Resources.react.generated.min.js", null))
.Returns(reactPrecompiledScript);
var fileSystem = new Mock<IFileSystem>();
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
factory.GetEngineForCurrentThread();
jsEngine.Verify(x => x.Execute(shimsPrecompiledScript));
jsEngine.Verify(x => x.Execute(reactPrecompiledScript));
}
[Fact]
public void ShouldThrowIfEngineNotSupportPrecompilationOfResources()
{
var reactCoreAssembly = typeof(JavaScriptEngineFactory).GetTypeInfo().Assembly;
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.Name).Returns("FooJsEngine");
jsEngine.Setup(x => x.Version).Returns("1.2.3");
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(false);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
var ex = Assert.Throws<ReactScriptPrecompilationNotAvailableException>(
() => factory.GetEngineForCurrentThread());
Assert.Equal("The FooJsEngine version 1.2.3 does not support the script pre-compilation.", ex.Message);
}
[Fact]
public void ShouldThrowIfPrecompilationOfResourcesIsPerformedWithoutCache()
{
var reactCoreAssembly = typeof(JavaScriptEngineFactory).GetTypeInfo().Assembly;
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new NullCache();
var fileSystem = new Mock<IFileSystem>();
var factory = CreateFactory(config.Object, cache, fileSystem.Object, () => jsEngine.Object);
var ex = Assert.Throws<ReactScriptPrecompilationNotAvailableException>(
() => factory.GetEngineForCurrentThread());
Assert.Equal("Usage of the script pre-compilation without caching does not make sense.", ex.Message);
}
[Fact]
public void ShouldLoadFilesThatDoNotRequireTransformWithoutPrecompilation()
{
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> { "First.js", "Second.js" });
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(false);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString(It.IsAny<string>())).Returns<string>(path => "CONTENTS_" + path);
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
factory.GetEngineForCurrentThread();
jsEngine.Verify(x => x.Execute("CONTENTS_First.js", "First.js"));
jsEngine.Verify(x => x.Execute("CONTENTS_Second.js", "Second.js"));
}
[Fact]
public void ShouldLoadFilesThatDoNotRequireTransformWithPrecompilationAndEmptyCache()
{
var firstPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var secondPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
jsEngine.Setup(x => x.Precompile("CONTENTS_First.js", "First.js")).Returns(firstPrecompiledScript);
jsEngine.Setup(x => x.Precompile("CONTENTS_Second.js", "Second.js")).Returns(secondPrecompiledScript);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> { "First.js", "Second.js" });
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString(It.IsAny<string>())).Returns<string>(path => "CONTENTS_" + path);
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
factory.GetEngineForCurrentThread();
jsEngine.Verify(x => x.Execute(firstPrecompiledScript));
jsEngine.Verify(x => x.Execute(secondPrecompiledScript));
}
[Fact]
public void ShouldLoadFilesThatDoNotRequireTransformWithPrecompilationAndNotEmptyCache()
{
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> { "First.js", "Second.js" });
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var firstPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var secondPrecompiledScript = new Mock<IPrecompiledScript>().Object;
var cache = new Mock<ICache>();
cache
.Setup(x => x.Get<IPrecompiledScript>("PRECOMPILED_JS_FILE_First.js", null))
.Returns(firstPrecompiledScript);
cache
.Setup(x => x.Get<IPrecompiledScript>("PRECOMPILED_JS_FILE_Second.js", null))
.Returns(secondPrecompiledScript);
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString(It.IsAny<string>())).Returns<string>(path => "CONTENTS_" + path);
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
factory.GetEngineForCurrentThread();
jsEngine.Verify(x => x.Execute(firstPrecompiledScript));
jsEngine.Verify(x => x.Execute(secondPrecompiledScript));
}
[Fact]
public void ShouldThrowIfEngineNotSupportPrecompilationOfFilesThatDoNotRequireTransform()
{
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.Name).Returns("FooJsEngine");
jsEngine.Setup(x => x.Version).Returns("1.2.3");
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(false);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> { "First.js", "Second.js" });
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString(It.IsAny<string>())).Returns<string>(path => "CONTENTS_" + path);
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
var ex = Assert.Throws<ReactScriptPrecompilationNotAvailableException>(
() => factory.GetEngineForCurrentThread());
Assert.Equal("The FooJsEngine version 1.2.3 does not support the script pre-compilation.", ex.Message);
}
[Fact]
public void ShouldThrowIfPrecompilationOfFilesThatDoNotRequireTransformIsPerformedWithoutCache()
{
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.SupportsScriptPrecompilation).Returns(true);
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> { "First.js", "Second.js" });
config.Setup(x => x.AllowJavaScriptPrecompilation).Returns(true);
config.Setup(x => x.LoadReact).Returns(true);
var cache = new NullCache();
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString(It.IsAny<string>())).Returns<string>(path => "CONTENTS_" + path);
var factory = CreateFactory(config.Object, cache, fileSystem.Object, () => jsEngine.Object);
var ex = Assert.Throws<ReactScriptPrecompilationNotAvailableException>(
() => factory.GetEngineForCurrentThread());
Assert.Equal("Usage of the script pre-compilation without caching does not make sense.", ex.Message);
}
[Fact]
public void ShouldHandleLoadingExternalReactVersion()
{
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
jsEngine.Setup(x => x.CallFunction<string>("ReactNET_initReact")).Returns(string.Empty);
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string>());
config.Setup(x => x.LoadReact).Returns(false);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
factory.GetEngineForCurrentThread();
jsEngine.Verify(x => x.CallFunction<string>("ReactNET_initReact"));
}
[Fact]
public void ShouldThrowIfReactVersionNotLoaded()
{
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
jsEngine.Setup(x => x.CallFunction<string>("ReactNET_initReact")).Returns("React");
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string>());
config.Setup(x => x.LoadReact).Returns(false);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
Assert.Throws<ReactNotInitialisedException>(() =>
{
factory.GetEngineForCurrentThread();
});
}
[Fact]
public void FileLockExceptionShouldBeWrapped()
{
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> { "foo.js" });
config.Setup(x => x.LoadReact).Returns(false);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString("foo.js")).Throws(new IOException("File was locked"));
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
jsEngine.Setup(x => x.Execute("Test"));
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
var ex = Assert.Throws<ReactScriptLoadException>(() => factory.GetEngineForCurrentThread());
Assert.Equal("File was locked", ex.Message);
}
[Fact]
public void ShouldThrowScriptErrorIfReactFails()
{
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> {"foo.js"});
config.Setup(x => x.LoadReact).Returns(false);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString("foo.js")).Returns("FAIL PLZ");
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
jsEngine.Setup(x => x.Execute("FAIL PLZ", "foo.js")).Throws(new JsRuntimeException("Fail")
{
LineNumber = 42,
ColumnNumber = 911,
});
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
var ex = Assert.Throws<ReactScriptLoadException>(() => factory.GetEngineForCurrentThread());
Assert.Equal("Error while loading \"foo.js\": Fail", ex.Message);
}
[Fact]
public void ShouldCatchErrorsWhileLoadingScripts()
{
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string> {"foo.js"});
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
fileSystem.Setup(x => x.ReadAsString("foo.js")).Returns("FAIL PLZ");
var jsEngine = new Mock<IJsEngine>();
jsEngine.Setup(x => x.Evaluate<int>("1 + 1")).Returns(2);
jsEngine.Setup(x => x.Execute("FAIL PLZ", "foo.js")).Throws(new JsRuntimeException("Fail")
{
LineNumber = 42,
ColumnNumber = 911,
});
var factory = CreateFactory(config, cache, fileSystem, () => jsEngine.Object);
var ex = Assert.Throws<ReactScriptLoadException>(() => factory.GetEngineForCurrentThread());
Assert.Equal("Error while loading \"foo.js\": Fail", ex.Message);
}
[Fact]
public void ShouldReturnDefaultEngine()
{
const string someEngineName = "SomeEngine";
const string defaultEngineName = "DefaultEngine";
const string someOtherEngineName = "SomeOtherEngine";
var someEngineFactory = new Mock<IJsEngineFactory>();
someEngineFactory.Setup(x => x.EngineName).Returns(someEngineName);
someEngineFactory.Setup(x => x.CreateEngine()).Returns(() =>
{
var someEngine = new Mock<IJsEngine>();
someEngine.Setup(x => x.Name).Returns(someEngineName);
return someEngine.Object;
});
var defaultEngineFactory = new Mock<IJsEngineFactory>();
defaultEngineFactory.Setup(x => x.EngineName).Returns(defaultEngineName);
defaultEngineFactory.Setup(x => x.CreateEngine()).Returns(() =>
{
var defaultEngine = new Mock<IJsEngine>();
defaultEngine.Setup(x => x.Name).Returns(defaultEngineName);
return defaultEngine.Object;
});
var someOtherEngineFactory = new Mock<IJsEngineFactory>();
someOtherEngineFactory.Setup(x => x.EngineName).Returns(someOtherEngineName);
someOtherEngineFactory.Setup(x => x.CreateEngine()).Returns(() =>
{
var someOtherEngine = new Mock<IJsEngine>();
someOtherEngine.Setup(x => x.Name).Returns(someOtherEngineName);
return someOtherEngine.Object;
});
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string>());
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
var engineSwitcher = new JsEngineSwitcher(
new JsEngineFactoryCollection
{
someEngineFactory.Object,
defaultEngineFactory.Object,
someOtherEngineFactory.Object
},
defaultEngineName
);
var factory = new JavaScriptEngineFactory(engineSwitcher, config.Object, cache.Object,
fileSystem.Object);
var engine = factory.GetEngineForCurrentThread();
Assert.Equal(defaultEngineName, engine.Name);
}
[Fact]
public void ShouldThrowIfDefaultEngineFactoryNotFound()
{
const string someEngineName = "SomeEngine";
const string defaultEngineName = "DefaultEngine";
const string someOtherEngineName = "SomeOtherEngine";
var someEngineFactory = new Mock<IJsEngineFactory>();
someEngineFactory.Setup(x => x.EngineName).Returns(someEngineName);
someEngineFactory.Setup(x => x.CreateEngine()).Returns(() =>
{
var someEngine = new Mock<IJsEngine>();
someEngine.Setup(x => x.Name).Returns(someEngineName);
return someEngine.Object;
});
var someOtherEngineFactory = new Mock<IJsEngineFactory>();
someOtherEngineFactory.Setup(x => x.EngineName).Returns(someOtherEngineName);
someOtherEngineFactory.Setup(x => x.CreateEngine()).Returns(() =>
{
var someOtherEngine = new Mock<IJsEngine>();
someOtherEngine.Setup(x => x.Name).Returns(someOtherEngineName);
return someOtherEngine.Object;
});
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string>());
config.Setup(x => x.LoadReact).Returns(true);
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
var engineSwitcher = new JsEngineSwitcher(
new JsEngineFactoryCollection
{
someEngineFactory.Object,
someOtherEngineFactory.Object
},
defaultEngineName
);
Assert.Throws<ReactEngineNotFoundException>(() =>
{
var factory = new JavaScriptEngineFactory(engineSwitcher, config.Object, cache.Object,
fileSystem.Object);
});
}
[Fact]
public void ShouldThrowIfNoEnginesRegistered()
{
var config = new Mock<IReactSiteConfiguration>();
var cache = new Mock<ICache>();
var fileSystem = new Mock<IFileSystem>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string>());
config.Setup(x => x.LoadReact).Returns(true);
var engineSwitcher = new JsEngineSwitcher(
new JsEngineFactoryCollection(),
string.Empty
);
var caughtException = Assert.Throws<ReactException>(() =>
{
new JavaScriptEngineFactory(engineSwitcher, config.Object, cache.Object, fileSystem.Object);
});
Assert.Contains("No JS engines were registered", caughtException.Message);
}
[Fact]
public void ShouldThrowIfJsEngineFails()
{
const string defaultEngineName = "DefaultEngine";
var defaultEngineFactory = new Mock<IJsEngineFactory>();
defaultEngineFactory.Setup(x => x.EngineName).Returns(defaultEngineName);
defaultEngineFactory.Setup(x => x.CreateEngine()).Throws(new JsEngineLoadException("This is a custom JS engine load error."));
var cache = new Mock<ICache>();
var config = new Mock<IReactSiteConfiguration>();
config.Setup(x => x.ScriptsWithoutTransform).Returns(new List<string>());
config.Setup(x => x.LoadReact).Returns(true);
var fileSystem = new Mock<IFileSystem>();
var engineSwitcher = new JsEngineSwitcher(
new JsEngineFactoryCollection
{
defaultEngineFactory.Object,
},
string.Empty
);
var caughtException = Assert.Throws<ReactEngineNotFoundException>(() =>
{
var factory = new JavaScriptEngineFactory(engineSwitcher, config.Object, cache.Object,
fileSystem.Object);
factory.GetEngineForCurrentThread();
});
Assert.Contains("This is a custom JS engine load error", caughtException.Message);
}
}
}
| |
// 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.Text;
using System.Reflection;
using System.Xml;
using System.Security;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
#if !NET_NATIVE
using ExtensionDataObject = System.Object;
#endif
namespace System.Runtime.Serialization.Json
{
#if NET_NATIVE
public class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#else
internal class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex
#endif
{
private DataContractJsonSerializer _jsonSerializer;
private DateTimeFormat _dateTimeFormat;
private bool _useSimpleDictionaryFormat;
public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
: base(null, int.MaxValue, new StreamingContext(), true)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.KnownTypes;
_jsonSerializer = serializer;
}
internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
: base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
{
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
_dateTimeFormat = serializer.DateTimeFormat;
_useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
}
internal static XmlObjectSerializerReadContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
{
return new XmlObjectSerializerReadContextComplexJson(serializer, rootTypeDataContract);
}
protected override object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
{
return DataContractJsonSerializerImpl.ReadJsonValue(dataContract, reader, this);
}
public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject extensionData)
{
int length = memberNames.Length;
if (length != 0)
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (xmlReader.IsStartElement(memberNames[index], XmlDictionaryString.Empty))
{
return index;
}
}
string name;
if (TryGetJsonLocalName(xmlReader, out name))
{
for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length)
{
if (memberNames[index].Value == name)
{
return index;
}
}
}
}
HandleMemberNotFound(xmlReader, extensionData, memberIndex);
return length;
}
internal IList<Type> SerializerKnownTypeList
{
get
{
return this.serializerKnownTypeList;
}
}
public bool UseSimpleDictionaryFormat
{
get
{
return _useSimpleDictionaryFormat;
}
}
internal override void ReadAttributes(XmlReaderDelegator xmlReader)
{
if (attributes == null)
attributes = new Attributes();
attributes.Reset();
if (xmlReader.MoveToAttribute(JsonGlobals.typeString) && xmlReader.Value == JsonGlobals.nullString)
{
attributes.XsiNil = true;
}
else if (xmlReader.MoveToAttribute(JsonGlobals.serverTypeString))
{
XmlQualifiedName qualifiedTypeName = JsonReaderDelegator.ParseQualifiedName(xmlReader.Value);
attributes.XsiTypeName = qualifiedTypeName.Name;
string serverTypeNamespace = qualifiedTypeName.Namespace;
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
attributes.XsiTypeNamespace = serverTypeNamespace;
}
xmlReader.MoveToElement();
}
internal DataContract ResolveDataContractFromType(string typeName, string typeNs, DataContract memberTypeContract)
{
this.PushKnownTypes(this.rootTypeDataContract);
this.PushKnownTypes(memberTypeContract);
XmlQualifiedName qname = ParseQualifiedName(typeName);
DataContract contract = ResolveDataContractFromKnownTypes(qname.Name, TrimNamespace(qname.Namespace), memberTypeContract);
this.PopKnownTypes(this.rootTypeDataContract);
this.PopKnownTypes(memberTypeContract);
return contract;
}
internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract)
{
bool verifyType = true;
CollectionDataContract collectionContract = declaredContract as CollectionDataContract;
if (collectionContract != null && collectionContract.UnderlyingType.GetTypeInfo().IsInterface)
{
switch (collectionContract.Kind)
{
case CollectionKind.Dictionary:
case CollectionKind.GenericDictionary:
verifyType = declaredContract.Name == runtimeContract.Name;
break;
default:
Type t = collectionContract.ItemType.MakeArrayType();
verifyType = (t != runtimeContract.UnderlyingType);
break;
}
}
if (verifyType)
{
this.PushKnownTypes(declaredContract);
VerifyType(runtimeContract);
this.PopKnownTypes(declaredContract);
}
}
internal void VerifyType(DataContract dataContract)
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
internal string TrimNamespace(string serverTypeNamespace)
{
if (!string.IsNullOrEmpty(serverTypeNamespace))
{
switch (serverTypeNamespace[0])
{
case '#':
serverTypeNamespace = string.Concat(Globals.DataContractXsdBaseNamespace, serverTypeNamespace.Substring(1));
break;
case '\\':
if (serverTypeNamespace.Length >= 2)
{
switch (serverTypeNamespace[1])
{
case '#':
case '\\':
serverTypeNamespace = serverTypeNamespace.Substring(1);
break;
default:
break;
}
}
break;
default:
break;
}
}
return serverTypeNamespace;
}
internal static XmlQualifiedName ParseQualifiedName(string qname)
{
string name, ns;
if (string.IsNullOrEmpty(qname))
{
name = ns = String.Empty;
}
else
{
qname = qname.Trim();
int colon = qname.IndexOf(':');
if (colon >= 0)
{
name = qname.Substring(0, colon);
ns = qname.Substring(colon + 1);
}
else
{
name = qname;
ns = string.Empty;
}
}
return new XmlQualifiedName(name, ns);
}
internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContract(typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
DataContract dataContract = base.GetDataContract(id, typeHandle);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out string name)
{
if (xmlReader.IsStartElement(JsonGlobals.itemDictionaryString, JsonGlobals.itemDictionaryString))
{
if (xmlReader.MoveToAttribute(JsonGlobals.itemString))
{
name = xmlReader.Value;
return true;
}
}
name = null;
return false;
}
public static string GetJsonMemberName(XmlReaderDelegator xmlReader)
{
string name;
if (!TryGetJsonLocalName(xmlReader, out name))
{
name = xmlReader.LocalName;
}
return name;
}
#if !NET_NATIVE
public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(
SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex])));
}
public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements)
{
StringBuilder stringBuilder = new StringBuilder();
int missingMembersCount = 0;
for (int i = 0; i < memberNames.Length; i++)
{
if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i))
{
if (stringBuilder.Length != 0)
stringBuilder.Append(", ");
stringBuilder.Append(memberNames[i]);
missingMembersCount++;
}
}
if (missingMembersCount == 1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(
SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString())));
}
}
[SecuritySafeCritical]
private static bool IsBitSet(byte[] bytes, int bitIndex)
{
return BitFlagsGenerator.IsBitSet(bytes, bitIndex);
}
#endif
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Searchservice
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Indexers operations.
/// </summary>
public partial interface IIndexers
{
/// <summary>
/// Resets the change tracking state associated with an Azure Search
/// indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946897.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to reset.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> ResetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Runs an Azure Search indexer on-demand.
/// <see href="https://msdn.microsoft.com/library/azure/dn946885.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to run.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> RunWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new Azure Search indexer or updates an indexer if it
/// already exists.
/// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to create or update.
/// </param>
/// <param name='indexer'>
/// The definition of the indexer to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Indexer>> CreateOrUpdateWithHttpMessagesAsync(string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes an Azure Search indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946898.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieves an indexer definition from Azure Search.
/// <see href="https://msdn.microsoft.com/library/azure/dn946874.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Indexer>> GetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all indexers available for an Azure Search service.
/// <see href="https://msdn.microsoft.com/library/azure/dn946883.aspx" />
/// </summary>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<IndexerListResult>> ListWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a new Azure Search indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" />
/// </summary>
/// <param name='indexer'>
/// The definition of the indexer to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Indexer>> CreateWithHttpMessagesAsync(Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the current status and execution history of an indexer.
/// <see href="https://msdn.microsoft.com/library/azure/dn946884.aspx" />
/// </summary>
/// <param name='indexerName'>
/// The name of the indexer for which to retrieve status.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<IndexerExecutionInfo>> GetStatusWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using Infoplus.Client;
using Infoplus.Model;
namespace Infoplus.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IProductTypeApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ProductType</returns>
ProductType GetProductTypeById (string productTypeId);
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ApiResponse of ProductType</returns>
ApiResponse<ProductType> GetProductTypeByIdWithHttpInfo (string productTypeId);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ProductType></returns>
List<ProductType> GetProductTypeBySearchText (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ProductType></returns>
ApiResponse<List<ProductType>> GetProductTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ProductType</returns>
System.Threading.Tasks.Task<ProductType> GetProductTypeByIdAsync (string productTypeId);
/// <summary>
/// Get a productType by id
/// </summary>
/// <remarks>
/// Returns the productType identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
System.Threading.Tasks.Task<ApiResponse<ProductType>> GetProductTypeByIdAsyncWithHttpInfo (string productTypeId);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ProductType></returns>
System.Threading.Tasks.Task<List<ProductType>> GetProductTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search productTypes
/// </summary>
/// <remarks>
/// Returns the list of productTypes that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ProductType>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ProductType>>> GetProductTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class ProductTypeApi : IProductTypeApi
{
private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeApi"/> class.
/// </summary>
/// <returns></returns>
public ProductTypeApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ProductTypeApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public Infoplus.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ProductType</returns>
public ProductType GetProductTypeById (string productTypeId)
{
ApiResponse<ProductType> localVarResponse = GetProductTypeByIdWithHttpInfo(productTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>ApiResponse of ProductType</returns>
public ApiResponse< ProductType > GetProductTypeByIdWithHttpInfo (string productTypeId)
{
// verify the required parameter 'productTypeId' is set
if (productTypeId == null)
throw new ApiException(400, "Missing required parameter 'productTypeId' when calling ProductTypeApi->GetProductTypeById");
var localVarPath = "/v1.0/productType/{productTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (productTypeId != null) localVarPathParams.Add("productTypeId", Configuration.ApiClient.ParameterToString(productTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetProductTypeById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ProductType</returns>
public async System.Threading.Tasks.Task<ProductType> GetProductTypeByIdAsync (string productTypeId)
{
ApiResponse<ProductType> localVarResponse = await GetProductTypeByIdAsyncWithHttpInfo(productTypeId);
return localVarResponse.Data;
}
/// <summary>
/// Get a productType by id Returns the productType identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="productTypeId">Id of productType to be returned.</param>
/// <returns>Task of ApiResponse (ProductType)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ProductType>> GetProductTypeByIdAsyncWithHttpInfo (string productTypeId)
{
// verify the required parameter 'productTypeId' is set
if (productTypeId == null)
throw new ApiException(400, "Missing required parameter 'productTypeId' when calling ProductTypeApi->GetProductTypeById");
var localVarPath = "/v1.0/productType/{productTypeId}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (productTypeId != null) localVarPathParams.Add("productTypeId", Configuration.ApiClient.ParameterToString(productTypeId)); // path parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetProductTypeById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ProductType>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ProductType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductType)));
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>List<ProductType></returns>
public List<ProductType> GetProductTypeBySearchText (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ProductType>> localVarResponse = GetProductTypeBySearchTextWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>ApiResponse of List<ProductType></returns>
public ApiResponse< List<ProductType> > GetProductTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/v1.0/productType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetProductTypeBySearchText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ProductType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductType>)));
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of List<ProductType></returns>
public async System.Threading.Tasks.Task<List<ProductType>> GetProductTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ProductType>> localVarResponse = await GetProductTypeBySearchTextAsyncWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search productTypes Returns the list of productTypes that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, used to filter results. (optional)</param>
/// <param name="page">Result page number. Defaults to 1. (optional)</param>
/// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param>
/// <returns>Task of ApiResponse (List<ProductType>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ProductType>>> GetProductTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/v1.0/productType/search";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter
if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter
if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter
// authentication (api_key) required
if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key")))
{
localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key");
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("GetProductTypeBySearchText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ProductType>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ProductType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductType>)));
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityStandardAssets.ImageEffects;
[RequireComponent(typeof(Rigidbody))]
public class Character : MonoBehaviour {
public Rigidbody rb;
public Transform directions;
public float thrust = 1.0f;
public GameObject deathEffect;
public GameObject hitEffect;
public float maxVel = 35.0f;
public float overdoseStepDur = 0.5f;
public int overdoseLossStep = 10;
public float overdoseHealthStep = 5.0f;
public int overdoseThreshold = 100;
private bool isOverdosing = false;
private bool odEffect = false;
private bool fadeOut = false;
private float fadeTarget = 100.0f;
public AudioSource wind, impact;
private float initVolume = 1.0f;
public static float playerVel = 0.0f;
public static Character playerInstance;
public GameObject playerObject;
public int deathNegScore = 10;
public int baseScore = 10;
public VignetteAndChromaticAberration chromAb;
public BloomAndFlares bloomF;
public ColorCorrectionCurves colCorr;
Vector3 velocity;
public float controllSmoothness;
public static Transform statdir;
public AudioSource ambientWind;
// Use this for initialization
void Start () {
StartCoroutine(start());
rb = gameObject.GetComponent<Rigidbody>();
if (statdir == null)
statdir = GameData.Instance.dirHelper;
if (directions == null)
directions = statdir;
initVolume = wind.volume;
playerInstance = this;
chromAb = Camera.main.GetComponent<VignetteAndChromaticAberration>();
bloomF = Camera.main.GetComponent<BloomAndFlares>();
colCorr = Camera.main.GetComponent<ColorCorrectionCurves>();
GameData.Instance.dead = false;
Camera.main.GetComponent<CameraFollow>().setFollow(gameObject.transform);
// StartCoroutine(overdoseDecay());
StartCoroutine(ambientW());
}
IEnumerator ambientW()
{
while (true) {
yield return new WaitForSeconds (Random.Range (6.0f, 10.0f));
SoundManager.playRandSound(ambientWind, SoundManager.Instance.windgust);
}
}
IEnumerator start()
{
GameData.Instance.state = GameData.GameState.Playing;
yield return new WaitForSeconds(GameData.Instance.StartDelay);
}
// Update is called once per frame
void FixedUpdate () {
if (!GameData.Instance.dead)
{
// rb.AddForce((directions.forward * Input.GetAxis("Vertical") + directions.right * Input.GetAxis("Horizontal")) * thrust, ForceMode.Impulse);
rb.velocity = Vector3.Lerp(rb.velocity, velocity + rb.velocity.y * Vector3.up, Time.fixedDeltaTime* controllSmoothness);
}
}
void Update()
{
ambientWind.volume = Mathf.Clamp (transform.position.y / 3000, 0, 1);
velocity = (directions.forward * Input.GetAxis("Vertical") + directions.right * Input.GetAxis("Horizontal")) * 40;
if (rb.velocity.magnitude > maxVel)
rb.velocity = rb.velocity.normalized * maxVel;
float cA = 2.0f;
if(odEffect)
cA += (GameData.Instance.overDoseMulti - 1) * 20f * Mathf.Sin (Time.time*GameData.Instance.overDoseMulti);
chromAb.chromaticAberration = Mathf.Lerp(chromAb.chromaticAberration, cA, Time.deltaTime * 10.0f);
/*
* if(odEffect)
{
if(!fadeOut) //during
{
chromAb.chromaticAberration = Mathf.Lerp(chromAb.chromaticAberration, fadeTarget, Time.deltaTime * 10.0f);
} else //fade out
{
chromAb.chromaticAberration = Mathf.Lerp(chromAb.chromaticAberration, 2.0f, Time.deltaTime * 4.0f);
}
}
*/
wind.volume = gameObject.GetComponent<Rigidbody>().velocity.magnitude / maxVel * initVolume;
playerVel = gameObject.GetComponent<Rigidbody>().velocity.magnitude;
}
void OnCollisionEnter(Collision col)
{
if (col.relativeVelocity.magnitude > 0.2f * maxVel && !col.collider.CompareTag("Boundary"))
{
SoundManager.playRandSound(impact,SoundManager.Instance.impact);
}
if (col.collider.CompareTag("Ground"))
{
float factor = col.relativeVelocity.y;
GameData.Instance.score += (int)(baseScore * factor) * GameData.Instance.Multi;
GetComponent<BoxCollider>().enabled = false;
killThis();
Debug.Log("Score: " + GameData.Instance.score);
//
GameObject penice = (GameObject)Instantiate(deathEffect, transform.position, Quaternion.identity);
SoundManager.playRandSound(penice.GetComponents<AudioSource>()[0], SoundManager.Instance.impact);
SoundManager.playRandSound(penice.GetComponents<AudioSource>()[1], SoundManager.Instance.blood);
if (gameObject.GetComponent<Rigidbody>().velocity.magnitude > maxVel / 2.0f)
{
SoundManager.playRandSound(penice.GetComponents<AudioSource>()[2], SoundManager.Instance.bone);
}
SoundManager.playRandSound(penice.GetComponents<AudioSource>()[3], SoundManager.Instance.brain);
setODEffect(false);
GameData.Instance.winLose();
}
}
public void DoOverdose(int od, float heal)
{
throw new UnityException();
GameData.Instance.overdose += od;
GameData.Instance.health += heal;
if(GameData.Instance.overdose >= overdoseThreshold)
{
GameData.Instance.overdose = overdoseThreshold;
GameData.Instance.overDoseMulti++;
odEffect = true;
GameUI.UIes.OverdoseBool = true;
fadeTarget = 100.0f;
bloomF.enabled = true;
colCorr.enabled = true;
if(!isOverdosing)
StartCoroutine(Overdosing());
StartCoroutine(ODEffect());
StopCoroutine(ODFadeOut());
isOverdosing = true;
}
}
public void setODEffect(bool val)
{
bloomF.enabled = val;
colCorr.enabled = val;
odEffect = val;
}
IEnumerator Overdosing()
{
Debug.Log("Overdosing! OD: " + GameData.Instance.overdose + "; HP: " + GameData.Instance.health);
yield return new WaitForSeconds(overdoseStepDur);
if(GameData.Instance.overdose > 0)
{
GameData.Instance.overdose -= overdoseLossStep;
GameData.Instance.health -= overdoseHealthStep;
StartCoroutine(Overdosing());
} else
{
GameData.Instance.overdose = 0;
bloomF.enabled = false;
colCorr.enabled = false;
GameUI.UIes.OverdoseBool = false;
GameData.Instance.overDoseMulti--;
StartCoroutine(ODFadeOut());
StopCoroutine(ODEffect());
isOverdosing = false;
}
}
IEnumerator ODEffect()
{
while (true)
{
fadeTarget = -fadeTarget * Random.Range(0.7f, 1.2f);
yield return new WaitForSeconds(Random.Range(0.03f, 0.15f));
}
}
IEnumerator ODFadeOut()
{
fadeOut = true;
yield return new WaitForSeconds(5.0f);
fadeOut = false;
odEffect = false;
chromAb.chromaticAberration = 2.0f;
}
IEnumerator overdoseDecay()
{
while (true)
{
yield return new WaitForSeconds(.1f);
if (!odEffect && GameData.Instance.overdose > 0)
GameData.Instance.overdose--;
}
}
public void killThis()
{
if (!GameData.Instance.dead)
{
Debug.Log("anis: " + GameData.Instance.overkillMulti + "enus: " + GameData.Instance.health);
if (GameData.Instance.overkillMulti == 1 && GameData.Instance.health > 0f)
{
Debug.Log("subbing " + (int)(deathNegScore * GameData.Instance.health));
GameData.Instance.score -= (int)(deathNegScore * GameData.Instance.health);
}
GameData.Instance.dead = true;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Services
{
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.Diagnostics.Metrics;
using Adxstudio.Xrm.Diagnostics.Trace;
using Adxstudio.Xrm.Performance;
using Adxstudio.Xrm.Web;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
public class CachedOrganizationService : OrganizationService, IOrganizationServiceCacheContainer
{
private class PortalClientMessageInspector : IClientMessageInspector
{
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
var site = HashPii.ComputeHashPiiSha256(WebAppSettings.Instance.SiteName);
var instance = HashPii.ComputeHashPiiSha256(WebAppSettings.Instance.InstanceId);
var userAgent = $"Portals (Site={site}; Instance={instance}; ActivityId={EventSource.CurrentThreadActivityId})";
var property = new HttpRequestMessageProperty
{
Headers = { { HttpRequestHeader.UserAgent, userAgent } }
};
request.Properties.Add(HttpRequestMessageProperty.Name, property);
return null;
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
}
}
private class PortalEndpointBehavior : IEndpointBehavior
{
public void Validate(ServiceEndpoint endpoint)
{
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.ClientMessageInspectors.Add(new PortalClientMessageInspector());
}
}
/// <summary>
/// The cache.
/// </summary>
public IOrganizationServiceCache Cache { get; private set; }
public CachedOrganizationService(string connectionStringName)
: this(new CrmConnection(connectionStringName))
{
}
public CachedOrganizationService(CrmConnection connection)
: this(connection, CreateOrganizationServiceCache(connection.GetConnectionId()))
{
}
public CachedOrganizationService(IOrganizationService service)
: this(service, (string)null)
{
}
public CachedOrganizationService(IOrganizationService service, string connectionId)
: this(service, CreateOrganizationServiceCache(connectionId))
{
}
public CachedOrganizationService(string connectionStringName, IOrganizationServiceCache cache)
: this(new CrmConnection(connectionStringName), cache)
{
}
public CachedOrganizationService(CrmConnection connection, IOrganizationServiceCache cache)
: base(connection)
{
this.Cache = cache;
}
public CachedOrganizationService(IOrganizationService service, IOrganizationServiceCache cache)
: base(service)
{
this.Cache = cache;
}
private static IOrganizationServiceCache CreateOrganizationServiceCache(string connectionId)
{
return CrmConfigurationManager.CreateServiceCache(null, connectionId, true);
}
public override Guid Create(Entity entity)
{
Guid guid;
var stopwatch = Stopwatch.StartNew();
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.CreateEntity))
{
guid = base.Create(entity);
}
}
finally
{
stopwatch.Stop();
MdmMetrics.CrmOrganizationRequestExecutionTimeMetric.LogValue(stopwatch.ElapsedMilliseconds);
ServicesEventSource.Log.Create(entity, stopwatch.ElapsedMilliseconds);
}
if (this.Cache != null)
{
this.Cache.Remove(entity);
}
return guid;
}
public override void Update(Entity entity)
{
var stopwatch = Stopwatch.StartNew();
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.UpdateEntity))
{
base.Update(entity);
}
}
finally
{
stopwatch.Stop();
MdmMetrics.CrmOrganizationRequestExecutionTimeMetric.LogValue(stopwatch.ElapsedMilliseconds);
ServicesEventSource.Log.Update(entity, stopwatch.ElapsedMilliseconds);
}
if (this.Cache != null)
{
this.Cache.Remove(entity);
}
}
public override void Delete(string entityName, Guid id)
{
var stopwatch = Stopwatch.StartNew();
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.DeleteEntity))
{
base.Delete(entityName, id);
}
}
finally
{
stopwatch.Stop();
MdmMetrics.CrmOrganizationRequestExecutionTimeMetric.LogValue(stopwatch.ElapsedMilliseconds);
ServicesEventSource.Log.Delete(entityName, id, stopwatch.ElapsedMilliseconds);
}
if (this.Cache != null)
{
this.Cache.Remove(entityName, id);
}
}
public override void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
{
var stopwatch = Stopwatch.StartNew();
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.AssociateEntity))
{
base.Associate(entityName, entityId, relationship, relatedEntities);
}
}
finally
{
stopwatch.Stop();
MdmMetrics.CrmOrganizationRequestExecutionTimeMetric.LogValue(stopwatch.ElapsedMilliseconds);
ServicesEventSource.Log.Associate(entityName, entityId, relationship, relatedEntities, stopwatch.ElapsedMilliseconds);
}
}
public override void Disassociate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
{
var stopwatch = Stopwatch.StartNew();
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.DisassociateEntity))
{
base.Disassociate(entityName, entityId, relationship, relatedEntities);
}
}
finally
{
stopwatch.Stop();
MdmMetrics.CrmOrganizationRequestExecutionTimeMetric.LogValue(stopwatch.ElapsedMilliseconds);
ServicesEventSource.Log.Disassociate(entityName, entityId, relationship, relatedEntities, stopwatch.ElapsedMilliseconds);
}
}
public override Entity Retrieve(string entityName, Guid id, ColumnSet columnSet)
{
// telemetry will be handled during InnerExecute for uncached requests
var request = new RetrieveRequest
{
Target = new EntityReference(entityName, id),
ColumnSet = columnSet
};
var response = this.Execute<RetrieveResponse>(request);
return response != null ? response.Entity : null;
}
public override EntityCollection RetrieveMultiple(QueryBase query)
{
// telemetry will be handled during InnerExecute for uncached requests
var request = new RetrieveMultipleRequest { Query = query };
var response = this.Execute<RetrieveMultipleResponse>(request);
return response != null ? response.EntityCollection : null;
}
public override OrganizationResponse Execute(OrganizationRequest request)
{
// telemetry will be handled during InnerExecute for uncached requests
return this.Execute<OrganizationResponse>(request);
}
protected override IServiceConfiguration<IOrganizationService> CreateServiceConfiguration(CrmConnection connection)
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.CreateServiceConfiguration))
{
var config = base.CreateServiceConfiguration(connection);
if (connection.ProxyTypesEnabled)
{
// configure the data contract surrogate at configuration time instead of at runtime
var behavior = config.CurrentServiceEndpoint.Behaviors.Remove<ProxyTypesBehavior>() as IEndpointBehavior;
if (behavior != null)
{
behavior.ApplyClientBehavior(config.CurrentServiceEndpoint, null);
}
}
var portalBehavior = config.CurrentServiceEndpoint.Behaviors.Find<PortalEndpointBehavior>();
if (portalBehavior == null)
{
config.CurrentServiceEndpoint.Behaviors.Add(new PortalEndpointBehavior());
}
return config;
}
}
private T Execute<T>(OrganizationRequest request) where T : OrganizationResponse
{
return this.Execute(request, response => response as T, null);
}
private T Execute<T>(OrganizationRequest request, Func<OrganizationResponse, T> selector, string selectorCacheKey)
{
var execute = this.Cache != null
? this.Cache.Execute
: (Func<OrganizationRequest, Func<OrganizationRequest, OrganizationResponse>, Func<OrganizationResponse, T>, string, T>)null;
return this.Execute(request, execute, selector, selectorCacheKey);
}
private T Execute<T>(OrganizationRequest request, Func<OrganizationRequest, Func<OrganizationRequest, OrganizationResponse>, Func<OrganizationResponse, T>, string, T> execute, Func<OrganizationResponse, T> selector, string selectorCacheKey)
{
return execute == null
? selector(this.InnerExecute(request))
: execute(ToCachedOrganizationRequest(request), this.InnerExecute, selector, selectorCacheKey);
}
private static CachedOrganizationRequest ToCachedOrganizationRequest(OrganizationRequest request)
{
// wrap the request in a container with telemetry
var cachedRequest = request as CachedOrganizationRequest;
return cachedRequest ?? new CachedOrganizationRequest(request, default(Caller));
}
/// <summary>
/// Execute an uncached request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>The response.</returns>
private OrganizationResponse InnerExecute(OrganizationRequest request)
{
var stopwatch = Stopwatch.StartNew();
// unwrap the original request from the container
var cached = request as CachedOrganizationRequest;
var innerRequest = cached != null ? cached.Request : request;
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.Services, PerformanceMarkerArea.Crm, PerformanceMarkerTagName.ExecuteOrganizationService))
{
var keyed = innerRequest as KeyedRequest;
var keyedInner = keyed != null ? keyed.Request : innerRequest;
var response = base.Execute(keyedInner);
var rsr = keyedInner as RetrieveSingleRequest;
if (rsr != null)
{
var rmr = response as RetrieveMultipleResponse;
if (rmr != null)
{
return new RetrieveSingleResponse(rsr, rmr);
}
}
return response;
}
}
catch (Exception e) when (LogGenericWarningException(e, cached))
{
throw;
}
finally
{
stopwatch.Stop();
MdmMetrics.CrmOrganizationRequestExecutionTimeMetric.LogValue(stopwatch.ElapsedMilliseconds);
ServicesEventSource.Log.OrganizationRequest(innerRequest, stopwatch.ElapsedMilliseconds, false);
if (cached != null && cached.Telemetry != null)
{
cached.Telemetry.Duration = stopwatch.Elapsed;
}
}
}
private static bool LogGenericWarningException(
Exception e,
CachedOrganizationRequest request,
[System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
[System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
[System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
// use caller's debug arguments if available
var telemetry = request?.Telemetry;
if (telemetry != null)
{
WebEventSource.Log.GenericWarningException(e, null, telemetry.Caller.MemberName, telemetry.Caller.SourceFilePath, telemetry.Caller.SourceLineNumber);
}
else
{
WebEventSource.Log.GenericWarningException(e, null, memberName, sourceFilePath, sourceLineNumber);
}
return false;
}
}
}
| |
namespace DCalcServer.UI
{
partial class DCalcServerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DCalcServerForm));
this.lbAlgorithms = new System.Windows.Forms.Label();
this.edtAlgorithms = new System.Windows.Forms.TextBox();
this.btStart = new System.Windows.Forms.Button();
this.btStop = new System.Windows.Forms.Button();
this.gbConfiguration = new System.Windows.Forms.GroupBox();
this.cbbServerType = new System.Windows.Forms.ComboBox();
this.lbServerType = new System.Windows.Forms.Label();
this.btRandom = new System.Windows.Forms.Button();
this.edtSecurityKey = new System.Windows.Forms.TextBox();
this.cbSecure = new System.Windows.Forms.CheckBox();
this.gbLocalThreads = new System.Windows.Forms.GroupBox();
this.rbCustomCount = new System.Windows.Forms.RadioButton();
this.edtCustomCount = new System.Windows.Forms.TextBox();
this.rbCoreCount = new System.Windows.Forms.RadioButton();
this.rbSingleThread = new System.Windows.Forms.RadioButton();
this.cbbLoadBalancer = new System.Windows.Forms.ComboBox();
this.lbLoadBalancer = new System.Windows.Forms.Label();
this.edtLifeTime = new System.Windows.Forms.TextBox();
this.lbLifeTime = new System.Windows.Forms.Label();
this.edtListeningPort = new System.Windows.Forms.TextBox();
this.lbPort = new System.Windows.Forms.Label();
this.gbStatus = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.graphView = new CustomUIControls.Graphing.C2DPushGraph();
this.edtClients = new System.Windows.Forms.TextBox();
this.lbClients = new System.Windows.Forms.Label();
this.btExit = new System.Windows.Forms.Button();
this.statsTimer = new System.Windows.Forms.Timer(this.components);
this.gbConfiguration.SuspendLayout();
this.gbLocalThreads.SuspendLayout();
this.gbStatus.SuspendLayout();
this.SuspendLayout();
//
// lbAlgorithms
//
this.lbAlgorithms.AutoSize = true;
this.lbAlgorithms.Location = new System.Drawing.Point(229, 16);
this.lbAlgorithms.Name = "lbAlgorithms";
this.lbAlgorithms.Size = new System.Drawing.Size(58, 13);
this.lbAlgorithms.TabIndex = 2;
this.lbAlgorithms.Text = "Algorithms:";
//
// edtAlgorithms
//
this.edtAlgorithms.Location = new System.Drawing.Point(293, 13);
this.edtAlgorithms.Name = "edtAlgorithms";
this.edtAlgorithms.ReadOnly = true;
this.edtAlgorithms.Size = new System.Drawing.Size(67, 20);
this.edtAlgorithms.TabIndex = 3;
this.edtAlgorithms.TabStop = false;
this.edtAlgorithms.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// btStart
//
this.btStart.Location = new System.Drawing.Point(216, 378);
this.btStart.Name = "btStart";
this.btStart.Size = new System.Drawing.Size(75, 23);
this.btStart.TabIndex = 8;
this.btStart.Text = "Start";
this.btStart.UseVisualStyleBackColor = true;
this.btStart.Click += new System.EventHandler(this.btStart_Click);
//
// btStop
//
this.btStop.Location = new System.Drawing.Point(297, 378);
this.btStop.Name = "btStop";
this.btStop.Size = new System.Drawing.Size(75, 23);
this.btStop.TabIndex = 9;
this.btStop.Text = "Stop";
this.btStop.UseVisualStyleBackColor = true;
this.btStop.Click += new System.EventHandler(this.btStop_Click);
//
// gbConfiguration
//
this.gbConfiguration.Controls.Add(this.cbbServerType);
this.gbConfiguration.Controls.Add(this.lbServerType);
this.gbConfiguration.Controls.Add(this.btRandom);
this.gbConfiguration.Controls.Add(this.edtSecurityKey);
this.gbConfiguration.Controls.Add(this.cbSecure);
this.gbConfiguration.Controls.Add(this.gbLocalThreads);
this.gbConfiguration.Controls.Add(this.cbbLoadBalancer);
this.gbConfiguration.Controls.Add(this.lbLoadBalancer);
this.gbConfiguration.Controls.Add(this.edtLifeTime);
this.gbConfiguration.Controls.Add(this.lbLifeTime);
this.gbConfiguration.Controls.Add(this.edtListeningPort);
this.gbConfiguration.Controls.Add(this.lbPort);
this.gbConfiguration.Location = new System.Drawing.Point(2, 3);
this.gbConfiguration.Name = "gbConfiguration";
this.gbConfiguration.Size = new System.Drawing.Size(370, 212);
this.gbConfiguration.TabIndex = 0;
this.gbConfiguration.TabStop = false;
this.gbConfiguration.Text = "Configuration";
//
// cbbServerType
//
this.cbbServerType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbbServerType.FormattingEnabled = true;
this.cbbServerType.Items.AddRange(new object[] {
"HTTP (Hyper Text Transfer Protocol)",
"TCP (Transmission Control Protocol)"});
this.cbbServerType.Location = new System.Drawing.Point(86, 37);
this.cbbServerType.Name = "cbbServerType";
this.cbbServerType.Size = new System.Drawing.Size(278, 21);
this.cbbServerType.TabIndex = 2;
//
// lbServerType
//
this.lbServerType.AutoSize = true;
this.lbServerType.Location = new System.Drawing.Point(6, 40);
this.lbServerType.Name = "lbServerType";
this.lbServerType.Size = new System.Drawing.Size(77, 13);
this.lbServerType.TabIndex = 19;
this.lbServerType.Text = "Listener Mode:";
//
// btRandom
//
this.btRandom.Location = new System.Drawing.Point(309, 112);
this.btRandom.Name = "btRandom";
this.btRandom.Size = new System.Drawing.Size(55, 23);
this.btRandom.TabIndex = 6;
this.btRandom.Text = "Random";
this.btRandom.UseVisualStyleBackColor = true;
this.btRandom.Click += new System.EventHandler(this.btRandom_Click);
//
// edtSecurityKey
//
this.edtSecurityKey.Location = new System.Drawing.Point(9, 114);
this.edtSecurityKey.Name = "edtSecurityKey";
this.edtSecurityKey.Size = new System.Drawing.Size(294, 20);
this.edtSecurityKey.TabIndex = 5;
this.edtSecurityKey.TextChanged += new System.EventHandler(this.all_TextChanged);
//
// cbSecure
//
this.cbSecure.AutoSize = true;
this.cbSecure.Location = new System.Drawing.Point(9, 95);
this.cbSecure.Name = "cbSecure";
this.cbSecure.Size = new System.Drawing.Size(128, 17);
this.cbSecure.TabIndex = 4;
this.cbSecure.Text = "Security key required:";
this.cbSecure.UseVisualStyleBackColor = true;
this.cbSecure.CheckedChanged += new System.EventHandler(this.cbSecure_CheckedChanged);
//
// gbLocalThreads
//
this.gbLocalThreads.Controls.Add(this.rbCustomCount);
this.gbLocalThreads.Controls.Add(this.edtCustomCount);
this.gbLocalThreads.Controls.Add(this.rbCoreCount);
this.gbLocalThreads.Controls.Add(this.rbSingleThread);
this.gbLocalThreads.Location = new System.Drawing.Point(9, 137);
this.gbLocalThreads.Name = "gbLocalThreads";
this.gbLocalThreads.Size = new System.Drawing.Size(355, 70);
this.gbLocalThreads.TabIndex = 7;
this.gbLocalThreads.TabStop = false;
this.gbLocalThreads.Text = "Number of Local Threads";
//
// rbCustomCount
//
this.rbCustomCount.AutoSize = true;
this.rbCustomCount.Location = new System.Drawing.Point(158, 18);
this.rbCustomCount.Name = "rbCustomCount";
this.rbCustomCount.Size = new System.Drawing.Size(90, 17);
this.rbCustomCount.TabIndex = 2;
this.rbCustomCount.Text = "Custom count";
this.rbCustomCount.UseVisualStyleBackColor = true;
this.rbCustomCount.CheckedChanged += new System.EventHandler(this.rbCustomCount_CheckedChanged);
//
// edtCustomCount
//
this.edtCustomCount.Enabled = false;
this.edtCustomCount.Location = new System.Drawing.Point(251, 17);
this.edtCustomCount.Name = "edtCustomCount";
this.edtCustomCount.Size = new System.Drawing.Size(100, 20);
this.edtCustomCount.TabIndex = 3;
this.edtCustomCount.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.edtCustomCount.TextChanged += new System.EventHandler(this.all_TextChanged);
//
// rbCoreCount
//
this.rbCoreCount.AutoSize = true;
this.rbCoreCount.Location = new System.Drawing.Point(8, 42);
this.rbCoreCount.Name = "rbCoreCount";
this.rbCoreCount.Size = new System.Drawing.Size(189, 17);
this.rbCoreCount.TabIndex = 1;
this.rbCoreCount.Text = "Multiple Threads (Processor count)";
this.rbCoreCount.UseVisualStyleBackColor = true;
//
// rbSingleThread
//
this.rbSingleThread.AutoSize = true;
this.rbSingleThread.Checked = true;
this.rbSingleThread.Location = new System.Drawing.Point(8, 19);
this.rbSingleThread.Name = "rbSingleThread";
this.rbSingleThread.Size = new System.Drawing.Size(91, 17);
this.rbSingleThread.TabIndex = 0;
this.rbSingleThread.TabStop = true;
this.rbSingleThread.Text = "Single Thread";
this.rbSingleThread.UseVisualStyleBackColor = true;
//
// cbbLoadBalancer
//
this.cbbLoadBalancer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbbLoadBalancer.FormattingEnabled = true;
this.cbbLoadBalancer.Location = new System.Drawing.Point(86, 63);
this.cbbLoadBalancer.Name = "cbbLoadBalancer";
this.cbbLoadBalancer.Size = new System.Drawing.Size(278, 21);
this.cbbLoadBalancer.TabIndex = 3;
//
// lbLoadBalancer
//
this.lbLoadBalancer.AutoSize = true;
this.lbLoadBalancer.Location = new System.Drawing.Point(6, 66);
this.lbLoadBalancer.Name = "lbLoadBalancer";
this.lbLoadBalancer.Size = new System.Drawing.Size(79, 13);
this.lbLoadBalancer.TabIndex = 15;
this.lbLoadBalancer.Text = "Load Balancer:";
//
// edtLifeTime
//
this.edtLifeTime.Location = new System.Drawing.Point(264, 13);
this.edtLifeTime.Name = "edtLifeTime";
this.edtLifeTime.Size = new System.Drawing.Size(100, 20);
this.edtLifeTime.TabIndex = 1;
this.edtLifeTime.Text = "20";
this.edtLifeTime.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.edtLifeTime.TextChanged += new System.EventHandler(this.all_TextChanged);
//
// lbLifeTime
//
this.lbLifeTime.AutoSize = true;
this.lbLifeTime.Location = new System.Drawing.Point(190, 16);
this.lbLifeTime.Name = "lbLifeTime";
this.lbLifeTime.Size = new System.Drawing.Size(75, 13);
this.lbLifeTime.TabIndex = 10;
this.lbLifeTime.Text = "Life time (sec):";
//
// edtListeningPort
//
this.edtListeningPort.Location = new System.Drawing.Point(86, 13);
this.edtListeningPort.Name = "edtListeningPort";
this.edtListeningPort.Size = new System.Drawing.Size(100, 20);
this.edtListeningPort.TabIndex = 0;
this.edtListeningPort.Text = "4456";
this.edtListeningPort.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.edtListeningPort.TextChanged += new System.EventHandler(this.all_TextChanged);
//
// lbPort
//
this.lbPort.AutoSize = true;
this.lbPort.Location = new System.Drawing.Point(6, 16);
this.lbPort.Name = "lbPort";
this.lbPort.Size = new System.Drawing.Size(74, 13);
this.lbPort.TabIndex = 8;
this.lbPort.Text = "Listening Port:";
//
// gbStatus
//
this.gbStatus.Controls.Add(this.label1);
this.gbStatus.Controls.Add(this.graphView);
this.gbStatus.Controls.Add(this.edtClients);
this.gbStatus.Controls.Add(this.lbClients);
this.gbStatus.Controls.Add(this.lbAlgorithms);
this.gbStatus.Controls.Add(this.edtAlgorithms);
this.gbStatus.Location = new System.Drawing.Point(2, 216);
this.gbStatus.Name = "gbStatus";
this.gbStatus.Size = new System.Drawing.Size(370, 156);
this.gbStatus.TabIndex = 1;
this.gbStatus.TabStop = false;
this.gbStatus.Text = "Status";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 47);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(153, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Server queue evolution in time:";
//
// graphView
//
this.graphView.AutoAdjustPeek = true;
this.graphView.BackColor = System.Drawing.Color.Black;
this.graphView.GridColor = System.Drawing.Color.Green;
this.graphView.GridSize = ((ushort)(15));
this.graphView.HighQuality = true;
this.graphView.LineInterval = ((ushort)(5));
this.graphView.Location = new System.Drawing.Point(9, 63);
this.graphView.MaxLabel = "0000 sets";
this.graphView.MaxPeekMagnitude = 10;
this.graphView.MinLabel = " ";
this.graphView.MinPeekMagnitude = 0;
this.graphView.Name = "graphView";
this.graphView.ShowGrid = true;
this.graphView.ShowLabels = true;
this.graphView.Size = new System.Drawing.Size(351, 87);
this.graphView.TabIndex = 4;
this.graphView.TextColor = System.Drawing.Color.Yellow;
//
// edtClients
//
this.edtClients.Location = new System.Drawing.Point(108, 13);
this.edtClients.Name = "edtClients";
this.edtClients.ReadOnly = true;
this.edtClients.Size = new System.Drawing.Size(55, 20);
this.edtClients.TabIndex = 3;
this.edtClients.TabStop = false;
this.edtClients.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// lbClients
//
this.lbClients.AutoSize = true;
this.lbClients.Location = new System.Drawing.Point(6, 16);
this.lbClients.Name = "lbClients";
this.lbClients.Size = new System.Drawing.Size(96, 13);
this.lbClients.TabIndex = 2;
this.lbClients.Text = "Clients Connected:";
//
// btExit
//
this.btExit.Location = new System.Drawing.Point(2, 378);
this.btExit.Name = "btExit";
this.btExit.Size = new System.Drawing.Size(75, 23);
this.btExit.TabIndex = 10;
this.btExit.Text = "Exit";
this.btExit.UseVisualStyleBackColor = true;
this.btExit.Click += new System.EventHandler(this.btExit_Click);
//
// statsTimer
//
this.statsTimer.Tick += new System.EventHandler(this.statsTimer_Tick);
//
// DCalcServerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(375, 405);
this.Controls.Add(this.btExit);
this.Controls.Add(this.gbStatus);
this.Controls.Add(this.gbConfiguration);
this.Controls.Add(this.btStop);
this.Controls.Add(this.btStart);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "DCalcServerForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "DCalc Server";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.DCalcServerForm_FormClosing);
this.gbConfiguration.ResumeLayout(false);
this.gbConfiguration.PerformLayout();
this.gbLocalThreads.ResumeLayout(false);
this.gbLocalThreads.PerformLayout();
this.gbStatus.ResumeLayout(false);
this.gbStatus.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label lbAlgorithms;
private System.Windows.Forms.TextBox edtAlgorithms;
private System.Windows.Forms.Button btStart;
private System.Windows.Forms.Button btStop;
private System.Windows.Forms.GroupBox gbConfiguration;
private System.Windows.Forms.TextBox edtListeningPort;
private System.Windows.Forms.Label lbPort;
private System.Windows.Forms.GroupBox gbStatus;
private System.Windows.Forms.TextBox edtClients;
private System.Windows.Forms.Label lbClients;
private System.Windows.Forms.Button btExit;
private System.Windows.Forms.Timer statsTimer;
private System.Windows.Forms.Label lbLoadBalancer;
private System.Windows.Forms.TextBox edtLifeTime;
private System.Windows.Forms.Label lbLifeTime;
private System.Windows.Forms.ComboBox cbbLoadBalancer;
private System.Windows.Forms.GroupBox gbLocalThreads;
private System.Windows.Forms.RadioButton rbCustomCount;
private System.Windows.Forms.TextBox edtCustomCount;
private System.Windows.Forms.RadioButton rbCoreCount;
private System.Windows.Forms.RadioButton rbSingleThread;
private CustomUIControls.Graphing.C2DPushGraph graphView;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btRandom;
private System.Windows.Forms.TextBox edtSecurityKey;
private System.Windows.Forms.CheckBox cbSecure;
private System.Windows.Forms.ComboBox cbbServerType;
private System.Windows.Forms.Label lbServerType;
}
}
| |
using System;
using System.Text;
using System.Web;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Core.Html;
using Nop.Services.Directory;
using Nop.Services.Localization;
using Nop.Services.Media;
using Nop.Services.Tax;
namespace Nop.Services.Catalog
{
/// <summary>
/// Product attribute formatter
/// </summary>
public partial class ProductAttributeFormatter : IProductAttributeFormatter
{
private readonly IWorkContext _workContext;
private readonly IProductAttributeService _productAttributeService;
private readonly IProductAttributeParser _productAttributeParser;
private readonly ICurrencyService _currencyService;
private readonly ILocalizationService _localizationService;
private readonly ITaxService _taxService;
private readonly IPriceFormatter _priceFormatter;
private readonly IDownloadService _downloadService;
private readonly IWebHelper _webHelper;
private readonly IPriceCalculationService _priceCalculationService;
private readonly ShoppingCartSettings _shoppingCartSettings;
public ProductAttributeFormatter(IWorkContext workContext,
IProductAttributeService productAttributeService,
IProductAttributeParser productAttributeParser,
ICurrencyService currencyService,
ILocalizationService localizationService,
ITaxService taxService,
IPriceFormatter priceFormatter,
IDownloadService downloadService,
IWebHelper webHelper,
IPriceCalculationService priceCalculationService,
ShoppingCartSettings shoppingCartSettings)
{
this._workContext = workContext;
this._productAttributeService = productAttributeService;
this._productAttributeParser = productAttributeParser;
this._currencyService = currencyService;
this._localizationService = localizationService;
this._taxService = taxService;
this._priceFormatter = priceFormatter;
this._downloadService = downloadService;
this._webHelper = webHelper;
this._priceCalculationService = priceCalculationService;
this._shoppingCartSettings = shoppingCartSettings;
}
/// <summary>
/// Formats attributes
/// </summary>
/// <param name="product">Product</param>
/// <param name="attributes">Attributes</param>
/// <returns>Attributes</returns>
public string FormatAttributes(Product product, string attributes)
{
var customer = _workContext.CurrentCustomer;
return FormatAttributes(product, attributes, customer);
}
/// <summary>
/// Formats attributes
/// </summary>
/// <param name="product">Product</param>
/// <param name="attributes">Attributes</param>
/// <param name="customer">Customer</param>
/// <param name="serapator">Serapator</param>
/// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
/// <param name="renderPrices">A value indicating whether to render prices</param>
/// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>
/// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
/// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
/// <returns>Attributes</returns>
public string FormatAttributes(Product product, string attributes,
Customer customer, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true,
bool renderProductAttributes = true, bool renderGiftCardAttributes = true,
bool allowHyperlinks = true)
{
var result = new StringBuilder();
//attributes
if (renderProductAttributes)
{
var pvaCollection = _productAttributeParser.ParseProductVariantAttributes(attributes);
for (int i = 0; i < pvaCollection.Count; i++)
{
var pva = pvaCollection[i];
var valuesStr = _productAttributeParser.ParseValues(attributes, pva.Id);
for (int j = 0; j < valuesStr.Count; j++)
{
string valueStr = valuesStr[j];
string pvaAttribute = string.Empty;
if (!pva.ShouldHaveValues())
{
//no values
if (pva.AttributeControlType == AttributeControlType.MultilineTextbox)
{
//multiline textbox
var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
//encode (if required)
if (htmlEncode)
attributeName = HttpUtility.HtmlEncode(attributeName);
pvaAttribute = string.Format("{0}: {1}", attributeName, HtmlHelper.FormatText(valueStr, false, true, false, false, false, false));
//we never encode multiline textbox input
}
else if (pva.AttributeControlType == AttributeControlType.FileUpload)
{
//file upload
Guid downloadGuid;
Guid.TryParse(valueStr, out downloadGuid);
var download = _downloadService.GetDownloadByGuid(downloadGuid);
if (download != null)
{
//TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
string attributeText = "";
var fileName = string.Format("{0}{1}",
download.Filename ?? download.DownloadGuid.ToString(),
download.Extension);
//encode (if required)
if (htmlEncode)
fileName = HttpUtility.HtmlEncode(fileName);
if (allowHyperlinks)
{
//hyperlinks are allowed
var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid);
attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
}
else
{
//hyperlinks aren't allowed
attributeText = fileName;
}
var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
//encode (if required)
if (htmlEncode)
attributeName = HttpUtility.HtmlEncode(attributeName);
pvaAttribute = string.Format("{0}: {1}", attributeName, attributeText);
}
}
else
{
//other attributes (textbox, datepicker)
pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
//encode (if required)
if (htmlEncode)
pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
}
}
else
{
//attributes with values
int pvaId = 0;
if (int.TryParse(valueStr, out pvaId))
{
var pvaValue = _productAttributeService.GetProductVariantAttributeValueById(pvaId);
if (pvaValue != null)
{
pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), pvaValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));
if (renderPrices)
{
decimal taxRate = decimal.Zero;
decimal pvaValuePriceAdjustment = _priceCalculationService.GetProductVariantAttributeValuePriceAdjustment(pvaValue);
decimal priceAdjustmentBase = _taxService.GetProductPrice(product, pvaValuePriceAdjustment, customer, out taxRate);
decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);
if (priceAdjustmentBase > 0)
{
string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, false, false);
pvaAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
}
else if (priceAdjustmentBase < decimal.Zero)
{
string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, false, false);
pvaAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
}
}
//display quantity
if (_shoppingCartSettings.RenderAssociatedAttributeValueQuantity &&
pvaValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
{
//render only when more than 1
if (pvaValue.Quantity > 1)
{
//TODO localize resource
pvaAttribute += string.Format(" - qty {0}", pvaValue.Quantity);
}
}
}
//encode (if required)
if (htmlEncode)
pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
}
}
if (!String.IsNullOrEmpty(pvaAttribute))
{
if (i != 0 || j != 0)
result.Append(serapator);
result.Append(pvaAttribute);
}
}
}
}
//gift cards
if (renderGiftCardAttributes)
{
if (product.IsGiftCard)
{
string giftCardRecipientName = "";
string giftCardRecipientEmail = "";
string giftCardSenderName = "";
string giftCardSenderEmail = "";
string giftCardMessage = "";
_productAttributeParser.GetGiftCardAttribute(attributes, out giftCardRecipientName, out giftCardRecipientEmail,
out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);
//sender
var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ?
string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) :
string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName);
//recipient
var giftCardFor = product.GiftCardType == GiftCardType.Virtual ?
string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) :
string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName);
//encode (if required)
if (htmlEncode)
{
giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom);
giftCardFor = HttpUtility.HtmlEncode(giftCardFor);
}
if (!String.IsNullOrEmpty(result.ToString()))
{
result.Append(serapator);
}
result.Append(giftCardFrom);
result.Append(serapator);
result.Append(giftCardFor);
}
}
return result.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using StructureMap.Construction;
using StructureMap.Graph;
using StructureMap.TypeRules;
using StructureMap.Util;
namespace StructureMap.Pipeline
{
public class ConstructorInstance : Instance, IConfiguredInstance, IStructuredInstance
{
private readonly Cache<string, Instance> _dependencies = new Cache<string, Instance>();
private readonly Plugin _plugin;
public ConstructorInstance(Type pluggedType)
: this(PluginCache.GetPlugin(pluggedType))
{
}
public ConstructorInstance(Plugin plugin)
{
_plugin = plugin;
_dependencies.OnMissing = key =>
{
if (_plugin.FindArgumentType(key).IsSimple())
{
throw new StructureMapException(205, key, Name);
}
return new DefaultInstance();
};
}
public ConstructorInstance(Type pluggedType, string name)
: this(pluggedType)
{
Name = name;
}
protected Plugin plugin { get { return _plugin; } }
void IConfiguredInstance.SetChild(string name, Instance instance)
{
SetChild(name, instance);
}
public void SetValue(Type type, object value, CannotFindProperty cannotFind)
{
string name = _plugin.FindArgumentNameForType(type, cannotFind);
if (name != null) SetValue(name, value);
}
void IConfiguredInstance.SetValue(string name, object value)
{
SetValue(name, value);
}
void IConfiguredInstance.SetCollection(string name, IEnumerable<Instance> children)
{
SetCollection(name, children);
}
public string GetProperty(string propertyName)
{
return _dependencies[propertyName].As<ObjectInstance>().Object.ToString();
}
public object Get(string propertyName, Type pluginType, BuildSession session)
{
return _dependencies[propertyName].Build(pluginType, session);
}
public T Get<T>(string propertyName, BuildSession session)
{
object o = Get(propertyName, typeof (T), session);
if (o == null) return default(T);
return (T) o;
}
public Type PluggedType { get { return _plugin.PluggedType; } }
public bool HasProperty(string propertyName, BuildSession session)
{
// TODO -- richer behavior
return _dependencies.Has(propertyName) && !(_dependencies[propertyName] is NullInstance);
}
Instance IStructuredInstance.GetChild(string name)
{
return _dependencies[name];
}
Instance[] IStructuredInstance.GetChildArray(string name)
{
return _dependencies[name].As<EnumerableInstance>().Children.ToArray();
}
void IStructuredInstance.RemoveKey(string name)
{
_dependencies.Remove(name);
}
protected override bool canBePartOfPluginFamily(PluginFamily family)
{
return _plugin.PluggedType.CanBeCastTo(family.PluginType);
}
public ConstructorInstance Override(ExplicitArguments arguments)
{
var instance = new ConstructorInstance(_plugin);
_dependencies.Each((key, i) => instance.SetChild(key, i));
arguments.Configure(instance);
return instance;
}
protected override sealed string getDescription()
{
return "Configured Instance of " + _plugin.PluggedType.AssemblyQualifiedName;
}
protected override sealed Type getConcreteType(Type pluginType)
{
return _plugin.PluggedType;
}
internal void SetChild(string name, Instance instance)
{
if (instance == null)
{
throw new ArgumentNullException("instance", "Instance for {0} was null".ToFormat(name));
}
_dependencies[name] = instance;
}
internal void SetValue(string name, object value)
{
Type dependencyType = getDependencyType(name);
Instance instance = buildInstanceForType(dependencyType, value);
SetChild(name, instance);
}
private Type getDependencyType(string name)
{
Type dependencyType = _plugin.FindArgumentType(name);
if (dependencyType == null)
{
throw new ArgumentOutOfRangeException("name",
"Could not find a constructor parameter or property for {0} named {1}"
.ToFormat(_plugin.PluggedType.AssemblyQualifiedName, name));
}
return dependencyType;
}
internal void SetCollection(string name, IEnumerable<Instance> children)
{
Type dependencyType = getDependencyType(name);
var instance = new EnumerableInstance(dependencyType, children);
SetChild(name, instance);
}
protected string findPropertyName<PLUGINTYPE>()
{
Type dependencyType = typeof (PLUGINTYPE);
return findPropertyName(dependencyType);
}
protected string findPropertyName(Type dependencyType)
{
string propertyName = _plugin.FindArgumentNameForType(dependencyType, CannotFindProperty.ThrowException);
if (string.IsNullOrEmpty(propertyName))
{
throw new StructureMapException(305, dependencyType);
}
return propertyName;
}
private Instance buildInstanceForType(Type dependencyType, object value)
{
if (value == null) return new NullInstance();
if (dependencyType.IsSimple() || dependencyType.IsNullable() || dependencyType == typeof (Guid) ||
dependencyType == typeof (DateTime))
{
try
{
if (value.GetType() == dependencyType) return new ObjectInstance(value);
TypeConverter converter = TypeDescriptor.GetConverter(dependencyType);
object convertedValue = converter.ConvertFrom(null, CultureInfo.InvariantCulture, value);
return new ObjectInstance(convertedValue);
}
catch (Exception e)
{
throw new StructureMapException(206, e, Name);
}
}
return new ObjectInstance(value);
}
protected override object build(Type pluginType, BuildSession session)
{
IInstanceBuilder builder = PluginCache.FindBuilder(_plugin.PluggedType);
return Build(pluginType, session, builder);
}
public object Build(Type pluginType, BuildSession session, IInstanceBuilder builder)
{
if (builder == null)
{
throw new StructureMapException(
201, _plugin.PluggedType.FullName, Name, pluginType);
}
try
{
var args = new Arguments(this, session);
return builder.BuildInstance(args);
}
catch (StructureMapException)
{
throw;
}
catch (InvalidCastException ex)
{
throw new StructureMapException(206, ex, Name);
}
catch (Exception ex)
{
throw new StructureMapException(207, ex, Name, pluginType.FullName);
}
}
public static ConstructorInstance For<T>()
{
return new ConstructorInstance(typeof (T));
}
public override Instance CloseType(Type[] types)
{
if(!_plugin.PluggedType.IsOpenGeneric())
return null;
Type closedType;
try {
closedType = _plugin.PluggedType.MakeGenericType(types);
}
catch {
return null;
}
var closedInstance = new ConstructorInstance(closedType);
_dependencies.Each((key, i) => {
if(i.CopyAsIsWhenClosingInstance) {
closedInstance.SetChild(key, i);
}
});
return closedInstance;
}
public override string ToString()
{
return "'{0}' -> {1}".ToFormat(Name, _plugin.PluggedType.FullName);
}
}
}
| |
//-----------------------------------------------------------------------------
// ParticleSystem.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
// Website: http://xbox.create.msdn.com/en-US/education/catalog/sample/particle
// Other Contributors: Thomas Slusny @ http://indiearmory.com
// License: Microsoft Permissive License (Ms-PL)
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Spooker.Time;
using Spooker.Core;
using Spooker.Content;
namespace Spooker.Graphics.Particles
{
/// <summary>
/// Particle system.
/// </summary>
public class ParticleSystem : GameComponent, IDrawable, IUpdateable, ILoadable
{
#region Private fields
// the graphic this particle system will use.
private Texture _texture;
private Rectangle _sourceRect;
private Vector2 _origin;
// the array of particles used by this system. these are reused, so that calling
// AddParticles will only cause allocations if we're trying to create more particles
// than we have available
private readonly List<Particle> _particles;
// the queue of free particles keeps track of particles that are not curently
// being used by an effect. when a new effect is requested, particles are taken
// from this queue. when particles are finished they are put onto this queue.
private readonly Queue<Particle> _freeParticles;
// The settings used for this particle system
private readonly ParticleSettings _settings;
#endregion
/// <summary>
/// returns the number of particles that are available for a new effect.
/// </summary>
public int FreeParticleCount
{
get { return _freeParticles.Count; }
}
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Particles.ParticleSystem"/> class.
/// </summary>
/// <param name="game">The host for this particle system.</param>
/// <param name="settings">Settings used for this particle system.</param>
public ParticleSystem(GameWindow game, ParticleSettings settings)
: this(game, settings, 10)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="Spooker.Graphics.Particles.ParticleSystem"/> class.
/// </summary>
/// <param name="game">The host for this particle system.</param>
/// <param name="settings">Settings used for this particle system.</param>
/// <param name="initialParticleCount">The initial number of particles this
/// system expects to use. The system will grow as needed, however setting
/// this value to be as close as possible will reduce allocations.</param>
public ParticleSystem(GameWindow game, ParticleSettings settings, int initialParticleCount)
: base(game)
{
_settings = settings;
// we create the particle list and queue with our initial count and create that
// many particles. If we picked a reasonable value, our system will not allocate
// any more objects after this point, however the AddParticles method will allocate
// more particles as needed.
_particles = new List<Particle>(initialParticleCount);
_freeParticles = new Queue<Particle>(initialParticleCount);
for (int i = 0; i < initialParticleCount; i++)
{
_particles.Add(new Particle());
_freeParticles.Enqueue(_particles[i]);
}
}
/// <summary>
/// AddParticles's job is to add an effect somewhere on the screen. If there
/// aren't enough particles in the freeParticles queue, it will use as many as
/// it can. This means that if there not enough particles available, calling
/// AddParticles will have no effect.
/// </summary>
/// <param name="where">Where the particle effect should be created</param>
/// <param name="velocity">A base velocity for all particles. This is weighted
/// by the EmitterVelocitySensitivity specified in the settings for the
/// particle system.</param>
public void AddParticles(Vector2 where, Vector2 velocity)
{
// the number of particles we want for this effect is a random number
// somewhere between the two constants specified by the settings.
var numParticles = (int)MathHelper.Random(_settings.MinNumParticles, _settings.MaxNumParticles);
// create that many particles, if you can.
for (int i = 0; i < numParticles; i++)
{
// if we're out of free particles, we allocate another ten particles
// which should keep us going.
if (_freeParticles.Count == 0)
{
for (int j = 0; j < 10; j++)
{
var newParticle = new Particle();
_particles.Add(newParticle);
_freeParticles.Enqueue(newParticle);
}
}
// grab a particle from the freeParticles queue, and Initialize it.
var p = _freeParticles.Dequeue();
InitializeParticle(p, where, velocity);
}
}
/// <summary>
/// InitializeParticle randomizes some properties for a particle, then
/// calls initialize on it. It can be overriden by subclasses if they
/// want to modify the way particles are created. For example,
/// SmokePlumeParticleSystem overrides this function make all particles
/// accelerate to the right, simulating wind.
/// </summary>
/// <param name="p">the particle to initialize</param>
/// <param name="where">the position on the screen that the particle should be
/// </param>
/// <param name="velocity">The base velocity that the particle should have</param>
private void InitializeParticle(Particle p, Vector2 where, Vector2 velocity)
{
// Adjust the input velocity based on how much
// this particle system wants to be affected by it.
velocity *= _settings.EmitterVelocitySensitivity;
// Adjust the velocity based on our random values
// our settings angles are in degrees, so we must convert to radians
var angle = (float)MathHelper.ToRadians (MathHelper.Random (_settings.MinDirectionAngle, _settings.MaxDirectionAngle));
var direction = new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
var speed = (float)MathHelper.Random(_settings.MinInitialSpeed, _settings.MaxInitialSpeed);
velocity += direction * speed;
// pick some random values for our particle
var lifetime =(float) MathHelper.Random(_settings.MinLifetime, _settings.MaxLifetime);
var scale = (float)MathHelper.Random(_settings.MinSize, _settings.MaxSize);
var rotationSpeed = (float)MathHelper.Random(_settings.MinRotationSpeed, _settings.MaxRotationSpeed);
// our settings angles are in degrees, so we must convert to radians
rotationSpeed = (float)MathHelper.ToRadians(rotationSpeed);
// figure out our acceleration base on our AccelerationMode
var acceleration = Vector2.Zero;
switch (_settings.AccelerationMode)
{
case AccelerationMode.Scalar:
// randomly pick our acceleration using our direction and
// the MinAcceleration/MaxAcceleration values
var accelerationScale = (float)MathHelper.Random(
_settings.MinAccelerationScale, _settings.MaxAccelerationScale);
acceleration = direction * accelerationScale;
break;
case AccelerationMode.EndVelocity:
// Compute our acceleration based on our ending velocity from the settings.
// We'll use the equation vt = v0 + (a0 * t). (If you're not familar with
// this, it's one of the basic kinematics equations for constant
// acceleration, and basically says:
// velocity at time t = initial velocity + acceleration * t)
// We're solving for a0 by substituting t for our lifetime, v0 for our
// velocity, and vt as velocity * settings.EndVelocity.
acceleration = (velocity * (_settings.EndVelocity - 1)) / lifetime;
break;
case AccelerationMode.Vector:
acceleration = new Vector2(
(float)MathHelper.Random(_settings.MinAccelerationVector.X, _settings.MaxAccelerationVector.X),
(float)MathHelper.Random(_settings.MinAccelerationVector.Y, _settings.MaxAccelerationVector.Y));
break;
}
// then initialize it with those random values. initialize will save those,
// and make sure it is marked as active.
p.Initialize(where, velocity, acceleration, lifetime, scale, rotationSpeed);
}
/// <summary>
/// Component uses this for loading itself
/// </summary>
/// <param name="content">Content.</param>
public void LoadContent(ContentManager content)
{
_texture = new Texture(_settings.TextureFilename);
_sourceRect = new Rectangle (0, 0, (int)_texture.Size.X, (int)_texture.Size.Y);
_origin = _texture.Size / 2;
}
/// <summary>
/// Allows the game component to update itself.
/// </summary>
/// <param name="gameTime">Provides snapshot of timing values.</param>
public void Update(GameTime gameTime)
{
// calculate dt, the change in the since the last frame. the particle
// updates will use this value.
var dt = (float)gameTime.ElapsedGameTime.Seconds;
// go through all of the particles...
foreach (Particle p in _particles)
{
if (p.Active)
{
// ... and if they're active, update them.
p.Acceleration += _settings.Gravity * dt;
p.Update(dt);
// if that update finishes them, put them onto the free particles
// queue.
if (!p.Active) _freeParticles.Enqueue(p);
}
}
}
/// <summary>
/// Component uses this for drawing itself
/// </summary>
/// <param name="spriteBatch">Sprite batch.</param>
/// <param name="effects">Effects.</param>
public void Draw(SpriteBatch spriteBatch, SpriteEffects effects)
{
// tell sprite batch to begin
spriteBatch.Begin (_settings.BlendMode);
foreach (Particle p in _particles)
{
// skip inactive particles
if (!p.Active)
continue;
// normalized lifetime is a value from 0 to 1 and represents how far
// a particle is through its life. 0 means it just started, .5 is half
// way through, and 1.0 means it's just about to be finished.
// this value will be used to calculate alpha and scale, to avoid
// having particles suddenly appear or disappear.
var normalizedLifetime = p.TimeSinceStart / p.Lifetime;
// we want particles to fade in and fade out, so we'll calculate alpha
// to be (normalizedLifetime) * (1-normalizedLifetime). this way, when
// normalizedLifetime is 0 or 1, alpha is 0. the maximum value is at
// normalizedLifetime = .5, and is
// (normalizedLifetime) * (1-normalizedLifetime)
// (.5) * (1-.5)
// .25
// since we want the maximum alpha to be 1, not .25, we'll scale the
// entire equation by 4.
var alpha = 4f * normalizedLifetime * (1f - normalizedLifetime);
// change color alpha based on lifetime
var color = _settings.Color;
color.A = alpha;
// make particles grow as they age. they'll start at 75% of their size,
// and increase to 100% once they're finished.
var scale = new Vector2 (p.Scale * (.75f + .25f * normalizedLifetime));
spriteBatch.Draw(_texture, p.Position, _sourceRect, color, scale, _origin, p.Rotation, effects);
}
// tell sprite batch to end, using the spriteBlendMode specified in
// particle settings
spriteBatch.End ();
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.DirectoryServices;
using Microsoft.Win32;
using WebsitePanel.Providers;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Server.Utils;
using System.Management;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
//using Microsoft.Rtc.Management.Hosted;
using Microsoft.Rtc.Management.WritableConfig.Settings.Edge;
using Microsoft.Rtc.Management.WritableConfig.Settings.SimpleUrl;
namespace WebsitePanel.Providers.HostedSolution
{
public class Lync2013HP : HostingServiceProviderBase, ILyncServer
{
#region Static constructor
static Lync2013HP()
{
LyncRegistryPath = "SOFTWARE\\Microsoft\\Real-Time Communications";
}
public static string LyncRegistryPath
{
get;
set;
}
#endregion
#region Properties
/// <summary>
/// Pool FQDN
/// </summary>
private string PoolFQDN
{
get { return ProviderSettings[LyncConstants.PoolFQDN]; }
}
private string SimpleUrlRoot
{
get { return ProviderSettings[LyncConstants.SimpleUrlRoot]; }
}
internal string PrimaryDomainController
{
get { return ProviderSettings["PrimaryDomainController"]; }
}
private string RootOU
{
get { return ProviderSettings["RootOU"]; }
}
private string RootDomain
{
get { return ServerSettings.ADRootDomain; }
}
#endregion
#region ILyncServer implementation
public string CreateOrganization(string organizationId, string sipDomain, bool enableConferencing, bool enableConferencingVideo, int maxConferenceSize, bool enabledFederation, bool enabledEnterpriseVoice)
{
return CreateOrganizationInternal(organizationId, sipDomain, enableConferencing, enableConferencingVideo, maxConferenceSize, enabledFederation, enabledEnterpriseVoice);
}
public string GetOrganizationTenantId(string organizationId)
{
return GetOrganizationTenantIdInternal(organizationId);
}
public bool DeleteOrganization(string organizationId, string sipDomain)
{
return DeleteOrganizationInternal(organizationId, sipDomain);
}
public bool CreateUser(string organizationId, string userUpn, LyncUserPlan plan)
{
return CreateUserInternal(organizationId, userUpn, plan);
}
public LyncUser GetLyncUserGeneralSettings(string organizationId, string userUpn)
{
return GetLyncUserGeneralSettingsInternal(organizationId, userUpn);
}
public bool SetLyncUserGeneralSettings(string organizationId, string userUpn, LyncUser lyncUser)
{
return SetLyncUserGeneralSettingsInternal(organizationId, userUpn, lyncUser);
}
public bool SetLyncUserPlan(string organizationId, string userUpn, LyncUserPlan plan)
{
return SetLyncUserPlanInternal(organizationId, userUpn, plan, null);
}
public bool DeleteUser(string userUpn)
{
return DeleteUserInternal(userUpn);
}
public LyncFederationDomain[] GetFederationDomains(string organizationId)
{
return GetFederationDomainsInternal(organizationId);
}
public bool AddFederationDomain(string organizationId, string domainName, string proxyFqdn)
{
return AddFederationDomainInternal(organizationId, domainName, proxyFqdn);
}
public bool RemoveFederationDomain(string organizationId, string domainName)
{
return RemoveFederationDomainInternal(organizationId, domainName);
}
public void ReloadConfiguration()
{
ReloadConfigurationInternal();
}
public string[] GetPolicyList(LyncPolicyType type, string name)
{
return GetPolicyListInternal(type, name);
}
#endregion
#region organization
private string CreateOrganizationInternal(string organizationId, string sipDomain, bool enableConferencing, bool enableConferencingVideo, int maxConferenceSize, bool enabledFederation, bool enabledEnterpriseVoice)
{
sipDomain = sipDomain.ToLower();
HostedSolutionLog.LogStart("CreateOrganizationInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("sipDomain: {0}", sipDomain);
string TenantId = string.Empty;
LyncTransaction transaction = StartTransaction();
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
// create sip domain
Command cmd = new Command("New-CsSipDomain");
cmd.Parameters.Add("Identity", sipDomain);
ExecuteShellCommand(runSpace, cmd, false);
transaction.RegisterNewSipDomain(sipDomain);
//set the msRTCSIP-Domains, TenantID, ObjectID
Guid id = Guid.NewGuid();
string path = AddADPrefix(GetOrganizationPath(organizationId));
DirectoryEntry ou = ActiveDirectoryUtils.GetADObject(path);
ActiveDirectoryUtils.SetADObjectPropertyValue(ou, "msRTCSIP-Domains", sipDomain);
ActiveDirectoryUtils.SetADObjectPropertyValue(ou, "msRTCSIP-TenantId", id);
ActiveDirectoryUtils.SetADObjectPropertyValue(ou, "msRTCSIP-ObjectId", id);
ActiveDirectoryUtils.SetADObjectPropertyValue(ou, "msRTCSIP-DomainUrlMap", sipDomain + "#" + SimpleUrlRoot+sipDomain);
ou.CommitChanges();
//Create simpleurls
CreateSimpleUrl(runSpace, sipDomain, id);
transaction.RegisterNewSimpleUrl(sipDomain, id.ToString());
//create conferencing policy
cmd = new Command("New-CsConferencingPolicy");
cmd.Parameters.Add("Identity", organizationId);
cmd.Parameters.Add("MaxMeetingSize", ((maxConferenceSize == -1) | (maxConferenceSize > 250)) ? 250 : maxConferenceSize);
cmd.Parameters.Add("AllowIPVideo", enableConferencingVideo);
ExecuteShellCommand(runSpace, cmd, false);
transaction.RegisterNewConferencingPolicy(organizationId);
//create external access policy
cmd = new Command("New-CsExternalAccessPolicy");
cmd.Parameters.Add("Identity", organizationId);
cmd.Parameters.Add("EnableFederationAccess", true);
cmd.Parameters.Add("EnableOutsideAccess", true);
cmd.Parameters.Add("EnablePublicCloudAccess", false);
cmd.Parameters.Add("EnablePublicCloudAudioVideoAccess", false);
ExecuteShellCommand(runSpace, cmd, false);
transaction.RegisterNewCsExternalAccessPolicy(organizationId);
//Enable for federation
AllowList allowList = new AllowList();
DomainPattern domain = new DomainPattern(sipDomain);
allowList.AllowedDomain.Add(domain);
cmd = new Command("Set-CsTenantFederationConfiguration");
cmd.Parameters.Add("Tenant", id);
cmd.Parameters.Add("AllowFederatedUsers", true);
cmd.Parameters.Add("AllowedDomains", allowList);
ExecuteShellCommand(runSpace, cmd, false);
//create mobility policy
cmd = new Command("New-CsMobilityPolicy");
cmd.Parameters.Add("Identity", organizationId + " EnableOutSideVoice");
cmd.Parameters.Add("EnableMobility", true);
cmd.Parameters.Add("EnableOutsideVoice", true);
ExecuteShellCommand(runSpace, cmd, false);
transaction.RegisterNewCsMobilityPolicy(organizationId + " EnableOutSideVoice");
cmd = new Command("New-CsMobilityPolicy");
cmd.Parameters.Add("Identity", organizationId + " DisableOutSideVoice");
cmd.Parameters.Add("EnableMobility", true);
cmd.Parameters.Add("EnableOutsideVoice", false);
ExecuteShellCommand(runSpace, cmd, false);
transaction.RegisterNewCsMobilityPolicy(organizationId + " DisableOutSideVoice");
cmd = new Command("Invoke-CsManagementStoreReplication");
ExecuteShellCommand(runSpace, cmd, false);
TenantId = id.ToString();
}
catch (Exception ex)
{
HostedSolutionLog.LogError("CreateOrganizationInternal", ex);
RollbackTransaction(transaction);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("CreateOrganizationInternal");
return TenantId;
}
private string GetOrganizationTenantIdInternal(string organizationId)
{
HostedSolutionLog.LogStart("GetOrganizationTenantIdInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
string tenantIdStr = string.Empty;
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Command cmd = new Command("Get-CsTenant");
cmd.Parameters.Add("Identity", GetOrganizationPath(organizationId));
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
Guid tenantId = (Guid)GetPSObjectProperty(result[0], "TenantId");
tenantIdStr = tenantId.ToString();
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("GetOrganizationTenantIdInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("GetOrganizationTenantIdnInternal");
return tenantIdStr;
}
private bool DeleteOrganizationInternal(string organizationId, string sipDomain)
{
HostedSolutionLog.LogStart("DeleteOrganizationInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("sipDomain: {0}", sipDomain);
bool ret = true;
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Command cmd = new Command("Get-CsTenant");
cmd.Parameters.Add("Identity", GetOrganizationPath(organizationId));
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
Guid tenantId = (Guid)GetPSObjectProperty(result[0], "TenantId");
// create sip domain
string path = AddADPrefix(GetOrganizationPath(organizationId));
DirectoryEntry ou = ActiveDirectoryUtils.GetADObject(path);
string[] sipDs = (string[])ActiveDirectoryUtils.GetADObjectPropertyMultiValue(ou, "msRTCSIP-Domains");
foreach (string sipD in sipDs)
DeleteSipDomain(runSpace, sipD);
//clear the msRTCSIP-Domains, TenantID, ObjectID
ActiveDirectoryUtils.ClearADObjectPropertyValue(ou, "msRTCSIP-Domains");
ActiveDirectoryUtils.ClearADObjectPropertyValue(ou, "msRTCSIP-TenantId");
ActiveDirectoryUtils.ClearADObjectPropertyValue(ou, "msRTCSIP-ObjectId");
ou.CommitChanges();
try
{
DeleteConferencingPolicy(runSpace, organizationId);
}
catch (Exception)
{
}
try
{
DeleteExternalAccessPolicy(runSpace, organizationId);
}
catch (Exception)
{
}
try
{
DeleteMobilityPolicy(runSpace, organizationId + " EnableOutSideVoice");
}
catch (Exception)
{
}
try
{
DeleteMobilityPolicy(runSpace, organizationId + " DisableOutSideVoice");
}
catch (Exception)
{
}
try
{
DeleteSimpleUrl(runSpace, sipDomain, tenantId);
}
catch (Exception)
{
}
}
cmd = new Command("Invoke-CsManagementStoreReplication");
ExecuteShellCommand(runSpace, cmd, false);
}
catch (Exception ex)
{
ret = false;
HostedSolutionLog.LogError("DeleteOrganizationInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("DeleteOrganizationInternal");
return ret;
}
#endregion
#region Users
private bool CreateUserInternal(string organizationId, string userUpn, LyncUserPlan plan)
{
HostedSolutionLog.LogStart("CreateUserInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
bool ret = true;
Guid tenantId = Guid.Empty;
LyncTransaction transaction = StartTransaction();
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Command cmd = new Command("Get-CsTenant");
cmd.Parameters.Add("Identity", GetOrganizationPath(organizationId));
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
tenantId = (Guid)GetPSObjectProperty(result[0], "TenantId");
string[] tmp = userUpn.Split('@');
if (tmp.Length < 2) return false;
// Get SipDomains and verify existence
bool bSipDomainExists = false;
cmd = new Command("Get-CsSipDomain");
Collection<PSObject> sipDomains = ExecuteShellCommand(runSpace, cmd, false);
foreach (PSObject domain in sipDomains)
{
string d = (string)GetPSObjectProperty(domain, "Name");
if (d.ToLower() == tmp[1].ToLower())
{
bSipDomainExists = true;
break;
}
}
string path = string.Empty;
if (!bSipDomainExists)
{
// Create Sip Domain
cmd = new Command("New-CsSipDomain");
cmd.Parameters.Add("Identity", tmp[1].ToLower());
ExecuteShellCommand(runSpace, cmd, false);
transaction.RegisterNewSipDomain(tmp[1].ToLower());
path = AddADPrefix(GetOrganizationPath(organizationId));
DirectoryEntry ou = ActiveDirectoryUtils.GetADObject(path);
string[] sipDs = (string[])ActiveDirectoryUtils.GetADObjectPropertyMultiValue(ou, "msRTCSIP-Domains");
List<string> listSipDs = new List<string>();
listSipDs.AddRange(sipDs);
listSipDs.Add(tmp[1]);
ActiveDirectoryUtils.SetADObjectPropertyValue(ou, "msRTCSIP-Domains", listSipDs.ToArray());
ou.CommitChanges();
//Create simpleurls
CreateSimpleUrl(runSpace, tmp[1].ToLower(), tenantId);
transaction.RegisterNewSimpleUrl(tmp[1].ToLower(), tenantId.ToString());
}
//enable for lync
cmd = new Command("Enable-CsUser");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("RegistrarPool", PoolFQDN);
cmd.Parameters.Add("SipAddressType", "UserPrincipalName");
ExecuteShellCommand(runSpace, cmd);
transaction.RegisterNewCsUser(userUpn);
//set groupingID and tenantID
cmd = new Command("Get-CsAdUser");
cmd.Parameters.Add("Identity", userUpn);
result = ExecuteShellCommand(runSpace, cmd);
path = AddADPrefix(GetResultObjectDN(result));
DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path);
ActiveDirectoryUtils.SetADObjectPropertyValue(user, "msRTCSIP-GroupingID", tenantId);
ActiveDirectoryUtils.SetADObjectPropertyValue(user, "msRTCSIP-TenantId", tenantId);
if (tmp.Length > 0)
{
string Url = SimpleUrlRoot + tmp[1];
ActiveDirectoryUtils.SetADObjectPropertyValue(user, "msRTCSIP-BaseSimpleUrl", Url.ToLower());
}
user.CommitChanges();
int trySleep = 2000; int tryMaxCount = 10; bool PlanSet = false;
for (int tryCount = 0; (tryCount < tryMaxCount) && (!PlanSet); tryCount++)
{
try
{
PlanSet = SetLyncUserPlanInternal(organizationId, userUpn, plan, runSpace);
}
catch { }
if (!PlanSet) System.Threading.Thread.Sleep(trySleep);
}
//initiate addressbook generation
cmd = new Command("Update-CsAddressBook");
ExecuteShellCommand(runSpace, cmd, false);
//initiate user database replication
cmd = new Command("Update-CsUserDatabase");
ExecuteShellCommand(runSpace, cmd, false);
}
else
{
ret = false;
HostedSolutionLog.LogError("Failed to retrieve tenantID", null);
}
}
catch (Exception ex)
{
ret = false;
HostedSolutionLog.LogError("CreateUserInternal", ex);
RollbackTransaction(transaction);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("CreateUserInternal");
return ret;
}
private LyncUser GetLyncUserGeneralSettingsInternal(string organizationId, string userUpn)
{
HostedSolutionLog.LogStart("GetLyncUserGeneralSettingsInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
LyncUser lyncUser = null;
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Command cmd = new Command("Get-CsUser");
cmd.Parameters.Add("Identity", userUpn);
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
if ((result != null) && (result.Count > 0))
{
PSObject user = result[0];
lyncUser = new LyncUser();
lyncUser.DisplayName = (string)GetPSObjectProperty(user, "DisplayName");
lyncUser.SipAddress = (string)GetPSObjectProperty(user, "SipAddress");
lyncUser.LineUri = (string)GetPSObjectProperty(user, "LineURI");
lyncUser.SipAddress = lyncUser.SipAddress.ToLower().Replace("sip:", "");
lyncUser.LineUri = lyncUser.LineUri.ToLower().Replace("tel:+", "");
lyncUser.LineUri = lyncUser.LineUri.ToLower().Replace("tel:", "");
}
else
HostedSolutionLog.LogInfo("GetLyncUserGeneralSettingsInternal: No info found");
}
catch (Exception ex)
{
HostedSolutionLog.LogError("GetLyncUserGeneralSettingsInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("GetLyncUserGeneralSettingsInternal");
return lyncUser;
}
private bool SetLyncUserGeneralSettingsInternal(string organizationId, string userUpn, LyncUser lyncUser)
{
HostedSolutionLog.LogStart("SetLyncUserGeneralSettingsInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
bool ret = true;
Runspace runSpace = null;
Guid tenantId = Guid.Empty;
LyncTransaction transaction = StartTransaction();
try
{
runSpace = OpenRunspace();
Command cmd = new Command("Get-CsTenant");
cmd.Parameters.Add("Identity", GetOrganizationPath(organizationId));
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
tenantId = (Guid)GetPSObjectProperty(result[0], "TenantId");
string[] tmp = userUpn.Split('@');
if (tmp.Length < 2) return false;
// Get SipDomains and verify existence
bool bSipDomainExists = false;
cmd = new Command("Get-CsSipDomain");
Collection<PSObject> sipDomains = ExecuteShellCommand(runSpace, cmd, false);
foreach (PSObject domain in sipDomains)
{
string d = (string)GetPSObjectProperty(domain, "Name");
if (d.ToLower() == tmp[1].ToLower())
{
bSipDomainExists = true;
break;
}
}
string path = string.Empty;
if (!bSipDomainExists)
{
// Create Sip Domain
cmd = new Command("New-CsSipDomain");
cmd.Parameters.Add("Identity", tmp[1].ToLower());
ExecuteShellCommand(runSpace, cmd, false);
transaction.RegisterNewSipDomain(tmp[1].ToLower());
path = AddADPrefix(GetOrganizationPath(organizationId));
DirectoryEntry ou = ActiveDirectoryUtils.GetADObject(path);
string[] sipDs = (string[])ActiveDirectoryUtils.GetADObjectPropertyMultiValue(ou, "msRTCSIP-Domains");
List<string> listSipDs = new List<string>();
listSipDs.AddRange(sipDs);
listSipDs.Add(tmp[1]);
ActiveDirectoryUtils.SetADObjectPropertyValue(ou, "msRTCSIP-Domains", listSipDs.ToArray());
ou.CommitChanges();
//Create simpleurls
CreateSimpleUrl(runSpace, tmp[1].ToLower(), tenantId);
transaction.RegisterNewSimpleUrl(tmp[1].ToLower(), tenantId.ToString());
path = AddADPrefix(GetResultObjectDN(result));
DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path);
if (tmp.Length > 0)
{
string Url = SimpleUrlRoot + tmp[1];
ActiveDirectoryUtils.SetADObjectPropertyValue(user, "msRTCSIP-BaseSimpleUrl", Url.ToLower());
}
user.CommitChanges();
}
}
cmd = new Command("Set-CsUser");
cmd.Parameters.Add("Identity", userUpn);
if (!string.IsNullOrEmpty(lyncUser.SipAddress)) cmd.Parameters.Add("SipAddress", "SIP:" + lyncUser.SipAddress);
if (!string.IsNullOrEmpty(lyncUser.LineUri)) cmd.Parameters.Add("LineUri", "TEL:+" + lyncUser.LineUri);
else cmd.Parameters.Add("LineUri", null);
ExecuteShellCommand(runSpace, cmd, false);
if (!String.IsNullOrEmpty(lyncUser.PIN))
{
cmd = new Command("Set-CsClientPin");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("Pin", lyncUser.PIN);
ExecuteShellCommand(runSpace, cmd, false);
}
//initiate addressbook generation
cmd = new Command("Update-CsAddressBook");
ExecuteShellCommand(runSpace, cmd, false);
//initiate user database replication
cmd = new Command("Update-CsUserDatabase");
ExecuteShellCommand(runSpace, cmd, false);
}
catch (Exception ex)
{
ret = false;
HostedSolutionLog.LogError("SetLyncUserGeneralSettingsInternal", ex);
RollbackTransaction(transaction);
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("SetLyncUserGeneralSettingsInternal");
return ret;
}
private bool SetLyncUserPlanInternal(string organizationId, string userUpn, LyncUserPlan plan, Runspace runSpace)
{
HostedSolutionLog.LogStart("SetLyncUserPlanInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
bool ret = true;
bool bCloseRunSpace = false;
try
{
if (runSpace == null)
{
runSpace = OpenRunspace();
bCloseRunSpace = true;
}
// EnterpriseVoice
Command cmd = new Command("Set-CsUser");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("EnterpriseVoiceEnabled", plan.EnterpriseVoice);
ExecuteShellCommand(runSpace, cmd, false);
//CsExternalAccessPolicy
cmd = new Command("Grant-CsExternalAccessPolicy");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("PolicyName", plan.Federation ? organizationId : null);
ExecuteShellCommand(runSpace, cmd);
//CsConferencingPolicy
cmd = new Command("Grant-CsConferencingPolicy");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("PolicyName", plan.Federation ? organizationId : null);
ExecuteShellCommand(runSpace, cmd);
//CsMobilityPolicy
cmd = new Command("Grant-CsMobilityPolicy");
cmd.Parameters.Add("Identity", userUpn);
if (plan.Mobility)
cmd.Parameters.Add("PolicyName", plan.MobilityEnableOutsideVoice ? organizationId + " EnableOutSideVoice" : organizationId + " DisableOutSideVoice");
else
cmd.Parameters.Add("PolicyName", null);
ExecuteShellCommand(runSpace, cmd);
// ArchivePolicy
cmd = new Command("Grant-CsArchivingPolicy");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("PolicyName", string.IsNullOrEmpty(plan.ArchivePolicy) ? null : plan.ArchivePolicy);
ExecuteShellCommand(runSpace, cmd);
// DialPlan
cmd = new Command("Grant-CsDialPlan");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("PolicyName", string.IsNullOrEmpty(plan.TelephonyDialPlanPolicy) ? null : plan.TelephonyDialPlanPolicy);
ExecuteShellCommand(runSpace, cmd);
// VoicePolicy
cmd = new Command("Grant-CsVoicePolicy");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("PolicyName", string.IsNullOrEmpty(plan.TelephonyVoicePolicy) ? null : plan.TelephonyVoicePolicy);
ExecuteShellCommand(runSpace, cmd);
//initiate user database replication
cmd = new Command("Update-CsUserDatabase");
ExecuteShellCommand(runSpace, cmd, false);
}
catch (Exception ex)
{
ret = false;
HostedSolutionLog.LogError("SetLyncUserPlanInternal", ex);
throw;
}
finally
{
if (bCloseRunSpace) CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("SetLyncUserPlanInternal");
return ret;
}
private bool DeleteUserInternal(string userUpn)
{
HostedSolutionLog.LogStart("DeleteUserInternal");
HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
bool ret = true;
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
//Delete User
DeleteUser(runSpace, userUpn);
//Clear groupingID and tenantID
Command cmd = new Command("Get-CsAdUser");
cmd.Parameters.Add("Identity", userUpn);
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd);
string path = AddADPrefix(GetResultObjectDN(result));
DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path);
ActiveDirectoryUtils.ClearADObjectPropertyValue(user, "msRTCSIP-GroupingID");
ActiveDirectoryUtils.ClearADObjectPropertyValue(user, "msRTCSIP-TenantId");
ActiveDirectoryUtils.ClearADObjectPropertyValue(user, "msRTCSIP-BaseSimpleUrl");
user.CommitChanges();
//initiate addressbook generation
cmd = new Command("Update-CsAddressBook");
ExecuteShellCommand(runSpace, cmd, false);
//initiate user database replication
cmd = new Command("Update-CsUserDatabase");
ExecuteShellCommand(runSpace, cmd, false);
}
catch (Exception ex)
{
ret = false;
HostedSolutionLog.LogError("DeleteUserInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("DeleteUserInternal");
return ret;
}
internal void DeleteUser(Runspace runSpace, string userUpn)
{
HostedSolutionLog.LogStart("DeleteUser");
HostedSolutionLog.DebugInfo("userUpn : {0}", userUpn);
Command cmd = new Command("Disable-CsUser");
cmd.Parameters.Add("Identity", userUpn);
cmd.Parameters.Add("Confirm", false);
ExecuteShellCommand(runSpace, cmd, false);
HostedSolutionLog.LogEnd("DeleteUser");
}
#endregion
#region SipDomains
internal void DeleteSipDomain(Runspace runSpace, string id)
{
HostedSolutionLog.LogStart("DeleteSipDomain");
HostedSolutionLog.DebugInfo("SipDomain : {0}", id);
Command cmd = new Command("Remove-CsSipDomain");
cmd.Parameters.Add("Identity", id);
cmd.Parameters.Add("Confirm", false);
cmd.Parameters.Add("Force", true);
ExecuteShellCommand(runSpace, cmd, false);
HostedSolutionLog.LogEnd("DeleteSipDomain");
}
private void CreateSimpleUrl(Runspace runSpace, string sipDomain, Guid id)
{
//Create the simpleUrlEntry
Command cmd = new Command("Get-CsSipDomain");
Collection<PSObject> sipDomains = ExecuteShellCommand(runSpace, cmd, false);
IList<PSObject> SimpleUrls = new List<PSObject>();
foreach (PSObject domain in sipDomains)
{
string d = (string)GetPSObjectProperty(domain, "Name");
string Url = SimpleUrlRoot + d;
//Create the simpleUrlEntry
cmd = new Command("New-CsSimpleUrlEntry");
cmd.Parameters.Add("Url", Url);
Collection<PSObject> simpleUrlEntry = ExecuteShellCommand(runSpace, cmd, false);
//Create the simpleUrl
cmd = new Command("New-CsSimpleUrl");
cmd.Parameters.Add("Component", "meet");
cmd.Parameters.Add("Domain", d);
cmd.Parameters.Add("SimpleUrl", simpleUrlEntry[0]);
cmd.Parameters.Add("ActiveUrl", Url);
Collection<PSObject> simpleUrl = ExecuteShellCommand(runSpace, cmd, false);
SimpleUrls.Add(simpleUrl[0]);
}
//PSListModifier
cmd = new Command("Set-CsSimpleUrlConfiguration");
cmd.Parameters.Add("Identity", "Global");
cmd.Parameters.Add("Tenant", id);
cmd.Parameters.Add("SimpleUrl", SimpleUrls);
ExecuteShellCommand(runSpace, cmd, false);
}
internal void DeleteSimpleUrl(Runspace runSpace, string sipDomain, Guid id)
{
/*
//build the url
string Url = SimpleUrlRoot + sipDomain;
//Create the simpleUrlEntry
Command cmd = new Command("New-CsSimpleUrlEntry");
cmd.Parameters.Add("Url", Url);
Collection<PSObject> simpleUrlEntry = ExecuteShellCommand(runSpace, cmd, false);
//Create the simpleUrl
cmd = new Command("New-CsSimpleUrl");
cmd.Parameters.Add("Component", "meet");
cmd.Parameters.Add("Domain", sipDomain);
cmd.Parameters.Add("SimpleUrl", simpleUrlEntry[0]);
cmd.Parameters.Add("ActiveUrl", Url);
Collection<PSObject> simpleUrl = ExecuteShellCommand(runSpace, cmd, false);
//PSListModifier
Hashtable properties = new Hashtable();
properties.Add("Remove", simpleUrl[0]);
cmd = new Command("Set-CsSimpleUrlConfiguration");
cmd.Parameters.Add("Identity", "Global");
cmd.Parameters.Add("Tenant", id);
cmd.Parameters.Add("SimpleUrl", properties);
ExecuteShellCommand(runSpace, cmd, false);
*/
}
#endregion
#region Policies
internal void DeleteConferencingPolicy(Runspace runSpace, string policyName)
{
HostedSolutionLog.LogStart("DeleteConferencingPolicy");
HostedSolutionLog.DebugInfo("policyName : {0}", policyName);
Command cmd = new Command("Remove-CsConferencingPolicy");
cmd.Parameters.Add("Identity", policyName);
cmd.Parameters.Add("Confirm", false);
cmd.Parameters.Add("Force", true);
ExecuteShellCommand(runSpace, cmd, false);
HostedSolutionLog.LogEnd("DeleteConferencingPolicy");
}
internal void DeleteExternalAccessPolicy(Runspace runSpace, string policyName)
{
HostedSolutionLog.LogStart("DeleteExternalAccessPolicy");
HostedSolutionLog.DebugInfo("policyName : {0}", policyName);
Command cmd = new Command("Remove-CsExternalAccessPolicy");
cmd.Parameters.Add("Identity", policyName);
cmd.Parameters.Add("Confirm", false);
cmd.Parameters.Add("Force", true);
ExecuteShellCommand(runSpace, cmd, false);
HostedSolutionLog.LogEnd("DeleteExternalAccessPolicy");
}
internal void DeleteMobilityPolicy(Runspace runSpace, string policyName)
{
HostedSolutionLog.LogStart("DeleteMobilityPolicy");
HostedSolutionLog.DebugInfo("policyName : {0}", policyName);
Command cmd = new Command("Remove-CsMobilityPolicy");
cmd.Parameters.Add("Identity", policyName);
cmd.Parameters.Add("Confirm", false);
cmd.Parameters.Add("Force", true);
ExecuteShellCommand(runSpace, cmd, false);
HostedSolutionLog.LogEnd("DeleteMobilityPolicy");
}
internal string[] GetPolicyListInternal(LyncPolicyType type, string name)
{
List<string> ret = new List<string>();
switch (type)
{
case LyncPolicyType.Archiving:
{
Runspace runSpace = OpenRunspace();
Command cmd = new Command("Get-CsArchivingPolicy");
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
foreach (PSObject res in result)
{
string Identity = GetPSObjectProperty(res, "Identity").ToString();
ret.Add(Identity);
}
}
}
break;
case LyncPolicyType.DialPlan:
{
Runspace runSpace = OpenRunspace();
Command cmd = new Command("Get-CsDialPlan");
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
foreach (PSObject res in result)
{
string Identity = GetPSObjectProperty(res, "Identity").ToString();
string Description = "" + (string)GetPSObjectProperty(res, "Description");
if (Description.ToLower().IndexOf(name.ToLower()) == -1) continue;
ret.Add(Identity);
}
}
}
break;
case LyncPolicyType.Voice:
{
Runspace runSpace = OpenRunspace();
Command cmd = new Command("Get-CsVoicePolicy");
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
foreach (PSObject res in result)
{
string Identity = GetPSObjectProperty(res, "Identity").ToString();
string Description = "" + (string)GetPSObjectProperty(res, "Description");
if (Description.ToLower().IndexOf(name.ToLower()) == -1) continue;
ret.Add(Identity);
}
}
}
break;
case LyncPolicyType.Pin:
{
Runspace runSpace = OpenRunspace();
Command cmd = new Command("Get-CsPinPolicy");
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
foreach (PSObject res in result)
{
string Identity = GetPSObjectProperty(res, "Identity").ToString();
string str = "" + GetPSObjectProperty(res, name);
ret.Add(str);
}
}
}
break;
}
return ret.ToArray();
}
#endregion
#region Sytsem Related Methods
private void ReloadConfigurationInternal()
{
HostedSolutionLog.LogStart("ReloadConfigurationInternal");
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Command cmd = new Command("Enable-CsComputer");
ExecuteShellCommand(runSpace, cmd, false);
}
catch (Exception ex)
{
HostedSolutionLog.LogError("ReloadConfigurationInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("ReloadConfigurationInternal");
}
#endregion
#region Federation Domains
private LyncFederationDomain[] GetFederationDomainsInternal(string organizationId)
{
HostedSolutionLog.LogStart("GetFederationDomainsInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
LyncFederationDomain[] domains = null;
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Guid tenantId = Guid.Empty;
domains = GetFederationDomainsInternal(runSpace, organizationId, ref tenantId);
}
catch (Exception ex)
{
HostedSolutionLog.LogError("GetFederationDomainsInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("GetFederationDomainsInternal");
return domains;
}
private LyncFederationDomain[] GetFederationDomainsInternal(Runspace runSpace, string organizationId, ref Guid tenantId)
{
//Get TenantID
List<LyncFederationDomain> domains = null;
Command cmd = new Command("Get-CsTenant");
cmd.Parameters.Add("Identity", GetOrganizationPath(organizationId));
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
tenantId = (Guid)GetPSObjectProperty(result[0], "TenantId");
//Get-CSTenantFederationConfiguration (AllowedDomains)
cmd = new Command("Get-CsTenantFederationConfiguration");
cmd.Parameters.Add("Tenant", tenantId);
result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
domains = new List<LyncFederationDomain>();
if (GetPSObjectProperty(result[0], "AllowedDomains").GetType().ToString() == "Microsoft.Rtc.Management.WritableConfig.Settings.Edge.AllowList")
{
AllowList allowList = (AllowList)GetPSObjectProperty(result[0], "AllowedDomains");
foreach (DomainPattern d in allowList.AllowedDomain)
{
LyncFederationDomain domain = new LyncFederationDomain();
domain.DomainName = d.Domain.ToString();
domains.Add(domain);
}
}
}
}
if (domains != null)
return domains.ToArray();
else
return null;
}
private bool AddFederationDomainInternal(string organizationId, string domainName, string proxyFqdn)
{
HostedSolutionLog.LogStart("AddFederationDomainInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("domainName: {0}", domainName);
domainName = domainName.ToLower();
proxyFqdn = proxyFqdn.ToLower();
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Guid tenantId = Guid.Empty;
Command cmd = new Command("Get-CsTenant");
cmd.Parameters.Add("Identity", GetOrganizationPath(organizationId));
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
tenantId = (Guid)GetPSObjectProperty(result[0], "TenantId");
//Get-CSTenantFederationConfiguration (AllowedDomains)
cmd = new Command("Get-CsTenantFederationConfiguration");
cmd.Parameters.Add("Tenant", tenantId);
result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
AllowList allowList = null;
if (GetPSObjectProperty(result[0], "AllowedDomains").GetType().ToString() == "Microsoft.Rtc.Management.WritableConfig.Settings.Edge.AllowList")
{
allowList = (AllowList)GetPSObjectProperty(result[0], "AllowedDomains");
DomainPattern domain = new DomainPattern(domainName);
allowList.AllowedDomain.Add(domain);
}
else
{
allowList = new AllowList();
DomainPattern domain = new DomainPattern(domainName);
allowList.AllowedDomain.Add(domain);
}
cmd = new Command("Set-CsTenantFederationConfiguration");
cmd.Parameters.Add("Tenant", tenantId);
cmd.Parameters.Add("AllowedDomains", allowList);
ExecuteShellCommand(runSpace, cmd, false);
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("AddFederationDomainInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("AddFederationDomainInternal");
return true;
}
private bool RemoveFederationDomainInternal(string organizationId, string domainName)
{
HostedSolutionLog.LogStart("RemoveFederationDomainInternal");
HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
HostedSolutionLog.DebugInfo("domainName: {0}", domainName);
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
Guid tenantId = Guid.Empty;
Command cmd = new Command("Get-CsTenant");
cmd.Parameters.Add("Identity", GetOrganizationPath(organizationId));
Collection<PSObject> result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
tenantId = (Guid)GetPSObjectProperty(result[0], "TenantId");
//Get-CSTenantFederationConfiguration (AllowedDomains)
cmd = new Command("Get-CsTenantFederationConfiguration");
cmd.Parameters.Add("Tenant", tenantId);
result = ExecuteShellCommand(runSpace, cmd, false);
if ((result != null) && (result.Count > 0))
{
AllowList allowList = null;
if (GetPSObjectProperty(result[0], "AllowedDomains").GetType().ToString() == "Microsoft.Rtc.Management.WritableConfig.Settings.Edge.AllowList")
{
HostedSolutionLog.DebugInfo("Remove DomainName: {0}", domainName);
allowList = (AllowList)GetPSObjectProperty(result[0], "AllowedDomains");
DomainPattern domain = null;
foreach (DomainPattern d in allowList.AllowedDomain)
{
if (d.Domain.ToLower() == domainName.ToLower())
{
domain = d;
break;
}
}
if (domain != null)
allowList.AllowedDomain.Remove(domain);
}
cmd = new Command("Set-CsTenantFederationConfiguration");
cmd.Parameters.Add("Tenant", tenantId);
cmd.Parameters.Add("AllowedDomains", allowList);
ExecuteShellCommand(runSpace, cmd, false);
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("RemoveFederationDomainInternal", ex);
throw;
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("RemoveFederationDomainInternal");
return true;
}
#endregion
#region PowerShell integration
private static InitialSessionState session = null;
internal virtual Runspace OpenRunspace()
{
HostedSolutionLog.LogStart("OpenRunspace");
if (session == null)
{
session = InitialSessionState.CreateDefault();
session.ImportPSModule(new string[] { "ActiveDirectory", "Lync", "LyncOnline" });
}
Runspace runSpace = RunspaceFactory.CreateRunspace(session);
//
runSpace.Open();
//
runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
HostedSolutionLog.LogEnd("OpenRunspace");
return runSpace;
}
internal void CloseRunspace(Runspace runspace)
{
try
{
if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened)
{
runspace.Close();
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("Runspace error", ex);
}
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd)
{
return ExecuteShellCommand(runSpace, cmd, true);
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController)
{
object[] errors;
return ExecuteShellCommand(runSpace, cmd, useDomainController, out errors);
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, out object[] errors)
{
return ExecuteShellCommand(runSpace, cmd, true, out errors);
}
internal Collection<PSObject> ExecuteShellCommand(Runspace runSpace, Command cmd, bool useDomainController, out object[] errors)
{
HostedSolutionLog.LogStart("ExecuteShellCommand");
List<object> errorList = new List<object>();
if (useDomainController)
{
CommandParameter dc = new CommandParameter("DomainController", PrimaryDomainController);
if (!cmd.Parameters.Contains(dc))
{
cmd.Parameters.Add(dc);
}
}
HostedSolutionLog.DebugCommand(cmd);
Collection<PSObject> results = null;
// Create a pipeline
Pipeline pipeLine = runSpace.CreatePipeline();
using (pipeLine)
{
// Add the command
pipeLine.Commands.Add(cmd);
// Execute the pipeline and save the objects returned.
results = pipeLine.Invoke();
// Log out any errors in the pipeline execution
// NOTE: These errors are NOT thrown as exceptions!
// Be sure to check this to ensure that no errors
// happened while executing the command.
if (pipeLine.Error != null && pipeLine.Error.Count > 0)
{
foreach (object item in pipeLine.Error.ReadToEnd())
{
errorList.Add(item);
string errorMessage = string.Format("Invoke error: {0}", item);
HostedSolutionLog.LogWarning(errorMessage);
}
}
}
pipeLine = null;
errors = errorList.ToArray();
HostedSolutionLog.LogEnd("ExecuteShellCommand");
return results;
}
internal object GetPSObjectProperty(PSObject obj, string name)
{
return obj.Members[name].Value;
}
/// <summary>
/// Returns the identity of the object from the shell execution result
/// </summary>
/// <param name="result"></param>
/// <returns></returns>
internal string GetResultObjectIdentity(Collection<PSObject> result)
{
HostedSolutionLog.LogStart("GetResultObjectIdentity");
if (result == null)
throw new ArgumentNullException("result", "Execution result is not specified");
if (result.Count < 1)
throw new ArgumentException("Execution result is empty", "result");
if (result.Count > 1)
throw new ArgumentException("Execution result contains more than one object", "result");
PSMemberInfo info = result[0].Members["Identity"];
if (info == null)
throw new ArgumentException("Execution result does not contain Identity property", "result");
string ret = info.Value.ToString();
HostedSolutionLog.LogEnd("GetResultObjectIdentity");
return ret;
}
internal string GetResultObjectDN(Collection<PSObject> result)
{
HostedSolutionLog.LogStart("GetResultObjectDN");
if (result == null)
throw new ArgumentNullException("result", "Execution result is not specified");
if (result.Count < 1)
throw new ArgumentException("Execution result does not contain any object");
if (result.Count > 1)
throw new ArgumentException("Execution result contains more than one object");
PSMemberInfo info = result[0].Members["DistinguishedName"];
if (info == null)
throw new ArgumentException("Execution result does not contain DistinguishedName property", "result");
string ret = info.Value.ToString();
HostedSolutionLog.LogEnd("GetResultObjectDN");
return ret;
}
#endregion
#region Transactions
internal LyncTransaction StartTransaction()
{
return new LyncTransaction();
}
internal void RollbackTransaction(LyncTransaction transaction)
{
HostedSolutionLog.LogStart("RollbackTransaction");
Runspace runSpace = null;
try
{
runSpace = OpenRunspace();
for (int i = transaction.Actions.Count - 1; i > -1; i--)
{
//reverse order
try
{
RollbackAction(transaction.Actions[i], runSpace);
}
catch (Exception ex)
{
HostedSolutionLog.LogError("Rollback error", ex);
}
}
}
catch (Exception ex)
{
HostedSolutionLog.LogError("Rollback error", ex);
}
finally
{
CloseRunspace(runSpace);
}
HostedSolutionLog.LogEnd("RollbackTransaction");
}
private void RollbackAction(TransactionAction action, Runspace runspace)
{
HostedSolutionLog.LogInfo("Rollback action: {0}", action.ActionType);
switch (action.ActionType)
{
case TransactionAction.TransactionActionTypes.LyncNewSipDomain:
DeleteSipDomain(runspace, action.Id);
break;
//case TransactionAction.TransactionActionTypes.LyncNewSimpleUrl:
//DeleteSimpleUrl(runspace, action.Id);
//break;
case TransactionAction.TransactionActionTypes.LyncNewUser:
DeleteUser(runspace, action.Id);
break;
case TransactionAction.TransactionActionTypes.LyncNewConferencingPolicy:
DeleteConferencingPolicy(runspace, action.Id);
break;
case TransactionAction.TransactionActionTypes.LyncNewExternalAccessPolicy:
DeleteExternalAccessPolicy(runspace, action.Id);
break;
case TransactionAction.TransactionActionTypes.LyncNewMobilityPolicy:
DeleteMobilityPolicy(runspace, action.Id);
break;
}
}
#endregion
#region helpers
private string GetOrganizationPath(string organizationId)
{
StringBuilder sb = new StringBuilder();
// append provider
AppendOUPath(sb, organizationId);
AppendOUPath(sb, RootOU);
AppendDomainPath(sb, RootDomain);
return sb.ToString();
}
private static void AppendOUPath(StringBuilder sb, string ou)
{
if (string.IsNullOrEmpty(ou))
return;
string path = ou.Replace("/", "\\");
string[] parts = path.Split('\\');
for (int i = parts.Length - 1; i != -1; i--)
sb.Append("OU=").Append(parts[i]).Append(",");
}
private static void AppendDomainPath(StringBuilder sb, string domain)
{
if (string.IsNullOrEmpty(domain))
return;
string[] parts = domain.Split('.');
for (int i = 0; i < parts.Length; i++)
{
sb.Append("DC=").Append(parts[i]);
if (i < (parts.Length - 1))
sb.Append(",");
}
}
internal string AddADPrefix(string path)
{
string dn = path;
if (!dn.ToUpper().StartsWith("LDAP://"))
{
dn = string.Format("LDAP://{0}/{1}", PrimaryDomainController, dn);
}
return dn;
}
#endregion
public override bool IsInstalled()
{
string value = "";
bool bResult = false;
RegistryKey root = Registry.LocalMachine;
RegistryKey rk = root.OpenSubKey(LyncRegistryPath);
if (rk != null)
{
value = (string)rk.GetValue("ProductVersion", null);
if (value == "5.0.8308.0")
bResult = true;
rk.Close();
}
return bResult;
}
}
}
| |
// <copyright file="Actions.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Drawing;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Interactions
{
/// <summary>
/// Provides values that indicate from where element offsets for MoveToElement
/// are calculated.
/// </summary>
public enum MoveToElementOffsetOrigin
{
/// <summary>
/// Offsets are calculated from the top-left corner of the element.
/// </summary>
TopLeft,
/// <summary>
/// Offsets are calcuated from the center of the element.
/// </summary>
Center
}
/// <summary>
/// Provides a mechanism for building advanced interactions with the browser.
/// </summary>
public class Actions : IAction
{
private readonly TimeSpan DefaultMouseMoveDuration = TimeSpan.FromMilliseconds(250);
private ActionBuilder actionBuilder = new ActionBuilder();
private PointerInputDevice defaultMouse = new PointerInputDevice(PointerKind.Mouse, "default mouse");
private KeyInputDevice defaultKeyboard = new KeyInputDevice("default keyboard");
private IKeyboard keyboard;
private IMouse mouse;
private IActionExecutor actionExecutor;
private CompositeAction action = new CompositeAction();
/// <summary>
/// Initializes a new instance of the <see cref="Actions"/> class.
/// </summary>
/// <param name="driver">The <see cref="IWebDriver"/> object on which the actions built will be performed.</param>
public Actions(IWebDriver driver)
{
//this.driver = driver;
IHasInputDevices inputDevicesDriver = GetDriverAs<IHasInputDevices>(driver);
if (inputDevicesDriver == null)
{
throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IHasInputDevices.", "driver");
}
IActionExecutor actionExecutor = GetDriverAs<IActionExecutor>(driver);
if (actionExecutor == null)
{
throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IActionExecutor.", "driver");
}
this.keyboard = inputDevicesDriver.Keyboard;
this.mouse = inputDevicesDriver.Mouse;
this.actionExecutor = actionExecutor;
}
/// <summary>
/// Sends a modifier key down message to the browser.
/// </summary>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyDown(string theKey)
{
return this.KeyDown(null, theKey);
}
/// <summary>
/// Sends a modifier key down message to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the key command.</param>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyDown(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new KeyDownAction(this.keyboard, this.mouse, target, theKey));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(theKey[0]));
this.actionBuilder.AddAction(new PauseInteraction(this.defaultKeyboard, TimeSpan.FromMilliseconds(100)));
return this;
}
/// <summary>
/// Sends a modifier key up message to the browser.
/// </summary>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyUp(string theKey)
{
return this.KeyUp(null, theKey);
}
/// <summary>
/// Sends a modifier up down message to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the key command.</param>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyUp(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new KeyUpAction(this.keyboard, this.mouse, target, theKey));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(theKey[0]));
return this;
}
/// <summary>
/// Sends a sequence of keystrokes to the browser.
/// </summary>
/// <param name="keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions SendKeys(string keysToSend)
{
return this.SendKeys(null, keysToSend);
}
/// <summary>
/// Sends a sequence of keystrokes to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the keystrokes.</param>
/// <param name="keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions SendKeys(IWebElement element, string keysToSend)
{
if (string.IsNullOrEmpty(keysToSend))
{
throw new ArgumentException("The key value must not be null or empty", "keysToSend");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new SendKeysAction(this.keyboard, this.mouse, target, keysToSend));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
foreach (char key in keysToSend)
{
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(key));
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(key));
}
return this;
}
/// <summary>
/// Clicks and holds the mouse button down on the specified element.
/// </summary>
/// <param name="onElement">The element on which to click and hold.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ClickAndHold(IWebElement onElement)
{
this.MoveToElement(onElement).ClickAndHold();
return this;
}
/// <summary>
/// Clicks and holds the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ClickAndHold()
{
this.action.AddAction(new ClickAndHoldAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
return this;
}
/// <summary>
/// Releases the mouse button on the specified element.
/// </summary>
/// <param name="onElement">The element on which to release the button.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Release(IWebElement onElement)
{
this.MoveToElement(onElement).Release();
return this;
}
/// <summary>
/// Releases the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Release()
{
this.action.AddAction(new ButtonReleaseAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Click(IWebElement onElement)
{
this.MoveToElement(onElement).Click();
return this;
}
/// <summary>
/// Clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Click()
{
this.action.AddAction(new ClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Double-clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to double-click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DoubleClick(IWebElement onElement)
{
this.MoveToElement(onElement).DoubleClick();
return this;
}
/// <summary>
/// Double-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DoubleClick()
{
this.action.AddAction(new DoubleClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Moves the mouse to the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement)
{
if (toElement == null)
{
throw new ArgumentException("MoveToElement cannot move to a null element with no offset.", "toElement");
}
ILocatable target = GetLocatableFromElement(toElement);
this.action.AddAction(new MoveMouseAction(this.mouse, target));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, 0, 0, DefaultMouseMoveDuration));
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the top-left corner of the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY)
{
return this.MoveToElement(toElement, offsetX, offsetY, MoveToElementOffsetOrigin.TopLeft);
}
/// <summary>
/// Moves the mouse to the specified offset of the top-left corner of the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY, MoveToElementOffsetOrigin offsetOrigin)
{
ILocatable target = GetLocatableFromElement(toElement);
Size elementSize = toElement.Size;
Point elementLocation = toElement.Location;
if (offsetOrigin == MoveToElementOffsetOrigin.TopLeft)
{
int modifiedOffsetX = offsetX - (elementSize.Width / 2);
int modifiedOffsetY = offsetY - (elementSize.Height / 2);
this.action.AddAction(new MoveToOffsetAction(this.mouse, target, offsetX, offsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, modifiedOffsetX, modifiedOffsetY, DefaultMouseMoveDuration));
}
else
{
int modifiedOffsetX = offsetX + (elementSize.Width / 2);
int modifiedOffsetY = offsetY + (elementSize.Height / 2);
this.action.AddAction(new MoveToOffsetAction(this.mouse, target, modifiedOffsetX, modifiedOffsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, offsetX, offsetY, DefaultMouseMoveDuration));
}
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the last known mouse coordinates.
/// </summary>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveByOffset(int offsetX, int offsetY)
{
this.action.AddAction(new MoveToOffsetAction(this.mouse, null, offsetX, offsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(CoordinateOrigin.Pointer, offsetX, offsetY, DefaultMouseMoveDuration));
return this;
}
/// <summary>
/// Right-clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to right-click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ContextClick(IWebElement onElement)
{
this.MoveToElement(onElement).ContextClick();
return this;
}
/// <summary>
/// Right-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ContextClick()
{
this.action.AddAction(new ContextClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Right));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Right));
return this;
}
/// <summary>
/// Performs a drag-and-drop operation from one element to another.
/// </summary>
/// <param name="source">The element on which the drag operation is started.</param>
/// <param name="target">The element on which the drop is performed.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DragAndDrop(IWebElement source, IWebElement target)
{
this.ClickAndHold(source).MoveToElement(target).Release(target);
return this;
}
/// <summary>
/// Performs a drag-and-drop operation on one element to a specified offset.
/// </summary>
/// <param name="source">The element on which the drag operation is started.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DragAndDropToOffset(IWebElement source, int offsetX, int offsetY)
{
this.ClickAndHold(source).MoveByOffset(offsetX, offsetY).Release();
return this;
}
/// <summary>
/// Builds the sequence of actions.
/// </summary>
/// <returns>A composite <see cref="IAction"/> which can be used to perform the actions.</returns>
public IAction Build()
{
return this;
}
/// <summary>
/// Performs the currently built action.
/// </summary>
public void Perform()
{
if (this.actionExecutor.IsActionExecutor)
{
this.actionExecutor.PerformActions(this.actionBuilder.ToActionSequenceList());
}
else
{
this.action.Perform();
}
}
/// <summary>
/// Gets the <see cref="ILocatable"/> instance of the specified <see cref="IWebElement"/>.
/// </summary>
/// <param name="element">The <see cref="IWebElement"/> to get the location of.</param>
/// <returns>The <see cref="ILocatable"/> of the <see cref="IWebElement"/>.</returns>
protected static ILocatable GetLocatableFromElement(IWebElement element)
{
if (element == null)
{
return null;
}
ILocatable target = null;
IWrapsElement wrapper = element as IWrapsElement;
while (wrapper != null)
{
target = wrapper.WrappedElement as ILocatable;
wrapper = wrapper.WrappedElement as IWrapsElement;
}
if (target == null)
{
target = element as ILocatable;
}
if (target == null)
{
throw new ArgumentException("The IWebElement object must implement or wrap an element that implements ILocatable.", "element");
}
return target;
}
/// <summary>
/// Adds an action to current list of actions to be performed.
/// </summary>
/// <param name="actionToAdd">The <see cref="IAction"/> to be added.</param>
protected void AddAction(IAction actionToAdd)
{
this.action.AddAction(actionToAdd);
}
private T GetDriverAs<T>(IWebDriver driver) where T : class
{
T driverAsType = driver as T;
if (driverAsType == null)
{
IWrapsDriver wrapper = driver as IWrapsDriver;
while (wrapper != null)
{
driverAsType = wrapper.WrappedDriver as T;
if (driverAsType != null)
{
driver = wrapper.WrappedDriver;
break;
}
wrapper = wrapper.WrappedDriver as IWrapsDriver;
}
}
return driverAsType;
}
}
}
| |
#region License
/*
* HttpServer.cs
*
* A simple HTTP server that allows to accept the WebSocket connection requests.
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
using WebSocketSharp.Net;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Server
{
/// <summary>
/// Provides a simple HTTP server that allows to accept the WebSocket connection requests.
/// </summary>
/// <remarks>
/// The HttpServer class can provide multiple WebSocket services.
/// </remarks>
public class HttpServer
{
#region Private Fields
private HttpListener _listener;
private Logger _logger;
private int _port;
private Thread _receiveThread;
private string _rootPath;
private bool _secure;
private WebSocketServiceManager _services;
private volatile ServerState _state;
private object _sync;
private bool _windows;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on port 80.
/// </remarks>
public HttpServer ()
: this (80, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with the specified
/// <paramref name="port"/>.
/// </summary>
/// <remarks>
/// <para>
/// An instance initialized by this constructor listens for the incoming requests
/// on <paramref name="port"/>.
/// </para>
/// <para>
/// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para>
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
public HttpServer (int port)
: this (port, port == 443)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpServer"/> class with the specified
/// <paramref name="port"/> and <paramref name="secure"/>.
/// </summary>
/// <remarks>
/// An instance initialized by this constructor listens for the incoming requests
/// on <paramref name="port"/>.
/// </remarks>
/// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen.
/// </param>
/// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not.
/// (<c>true</c> indicates providing a secure connection.)
/// </param>
/// <exception cref="ArgumentException">
/// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
public HttpServer (int port, bool secure)
{
if (!port.IsPortNumber ())
throw new ArgumentOutOfRangeException ("port", "Not between 1 and 65535: " + port);
if ((port == 80 && secure) || (port == 443 && !secure))
throw new ArgumentException (
String.Format ("An invalid pair of 'port' and 'secure': {0}, {1}", port, secure));
_port = port;
_secure = secure;
_listener = new HttpListener ();
_logger = _listener.Log;
_services = new WebSocketServiceManager (_logger);
_state = ServerState.Ready;
_sync = new object ();
var os = Environment.OSVersion;
_windows = os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX;
var pref = String.Format ("http{0}://*:{1}/", _secure ? "s" : "", _port);
_listener.Prefixes.Add (pref);
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// indicates the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
public AuthenticationSchemes AuthenticationSchemes {
get {
return _listener.AuthenticationSchemes;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.AuthenticationSchemes = value;
}
}
/// <summary>
/// Gets a value indicating whether the server has started.
/// </summary>
/// <value>
/// <c>true</c> if the server has started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _state == ServerState.Start;
}
}
/// <summary>
/// Gets a value indicating whether the server provides a secure connection.
/// </summary>
/// <value>
/// <c>true</c> if the server provides a secure connection; otherwise, <c>false</c>.
/// </value>
public bool IsSecure {
get {
return _secure;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server cleans up the inactive sessions
/// in the WebSocket services periodically.
/// </summary>
/// <value>
/// <c>true</c> if the server cleans up the inactive sessions every 60 seconds;
/// otherwise, <c>false</c>. The default value is <c>true</c>.
/// </value>
public bool KeepClean {
get {
return _services.KeepClean;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.KeepClean = value;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log {
get {
return _logger;
}
}
/// <summary>
/// Gets the port on which to listen for incoming requests.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the port number on which to listen.
/// </value>
public int Port {
get {
return _port;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the realm.
/// The default value is <c>"SECRET AREA"</c>.
/// </value>
public string Realm {
get {
return _listener.Realm;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.Realm = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the server is allowed to be bound to an address
/// that is already in use.
/// </summary>
/// <remarks>
/// If you would like to resolve to wait for socket in <c>TIME_WAIT</c> state, you should set
/// this property to <c>true</c>.
/// </remarks>
/// <value>
/// <c>true</c> if the server is allowed to be bound to an address that is already in use;
/// otherwise, <c>false</c>. The default value is <c>false</c>.
/// </value>
public bool ReuseAddress {
get {
return _listener.ReuseAddress;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.ReuseAddress = value;
}
}
/// <summary>
/// Gets or sets the document root path of the server.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the document root path of the server.
/// The default value is <c>"./Public"</c>.
/// </value>
public string RootPath {
get {
return _rootPath != null && _rootPath.Length > 0
? _rootPath
: (_rootPath = "./Public");
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_rootPath = value;
}
}
/// <summary>
/// Gets or sets the SSL configuration used to authenticate the server and
/// optionally the client for secure connection.
/// </summary>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents the configuration used
/// to authenticate the server and optionally the client for secure connection.
/// </value>
public ServerSslConfiguration SslConfiguration {
get {
return _listener.SslConfiguration;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.SslConfiguration = value;
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>> delegate that
/// references the method(s) used to find the credentials. The default value is a function
/// that only returns <see langword="null"/>.
/// </value>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
return _listener.UserCredentialsFinder;
}
set {
var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return;
}
_listener.UserCredentialsFinder = value;
}
}
/// <summary>
/// Gets or sets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time. The default value is
/// the same as 1 second.
/// </value>
public TimeSpan WaitTime {
get {
return _services.WaitTime;
}
set {
var msg = _state.CheckIfStartable () ?? value.CheckIfValidWaitTime ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.WaitTime = value;
}
}
/// <summary>
/// Gets the access to the WebSocket services provided by the server.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceManager"/> that manages the WebSocket services.
/// </value>
public WebSocketServiceManager WebSocketServices {
get {
return _services;
}
}
#endregion
#region Public Events
/// <summary>
/// Occurs when the server receives an HTTP CONNECT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnConnect;
/// <summary>
/// Occurs when the server receives an HTTP DELETE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnDelete;
/// <summary>
/// Occurs when the server receives an HTTP GET request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnGet;
/// <summary>
/// Occurs when the server receives an HTTP HEAD request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnHead;
/// <summary>
/// Occurs when the server receives an HTTP OPTIONS request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnOptions;
/// <summary>
/// Occurs when the server receives an HTTP PATCH request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPatch;
/// <summary>
/// Occurs when the server receives an HTTP POST request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPost;
/// <summary>
/// Occurs when the server receives an HTTP PUT request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnPut;
/// <summary>
/// Occurs when the server receives an HTTP TRACE request.
/// </summary>
public event EventHandler<HttpRequestEventArgs> OnTrace;
#endregion
#region Private Methods
private void abort ()
{
lock (_sync) {
if (!IsListening)
return;
_state = ServerState.ShuttingDown;
}
_services.Stop (new CloseEventArgs (CloseStatusCode.ServerError), true, false);
_listener.Abort ();
_state = ServerState.Stop;
}
private string checkIfCertificateExists ()
{
if (!_secure)
return null;
var usr = _listener.SslConfiguration.ServerCertificate != null;
var port = EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath);
if (usr && port) {
_logger.Warn ("The server certificate associated with the port number already exists.");
return null;
}
return !(usr || port)
? "The secure connection requires a server certificate."
: null;
}
private void processRequest (HttpListenerContext context)
{
var method = context.Request.HttpMethod;
var evt = method == "GET"
? OnGet
: method == "HEAD"
? OnHead
: method == "POST"
? OnPost
: method == "PUT"
? OnPut
: method == "DELETE"
? OnDelete
: method == "OPTIONS"
? OnOptions
: method == "TRACE"
? OnTrace
: method == "CONNECT"
? OnConnect
: method == "PATCH"
? OnPatch
: null;
if (evt != null)
evt (this, new HttpRequestEventArgs (context));
else
context.Response.StatusCode = (int) HttpStatusCode.NotImplemented;
context.Response.Close ();
}
private void processRequest (HttpListenerWebSocketContext context)
{
WebSocketServiceHost host;
if (!_services.InternalTryGetServiceHost (context.RequestUri.AbsolutePath, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private void receiveRequest ()
{
while (true) {
try {
var ctx = _listener.GetContext ();
ThreadPool.QueueUserWorkItem (
state => {
try {
if (ctx.Request.IsUpgradeTo ("websocket")) {
processRequest (ctx.AcceptWebSocket (null));
return;
}
processRequest (ctx);
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
ctx.Connection.Close (true);
}
});
}
catch (HttpListenerException ex) {
_logger.Warn ("Receiving has been stopped.\nreason: " + ex.Message);
break;
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
break;
}
}
if (IsListening)
abort ();
}
private void startReceiving ()
{
_listener.Start ();
_receiveThread = new Thread (new ThreadStart (receiveRequest));
_receiveThread.IsBackground = true;
_receiveThread.Start ();
}
private void stopReceiving (int millisecondsTimeout)
{
_listener.Close ();
_receiveThread.Join (millisecondsTimeout);
}
#endregion
#region Public Methods
/// <summary>
/// Adds a WebSocket service with the specified behavior and <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <typeparam name="TBehaviorWithNew">
/// The type of the behavior of the service to add. The TBehaviorWithNew must inherit
/// the <see cref="WebSocketBehavior"/> class, and must have a public parameterless
/// constructor.
/// </typeparam>
public void AddWebSocketService<TBehaviorWithNew> (string path)
where TBehaviorWithNew : WebSocketBehavior, new ()
{
AddWebSocketService<TBehaviorWithNew> (path, () => new TBehaviorWithNew ());
}
/// <summary>
/// Adds the WebSocket service with the specified behavior, <paramref name="path"/>,
/// and <paramref name="initializer"/>.
/// </summary>
/// <remarks>
/// <para>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </para>
/// <para>
/// <paramref name="initializer"/> returns an initialized specified typed
/// <see cref="WebSocketBehavior"/> instance.
/// </para>
/// </remarks>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to add.
/// </param>
/// <param name="initializer">
/// A Func<T> delegate that references the method used to initialize a new specified
/// typed <see cref="WebSocketBehavior"/> instance (a new <see cref="IWebSocketSession"/>
/// instance).
/// </param>
/// <typeparam name="TBehavior">
/// The type of the behavior of the service to add. The TBehavior must inherit
/// the <see cref="WebSocketBehavior"/> class.
/// </typeparam>
public void AddWebSocketService<TBehavior> (string path, Func<TBehavior> initializer)
where TBehavior : WebSocketBehavior
{
var msg = path.CheckIfValidServicePath () ??
(initializer == null ? "'initializer' is null." : null);
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Add<TBehavior> (path, initializer);
}
/// <summary>
/// Gets the contents of the file with the specified <paramref name="path"/>.
/// </summary>
/// <returns>
/// An array of <see cref="byte"/> that receives the contents of the file,
/// or <see langword="null"/> if it doesn't exist.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the virtual path to the file to find.
/// </param>
public byte[] GetFile (string path)
{
path = RootPath + path;
if (_windows)
path = path.Replace ("/", "\\");
return File.Exists (path)
? File.ReadAllBytes (path)
: null;
}
/// <summary>
/// Removes the WebSocket service with the specified <paramref name="path"/>.
/// </summary>
/// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string,
/// and removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks>
/// <returns>
/// <c>true</c> if the service is successfully found and removed; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
public bool RemoveWebSocketService (string path)
{
var msg = path.CheckIfValidServicePath ();
if (msg != null) {
_logger.Error (msg);
return false;
}
return _services.Remove (path);
}
/// <summary>
/// Starts receiving the HTTP requests.
/// </summary>
public void Start ()
{
lock (_sync) {
var msg = _state.CheckIfStartable () ?? checkIfCertificateExists ();
if (msg != null) {
_logger.Error (msg);
return;
}
_services.Start ();
startReceiving ();
_state = ServerState.Start;
}
}
/// <summary>
/// Stops receiving the HTTP requests.
/// </summary>
public void Stop ()
{
lock (_sync) {
var msg = _state.CheckIfStart ();
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
_services.Stop (new CloseEventArgs (), true, true);
stopReceiving (5000);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the HTTP requests with the specified <see cref="ushort"/> and
/// <see cref="string"/> used to stop the WebSocket services.
/// </summary>
/// <param name="code">
/// A <see cref="ushort"/> that represents the status code indicating the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop (ushort code, string reason)
{
lock (_sync) {
var msg = _state.CheckIfStart () ?? WebSocket.CheckCloseParameters (code, reason, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
if (code == (ushort) CloseStatusCode.NoStatus) {
_services.Stop (new CloseEventArgs (), true, true);
}
else {
var send = !code.IsReserved ();
_services.Stop (new CloseEventArgs (code, reason), send, send);
}
stopReceiving (5000);
_state = ServerState.Stop;
}
/// <summary>
/// Stops receiving the HTTP requests with the specified <see cref="CloseStatusCode"/> and
/// <see cref="string"/> used to stop the WebSocket services.
/// </summary>
/// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
/// indicating the reason for the stop.
/// </param>
/// <param name="reason">
/// A <see cref="string"/> that represents the reason for the stop.
/// </param>
public void Stop (CloseStatusCode code, string reason)
{
lock (_sync) {
var msg = _state.CheckIfStart () ?? WebSocket.CheckCloseParameters (code, reason, false);
if (msg != null) {
_logger.Error (msg);
return;
}
_state = ServerState.ShuttingDown;
}
if (code == CloseStatusCode.NoStatus) {
_services.Stop (new CloseEventArgs (), true, true);
}
else {
var send = !code.IsReserved ();
_services.Stop (new CloseEventArgs (code, reason), send, send);
}
stopReceiving (5000);
_state = ServerState.Stop;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for ProjectItemDefinition</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Definition
{
/// <summary>
/// Tests for ProjectItemDefinition
/// </summary>
public class ProjectItemDefinition_Tests
{
/// <summary>
/// Add metadata; should add to an existing item definition group that has item definitions of the same item type
/// </summary>
[Fact]
public void AddMetadataExistingItemDefinitionGroup()
{
ProjectRootElement xml = ProjectRootElement.Create();
xml.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0");
Project project = new Project(xml);
project.ItemDefinitions["i"].SetMetadataValue("n", "n0");
string expected = ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m>m0</m>
</i>
<i>
<n>n0</n>
</i>
</ItemDefinitionGroup>
</Project>");
Helpers.VerifyAssertProjectContent(expected, project.Xml);
}
/// <summary>
/// Set metadata with property expression; should be expanded
/// </summary>
[Fact]
public void SetMetadata()
{
ProjectRootElement xml = ProjectRootElement.Create();
xml.AddProperty("p", "v");
xml.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0");
xml.AddItem("i", "i1");
Project project = new Project(xml);
ProjectMetadata metadatum = project.ItemDefinitions["i"].GetMetadata("m");
metadatum.UnevaluatedValue = "$(p)";
Assert.Equal("v", Helpers.GetFirst(project.GetItems("i")).GetMetadataValue("m"));
}
/// <summary>
/// Access metadata when there isn't any
/// </summary>
[Fact]
public void EmptyMetadataCollection()
{
ProjectRootElement xml = ProjectRootElement.Create();
xml.AddItemDefinitionGroup().AddItemDefinition("i");
Project project = new Project(xml);
ProjectItemDefinition itemDefinition = project.ItemDefinitions["i"];
IEnumerable<ProjectMetadata> metadataCollection = itemDefinition.Metadata;
List<ProjectMetadata> metadataList = Helpers.MakeList(metadataCollection);
Assert.Equal(0, metadataList.Count);
Assert.Equal(null, itemDefinition.GetMetadata("m"));
}
/// <summary>
/// Set metadata get collection
/// </summary>
[Fact]
public void GetMetadataCollection()
{
ProjectRootElement xml = ProjectRootElement.Create();
xml.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0");
Project project = new Project(xml);
IEnumerable<ProjectMetadata> metadataCollection = project.ItemDefinitions["i"].Metadata;
List<ProjectMetadata> metadataList = Helpers.MakeList(metadataCollection);
Assert.Equal(1, metadataList.Count);
Assert.Equal("m", metadataList[0].Name);
Assert.Equal("m0", metadataList[0].EvaluatedValue);
}
/// <summary>
/// Attempt to update metadata on imported item definition should fail
/// </summary>
[Fact]
public void UpdateMetadataImported()
{
Assert.Throws<InvalidOperationException>(() =>
{
string file = null;
try
{
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement import = ProjectRootElement.Create(file);
import.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0");
import.Save();
ProjectRootElement main = ProjectRootElement.Create();
Project project = new Project(main);
main.AddImport(file);
project.ReevaluateIfNecessary();
ProjectItemDefinition definition = project.ItemDefinitions["i"];
definition.SetMetadataValue("m", "m1");
}
finally
{
File.Delete(file);
}
}
);
}
/// <summary>
/// Attempt to add new metadata on imported item definition should succeed,
/// creating a new item definition in the main project
/// </summary>
[Fact]
public void SetMetadataImported()
{
string file = null;
try
{
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement import = ProjectRootElement.Create(file);
import.AddItemDefinitionGroup().AddItemDefinition("i").AddMetadata("m", "m0");
import.Save();
ProjectRootElement main = ProjectRootElement.Create();
Project project = new Project(main);
main.AddImport(file);
project.ReevaluateIfNecessary();
ProjectItemDefinition definition = project.ItemDefinitions["i"];
definition.SetMetadataValue("n", "n0");
string expected = String.Format
(
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<n>n0</n>
</i>
</ItemDefinitionGroup>
<Import Project=""{0}"" />
</Project>"),
file
);
Helpers.VerifyAssertProjectContent(expected, project.Xml);
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Item definition metadata should be sufficient to avoid errors like
/// "error MSB4096: The item "a.foo" in item list "h" does not define a value for metadata "m". In
/// order to use this metadata, either qualify it by specifying %(h.m), or ensure that all items in this list define a value
/// for this metadata."
/// </summary>
[Fact]
[Trait("Category", "serialize")]
public void BatchingConsidersItemDefinitionMetadata()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m>m1</m>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='a.foo;a.bar'/>
</ItemGroup>
<Target Name='t'>
<Message Text='@(i)/%(m)'/>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
MockLogger logger = new MockLogger();
List<ILogger> loggers = new List<ILogger>() { logger };
Assert.Equal(true, project.Build(loggers));
logger.AssertLogContains("a.foo;a.bar/m1");
logger.AssertNoErrors();
logger.AssertNoWarnings();
}
/// <summary>
/// Expand built-in metadata "late"
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m>%(filename)</m>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='c:\a\b.ext'/>
</ItemGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectItem item = project.GetItems("i").ElementAt(0);
Assert.Equal("b", item.GetMetadataValue("m"));
}
/// <summary>
/// Expand built-in metadata "late"
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_ReferToMetadataAbove()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m>%(filename)</m>
<m>%(m)%(extension)</m>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='c:\a\b.ext'/>
</ItemGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectItem item = project.GetItems("i").ElementAt(0);
Assert.Equal("b.ext", item.GetMetadataValue("m"));
}
/// <summary>
/// Expand built-in metadata "late"
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_MixtureOfCustomAndBuiltIn()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<l>l1</l>
<m>%(filename).%(l)</m>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='c:\a\b.ext'/>
</ItemGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectItem item = project.GetItems("i").ElementAt(0);
Assert.Equal("b.l1", item.GetMetadataValue("m"));
}
/// <summary>
/// Custom metadata expressions on metadata on an ItemDefinitionGroup is still always
/// expanded right there.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_CustomEvaluationNeverDelayed()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<n>n1</n>
<m>%(filename).%(n)</m>
<n>n2</n>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='c:\a\b.ext'>
<n>n3</n>
</i>
</ItemGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectItem item = project.GetItems("i").ElementAt(0);
Assert.Equal("b.n1", item.GetMetadataValue("m"));
}
/// <summary>
/// A custom metadata that bizarrely expands to a built in metadata expression should
/// not evaluate again.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_DoNotDoubleEvaluate()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<n>%25(filename)</n> <!-- escaped % sign -->
<m>%(n)</m>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='c:\a\b.ext'/>
</ItemGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectItem item = project.GetItems("i").ElementAt(0);
Assert.Equal("%25(filename)", Project.GetMetadataValueEscaped(item, "m"));
Assert.Equal("%(filename)", item.GetMetadataValue("m"));
}
/// <summary>
/// Items created from other items should still have the built-in metadata expanded
/// on them, not the original items.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_CopyItems()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m>%(extension)</m>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<h Include='a.foo'/>
<i Include=""@(h->'%(identity).bar')""/>
</ItemGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectItem item = project.GetItems("i").ElementAt(0);
Assert.Equal(".bar", item.GetMetadataValue("m"));
}
/// <summary>
/// Items created from other items should still have the built-in metadata expanded
/// on them, not the original items.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_UseInTransform()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<h>
<m>%(extension)</m>
</h>
</ItemDefinitionGroup>
<ItemGroup>
<h Include='a.foo'/>
<i Include=""@(h->'%(m)')""/>
</ItemGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectItem item = project.GetItems("i").ElementAt(0);
Assert.Equal(".foo", item.EvaluatedInclude);
}
/// <summary>
/// Items created from other items should still have the built-in metadata expanded
/// on them, not the original items.
/// </summary>
[Fact]
[Trait("Category", "serialize")]
public void ExpandBuiltInMetadataAtPointOfUse_UseInBatching()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<h>
<m>%(extension)</m>
</h>
</ItemDefinitionGroup>
<ItemGroup>
<h Include='a.foo;a.bar'/>
</ItemGroup>
<Target Name='t'>
<ItemGroup>
<i Include=""@(h)"">
<n Condition=""'%(m)'=='.foo'"">n1</n>
</i>
</ItemGroup>
</Target>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectInstance instance = project.CreateProjectInstance();
MockLogger l = new MockLogger();
List<ILogger> loggers = new List<ILogger>() { l };
instance.Build(loggers);
ProjectItemInstance item1 = instance.GetItems("i").ElementAt(0);
Assert.Equal("n1", item1.GetMetadataValue("n"));
ProjectItemInstance item2 = instance.GetItems("i").ElementAt(1);
Assert.Equal("", item2.GetMetadataValue("n"));
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_BuiltInProhibitedOnItemDefinitionMetadataCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m Condition=""'%(filename)'!=''"">m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_UnquotedBuiltInProhibitedOnItemDefinitionMetadataCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m Condition=""%(filename)!=''"">m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_BuiltInProhibitedOnItemDefinitionCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i Condition=""'%(filename)'!=''"">
<m>m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_BuiltInProhibitedOnItemDefinitionGroupCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup Condition=""'%(filename)'!=''"">
<i>
<m>m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_QualifiedBuiltInProhibitedOnItemDefinitionMetadataCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i>
<m Condition=""'%(i.filename)'!=''"">m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_QualifiedBuiltInProhibitedOnItemDefinitionCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i Condition=""'%(i.filename)'!=''"">
<m>m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_QualifiedBuiltInProhibitedOnItemDefinitionGroupCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup Condition=""'%(i.filename)'!=''"">
<i>
<m>m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Built-in metadata is prohibited in item definition conditions.
/// Ideally it would also be late evaluated, but that's too difficult.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_UnquotedQualifiedBuiltInProhibitedOnItemDefinitionCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i Condition=""%(i.filename)!=''"">
<m>m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Custom metadata is allowed in item definition conditions.
/// </summary>
[Fact]
public void ExpandBuiltInMetadataAtPointOfUse_UnquotedQualifiedCustomAllowedOnItemDefinitionCondition()
{
string content =
ObjectModelHelpers.CleanupFileContents(
@"<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemDefinitionGroup>
<i Condition=""%(i.custom)!=''"">
<m Condition=""%(i.custom)!=''"">m1</m>
</i>
</ItemDefinitionGroup>
</Project>");
Project project = new Project(XmlReader.Create(new StringReader(content))); // No exception
}
}
}
| |
// GtkSharp.Generation.OpaqueGen.cs - The Opaque Generatable.
//
// Author: Mike Kestner <mkestner@speakeasy.net>
//
// Copyright (c) 2001-2003 Mike Kestner
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of version 2 of the GNU General Public
// License as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301
namespace GtkSharp.Generation {
using System;
using System.Collections;
using System.IO;
using System.Xml;
public class OpaqueGen : HandleBase {
public OpaqueGen (XmlElement ns, XmlElement elem) : base (ns, elem) {}
public override string FromNative(string var, bool owned)
{
return var + " == IntPtr.Zero ? null : (" + QualifiedName + ") GLib.Opaque.GetOpaque (" + var + ", typeof (" + QualifiedName + "), " + (owned ? "true" : "false") + ")";
}
private bool DisableRawCtor {
get {
return Elem.HasAttribute ("disable_raw_ctor");
}
}
public override void Generate (GenerationInfo gen_info)
{
gen_info.CurrentType = Name;
StreamWriter sw = gen_info.Writer = gen_info.OpenStream (Name);
sw.WriteLine ("namespace " + NS + " {");
sw.WriteLine ();
sw.WriteLine ("\tusing System;");
sw.WriteLine ("\tusing System.Collections;");
sw.WriteLine ("\tusing System.Runtime.InteropServices;");
sw.WriteLine ();
sw.WriteLine ("#region Autogenerated code");
SymbolTable table = SymbolTable.Table;
Method ref_, unref, dispose;
GetSpecialMethods (out ref_, out unref, out dispose);
if (IsDeprecated)
sw.WriteLine ("\t[Obsolete]");
sw.Write ("\t{0} class " + Name, IsInternal ? "internal" : "public");
string cs_parent = table.GetCSType(Elem.GetAttribute("parent"));
if (cs_parent != "")
sw.Write (" : " + cs_parent);
else
sw.Write (" : GLib.Opaque");
foreach (string iface in managed_interfaces) {
if (Parent != null && Parent.Implements (iface))
continue;
sw.Write (", " + iface);
}
sw.WriteLine (" {");
sw.WriteLine ();
GenFields (gen_info);
GenMethods (gen_info, null, null);
GenCtors (gen_info);
if (ref_ != null) {
ref_.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Ref (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (!Owned) {");
sw.WriteLine ("\t\t\t\t" + ref_.CName + " (raw);");
sw.WriteLine ("\t\t\t\tOwned = true;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (ref_.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now refcounted automatically\")]");
if (ref_.ReturnType == "void")
sw.WriteLine ("\t\tpublic void Ref () {}");
else
sw.WriteLine ("\t\tpublic " + Name + " Ref () { return this; }");
sw.WriteLine ();
}
}
bool finalizer_needed = false;
if (unref != null) {
unref.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Unref (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (Owned) {");
sw.WriteLine ("\t\t\t\t" + unref.CName + " (raw);");
sw.WriteLine ("\t\t\t\tOwned = false;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (unref.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now refcounted automatically\")]");
sw.WriteLine ("\t\tpublic void Unref () {}");
sw.WriteLine ();
}
finalizer_needed = true;
}
if (dispose != null) {
dispose.GenerateImport (sw);
sw.WriteLine ("\t\tprotected override void Free (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\t" + dispose.CName + " (raw);");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
if (dispose.IsDeprecated) {
sw.WriteLine ("\t\t[Obsolete(\"" + QualifiedName + " is now freed automatically\")]");
sw.WriteLine ("\t\tpublic void " + dispose.Name + " () {}");
sw.WriteLine ();
}
finalizer_needed = true;
}
if (finalizer_needed) {
sw.WriteLine ("\t\tclass FinalizerInfo {");
sw.WriteLine ("\t\t\tIntPtr handle;");
sw.WriteLine ();
sw.WriteLine ("\t\t\tpublic FinalizerInfo (IntPtr handle)");
sw.WriteLine ("\t\t\t{");
sw.WriteLine ("\t\t\t\tthis.handle = handle;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t\tpublic bool Handler ()");
sw.WriteLine ("\t\t\t{");
if (dispose != null)
sw.WriteLine ("\t\t\t\t{0} (handle);", dispose.CName);
else if (unref != null)
sw.WriteLine ("\t\t\t\t{0} (handle);", unref.CName);
sw.WriteLine ("\t\t\t\treturn false;");
sw.WriteLine ("\t\t\t}");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
sw.WriteLine ("\t\t~{0} ()", Name);
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tif (!Owned)");
sw.WriteLine ("\t\t\t\treturn;");
sw.WriteLine ("\t\t\tFinalizerInfo info = new FinalizerInfo (Handle);");
sw.WriteLine ("\t\t\tGLib.Timeout.Add (50, new GLib.TimeoutHandler (info.Handler));");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
#if false
Method copy = Methods ["Copy"] as Method;
if (copy != null && copy.Parameters.Count == 0) {
sw.WriteLine ("\t\tprotected override GLib.Opaque Copy (IntPtr raw)");
sw.WriteLine ("\t\t{");
sw.WriteLine ("\t\t\tGLib.Opaque result = new " + QualifiedName + " (" + copy.CName + " (raw));");
sw.WriteLine ("\t\t\tresult.Owned = true;");
sw.WriteLine ("\t\t\treturn result;");
sw.WriteLine ("\t\t}");
sw.WriteLine ();
}
#endif
sw.WriteLine ("#endregion");
AppendCustom(sw, gen_info.CustomDir);
sw.WriteLine ("\t}");
sw.WriteLine ("}");
sw.Close ();
gen_info.Writer = null;
Statistics.OpaqueCount++;
}
void GetSpecialMethods (out Method ref_, out Method unref, out Method dispose)
{
ref_ = CheckSpecialMethod (GetMethod ("Ref"));
unref = CheckSpecialMethod (GetMethod ("Unref"));
dispose = GetMethod ("Free");
if (dispose == null) {
dispose = GetMethod ("Destroy");
if (dispose == null)
dispose = GetMethod ("Dispose");
}
dispose = CheckSpecialMethod (dispose);
}
Method CheckSpecialMethod (Method method)
{
if (method == null)
return null;
if (method.ReturnType != "void" &&
method.ReturnType != QualifiedName)
return null;
if (method.Signature.ToString () != "")
return null;
methods.Remove (method.Name);
return method;
}
protected override void GenCtors (GenerationInfo gen_info)
{
if (!DisableRawCtor) {
gen_info.Writer.WriteLine("\t\tpublic " + Name + "(IntPtr raw) : base(raw) {}");
gen_info.Writer.WriteLine();
}
base.GenCtors (gen_info);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using gView.Framework.Data;
using gView.Framework.IO;
using gView.Framework.Geometry;
using gView.Framework.XML;
using System.IO;
using gView.MapServer;
namespace gView.Interoperability.ArcXML.Dataset
{
[gView.Framework.system.RegisterPlugIn("3B26682C-BF6E-4fe8-BE80-762260ABA581")]
public class ArcIMSDataset : DatasetMetadata, IFeatureDataset, IRequestDependentDataset, IPersistable
{
internal string _connection = "";
internal string _name = "";
internal List<IWebServiceTheme> _themes = new List<IWebServiceTheme>();
private IClass _class = null;
private IEnvelope _envelope;
private string _errMsg = "";
internal ArcXMLProperties _properties = new ArcXMLProperties();
//internal dotNETConnector _connector = null;
private DatasetState _state = DatasetState.unknown;
private ISpatialReference _sRef = null;
public ArcIMSDataset() { }
public ArcIMSDataset(string connection, string name)
{
_connection = connection;
_name = name;
_class = new ArcIMSClass(this);
}
internal ArcIMSClass WebServiceClass
{
get
{
return _class as ArcIMSClass;
}
}
public XmlDocument Properties
{
get { return _properties.Properties; }
}
#region IFeatureDataset Member
public gView.Framework.Geometry.IEnvelope Envelope
{
get { return _envelope; }
}
public gView.Framework.Geometry.ISpatialReference SpatialReference
{
get
{
return _sRef;
}
set
{
_sRef = value;
}
}
#endregion
#region IDataset Member
public void Dispose()
{
_state = DatasetState.unknown;
}
public string ConnectionString
{
get
{
return _connection + ";service=" + _name;
}
set
{
_connection = "server=" + ConfigTextStream.ExtractValue(value, "server") +
";user=" + ConfigTextStream.ExtractValue(value, "user") +
";pwd=" + ConfigTextStream.ExtractValue(value, "pwd");
_name = ConfigTextStream.ExtractValue(value, "service");
}
}
public string DatasetGroupName
{
get { return "ESRI ArcIMS"; }
}
public string DatasetName
{
get { return "ESRI ArcIMS Service"; }
}
public string ProviderName
{
get { return "ESRI"; }
}
public DatasetState State
{
get { return _state; }
}
public bool Open()
{
return Open(null);
}
public string lastErrorMsg
{
get { return _errMsg; }
}
public int order
{
get
{
return 0;
}
set
{
}
}
public IDatasetEnum DatasetEnum
{
get { return null; }
}
public List<IDatasetElement> Elements
{
get
{
List<IDatasetElement> elements = new List<IDatasetElement>();
if (_class != null)
{
elements.Add(new DatasetElement(_class));
}
return elements;
}
}
public string Query_FieldPrefix
{
get { return ""; }
}
public string Query_FieldPostfix
{
get { return ""; }
}
public gView.Framework.FDB.IDatabase Database
{
get { return null; }
}
public IDatasetElement this[string title]
{
get
{
if (_class != null && title == _class.Name) return new DatasetElement(_class);
return null;
}
}
public void RefreshClasses()
{
}
#endregion
#region IRequestDependentDataset Member
public bool Open(IServiceRequestContext context)
{
if (_class == null) _class = new ArcIMSClass(this);
string server = ConfigTextStream.ExtractValue(ConnectionString, "server");
string service = ConfigTextStream.ExtractValue(ConnectionString, "service");
string user = ConfigTextStream.ExtractValue(ConnectionString, "user");
string pwd = ConfigTextStream.ExtractValue(ConnectionString, "pwd");
if ((user == "#" || user == "$") &&
context != null && context.ServiceRequest != null && context.ServiceRequest.Identity != null)
{
string roles = String.Empty;
if (user == "#" && context.ServiceRequest.Identity.UserRoles != null)
{
foreach (string role in context.ServiceRequest.Identity.UserRoles)
{
if (String.IsNullOrEmpty(role)) continue;
roles += "|" + role;
}
}
user = context.ServiceRequest.Identity.UserName + roles;
pwd = context.ServiceRequest.Identity.HashedPassword;
}
dotNETConnector connector = new dotNETConnector();
if (!String.IsNullOrEmpty(user) || !String.IsNullOrEmpty(pwd))
connector.setAuthentification(user, pwd);
try
{
_themes.Clear();
string axl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ARCXML version=\"1.1\"><REQUEST><GET_SERVICE_INFO fields=\"true\" envelope=\"true\" renderer=\"true\" extensions=\"true\" /></REQUEST></ARCXML>";
//string axl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ARCXML version=\"1.1\"><REQUEST><GET_SERVICE_INFO dpi=\"96\" toc=\"true\" /></REQUEST></ARCXML>";
ArcIMSClass.Log(context, "GetServiceInfo Response", server, service, axl);
axl = connector.SendRequest(axl, server, service);
ArcIMSClass.Log(context, "GetServiceInfo Response", server, service, axl);
XmlDocument doc = new XmlDocument();
doc.LoadXml(axl);
double dpi = 96.0;
XmlNode screen = doc.SelectSingleNode("//ENVIRONMENT/SCREEN");
if (screen != null)
{
if (screen.Attributes["dpi"] != null)
dpi = Convert.ToDouble(screen.Attributes["dpi"].Value.Replace(".", ","));
}
double dpm = (dpi / 0.0254);
XmlNode FeatureCoordSysNode = doc.SelectSingleNode("ARCXML/RESPONSE/SERVICEINFO/PROPERTIES/FEATURECOORDSYS");
_sRef = ArcXMLGeometry.AXL2SpatialReference(FeatureCoordSysNode);
foreach (XmlNode envelopeNode in doc.SelectNodes("//ENVELOPE"))
{
if (_envelope == null)
{
_envelope = new Envelope(envelopeNode);
}
else
{
_envelope.Union(new Envelope(envelopeNode));
}
}
foreach (XmlNode layerNode in doc.SelectNodes("//LAYERINFO[@id]"))
{
bool visible = true;
if (layerNode.Attributes["visible"] != null) bool.TryParse(layerNode.Attributes["visible"].Value, out visible);
XmlNode tocNode = layerNode.SelectSingleNode("TOC");
if (tocNode != null)
{
ReadTocNode(tocNode);
}
IClass themeClass = null;
IWebServiceTheme theme;
if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "featureclass")
{
themeClass = new ArcIMSThemeFeatureClass(this, layerNode.Attributes["id"].Value);
((ArcIMSThemeFeatureClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
((ArcIMSThemeFeatureClass)themeClass).fieldsFromAXL = layerNode.InnerXml;
((ArcIMSThemeFeatureClass)themeClass).SpatialReference = _sRef;
XmlNode FCLASS = layerNode.SelectSingleNode("FCLASS[@type]");
if (FCLASS != null)
{
((ArcIMSThemeFeatureClass)themeClass).fClassTypeString = FCLASS.Attributes["type"].Value;
}
foreach (XmlNode child in layerNode.ChildNodes)
{
switch (child.Name)
{
case "SIMPLERENDERER":
case "SIMPLELABELRENDERER":
case "VALUEMAPRENDERER":
case "SCALEDEPENDENTRENDERER":
case "VALUEMAPLABELRENDERER":
case "GROUPRENDERER":
((ArcIMSThemeFeatureClass)themeClass).OriginalRendererNode = child;
break;
}
}
theme = LayerFactory.Create(themeClass, _class as IWebServiceClass) as IWebServiceTheme;
if (theme == null) continue;
theme.Visible = visible;
}
else if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "image")
{
//themeClass = new ArcIMSThemeRasterClass(this,
// layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value);
themeClass = new ArcIMSThemeRasterClass(this, layerNode.Attributes["id"].Value);
((ArcIMSThemeRasterClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
theme = new WebServiceTheme(
themeClass,
themeClass.Name,
layerNode.Attributes["id"].Value,
visible,
_class as IWebServiceClass);
}
else
{
continue;
}
try
{
if (layerNode.Attributes["minscale"] != null)
theme.MinimumScale = Convert.ToDouble(layerNode.Attributes["minscale"].Value.Replace(".", ",")) * dpm;
if (layerNode.Attributes["maxscale"] != null)
theme.MaximumScale = Convert.ToDouble(layerNode.Attributes["maxscale"].Value.Replace(".", ",")) * dpm;
}
catch { }
_themes.Add(theme);
}
_state = DatasetState.opened;
return true;
}
catch (Exception ex)
{
_state = DatasetState.unknown;
_errMsg = ex.Message;
ArcIMSClass.ErrorLog(context, "Open Dataset", server, service, ex);
return false;
}
}
#endregion
#region IPersistable Member
public void Load(IPersistStream stream)
{
this.ConnectionString = (string)stream.Load("ConnectionString", "");
_properties = stream.Load("Properties", new ArcXMLProperties(), new ArcXMLProperties()) as ArcXMLProperties;
_class = new ArcIMSClass(this);
Open();
}
public void Save(IPersistStream stream)
{
stream.Save("ConnectionString", this.ConnectionString);
stream.Save("Properties", _properties);
}
#endregion
#region Helper
private void ReadTocNode(XmlNode tocNode)
{
foreach (XmlNode tocclass in tocNode.SelectNodes("TOCGROUP/TOCCLASS"))
{
try
{
MemoryStream ms = new MemoryStream();
byte[] imgBytes = Convert.FromBase64String(tocclass.InnerText);
ms.Write(imgBytes, 0, imgBytes.Length);
ms.Position = 0;
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
image.Dispose();
}
catch { }
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for the ProjectOutputElement class.</summary>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Test the ProjectOutputElement class
/// </summary>
[TestClass]
public class ProjectOutputElement_Tests
{
/// <summary>
/// Read an output item
/// </summary>
[TestMethod]
public void ReadOutputItem()
{
ProjectOutputElement output = GetOutputItem();
Assert.AreEqual(false, output.IsOutputProperty);
Assert.AreEqual(true, output.IsOutputItem);
Assert.AreEqual("p", output.TaskParameter);
Assert.AreEqual(String.Empty, output.PropertyName);
Assert.AreEqual("i1", output.ItemType);
}
/// <summary>
/// Read an output property
/// </summary>
[TestMethod]
public void ReadOutputProperty()
{
ProjectOutputElement output = GetOutputProperty();
Assert.AreEqual(true, output.IsOutputProperty);
Assert.AreEqual(false, output.IsOutputItem);
Assert.AreEqual("p", output.TaskParameter);
Assert.AreEqual("p1", output.PropertyName);
Assert.AreEqual(String.Empty, output.ItemType);
}
/// <summary>
/// Read an output property with missing itemname and propertyname
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidOutputWithoutPropertyOrItem()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output TaskParameter='p'/>
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read an output property with reserved property name
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidReservedOutputPropertyName()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output TaskParameter='p' PropertyName='MSBuildProjectFile'/>
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read an output property with missing taskparameter
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidOutputWithoutTaskName()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output ItemName='i'/>
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read an output property with missing taskparameter
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidOutputWithEmptyTaskName()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output TaskName='' ItemName='i'/>
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read an output property with child element
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidOutputWithChildElement()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output ItemName='i' TaskParameter='x'>
xxxxxxx
</Output>
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read an output property with propertyname but an empty itemname attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidPropertyValueItemBlank()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output TaskParameter='t' PropertyName='p' ItemName=''/>
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read an output property with an itemname but an empty propertyname attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidItemValuePropertyBlank()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output TaskParameter='t' ItemName='i' PropertyName=''/>
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Modify the condition
/// </summary>
[TestMethod]
public void SetOutputPropertyCondition()
{
ProjectOutputElement output = GetOutputProperty();
Helpers.ClearDirtyFlag(output.ContainingProject);
output.Condition = "c";
Assert.AreEqual("c", output.Condition);
Assert.AreEqual(true, output.ContainingProject.HasUnsavedChanges);
}
/// <summary>
/// Modify the property name value
/// </summary>
[TestMethod]
public void SetOutputPropertyName()
{
ProjectOutputElement output = GetOutputProperty();
Helpers.ClearDirtyFlag(output.ContainingProject);
output.PropertyName = "p1b";
Assert.AreEqual("p1b", output.PropertyName);
Assert.AreEqual(true, output.ContainingProject.HasUnsavedChanges);
}
/// <summary>
/// Attempt to set the item name value when property name is set
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void SetOutputPropertyItemType()
{
ProjectOutputElement output = GetOutputProperty();
output.ItemType = "i1b";
}
/// <summary>
/// Set the item name value
/// </summary>
[TestMethod]
public void SetOutputItemItemType()
{
ProjectOutputElement output = GetOutputItem();
Helpers.ClearDirtyFlag(output.ContainingProject);
output.ItemType = "p1b";
Assert.AreEqual("p1b", output.ItemType);
Assert.AreEqual(true, output.ContainingProject.HasUnsavedChanges);
}
/// <summary>
/// Attempt to set the property name when the item name is set
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void SetOutputItemPropertyName()
{
ProjectOutputElement output = GetOutputItem();
output.PropertyName = "p1b";
}
/// <summary>
/// Helper to get a ProjectOutputElement for an output item
/// </summary>
private static ProjectOutputElement GetOutputItem()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output TaskParameter='p' ItemName='i1' />
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectTaskElement task = (ProjectTaskElement)Helpers.GetFirst(target.Children);
return Helpers.GetFirst(task.Outputs);
}
/// <summary>
/// Helper to get a ProjectOutputElement for an output property
/// </summary>
private static ProjectOutputElement GetOutputProperty()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='t'>
<t1>
<Output TaskParameter='p' PropertyName='p1' />
</t1>
<t2/>
</Target>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectTargetElement target = (ProjectTargetElement)Helpers.GetFirst(project.Children);
ProjectTaskElement task = (ProjectTaskElement)Helpers.GetFirst(target.Children);
return Helpers.GetFirst(task.Outputs);
}
}
}
| |
using MQTTnet.Adapter;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.ExtendedAuthenticationExchange;
using MQTTnet.Client.Options;
using MQTTnet.Client.Publishing;
using MQTTnet.Client.Receiving;
using MQTTnet.Client.Subscribing;
using MQTTnet.Client.Unsubscribing;
using MQTTnet.Diagnostics;
using MQTTnet.Exceptions;
using MQTTnet.Internal;
using MQTTnet.PacketDispatcher;
using MQTTnet.Packets;
using MQTTnet.Protocol;
using System;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet.Diagnostics.Logger;
using MQTTnet.Implementations;
namespace MQTTnet.Client
{
public class MqttClient : Disposable, IMqttClient
{
readonly MqttPacketIdentifierProvider _packetIdentifierProvider = new MqttPacketIdentifierProvider();
readonly MqttPacketDispatcher _packetDispatcher = new MqttPacketDispatcher();
readonly object _disconnectLock = new object();
readonly IMqttClientAdapterFactory _adapterFactory;
readonly MqttNetSourceLogger _logger;
CancellationTokenSource _backgroundCancellationTokenSource;
Task _packetReceiverTask;
Task _keepAlivePacketsSenderTask;
Task _publishPacketReceiverTask;
AsyncQueue<MqttPublishPacket> _publishPacketReceiverQueue;
IMqttChannelAdapter _adapter;
bool _cleanDisconnectInitiated;
volatile int _connectionStatus;
MqttClientDisconnectReason _disconnectReason;
DateTime _lastPacketSentTimestamp;
public MqttClient(IMqttClientAdapterFactory channelFactory, IMqttNetLogger logger)
{
if (logger == null) throw new ArgumentNullException(nameof(logger));
_adapterFactory = channelFactory ?? throw new ArgumentNullException(nameof(channelFactory));
_logger = logger.WithSource(nameof(MqttClient));
}
public IMqttClientConnectedHandler ConnectedHandler { get; set; }
public IMqttClientDisconnectedHandler DisconnectedHandler { get; set; }
public IMqttApplicationMessageReceivedHandler ApplicationMessageReceivedHandler { get; set; }
public bool IsConnected => (MqttClientConnectionStatus)_connectionStatus == MqttClientConnectionStatus.Connected;
public IMqttClientOptions Options { get; private set; }
public async Task<MqttClientConnectResult> ConnectAsync(IMqttClientOptions options, CancellationToken cancellationToken)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (options.ChannelOptions == null) throw new ArgumentException("ChannelOptions are not set.");
ThrowIfConnected("It is not allowed to connect with a server after the connection is established.");
ThrowIfDisposed();
if (CompareExchangeConnectionStatus(MqttClientConnectionStatus.Connecting, MqttClientConnectionStatus.Disconnected) != MqttClientConnectionStatus.Disconnected)
{
throw new InvalidOperationException("Not allowed to connect while connect/disconnect is pending.");
}
MqttClientConnectResult connectResult = null;
try
{
Options = options;
_packetIdentifierProvider.Reset();
_packetDispatcher.CancelAll();
_backgroundCancellationTokenSource = new CancellationTokenSource();
var backgroundCancellationToken = _backgroundCancellationTokenSource.Token;
var adapter = _adapterFactory.CreateClientAdapter(options);
_adapter = adapter;
using (var combined = CancellationTokenSource.CreateLinkedTokenSource(backgroundCancellationToken, cancellationToken))
{
_logger.Verbose("Trying to connect with server '{0}' (Timeout={1}).", options.ChannelOptions, options.CommunicationTimeout);
await adapter.ConnectAsync(options.CommunicationTimeout, combined.Token).ConfigureAwait(false);
_logger.Verbose("Connection with server established.");
_publishPacketReceiverQueue = new AsyncQueue<MqttPublishPacket>();
_publishPacketReceiverTask = Task.Run(() => ProcessReceivedPublishPackets(backgroundCancellationToken), backgroundCancellationToken);
_packetReceiverTask = Task.Run(() => TryReceivePacketsAsync(backgroundCancellationToken), backgroundCancellationToken);
connectResult = await AuthenticateAsync(adapter, options.WillMessage, combined.Token).ConfigureAwait(false);
}
_lastPacketSentTimestamp = DateTime.UtcNow;
if (Options.KeepAlivePeriod != TimeSpan.Zero)
{
_keepAlivePacketsSenderTask = Task.Run(() => TrySendKeepAliveMessagesAsync(backgroundCancellationToken), backgroundCancellationToken);
}
CompareExchangeConnectionStatus(MqttClientConnectionStatus.Connected, MqttClientConnectionStatus.Connecting);
_logger.Info("Connected.");
var connectedHandler = ConnectedHandler;
if (connectedHandler != null)
{
await connectedHandler.HandleConnectedAsync(new MqttClientConnectedEventArgs(connectResult)).ConfigureAwait(false);
}
return connectResult;
}
catch (Exception exception)
{
_disconnectReason = MqttClientDisconnectReason.UnspecifiedError;
_logger.Error(exception, "Error while connecting with server.");
await DisconnectInternalAsync(null, exception, connectResult).ConfigureAwait(false);
throw;
}
}
public async Task DisconnectAsync(MqttClientDisconnectOptions options, CancellationToken cancellationToken)
{
if (options is null) throw new ArgumentNullException(nameof(options));
ThrowIfDisposed();
var clientWasConnected = IsConnected;
if (DisconnectIsPendingOrFinished())
{
return;
}
try
{
_disconnectReason = MqttClientDisconnectReason.NormalDisconnection;
_cleanDisconnectInitiated = true;
if (clientWasConnected)
{
var disconnectPacket = _adapter.PacketFormatterAdapter.DataConverter.CreateDisconnectPacket(options);
await SendAsync(disconnectPacket, cancellationToken).ConfigureAwait(false);
}
}
finally
{
await DisconnectCoreAsync(null, null, null, clientWasConnected).ConfigureAwait(false);
}
}
public Task PingAsync(CancellationToken cancellationToken)
{
return SendAndReceiveAsync<MqttPingRespPacket>(MqttPingReqPacket.Instance, cancellationToken);
}
public Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken)
{
if (data == null) throw new ArgumentNullException(nameof(data));
ThrowIfDisposed();
ThrowIfNotConnected();
return SendAsync(new MqttAuthPacket
{
Properties = new MqttAuthPacketProperties
{
// This must always be equal to the value from the CONNECT packet. So we use it here to ensure that.
AuthenticationMethod = Options.AuthenticationMethod,
AuthenticationData = data.AuthenticationData,
ReasonString = data.ReasonString,
UserProperties = data.UserProperties
}
}, cancellationToken);
}
public async Task<MqttClientSubscribeResult> SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken)
{
if (options == null) throw new ArgumentNullException(nameof(options));
foreach (var topicFilter in options.TopicFilters)
{
MqttTopicValidator.ThrowIfInvalidSubscribe(topicFilter.Topic);
}
ThrowIfDisposed();
ThrowIfNotConnected();
var subscribePacket = _adapter.PacketFormatterAdapter.DataConverter.CreateSubscribePacket(options);
subscribePacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
var subAckPacket = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket, cancellationToken).ConfigureAwait(false);
return _adapter.PacketFormatterAdapter.DataConverter.CreateClientSubscribeResult(subscribePacket, subAckPacket);
}
public async Task<MqttClientUnsubscribeResult> UnsubscribeAsync(MqttClientUnsubscribeOptions options, CancellationToken cancellationToken)
{
if (options == null) throw new ArgumentNullException(nameof(options));
ThrowIfDisposed();
ThrowIfNotConnected();
var unsubscribePacket = _adapter.PacketFormatterAdapter.DataConverter.CreateUnsubscribePacket(options);
unsubscribePacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
var unsubAckPacket = await SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket, cancellationToken).ConfigureAwait(false);
return _adapter.PacketFormatterAdapter.DataConverter.CreateClientUnsubscribeResult(unsubscribePacket, unsubAckPacket);
}
public Task<MqttClientPublishResult> PublishAsync(MqttApplicationMessage applicationMessage, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
MqttTopicValidator.ThrowIfInvalid(applicationMessage);
ThrowIfDisposed();
ThrowIfNotConnected();
var publishPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePublishPacket(applicationMessage);
switch (applicationMessage.QualityOfServiceLevel)
{
case MqttQualityOfServiceLevel.AtMostOnce:
{
return PublishAtMostOnce(publishPacket, cancellationToken);
}
case MqttQualityOfServiceLevel.AtLeastOnce:
{
return PublishAtLeastOnceAsync(publishPacket, cancellationToken);
}
case MqttQualityOfServiceLevel.ExactlyOnce:
{
return PublishExactlyOnceAsync(publishPacket, cancellationToken);
}
default:
{
throw new NotSupportedException();
}
}
}
void Cleanup()
{
try
{
_backgroundCancellationTokenSource?.Cancel(false);
}
finally
{
_backgroundCancellationTokenSource?.Dispose();
_backgroundCancellationTokenSource = null;
_publishPacketReceiverQueue?.Dispose();
_publishPacketReceiverQueue = null;
_adapter?.Dispose();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Cleanup();
}
base.Dispose(disposing);
}
async Task<MqttClientConnectResult> AuthenticateAsync(IMqttChannelAdapter channelAdapter, MqttApplicationMessage willApplicationMessage, CancellationToken cancellationToken)
{
MqttClientConnectResult result;
try
{
var connectPacket = channelAdapter.PacketFormatterAdapter.DataConverter.CreateConnectPacket(
willApplicationMessage,
Options);
var connAckPacket = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket, cancellationToken).ConfigureAwait(false);
result = channelAdapter.PacketFormatterAdapter.DataConverter.CreateClientConnectResult(connAckPacket);
}
catch (Exception exception)
{
throw new MqttConnectingFailedException($"Error while authenticating. {exception.Message}", exception, null);
}
if (result.ResultCode != MqttClientConnectResultCode.Success)
{
throw new MqttConnectingFailedException($"Connecting with MQTT server failed ({result.ResultCode}).", null, result);
}
_logger.Verbose("Authenticated MQTT connection with server established.");
return result;
}
void ThrowIfNotConnected()
{
if (!IsConnected)
{
throw new MqttCommunicationException("The client is not connected.");
}
}
void ThrowIfConnected(string message)
{
if (IsConnected) throw new MqttProtocolViolationException(message);
}
Task DisconnectInternalAsync(Task sender, Exception exception, MqttClientConnectResult connectResult)
{
var clientWasConnected = IsConnected;
if (!DisconnectIsPendingOrFinished())
{
return DisconnectCoreAsync(sender, exception, connectResult, clientWasConnected);
}
return PlatformAbstractionLayer.CompletedTask;
}
async Task DisconnectCoreAsync(Task sender, Exception exception, MqttClientConnectResult connectResult, bool clientWasConnected)
{
TryInitiateDisconnect();
try
{
if (_adapter != null)
{
_logger.Verbose("Disconnecting [Timeout={0}]", Options.CommunicationTimeout);
await _adapter.DisconnectAsync(Options.CommunicationTimeout, CancellationToken.None).ConfigureAwait(false);
}
_logger.Verbose("Disconnected from adapter.");
}
catch (Exception adapterException)
{
_logger.Warning(adapterException, "Error while disconnecting from adapter.");
}
try
{
var receiverTask = WaitForTaskAsync(_packetReceiverTask, sender);
var publishPacketReceiverTask = WaitForTaskAsync(_publishPacketReceiverTask, sender);
var keepAliveTask = WaitForTaskAsync(_keepAlivePacketsSenderTask, sender);
await Task.WhenAll(receiverTask, publishPacketReceiverTask, keepAliveTask).ConfigureAwait(false);
}
catch (Exception innerException)
{
_logger.Warning(innerException, "Error while waiting for internal tasks.");
}
finally
{
Cleanup();
_cleanDisconnectInitiated = false;
CompareExchangeConnectionStatus(MqttClientConnectionStatus.Disconnected, MqttClientConnectionStatus.Disconnecting);
_logger.Info("Disconnected.");
var disconnectedHandler = DisconnectedHandler;
if (disconnectedHandler != null)
{
// This handler must be executed in a new thread because otherwise a dead lock may happen
// when trying to reconnect in that handler etc.
Task.Run(() => disconnectedHandler.HandleDisconnectedAsync(new MqttClientDisconnectedEventArgs(clientWasConnected, exception, connectResult, _disconnectReason))).RunInBackground(_logger);
}
}
}
void TryInitiateDisconnect()
{
lock (_disconnectLock)
{
try
{
_backgroundCancellationTokenSource?.Cancel(false);
}
catch (Exception exception)
{
_logger.Warning(exception, "Error while initiating disconnect.");
}
}
}
Task SendAsync(MqttBasePacket packet, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_lastPacketSentTimestamp = DateTime.UtcNow;
return _adapter.SendPacketAsync(packet, cancellationToken);
}
async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket, CancellationToken cancellationToken) where TResponsePacket : MqttBasePacket
{
cancellationToken.ThrowIfCancellationRequested();
ushort packetIdentifier = 0;
if (requestPacket is IMqttPacketWithIdentifier packetWithIdentifier)
{
packetIdentifier = packetWithIdentifier.PacketIdentifier;
}
using (var packetAwaiter = _packetDispatcher.AddAwaitable<TResponsePacket>(packetIdentifier))
{
try
{
await SendAsync(requestPacket, cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
_logger.Warning(exception, "Error when sending request packet ({0}).", requestPacket.GetType().Name);
packetAwaiter.Fail(exception);
}
try
{
return await packetAwaiter.WaitOneAsync(Options.CommunicationTimeout).ConfigureAwait(false);
}
catch (Exception exception)
{
if (exception is MqttCommunicationTimedOutException)
{
_logger.Warning("Timeout while waiting for response packet ({0}).", typeof(TResponsePacket).Name);
}
throw;
}
}
}
async Task TrySendKeepAliveMessagesAsync(CancellationToken cancellationToken)
{
try
{
_logger.Verbose("Start sending keep alive packets.");
var keepAlivePeriod = Options.KeepAlivePeriod;
while (!cancellationToken.IsCancellationRequested)
{
// Values described here: [MQTT-3.1.2-24].
var timeWithoutPacketSent = DateTime.UtcNow - _lastPacketSentTimestamp;
if (timeWithoutPacketSent > keepAlivePeriod)
{
await PingAsync(cancellationToken).ConfigureAwait(false);
}
// Wait a fixed time in all cases. Calculation of the remaining time is complicated
// due to some edge cases and was buggy in the past. Now we wait several ms because the
// min keep alive value is one second so that the server will wait 1.5 seconds for a PING
// packet.
await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken).ConfigureAwait(false);
}
}
catch (Exception exception)
{
if (_cleanDisconnectInitiated)
{
return;
}
if (exception is OperationCanceledException)
{
return;
}
else if (exception is MqttCommunicationException)
{
_logger.Warning(exception, "Communication error while sending/receiving keep alive packets.");
}
else
{
_logger.Error(exception, "Error exception while sending/receiving keep alive packets.");
}
await DisconnectInternalAsync(_keepAlivePacketsSenderTask, exception, null).ConfigureAwait(false);
}
finally
{
_logger.Verbose("Stopped sending keep alive packets.");
}
}
async Task TryReceivePacketsAsync(CancellationToken cancellationToken)
{
try
{
_logger.Verbose("Start receiving packets.");
while (!cancellationToken.IsCancellationRequested)
{
var packet = await _adapter.ReceivePacketAsync(cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
{
return;
}
if (packet == null)
{
await DisconnectInternalAsync(_packetReceiverTask, null, null).ConfigureAwait(false);
return;
}
await TryProcessReceivedPacketAsync(packet, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception exception)
{
if (_cleanDisconnectInitiated)
{
return;
}
if (exception is OperationCanceledException)
{
}
else if (exception is MqttCommunicationException)
{
_logger.Warning(exception, "Communication error while receiving packets.");
}
else
{
_logger.Error(exception, "Error while receiving packets.");
}
_packetDispatcher.FailAll(exception);
await DisconnectInternalAsync(_packetReceiverTask, exception, null).ConfigureAwait(false);
}
finally
{
_logger.Verbose("Stopped receiving packets.");
}
}
async Task TryProcessReceivedPacketAsync(MqttBasePacket packet, CancellationToken cancellationToken)
{
try
{
if (packet is MqttPublishPacket publishPacket)
{
EnqueueReceivedPublishPacket(publishPacket);
}
else if (packet is MqttPubRecPacket pubRecPacket)
{
await ProcessReceivedPubRecPacket(pubRecPacket, cancellationToken).ConfigureAwait(false);
}
else if (packet is MqttPubRelPacket pubRelPacket)
{
await ProcessReceivedPubRelPacket(pubRelPacket, cancellationToken).ConfigureAwait(false);
}
else if (packet is MqttDisconnectPacket disconnectPacket)
{
await ProcessReceivedDisconnectPacket(disconnectPacket).ConfigureAwait(false);
}
else if (packet is MqttAuthPacket authPacket)
{
await ProcessReceivedAuthPacket(authPacket).ConfigureAwait(false);
}
else if (packet is MqttPingRespPacket)
{
_packetDispatcher.TryDispatch(packet);
}
else if (packet is MqttPingReqPacket)
{
throw new MqttProtocolViolationException("The PINGREQ Packet is sent from a Client to the Server only.");
}
else
{
if (!_packetDispatcher.TryDispatch(packet))
{
throw new MqttProtocolViolationException($"Received packet '{packet}' at an unexpected time.");
}
}
}
catch (Exception exception)
{
if (_cleanDisconnectInitiated)
{
return;
}
if (exception is OperationCanceledException)
{
}
else if (exception is MqttCommunicationException)
{
_logger.Warning(exception, "Communication error while receiving packets.");
}
else
{
_logger.Error(exception, "Error while receiving packets.");
}
_packetDispatcher.FailAll(exception);
await DisconnectInternalAsync(_packetReceiverTask, exception, null).ConfigureAwait(false);
}
}
void EnqueueReceivedPublishPacket(MqttPublishPacket publishPacket)
{
try
{
_publishPacketReceiverQueue.Enqueue(publishPacket);
}
catch (Exception exception)
{
_logger.Error(exception, "Error while queueing application message.");
}
}
async Task ProcessReceivedPublishPackets(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
var publishPacketDequeueResult = await _publishPacketReceiverQueue.TryDequeueAsync(cancellationToken).ConfigureAwait(false);
if (!publishPacketDequeueResult.IsSuccess)
{
return;
}
var publishPacket = publishPacketDequeueResult.Item;
var eventArgs = await HandleReceivedApplicationMessageAsync(publishPacket).ConfigureAwait(false);
if (eventArgs.AutoAcknowledge)
{
await eventArgs.AcknowledgeAsync(cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
}
catch (Exception exception)
{
_logger.Error(exception, "Error while handling application message.");
}
}
}
Task AcknowledgeReceivedPublishPacket(MqttApplicationMessageReceivedEventArgs eventArgs, CancellationToken cancellationToken)
{
if (eventArgs.PublishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
{
// no response required
}
else if (eventArgs.PublishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
{
if (!eventArgs.ProcessingFailed)
{
var pubAckPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubAckPacket(eventArgs.PublishPacket, eventArgs.ReasonCode);
return SendAsync(pubAckPacket, cancellationToken);
}
}
else if (eventArgs.PublishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
{
if (!eventArgs.ProcessingFailed)
{
var pubRecPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubRecPacket(eventArgs.PublishPacket, eventArgs.ReasonCode);
return SendAsync(pubRecPacket, cancellationToken);
}
}
else
{
throw new MqttProtocolViolationException("Received a not supported QoS level.");
}
return PlatformAbstractionLayer.CompletedTask;
}
Task ProcessReceivedPubRecPacket(MqttPubRecPacket pubRecPacket, CancellationToken cancellationToken)
{
if (!_packetDispatcher.TryDispatch(pubRecPacket))
{
// The packet is unknown. Probably due to a restart of the client.
// So wen send this to the server to trigger a full resend of the message.
var pubRelPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubRelPacket(pubRecPacket, MqttApplicationMessageReceivedReasonCode.PacketIdentifierNotFound);
return SendAsync(pubRelPacket, cancellationToken);
}
return PlatformAbstractionLayer.CompletedTask;
}
Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken)
{
var pubCompPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubCompPacket(pubRelPacket, MqttApplicationMessageReceivedReasonCode.Success);
return SendAsync(pubCompPacket, cancellationToken);
}
Task ProcessReceivedDisconnectPacket(MqttDisconnectPacket disconnectPacket)
{
_disconnectReason = (MqttClientDisconnectReason) (disconnectPacket.ReasonCode ?? MqttDisconnectReasonCode.NormalDisconnection);
// Also dispatch disconnect to waiting threads to generate a proper exception.
_packetDispatcher.FailAll(new MqttUnexpectedDisconnectReceivedException(disconnectPacket));
return DisconnectInternalAsync(_packetReceiverTask, null, null);
}
Task ProcessReceivedAuthPacket(MqttAuthPacket authPacket)
{
var extendedAuthenticationExchangeHandler = Options.ExtendedAuthenticationExchangeHandler;
if (extendedAuthenticationExchangeHandler != null)
{
return extendedAuthenticationExchangeHandler.HandleRequestAsync(new MqttExtendedAuthenticationExchangeContext(authPacket, this));
}
return PlatformAbstractionLayer.CompletedTask;
}
async Task<MqttClientPublishResult> PublishAtMostOnce(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
{
// No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
await SendAsync(publishPacket, cancellationToken).ConfigureAwait(false);
return _adapter.PacketFormatterAdapter.DataConverter.CreateClientPublishResult(null);
}
async Task<MqttClientPublishResult> PublishAtLeastOnceAsync(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
{
publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
var pubAckPacket = await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket, cancellationToken).ConfigureAwait(false);
return _adapter.PacketFormatterAdapter.DataConverter.CreateClientPublishResult(pubAckPacket);
}
async Task<MqttClientPublishResult> PublishExactlyOnceAsync(MqttPublishPacket publishPacket, CancellationToken cancellationToken)
{
publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();
var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket, cancellationToken).ConfigureAwait(false);
var pubRelPacket = _adapter.PacketFormatterAdapter.DataConverter.CreatePubRelPacket(pubRecPacket, MqttApplicationMessageReceivedReasonCode.Success);
var pubCompPacket = await SendAndReceiveAsync<MqttPubCompPacket>(pubRelPacket, cancellationToken).ConfigureAwait(false);
return _adapter.PacketFormatterAdapter.DataConverter.CreateClientPublishResult(pubRecPacket, pubCompPacket);
}
async Task<MqttApplicationMessageReceivedEventArgs> HandleReceivedApplicationMessageAsync(MqttPublishPacket publishPacket)
{
var applicationMessage = _adapter.PacketFormatterAdapter.DataConverter.CreateApplicationMessage(publishPacket);
var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options.ClientId, applicationMessage, publishPacket, AcknowledgeReceivedPublishPacket);
var handler = ApplicationMessageReceivedHandler;
if (handler != null)
{
await handler.HandleApplicationMessageReceivedAsync(eventArgs).ConfigureAwait(false);
}
return eventArgs;
}
async Task WaitForTaskAsync(Task task, Task sender)
{
if (task == null)
{
return;
}
if (task == sender)
{
// Return here to avoid deadlocks, but first any eventual exception in the task
// must be handled to avoid not getting an unhandled task exception
if (!task.IsFaulted)
{
return;
}
// By accessing the Exception property the exception is considered handled and will
// not result in an unhandled task exception later by the finalizer
_logger.Warning(task.Exception, "Error while waiting for background task.");
return;
}
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
bool DisconnectIsPendingOrFinished()
{
var connectionStatus = (MqttClientConnectionStatus)_connectionStatus;
do
{
switch (connectionStatus)
{
case MqttClientConnectionStatus.Disconnected:
case MqttClientConnectionStatus.Disconnecting:
return true;
case MqttClientConnectionStatus.Connected:
case MqttClientConnectionStatus.Connecting:
// This will compare the _connectionStatus to old value and set it to "MqttClientConnectionStatus.Disconnecting" afterwards.
// So the first caller will get a "false" and all subsequent ones will get "true".
var curStatus = CompareExchangeConnectionStatus(MqttClientConnectionStatus.Disconnecting, connectionStatus);
if (curStatus == connectionStatus)
{
return false;
}
connectionStatus = curStatus;
break;
}
} while (true);
}
MqttClientConnectionStatus CompareExchangeConnectionStatus(MqttClientConnectionStatus value, MqttClientConnectionStatus comparand)
{
return (MqttClientConnectionStatus)Interlocked.CompareExchange(ref _connectionStatus, (int)value, (int)comparand);
}
}
}
| |
// 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.Linq;
using System.Globalization;
using Xunit;
public static class GuidTests
{
private static readonly Guid _testGuid = new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff");
[Fact]
public static void Testctor()
{
// Void Guid..ctor(Byte[])
var g1 = new Guid(_testGuid.ToByteArray());
Assert.Equal(_testGuid, g1);
// Void Guid..ctor(Int32, Int16, Int16, Byte, Byte, Byte, Byte, Byte, Byte, Byte, Byte)
var g2 = new Guid(unchecked((int)0xa8a110d5), unchecked((short)0xfc49), (short)0x43c5, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff);
Assert.Equal(_testGuid, g2);
// Void Guid..ctor(Int32, Int16, Int16, Byte[])
var g3 = new Guid(unchecked((int)0xa8a110d5), unchecked((short)0xfc49), (short)0x43c5, new byte[] { 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff });
Assert.Equal(_testGuid, g3);
// Void Guid..ctor(String)
var g4 = new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid, g4);
}
[Fact]
public static void TestEquals()
{
// Boolean Guid.Equals(Guid)
Assert.True(_testGuid.Equals(_testGuid));
Assert.False(_testGuid.Equals(Guid.Empty));
Assert.False(Guid.Empty.Equals(_testGuid));
// Boolean Guid.Equals(Object)
Assert.False(_testGuid.Equals(null));
Assert.False(_testGuid.Equals("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
// Boolean Guid.op_Equality(Guid, Guid)
Assert.True(_testGuid == new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.True(Guid.Empty == new Guid(0, 0, 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
// Boolean Guid.op_Inequality(Guid, Guid)
Assert.True(_testGuid != Guid.Empty);
Assert.True(Guid.Empty != _testGuid);
}
[Fact]
public static void TestCompareTo()
{
// Int32 Guid.CompareTo(Guid)
Assert.True(_testGuid.CompareTo(new Guid("98a110d5-fc49-43c5-bf46-802db8f843ff")) > 0);
Assert.True(_testGuid.CompareTo(new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff")) == 0);
Assert.True(_testGuid.CompareTo(new Guid("e8a110d5-fc49-43c5-bf46-802db8f843ff")) < 0);
// Int32 Guid.System.IComparable.CompareTo(Object)
IComparable icomp = _testGuid;
Assert.True(icomp.CompareTo(new Guid("98a110d5-fc49-43c5-bf46-802db8f843ff")) > 0);
Assert.True(icomp.CompareTo(new Guid("a8a110d5-fc49-43c5-bf46-802db8f843ff")) == 0);
Assert.True(icomp.CompareTo(new Guid("e8a110d5-fc49-43c5-bf46-802db8f843ff")) < 0);
Assert.True(icomp.CompareTo(null) > 0);
Assert.Throws<ArgumentException>(() => icomp.CompareTo("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
}
[Fact]
public static void TestToByteArray()
{
// Byte[] Guid.ToByteArray()
var bytes1 = new byte[] { 0xd5, 0x10, 0xa1, 0xa8, 0x49, 0xfc, 0xc5, 0x43, 0xbf, 0x46, 0x80, 0x2d, 0xb8, 0xf8, 0x43, 0xff };
var bytes2 = _testGuid.ToByteArray();
Assert.Equal(bytes1.Length, bytes2.Length);
for (int i = 0; i < bytes1.Length; i++)
Assert.Equal(bytes1[i], bytes2[i]);
}
[Fact]
public static void TestEmpty()
{
// Guid Guid.Empty
Assert.Equal(Guid.Empty, new Guid(0, 0, 0, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }));
}
[Fact]
public static void TestNewGuid()
{
// Guid Guid.NewGuid()
var g = Guid.NewGuid();
Assert.NotEqual(Guid.Empty, g);
var g2 = Guid.NewGuid();
Assert.NotEqual(g, g2);
}
[Fact]
public static void TestParse()
{
// Guid Guid.Parse(String)
// Guid Guid.ParseExact(String, String)
Assert.Equal(_testGuid, Guid.Parse("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("a8a110d5fc4943c5bf46802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("a8a110d5-fc49-43c5-bf46-802db8f843ff"));
Assert.Equal(_testGuid, Guid.Parse("{a8a110d5-fc49-43c5-bf46-802db8f843ff}"));
Assert.Equal(_testGuid, Guid.Parse("(a8a110d5-fc49-43c5-bf46-802db8f843ff)"));
Assert.Equal(_testGuid, Guid.Parse("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}"));
Assert.Equal(_testGuid, Guid.ParseExact("a8a110d5fc4943c5bf46802db8f843ff", "N"));
Assert.Equal(_testGuid, Guid.ParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "D"));
Assert.Equal(_testGuid, Guid.ParseExact("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", "B"));
Assert.Equal(_testGuid, Guid.ParseExact("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", "P"));
Assert.Equal(_testGuid, Guid.ParseExact("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", "X"));
}
[Fact]
public static void TestTryParse()
{
// Boolean Guid.TryParse(String, Guid)
// Boolean Guid.TryParseExact(String, String, Guid)
Guid g;
Assert.True(Guid.TryParse("a8a110d5-fc49-43c5-bf46-802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("a8a110d5fc4943c5bf46802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("a8a110d5-fc49-43c5-bf46-802db8f843ff", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParse("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("a8a110d5fc4943c5bf46802db8f843ff", "N", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "D", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("{a8a110d5-fc49-43c5-bf46-802db8f843ff}", "B", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("(a8a110d5-fc49-43c5-bf46-802db8f843ff)", "P", out g));
Assert.Equal(_testGuid, g);
Assert.True(Guid.TryParseExact("{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}", "X", out g));
Assert.Equal(_testGuid, g);
Assert.False(Guid.TryParse("a8a110d5fc4943c5bf46802db8f843f", out g)); // One two few digits
Assert.False(Guid.TryParseExact("a8a110d5-fc49-43c5-bf46-802db8f843ff", "N", out g)); // Contains '-' when "N" doesn't support those
}
[Fact]
public static void TestGetHashCode()
{
// Int32 Guid.GetHashCode()
Assert.NotEqual(_testGuid.GetHashCode(), Guid.Empty.GetHashCode());
}
[Fact]
public static void TestToString()
{
// String Guid.ToString()
// String Guid.ToString(String)
// String Guid.System.IFormattable.ToString(String, IFormatProvider) // The IFormatProvider is ignored so don't need to test
Assert.Equal(_testGuid.ToString(), "a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid.ToString("N"), "a8a110d5fc4943c5bf46802db8f843ff");
Assert.Equal(_testGuid.ToString("D"), "a8a110d5-fc49-43c5-bf46-802db8f843ff");
Assert.Equal(_testGuid.ToString("B"), "{a8a110d5-fc49-43c5-bf46-802db8f843ff}");
Assert.Equal(_testGuid.ToString("P"), "(a8a110d5-fc49-43c5-bf46-802db8f843ff)");
Assert.Equal(_testGuid.ToString("X"), "{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}");
}
[Fact]
public static void TestRandomness()
{
const int Iterations = 100;
const int GuidSize = 16;
byte[] random = new byte[GuidSize * Iterations];
for (int i = 0; i < Iterations; i++)
{
// Get a new Guid
Guid g = Guid.NewGuid();
byte[] bytes = g.ToByteArray();
// Make sure it's different from all of the previously created ones
for (int j = 0; j < i; j++)
{
Assert.False(bytes.SequenceEqual(new ArraySegment<byte>(random, j * GuidSize, GuidSize)));
}
// Copy it to our randomness array
Array.Copy(bytes, 0, random, i * GuidSize, GuidSize);
}
// Verify the randomness of the data in the array. Guid has some small bias in it
// due to several bits fixed based on the format, but that bias is small enough and
// the variability allowed by VerifyRandomDistribution large enough that we don't do
// anything special for it.
RandomDataGenerator.VerifyRandomDistribution(random);
}
}
| |
/*
Text description/attribute names.
Copyright (C) 1999-2003
David Corcoran <corcoran@linuxnet.com>
Ludovic Rousseau <ludovic.rousseau@free.fr>
Program code.
Copyright (C) 2010
Daniel Mueller <daniel@danm.de>
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.
Changes to this license can be made only by the copyright author with
explicit written consent.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.ComponentModel;
using System.Reflection;
using System.Runtime;
using System.Runtime.InteropServices;
using PCSC.Interop;
namespace PCSC
{
[FlagsAttribute]
public enum SCRState : int
{
[DescriptionAttribute("Application wants status")]
Unaware = 0x0000,
[DescriptionAttribute("Ignore this reader")]
Ignore = 0x0001,
[DescriptionAttribute("State has changed")]
Changed = 0x0002,
[DescriptionAttribute("Reader unknown")]
Unknown = 0x0004,
[DescriptionAttribute("Status unavailable")]
Unavailable = 0x0008,
[DescriptionAttribute("Card removed")]
Empty = 0x0010,
[DescriptionAttribute("Card inserted")]
Present = 0x0020,
[DescriptionAttribute("ATR matches card")]
ATRMatch = 0x0040,
[DescriptionAttribute("Exclusive Mode")]
Exclusive = 0x0080,
[DescriptionAttribute("Shared Mode")]
InUse = 0x0100,
[DescriptionAttribute("Unresponsive card")]
Mute = 0x0200,
[DescriptionAttribute("Unpowered card")]
Unpowered = 0x0400
}
public class SCardReaderState : IDisposable
{
// we're getting values greater than 0xFFFF back from SCardGetStatusChange
private const int _EVENTSTATE_RANGE = 0xFFFF;
private const long _CHCOUNT_RANGE = 0xFFFF0000;
internal WinSCardAPI.SCARD_READERSTATE winscard_rstate;
internal PCSCliteAPI.SCARD_READERSTATE pcsclite_rstate;
private IntPtr pReaderName = IntPtr.Zero;
private int pReaderNameSize = 0;
private bool disposed = false;
~SCardReaderState()
{
Dispose();
}
public void Dispose()
{
if (!disposed)
{
if (pReaderName != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pReaderName);
pReaderName = IntPtr.Zero;
pReaderNameSize = 0;
}
disposed = true;
GC.SuppressFinalize(this);
}
}
public SCardReaderState()
{
if (SCardAPI.IsWindows)
{
winscard_rstate = new WinSCardAPI.SCARD_READERSTATE();
// initialize embedded array
winscard_rstate.rgbAtr = new byte[WinSCardAPI.MAX_ATR_SIZE];
winscard_rstate.cbAtr = (Int32)WinSCardAPI.MAX_ATR_SIZE;
}
else
{
pcsclite_rstate = new PCSCliteAPI.SCARD_READERSTATE();
// initialize embedded array
pcsclite_rstate.rgbAtr = new byte[PCSCliteAPI.MAX_ATR_SIZE];
pcsclite_rstate.cbAtr = (IntPtr)PCSCliteAPI.MAX_ATR_SIZE;
}
}
public long UserData
{
get
{
return (long)UserDataPointer;
}
set
{
UserDataPointer = unchecked((IntPtr)value);
}
}
public IntPtr UserDataPointer
{
get
{
if (SCardAPI.IsWindows)
return winscard_rstate.pvUserData;
else
return pcsclite_rstate.pvUserData;
}
set
{
if (SCardAPI.IsWindows)
winscard_rstate.pvUserData = value;
else
pcsclite_rstate.pvUserData = value;
}
}
public SCRState CurrentState
{
get
{
if (SCardAPI.IsWindows)
return SCardHelper.ToSCRState(
((int)winscard_rstate.dwCurrentState & _EVENTSTATE_RANGE));
else
return SCardHelper.ToSCRState(
((int)pcsclite_rstate.dwCurrentState & _EVENTSTATE_RANGE));
}
set
{
if (SCardAPI.IsWindows)
winscard_rstate.dwCurrentState =
(Int32)((int)value & _EVENTSTATE_RANGE);
else
pcsclite_rstate.dwCurrentState =
(IntPtr)((int)value & _EVENTSTATE_RANGE);
}
}
public SCRState EventState
{
get
{
if (SCardAPI.IsWindows)
return SCardHelper.ToSCRState(
(((int)winscard_rstate.dwEventState) & _EVENTSTATE_RANGE));
else
return SCardHelper.ToSCRState(
(((int)pcsclite_rstate.dwEventState) & _EVENTSTATE_RANGE));
}
set
{
long l = CardChangeEventCnt; // save card change event counter
if (SCardAPI.IsWindows)
winscard_rstate.dwEventState = (Int32)
(((int)value & _EVENTSTATE_RANGE) | (int)l);
else
pcsclite_rstate.dwEventState = (IntPtr)
(((int)value & _EVENTSTATE_RANGE) | (int)l);
}
}
public IntPtr EventStateValue
{
get
{
if (SCardAPI.IsWindows)
return (IntPtr)winscard_rstate.dwEventState;
else
return (IntPtr)pcsclite_rstate.dwEventState;
}
set
{
if (SCardAPI.IsWindows)
// On a 64-bit platforms .ToInt32() will throw an OverflowException
winscard_rstate.dwEventState = unchecked((Int32)value.ToInt64());
else
pcsclite_rstate.dwEventState = (IntPtr)value;
}
}
public IntPtr CurrentStateValue
{
get
{
if (SCardAPI.IsWindows)
return (IntPtr)winscard_rstate.dwCurrentState;
else
return (IntPtr)pcsclite_rstate.dwCurrentState;
}
set
{
if (SCardAPI.IsWindows)
// On a 64-bit platform .ToInt32() will throw an OverflowException
winscard_rstate.dwCurrentState = unchecked((Int32)value.ToInt64());
else
pcsclite_rstate.dwCurrentState = (IntPtr)value;
}
}
public int CardChangeEventCnt
{
get
{
if (SCardAPI.IsWindows)
return (int)((
((long)winscard_rstate.dwEventState) & _CHCOUNT_RANGE) >> 16);
else
return (int)((
((long)pcsclite_rstate.dwEventState) & _CHCOUNT_RANGE) >> 16);
}
set
{
long e = (long)EventState; // save event state
if (SCardAPI.IsWindows)
winscard_rstate.dwEventState = unchecked((Int32)
(((long)(value & _CHCOUNT_RANGE) << 16) | e));
else
pcsclite_rstate.dwEventState = unchecked((IntPtr)
(((long)(value & _CHCOUNT_RANGE) << 16) | e));
}
}
public string ReaderName
{
get
{
if (pReaderName == IntPtr.Zero)
return null;
byte[] tmp = new byte[pReaderNameSize];
Marshal.Copy(pReaderName, tmp, 0, pReaderNameSize);
return SCardHelper._ConvertToString(tmp, tmp.Length, SCardAPI.Lib.TextEncoding);
}
set
{
// Free reserved memory
if (pReaderName != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pReaderName);
pReaderName = IntPtr.Zero;
pReaderNameSize = 0;
}
if (value != null)
{
byte[] tmp = SCardHelper._ConvertToByteArray(value, SCardAPI.Lib.TextEncoding, 0);
pReaderName = Marshal.AllocCoTaskMem(tmp.Length + SCardAPI.Lib.CharSize);
pReaderNameSize = tmp.Length;
Marshal.Copy(tmp, 0, pReaderName, tmp.Length);
for (int i = 0; i < (SCardAPI.Lib.CharSize); i++)
{
Marshal.WriteByte(pReaderName, tmp.Length + i, (byte)0); // String ends with \0 (or 0x00 0x00)
}
}
if (SCardAPI.IsWindows)
winscard_rstate.pszReader = pReaderName;
else
pcsclite_rstate.pszReader = pReaderName;
}
}
public byte[] ATR
{
get
{
byte[] tmp = null;
if (SCardAPI.IsWindows)
{
if ((int)winscard_rstate.cbAtr <= WinSCardAPI.MAX_ATR_SIZE)
tmp = new byte[(int)winscard_rstate.cbAtr];
else
{ // error occurred during SCardGetStatusChange()
tmp = new byte[WinSCardAPI.MAX_ATR_SIZE];
winscard_rstate.cbAtr = (Int32)WinSCardAPI.MAX_ATR_SIZE;
}
Array.Copy(winscard_rstate.rgbAtr, tmp, (int)winscard_rstate.cbAtr);
}
else
{
if ((int)pcsclite_rstate.cbAtr <= PCSCliteAPI.MAX_ATR_SIZE)
tmp = new byte[(int)pcsclite_rstate.cbAtr];
else
{ // error occurred during SCardGetStatusChange()
tmp = new byte[PCSCliteAPI.MAX_ATR_SIZE];
pcsclite_rstate.cbAtr = (IntPtr)PCSCliteAPI.MAX_ATR_SIZE;
}
Array.Copy(pcsclite_rstate.rgbAtr, tmp, (int)pcsclite_rstate.cbAtr);
}
return tmp;
}
set
{
byte[] tmp = value;
// the size of rstate.rgbAtr MUST(!) be MAX_ATR_SIZE
if (SCardAPI.IsWindows)
{
if (tmp.Length != WinSCardAPI.MAX_ATR_SIZE)
Array.Resize<byte>(ref tmp, WinSCardAPI.MAX_ATR_SIZE);
winscard_rstate.rgbAtr = tmp;
winscard_rstate.cbAtr = (Int32)value.Length;
}
else
{
if (tmp.Length != PCSCliteAPI.MAX_ATR_SIZE)
Array.Resize<byte>(ref tmp, PCSCliteAPI.MAX_ATR_SIZE);
pcsclite_rstate.rgbAtr = tmp;
pcsclite_rstate.cbAtr = (IntPtr)value.Length;
}
}
}
}
}
| |
// 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.Buffers;
using Xunit;
namespace System.Memory.Tests
{
public class ReadOnlySequenceTestsDefault
{
#region Constructor
[Fact]
public void Default_Constructor()
{
ReadOnlySequence<byte> buffer = default;
Assert.Equal(default, buffer.Start);
Assert.Equal(default, buffer.End);
Assert.True(buffer.IsEmpty);
Assert.True(buffer.IsSingleSegment);
Assert.Equal(0, buffer.Length);
Assert.True(buffer.First.IsEmpty);
Assert.True(buffer.FirstSpan.IsEmpty);
Assert.Equal($"System.Buffers.ReadOnlySequence<{typeof(byte).Name}>[0]", buffer.ToString());
}
#endregion
#region GetPosition
[Fact]
public void Default_GetPosition()
{
ReadOnlySequence<byte> buffer = default;
SequencePosition position = default;
Assert.Equal(position, buffer.GetPosition(0));
Assert.Equal(position, buffer.GetPosition(0, buffer.Start));
Assert.Equal(position, buffer.GetPosition(0, buffer.End));
}
[Fact]
public void Default_GetPositionPositive()
{
ReadOnlySequence<byte> buffer = default;
Assert.Throws<ArgumentOutOfRangeException>("offset", () => buffer.GetPosition(1));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => buffer.GetPosition(1, buffer.Start));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => buffer.GetPosition(1, buffer.End));
}
[Fact]
public void Default_GetPositionNegative()
{
ReadOnlySequence<byte> buffer = default;
Assert.Throws<ArgumentOutOfRangeException>("offset", () => buffer.GetPosition(-1));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => buffer.GetPosition(-1, buffer.Start));
Assert.Throws<ArgumentOutOfRangeException>("offset", () => buffer.GetPosition(-1, buffer.End));
}
#endregion
#region Slice
[Fact]
public void Default_Slice()
{
ReadOnlySequence<byte> buffer = default;
Assert.Equal(buffer, buffer.Slice(0, 0));
Assert.Equal(buffer, buffer.Slice(0, buffer.End));
Assert.Equal(buffer, buffer.Slice(0));
Assert.Equal(buffer, buffer.Slice(0L, 0L));
Assert.Equal(buffer, buffer.Slice(0L, buffer.End));
Assert.Equal(buffer, buffer.Slice(buffer.Start));
Assert.Equal(buffer, buffer.Slice(buffer.Start, 0));
Assert.Equal(buffer, buffer.Slice(buffer.Start, 0L));
Assert.Equal(buffer, buffer.Slice(buffer.Start, buffer.End));
}
[Fact]
public void Default_SlicePositiveStart()
{
ReadOnlySequence<byte> buffer = default;
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(1, 0));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(1, 0));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(1, buffer.End));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(1));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(1L, 0L));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(1L, buffer.End));
}
[Fact]
public void Default_SliceNegativeStart()
{
ReadOnlySequence<byte> buffer = default;
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(-1, -1));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(-1, buffer.End));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(-1));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(-1L, 0L));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(-1L, -1L));
Assert.Throws<ArgumentOutOfRangeException>("start", () => buffer.Slice(-1L, buffer.End));
}
[Fact]
public void Default_SlicePositiveLength()
{
ReadOnlySequence<byte> buffer = default;
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(0, 1));
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(0L, 1L));
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(buffer.Start, 1));
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(buffer.Start, 1L));
}
[Fact]
public void Default_SliceNegativeLength()
{
ReadOnlySequence<byte> buffer = default;
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(0, -1));
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(0L, -1L));
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(buffer.Start, -1));
Assert.Throws<ArgumentOutOfRangeException>("length", () => buffer.Slice(buffer.Start, -1L));
}
[Fact]
public void Slice_DefaultSequencePosition()
{
var firstSegment = new BufferSegment<byte>(new byte[4]);
BufferSegment<byte> secondSegment = firstSegment.Append(new byte[4]);
var sequence = new ReadOnlySequence<byte>(firstSegment, 0, secondSegment, firstSegment.Memory.Length);
ReadOnlySequence<byte> slicedSequence = sequence.Slice(default(SequencePosition));
Assert.Equal(sequence, slicedSequence);
// Slice(default, default) should return an empty sequence
slicedSequence = sequence.Slice(default(SequencePosition), default(SequencePosition));
Assert.Equal(0, slicedSequence.Length);
// Slice(x, default) returns empty if x = 0. Otherwise throws
sequence = sequence.Slice(2);
slicedSequence = sequence.Slice(0, default(SequencePosition));
Assert.Equal(0, slicedSequence.Length);
Assert.Throws<ArgumentOutOfRangeException>(() => sequence.Slice(1, default(SequencePosition)));
// Slice(default, x) returns sequence from the beginning to x
slicedSequence = sequence.Slice(default(SequencePosition), 1);
Assert.Equal(1, slicedSequence.Length);
Assert.Equal(sequence.Start, slicedSequence.Start);
}
#endregion
#region Enumerator
[Fact]
public void Default_Enumerator()
{
ReadOnlySequence<byte> buffer = default;
ReadOnlySequence<byte>.Enumerator enumerator = buffer.GetEnumerator();
{
Assert.Equal(default, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
enumerator = new ReadOnlySequence<byte>.Enumerator(default);
{
Assert.Equal(default, enumerator.Current);
Assert.False(enumerator.MoveNext());
}
}
#endregion
#region TryGet
[Fact]
public void Default_TryGet()
{
ReadOnlySequence<byte> buffer = default;
ReadOnlyMemory<byte> memory;
SequencePosition c1 = buffer.Start;
Assert.False(buffer.TryGet(ref c1, out memory, false));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
Assert.False(buffer.TryGet(ref c1, out memory, true));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
Assert.False(buffer.TryGet(ref c1, out memory, false));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
Assert.False(buffer.TryGet(ref c1, out memory, true));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
c1 = buffer.End;
Assert.False(buffer.TryGet(ref c1, out memory, false));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
Assert.False(buffer.TryGet(ref c1, out memory, true));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
Assert.False(buffer.TryGet(ref c1, out memory, false));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
Assert.False(buffer.TryGet(ref c1, out memory, true));
Assert.Null(c1.GetObject());
Assert.True(memory.IsEmpty);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.NetFramework, "uap: dotnet/corefx #20010, netfx: dotnet/corefx #16805")]
public partial class HttpClientHandler_ServerCertificates_Test
{
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_ValidCertificate_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public void UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
var handler = new HttpClientHandler();
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent("This is a test"));
Task.WaitAll(proxyTask, responseTask);
using (responseTask.Result)
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagates()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)));
}
}
public static readonly object[][] CertificateValidationServers =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
[ActiveIssue(7812, TestPlatforms.Windows)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
// On macOS (libcurl+darwinssl) we cannot turn revocation off.
// But we also can't realistically say that the default value for
// CheckCertificateRevocationList throws in the general case.
try
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
catch (HttpRequestException)
{
if (!ShouldSuppressRevocationException)
throw;
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
}
}
public static readonly object[][] CertificateValidationServersAndExpectedPolicies =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
[ActiveIssue(7812, TestPlatforms.Windows)]
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
Assert.Equal(expectedErrors, errors);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
// For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply.
[PlatformSpecific(~TestPlatforms.OSX)]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
}
}
| |
#if ENABLE_PLAYFABSERVER_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.MatchmakerModels
{
[Serializable]
public class AuthUserRequest : PlayFabRequestCommon
{
/// <summary>
/// Session Ticket provided by the client.
/// </summary>
public string AuthorizationTicket;
}
[Serializable]
public class AuthUserResponse : PlayFabResultCommon
{
/// <summary>
/// Boolean indicating if the user has been authorized to use the external match-making service.
/// </summary>
public bool Authorized;
/// <summary>
/// PlayFab unique identifier of the account that has been authorized.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class DeregisterGameRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier for the Game Server Instance that is being deregistered.
/// </summary>
public string LobbyId;
}
[Serializable]
public class DeregisterGameResponse : PlayFabResultCommon
{
}
/// <summary>
/// A unique instance of an item in a user's inventory. Note, to retrieve additional information for an item instance (such as Tags, Description, or Custom Data that are set on the root catalog item), a call to GetCatalogItems is required. The Item ID of the instance can then be matched to a catalog entry, which contains the additional information. Also note that Custom Data is only set here from a call to UpdateUserInventoryItemCustomData.
/// </summary>
[Serializable]
public class ItemInstance
{
/// <summary>
/// Unique identifier for the inventory item, as defined in the catalog.
/// </summary>
public string ItemId;
/// <summary>
/// Unique item identifier for this specific instance of the item.
/// </summary>
public string ItemInstanceId;
/// <summary>
/// Class name for the inventory item, as defined in the catalog.
/// </summary>
public string ItemClass;
/// <summary>
/// Timestamp for when this instance was purchased.
/// </summary>
public DateTime? PurchaseDate;
/// <summary>
/// Timestamp for when this instance will expire.
/// </summary>
public DateTime? Expiration;
/// <summary>
/// Total number of remaining uses, if this is a consumable item.
/// </summary>
public int? RemainingUses;
/// <summary>
/// The number of uses that were added or removed to this item in this call.
/// </summary>
public int? UsesIncrementedBy;
/// <summary>
/// Game specific comment associated with this instance when it was added to the user inventory.
/// </summary>
public string Annotation;
/// <summary>
/// Catalog version for the inventory item, when this instance was created.
/// </summary>
public string CatalogVersion;
/// <summary>
/// Unique identifier for the parent inventory item, as defined in the catalog, for object which were added from a bundle or container.
/// </summary>
public string BundleParent;
/// <summary>
/// CatalogItem.DisplayName at the time this item was purchased.
/// </summary>
public string DisplayName;
/// <summary>
/// Currency type for the cost of the catalog item.
/// </summary>
public string UnitCurrency;
/// <summary>
/// Cost of the catalog item in the given currency.
/// </summary>
public uint UnitPrice;
/// <summary>
/// Array of unique items that were awarded when this catalog item was purchased.
/// </summary>
public List<string> BundleContents;
/// <summary>
/// A set of custom key-value pairs on the inventory item.
/// </summary>
public Dictionary<string,string> CustomData;
}
[Serializable]
public class PlayerJoinedRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance the user is joining. This must be a Game Server Instance started with the Matchmaker/StartGame API.
/// </summary>
public string LobbyId;
/// <summary>
/// PlayFab unique identifier for the player joining.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class PlayerJoinedResponse : PlayFabResultCommon
{
}
[Serializable]
public class PlayerLeftRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the Game Server Instance the user is leaving. This must be a Game Server Instance started with the Matchmaker/StartGame API.
/// </summary>
public string LobbyId;
/// <summary>
/// PlayFab unique identifier for the player leaving.
/// </summary>
public string PlayFabId;
}
[Serializable]
public class PlayerLeftResponse : PlayFabResultCommon
{
}
public enum Region
{
USCentral,
USEast,
EUWest,
Singapore,
Japan,
Brazil,
Australia
}
[Serializable]
public class RegisterGameRequest : PlayFabRequestCommon
{
/// <summary>
/// Previous lobby id if re-registering an existing game.
/// </summary>
public string LobbyId;
/// <summary>
/// IP address of the Game Server Instance.
/// </summary>
public string ServerHost;
/// <summary>
/// Port number for communication with the Game Server Instance.
/// </summary>
public string ServerPort;
/// <summary>
/// Unique identifier of the build running on the Game Server Instance.
/// </summary>
public string Build;
/// <summary>
/// Region in which the Game Server Instance is running. For matchmaking using non-AWS region names, set this to any AWS region and use Tags (below) to specify your custom region.
/// </summary>
public Region Region;
/// <summary>
/// Game Mode the Game Server instance is running. Note that this must be defined in the Game Modes tab in the PlayFab Game Manager, along with the Build ID (the same Game Mode can be defined for multiple Build IDs).
/// </summary>
public string GameMode;
/// <summary>
/// Tags for the Game Server Instance
/// </summary>
public Dictionary<string,string> Tags;
}
[Serializable]
public class RegisterGameResponse : PlayFabResultCommon
{
/// <summary>
/// Unique identifier generated for the Game Server Instance that is registered. If LobbyId is specified in request and the game still exists in PlayFab, the LobbyId in request is returned. Otherwise a new lobby id will be returned.
/// </summary>
public string LobbyId;
}
[Serializable]
public class StartGameRequest : PlayFabRequestCommon
{
/// <summary>
/// Unique identifier of the previously uploaded build executable which is to be started.
/// </summary>
public string Build;
/// <summary>
/// Region with which to associate the server, for filtering.
/// </summary>
public Region Region;
/// <summary>
/// Game mode for this Game Server Instance.
/// </summary>
public string GameMode;
/// <summary>
/// Custom command line argument when starting game server process.
/// </summary>
public string CustomCommandLineData;
/// <summary>
/// HTTP endpoint URL for receiving game status events, if using an external matchmaker. When the game ends, PlayFab will make a POST request to this URL with the X-SecretKey header set to the value of the game's secret and an application/json body of { "EventName": "game_ended", "GameID": "<gameid>" }.
/// </summary>
public string ExternalMatchmakerEventEndpoint;
}
[Serializable]
public class StartGameResponse : PlayFabResultCommon
{
/// <summary>
/// Unique identifier for the game/lobby in the new Game Server Instance.
/// </summary>
public string GameID;
/// <summary>
/// IP address of the new Game Server Instance.
/// </summary>
public string ServerHostname;
/// <summary>
/// Port number for communication with the Game Server Instance.
/// </summary>
public uint ServerPort;
}
[Serializable]
public class UserInfoRequest : PlayFabRequestCommon
{
/// <summary>
/// PlayFab unique identifier of the user whose information is being requested.
/// </summary>
public string PlayFabId;
/// <summary>
/// Minimum catalog version for which data is requested (filters the results to only contain inventory items which have a catalog version of this or higher).
/// </summary>
public int MinCatalogVersion;
}
[Serializable]
public class UserInfoResponse : PlayFabResultCommon
{
/// <summary>
/// PlayFab unique identifier of the user whose information was requested.
/// </summary>
public string PlayFabId;
/// <summary>
/// PlayFab unique user name.
/// </summary>
public string Username;
/// <summary>
/// Title specific display name, if set.
/// </summary>
public string TitleDisplayName;
/// <summary>
/// Array of inventory items in the user's current inventory.
/// </summary>
public List<ItemInstance> Inventory;
/// <summary>
/// Array of virtual currency balance(s) belonging to the user.
/// </summary>
public Dictionary<string,int> VirtualCurrency;
/// <summary>
/// Array of remaining times and timestamps for virtual currencies.
/// </summary>
public Dictionary<string,VirtualCurrencyRechargeTime> VirtualCurrencyRechargeTimes;
/// <summary>
/// Boolean indicating whether the user is a developer.
/// </summary>
public bool IsDeveloper;
/// <summary>
/// Steam unique identifier, if the user has an associated Steam account.
/// </summary>
public string SteamId;
}
[Serializable]
public class VirtualCurrencyRechargeTime
{
/// <summary>
/// Time remaining (in seconds) before the next recharge increment of the virtual currency.
/// </summary>
public int SecondsToRecharge;
/// <summary>
/// Server timestamp in UTC indicating the next time the virtual currency will be incremented.
/// </summary>
public DateTime RechargeTime;
/// <summary>
/// Maximum value to which the regenerating currency will automatically increment. Note that it can exceed this value through use of the AddUserVirtualCurrency API call. However, it will not regenerate automatically until it has fallen below this value.
/// </summary>
public int RechargeMax;
}
}
#endif
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace fastJSON
{
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
/// </summary>
internal sealed class JsonParser
{
enum Token
{
None = -1, // Used to denote no Lookahead available
Curly_Open,
Curly_Close,
Squared_Open,
Squared_Close,
Colon,
Comma,
String,
Number,
True,
False,
Null
}
readonly char[] json;
readonly StringBuilder s = new StringBuilder();
Token lookAheadToken = Token.None;
int index;
bool _ignorecase = false;
internal JsonParser(string json, bool ignorecase)
{
this.json = json.ToCharArray();
_ignorecase = ignorecase;
}
public object Decode()
{
return ParseValue();
}
private Dictionary<string, object> ParseObject()
{
Dictionary<string, object> table = new Dictionary<string, object>();
ConsumeToken(); // {
while (true)
{
switch (LookAhead())
{
case Token.Comma:
ConsumeToken();
break;
case Token.Curly_Close:
ConsumeToken();
return table;
default:
{
// name
string name = ParseString();
if (_ignorecase)
name = name.ToLower();
// :
if (NextToken() != Token.Colon)
{
throw new Exception("Expected colon at index " + index);
}
// value
object value = ParseValue();
table[name] = value;
}
break;
}
}
}
private List<object> ParseArray()
{
List<object> array = new List<object>();
ConsumeToken(); // [
while (true)
{
switch (LookAhead())
{
case Token.Comma:
ConsumeToken();
break;
case Token.Squared_Close:
ConsumeToken();
return array;
default:
array.Add(ParseValue());
break;
}
}
}
private object ParseValue()
{
switch (LookAhead())
{
case Token.Number:
return ParseNumber();
case Token.String:
return ParseString();
case Token.Curly_Open:
return ParseObject();
case Token.Squared_Open:
return ParseArray();
case Token.True:
ConsumeToken();
return true;
case Token.False:
ConsumeToken();
return false;
case Token.Null:
ConsumeToken();
return null;
}
throw new Exception("Unrecognized token at index" + index);
}
private string ParseString()
{
ConsumeToken(); // "
s.Length = 0;
int runIndex = -1;
while (index < json.Length)
{
var c = json[index++];
if (c == '"')
{
if (runIndex != -1)
{
if (s.Length == 0)
return new string(json, runIndex, index - runIndex - 1);
s.Append(json, runIndex, index - runIndex - 1);
}
return s.ToString();
}
if (c != '\\')
{
if (runIndex == -1)
runIndex = index - 1;
continue;
}
if (index == json.Length) break;
if (runIndex != -1)
{
s.Append(json, runIndex, index - runIndex - 1);
runIndex = -1;
}
switch (json[index++])
{
case '"':
s.Append('"');
break;
case '\\':
s.Append('\\');
break;
case '/':
s.Append('/');
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
{
int remainingLength = json.Length - index;
if (remainingLength < 4) break;
// parse the 32 bit hex into an integer codepoint
uint codePoint = ParseUnicode(json[index], json[index + 1], json[index + 2], json[index + 3]);
s.Append((char)codePoint);
// skip 4 chars
index += 4;
}
break;
}
}
throw new Exception("Unexpectedly reached end of string");
}
private uint ParseSingleChar(char c1, uint multipliyer)
{
uint p1 = 0;
if (c1 >= '0' && c1 <= '9')
p1 = (uint)(c1 - '0') * multipliyer;
else if (c1 >= 'A' && c1 <= 'F')
p1 = (uint)((c1 - 'A') + 10) * multipliyer;
else if (c1 >= 'a' && c1 <= 'f')
p1 = (uint)((c1 - 'a') + 10) * multipliyer;
return p1;
}
private uint ParseUnicode(char c1, char c2, char c3, char c4)
{
uint p1 = ParseSingleChar(c1, 0x1000);
uint p2 = ParseSingleChar(c2, 0x100);
uint p3 = ParseSingleChar(c3, 0x10);
uint p4 = ParseSingleChar(c4, 1);
return p1 + p2 + p3 + p4;
}
private long CreateLong(string s)
{
long num = 0;
bool neg = false;
foreach (char cc in s)
{
if (cc == '-')
neg = true;
else if (cc == '+')
neg = false;
else
{
num *= 10;
num += (int)(cc - '0');
}
}
return neg ? -num : num;
}
private object ParseNumber()
{
ConsumeToken();
// Need to start back one place because the first digit is also a token and would have been consumed
var startIndex = index - 1;
bool dec = false;
do
{
if (index == json.Length)
break;
var c = json[index];
if ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')
{
if (c == '.' || c == 'e' || c == 'E')
dec = true;
if (++index == json.Length)
break; //throw new Exception("Unexpected end of string whilst parsing number");
continue;
}
break;
} while (true);
if (dec)
{
string s = new string(json, startIndex, index - startIndex);
return double.Parse(s, NumberFormatInfo.InvariantInfo);
}
long num;
return JSON.CreateLong(out num, json, startIndex, index - startIndex);
}
private Token LookAhead()
{
if (lookAheadToken != Token.None) return lookAheadToken;
return lookAheadToken = NextTokenCore();
}
private void ConsumeToken()
{
lookAheadToken = Token.None;
}
private Token NextToken()
{
var result = lookAheadToken != Token.None ? lookAheadToken : NextTokenCore();
lookAheadToken = Token.None;
return result;
}
private Token NextTokenCore()
{
char c;
// Skip past whitespace
do
{
c = json[index];
if (c > ' ') break;
if (c != ' ' && c != '\t' && c != '\n' && c != '\r') break;
} while (++index < json.Length);
if (index == json.Length)
{
throw new Exception("Reached end of string unexpectedly");
}
c = json[index];
index++;
switch (c)
{
case '{':
return Token.Curly_Open;
case '}':
return Token.Curly_Close;
case '[':
return Token.Squared_Open;
case ']':
return Token.Squared_Close;
case ',':
return Token.Comma;
case '"':
return Token.String;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
case '.':
return Token.Number;
case ':':
return Token.Colon;
case 'f':
if (json.Length - index >= 4 &&
json[index + 0] == 'a' &&
json[index + 1] == 'l' &&
json[index + 2] == 's' &&
json[index + 3] == 'e')
{
index += 4;
return Token.False;
}
break;
case 't':
if (json.Length - index >= 3 &&
json[index + 0] == 'r' &&
json[index + 1] == 'u' &&
json[index + 2] == 'e')
{
index += 3;
return Token.True;
}
break;
case 'n':
if (json.Length - index >= 3 &&
json[index + 0] == 'u' &&
json[index + 1] == 'l' &&
json[index + 2] == 'l')
{
index += 3;
return Token.Null;
}
break;
}
throw new Exception("Could not find token at index " + --index);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Timer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Timers {
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.ComponentModel;
using System.ComponentModel.Design;
using System;
using System.Runtime.Versioning;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
/// <devdoc>
/// <para>Handles recurring events in an application.</para>
/// </devdoc>
[
DefaultProperty("Interval"),
DefaultEvent("Elapsed"),
HostProtection(Synchronization=true, ExternalThreading=true)
]
public class Timer : Component, ISupportInitialize {
private double interval;
private bool enabled;
private bool initializing;
private bool delayedEnable;
private ElapsedEventHandler onIntervalElapsed;
private bool autoReset;
private ISynchronizeInvoke synchronizingObject;
private bool disposed;
private System.Threading.Timer timer;
private TimerCallback callback;
private Object cookie;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Timers.Timer'/> class, with the properties
/// set to initial values.</para>
/// </devdoc>
public Timer()
: base() {
interval = 100;
enabled = false;
autoReset = true;
initializing = false;
delayedEnable = false;
callback = new TimerCallback(this.MyTimerCallback);
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Timers.Timer'/> class, setting the <see cref='System.Timers.Timer.Interval'/> property to the specified period.
/// </para>
/// </devdoc>
public Timer(double interval)
: this() {
if (interval <= 0)
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "interval", interval));
this.interval = CalculateRoundedInterval(interval, true);
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the Timer raises the Tick event each time the specified
/// Interval has elapsed,
/// when Enabled is set to true.</para>
/// </devdoc>
[Category("Behavior"), TimersDescription(SR.TimerAutoReset), DefaultValue(true)]
public bool AutoReset {
get {
return this.autoReset;
}
set {
if (DesignMode)
this.autoReset = value;
else if (this.autoReset != value) {
this.autoReset = value;
if( timer != null) {
UpdateTimer();
}
}
}
}
/// <devdoc>
/// <para>Gets or sets a value indicating whether the <see cref='System.Timers.Timer'/>
/// is able
/// to raise events at a defined interval.</para>
/// </devdoc>
//[....] - The default value by design is false, don't change it.
[Category("Behavior"), TimersDescription(SR.TimerEnabled), DefaultValue(false)]
public bool Enabled {
get {
return this.enabled;
}
set {
if (DesignMode) {
this.delayedEnable = value;
this.enabled = value;
}
else if (initializing)
this.delayedEnable = value;
else if (enabled != value) {
if (!value) {
if( timer != null) {
cookie = null;
timer.Dispose();
timer = null;
}
enabled = value;
}
else {
enabled = value;
if( timer == null) {
if (disposed) {
throw new ObjectDisposedException(GetType().Name);
}
int i = CalculateRoundedInterval(interval);
cookie = new Object();
timer = new System.Threading.Timer(callback, cookie, i, autoReset? i:Timeout.Infinite);
}
else {
UpdateTimer();
}
}
}
}
}
private static int CalculateRoundedInterval(double interval, bool argumentCheck = false) {
double roundedInterval = Math.Ceiling(interval);
if (roundedInterval > Int32.MaxValue || roundedInterval <= 0) {
if (argumentCheck)
throw new ArgumentException(SR.GetString(SR.InvalidParameter, "interval", interval));
throw new ArgumentOutOfRangeException(SR.GetString(SR.InvalidParameter, "interval", interval));
}
return (int)roundedInterval;
}
private void UpdateTimer() {
int i = CalculateRoundedInterval(interval);
timer.Change(i, autoReset? i :Timeout.Infinite );
}
/// <devdoc>
/// <para>Gets or
/// sets the interval on which
/// to raise events.</para>
/// </devdoc>
[Category("Behavior"), TimersDescription(SR.TimerInterval), DefaultValue(100d), SettingsBindable(true)]
public double Interval {
get {
return this.interval;
}
set {
if (value <= 0)
throw new ArgumentException(SR.GetString(SR.TimerInvalidInterval, value, 0));
interval = value;
if (timer != null) {
UpdateTimer();
}
}
}
/// <devdoc>
/// <para>Occurs when the <see cref='System.Timers.Timer.Interval'/> has
/// elapsed.</para>
/// </devdoc>
[Category("Behavior"), TimersDescription(SR.TimerIntervalElapsed)]
public event ElapsedEventHandler Elapsed {
add {
onIntervalElapsed += value;
}
remove {
onIntervalElapsed -= value;
}
}
/// <devdoc>
/// <para>
/// Sets the enable property in design mode to true by default.
/// </para>
/// </devdoc>
/// <internalonly/>
public override ISite Site {
set {
base.Site = value;
if (this.DesignMode)
this.enabled= true;
}
get {
return base.Site;
}
}
/// <devdoc>
/// <para>Gets or sets the object used to marshal event-handler calls that are issued when
/// an interval has elapsed.</para>
/// </devdoc>
[
Browsable(false),
DefaultValue(null),
TimersDescription(SR.TimerSynchronizingObject)
]
public ISynchronizeInvoke SynchronizingObject {
get {
if (this.synchronizingObject == null && DesignMode) {
IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
if (host != null) {
object baseComponent = host.RootComponent;
if (baseComponent != null && baseComponent is ISynchronizeInvoke)
this.synchronizingObject = (ISynchronizeInvoke)baseComponent;
}
}
return this.synchronizingObject;
}
set {
this.synchronizingObject = value;
}
}
/// <devdoc>
/// <para>
/// Notifies
/// the object that initialization is beginning and tells it to stand by.
/// </para>
/// </devdoc>
public void BeginInit() {
this.Close();
this.initializing = true;
}
/// <devdoc>
/// <para>Disposes of the resources (other than memory) used by
/// the <see cref='System.Timers.Timer'/>.</para>
/// </devdoc>
public void Close() {
initializing = false;
delayedEnable = false;
enabled = false;
if (timer != null ) {
timer.Dispose();
timer = null;
}
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected override void Dispose(bool disposing) {
Close();
this.disposed = true;
base.Dispose(disposing);
}
/// <devdoc>
/// <para>
/// Notifies the object that initialization is complete.
/// </para>
/// </devdoc>
public void EndInit() {
this.initializing = false;
this.Enabled = this.delayedEnable;
}
/// <devdoc>
/// <para>Starts the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='true'/>.</para>
/// </devdoc>
public void Start() {
Enabled = true;
}
/// <devdoc>
/// <para>
/// Stops the timing by setting <see cref='System.Timers.Timer.Enabled'/> to <see langword='false'/>.
/// </para>
/// </devdoc>
public void Stop() {
Enabled = false;
}
private void MyTimerCallback(object state) {
// System.Threading.Timer will not cancel the work item queued before the timer is stopped.
// We don't want to handle the callback after a timer is stopped.
if( state != cookie) {
return;
}
if (!this.autoReset) {
enabled = false;
}
#if MONO
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(DateTime.Now);
#else
FILE_TIME filetime = new FILE_TIME();
GetSystemTimeAsFileTime(ref filetime);
ElapsedEventArgs elapsedEventArgs = new ElapsedEventArgs(filetime.ftTimeLow, filetime.ftTimeHigh);
#endif
try {
// To avoid ---- between remove handler and raising the event
ElapsedEventHandler intervalElapsed = this.onIntervalElapsed;
if (intervalElapsed != null) {
if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired)
this.SynchronizingObject.BeginInvoke(intervalElapsed, new object[]{this, elapsedEventArgs});
else
intervalElapsed(this, elapsedEventArgs);
}
}
catch {
}
}
#if !MONO
[StructLayout(LayoutKind.Sequential)]
internal struct FILE_TIME {
internal int ftTimeLow;
internal int ftTimeHigh;
}
[ResourceExposure(ResourceScope.None)]
[DllImport(ExternDll.Kernel32), SuppressUnmanagedCodeSecurityAttribute()]
internal static extern void GetSystemTimeAsFileTime(ref FILE_TIME lpSystemTimeAsFileTime);
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoadBalancersOperations operations.
/// </summary>
internal partial class LoadBalancersOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancersOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LoadBalancersOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, loadBalancerName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LoadBalancer>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LoadBalancer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<LoadBalancer>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<LoadBalancer> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, loadBalancerName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update load balancer operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LoadBalancer>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, LoadBalancer parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LoadBalancer>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancer>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancers in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancers in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancer>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancer>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancer>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Linq.Expressions
{
/// <summary>
/// Strongly-typed and parameterized string resources.
/// </summary>
internal static class Strings
{
/// <summary>
/// A string like "reducible nodes must override Expression.Reduce()"
/// </summary>
internal static string ReducibleMustOverrideReduce => SR.ReducibleMustOverrideReduce;
/// <summary>
/// A string like "node cannot reduce to itself or null"
/// </summary>
internal static string MustReduceToDifferent => SR.MustReduceToDifferent;
/// <summary>
/// A string like "cannot assign from the reduced node type to the original node type"
/// </summary>
internal static string ReducedNotCompatible => SR.ReducedNotCompatible;
/// <summary>
/// A string like "Setter must have parameters."
/// </summary>
internal static string SetterHasNoParams => SR.SetterHasNoParams;
/// <summary>
/// A string like "Property cannot have a managed pointer type."
/// </summary>
internal static string PropertyCannotHaveRefType => SR.PropertyCannotHaveRefType;
/// <summary>
/// A string like "Indexing parameters of getter and setter must match."
/// </summary>
internal static string IndexesOfSetGetMustMatch => SR.IndexesOfSetGetMustMatch;
/// <summary>
/// A string like "Accessor method should not have VarArgs."
/// </summary>
internal static string AccessorsCannotHaveVarArgs => SR.AccessorsCannotHaveVarArgs;
/// <summary>
/// A string like "Accessor indexes cannot be passed ByRef."
/// </summary>
internal static string AccessorsCannotHaveByRefArgs => SR.AccessorsCannotHaveByRefArgs;
/// <summary>
/// A string like "Bounds count cannot be less than 1"
/// </summary>
internal static string BoundsCannotBeLessThanOne => SR.BoundsCannotBeLessThanOne;
/// <summary>
/// A string like "Type must not be ByRef"
/// </summary>
internal static string TypeMustNotBeByRef => SR.TypeMustNotBeByRef;
/// <summary>
/// A string like "Type must not be a pointer type"
/// </summary>
internal static string TypeMustNotBePointer => SR.TypeMustNotBePointer;
/// <summary>
/// A string like "Setter should have void type."
/// </summary>
internal static string SetterMustBeVoid => SR.SetterMustBeVoid;
/// <summary>
/// A string like "Property type must match the value type of getter"
/// </summary>
internal static string PropertyTypeMustMatchGetter => SR.PropertyTypeMustMatchGetter;
/// <summary>
/// A string like "Property type must match the value type of setter"
/// </summary>
internal static string PropertyTypeMustMatchSetter => SR.PropertyTypeMustMatchSetter;
/// <summary>
/// A string like "Both accessors must be static."
/// </summary>
internal static string BothAccessorsMustBeStatic => SR.BothAccessorsMustBeStatic;
/// <summary>
/// A string like "Static field requires null instance, non-static field requires non-null instance."
/// </summary>
internal static string OnlyStaticFieldsHaveNullInstance => SR.OnlyStaticFieldsHaveNullInstance;
/// <summary>
/// A string like "Static property requires null instance, non-static property requires non-null instance."
/// </summary>
internal static string OnlyStaticPropertiesHaveNullInstance => SR.OnlyStaticPropertiesHaveNullInstance;
/// <summary>
/// A string like "Static method requires null instance, non-static method requires non-null instance."
/// </summary>
internal static string OnlyStaticMethodsHaveNullInstance => SR.OnlyStaticMethodsHaveNullInstance;
/// <summary>
/// A string like "Property cannot have a void type."
/// </summary>
internal static string PropertyTypeCannotBeVoid => SR.PropertyTypeCannotBeVoid;
/// <summary>
/// A string like "Can only unbox from an object or interface type to a value type."
/// </summary>
internal static string InvalidUnboxType => SR.InvalidUnboxType;
/// <summary>
/// A string like "Expression must be writeable"
/// </summary>
internal static string ExpressionMustBeWriteable => SR.ExpressionMustBeWriteable;
/// <summary>
/// A string like "Argument must not have a value type."
/// </summary>
internal static string ArgumentMustNotHaveValueType => SR.ArgumentMustNotHaveValueType;
/// <summary>
/// A string like "must be reducible node"
/// </summary>
internal static string MustBeReducible => SR.MustBeReducible;
/// <summary>
/// A string like "All test values must have the same type."
/// </summary>
internal static string AllTestValuesMustHaveSameType => SR.AllTestValuesMustHaveSameType;
/// <summary>
/// A string like "All case bodies and the default body must have the same type."
/// </summary>
internal static string AllCaseBodiesMustHaveSameType => SR.AllCaseBodiesMustHaveSameType;
/// <summary>
/// A string like "Default body must be supplied if case bodies are not System.Void."
/// </summary>
internal static string DefaultBodyMustBeSupplied => SR.DefaultBodyMustBeSupplied;
/// <summary>
/// A string like "Label type must be System.Void if an expression is not supplied"
/// </summary>
internal static string LabelMustBeVoidOrHaveExpression => SR.LabelMustBeVoidOrHaveExpression;
/// <summary>
/// A string like "Type must be System.Void for this label argument"
/// </summary>
internal static string LabelTypeMustBeVoid => SR.LabelTypeMustBeVoid;
/// <summary>
/// A string like "Quoted expression must be a lambda"
/// </summary>
internal static string QuotedExpressionMustBeLambda => SR.QuotedExpressionMustBeLambda;
/// <summary>
/// A string like "Collection was modified; enumeration operation may not execute."
/// </summary>
internal static string CollectionModifiedWhileEnumerating => SR.CollectionModifiedWhileEnumerating;
/// <summary>
/// A string like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables."
/// </summary>
internal static string VariableMustNotBeByRef(object p0, object p1) => SR.Format(SR.VariableMustNotBeByRef, p0, p1);
/// <summary>
/// A string like "Collection is read-only."
/// </summary>
internal static string CollectionReadOnly => SR.CollectionReadOnly;
/// <summary>
/// A string like "More than one key matching '{0}' was found in the ExpandoObject."
/// </summary>
internal static string AmbiguousMatchInExpandoObject(object p0) => SR.Format(SR.AmbiguousMatchInExpandoObject, p0);
/// <summary>
/// A string like "An element with the same key '{0}' already exists in the ExpandoObject."
/// </summary>
internal static string SameKeyExistsInExpando(object p0) => SR.Format(SR.SameKeyExistsInExpando, p0);
/// <summary>
/// A string like "The specified key '{0}' does not exist in the ExpandoObject."
/// </summary>
internal static string KeyDoesNotExistInExpando(object p0) => SR.Format(SR.KeyDoesNotExistInExpando, p0);
/// <summary>
/// A string like "Argument count must be greater than number of named arguments."
/// </summary>
internal static string ArgCntMustBeGreaterThanNameCnt => SR.ArgCntMustBeGreaterThanNameCnt;
/// <summary>
/// A string like "An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance."
/// </summary>
internal static string InvalidMetaObjectCreated(object p0) => SR.Format(SR.InvalidMetaObjectCreated, p0);
/// <summary>
/// A string like "The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site."
/// </summary>
internal static string BinderNotCompatibleWithCallSite(object p0, object p1, object p2) => SR.Format(SR.BinderNotCompatibleWithCallSite, p0, p1, p2);
/// <summary>
/// A string like "The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction."
/// </summary>
internal static string DynamicBindingNeedsRestrictions(object p0, object p1) => SR.Format(SR.DynamicBindingNeedsRestrictions, p0, p1);
/// <summary>
/// A string like "The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site."
/// </summary>
internal static string DynamicObjectResultNotAssignable(object p0, object p1, object p2, object p3) => SR.Format(SR.DynamicObjectResultNotAssignable, p0, p1, p2, p3);
/// <summary>
/// A string like "The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site."
/// </summary>
internal static string DynamicBinderResultNotAssignable(object p0, object p1, object p2) => SR.Format(SR.DynamicBinderResultNotAssignable, p0, p1, p2);
/// <summary>
/// A string like "Bind cannot return null."
/// </summary>
internal static string BindingCannotBeNull => SR.BindingCannotBeNull;
/// <summary>
/// A string like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object."
/// </summary>
internal static string DuplicateVariable(object p0) => SR.Format(SR.DuplicateVariable, p0);
/// <summary>
/// A string like "Argument type cannot be void"
/// </summary>
internal static string ArgumentTypeCannotBeVoid => SR.ArgumentTypeCannotBeVoid;
/// <summary>
/// A string like "Type parameter is {0}. Expected a delegate."
/// </summary>
internal static string TypeParameterIsNotDelegate(object p0) => SR.Format(SR.TypeParameterIsNotDelegate, p0);
/// <summary>
/// A string like "No or Invalid rule produced"
/// </summary>
internal static string NoOrInvalidRuleProduced => SR.NoOrInvalidRuleProduced;
/// <summary>
/// A string like "Type must be derived from System.Delegate"
/// </summary>
internal static string TypeMustBeDerivedFromSystemDelegate => SR.TypeMustBeDerivedFromSystemDelegate;
/// <summary>
/// A string like "First argument of delegate must be CallSite"
/// </summary>
internal static string FirstArgumentMustBeCallSite => SR.FirstArgumentMustBeCallSite;
/// <summary>
/// A string like "Start and End must be well ordered"
/// </summary>
internal static string StartEndMustBeOrdered => SR.StartEndMustBeOrdered;
/// <summary>
/// A string like "fault cannot be used with catch or finally clauses"
/// </summary>
internal static string FaultCannotHaveCatchOrFinally => SR.FaultCannotHaveCatchOrFinally;
/// <summary>
/// A string like "try must have at least one catch, finally, or fault clause"
/// </summary>
internal static string TryMustHaveCatchFinallyOrFault => SR.TryMustHaveCatchFinallyOrFault;
/// <summary>
/// A string like "Body of catch must have the same type as body of try."
/// </summary>
internal static string BodyOfCatchMustHaveSameTypeAsBodyOfTry => SR.BodyOfCatchMustHaveSameTypeAsBodyOfTry;
/// <summary>
/// A string like "Extension node must override the property {0}."
/// </summary>
internal static string ExtensionNodeMustOverrideProperty(object p0) => SR.Format(SR.ExtensionNodeMustOverrideProperty, p0);
/// <summary>
/// A string like "User-defined operator method '{0}' must be static."
/// </summary>
internal static string UserDefinedOperatorMustBeStatic(object p0) => SR.Format(SR.UserDefinedOperatorMustBeStatic, p0);
/// <summary>
/// A string like "User-defined operator method '{0}' must not be void."
/// </summary>
internal static string UserDefinedOperatorMustNotBeVoid(object p0) => SR.Format(SR.UserDefinedOperatorMustNotBeVoid, p0);
/// <summary>
/// A string like "No coercion operator is defined between types '{0}' and '{1}'."
/// </summary>
internal static string CoercionOperatorNotDefined(object p0, object p1) => SR.Format(SR.CoercionOperatorNotDefined, p0, p1);
/// <summary>
/// A string like "The unary operator {0} is not defined for the type '{1}'."
/// </summary>
internal static string UnaryOperatorNotDefined(object p0, object p1) => SR.Format(SR.UnaryOperatorNotDefined, p0, p1);
/// <summary>
/// A string like "The binary operator {0} is not defined for the types '{1}' and '{2}'."
/// </summary>
internal static string BinaryOperatorNotDefined(object p0, object p1, object p2) => SR.Format(SR.BinaryOperatorNotDefined, p0, p1, p2);
/// <summary>
/// A string like "Reference equality is not defined for the types '{0}' and '{1}'."
/// </summary>
internal static string ReferenceEqualityNotDefined(object p0, object p1) => SR.Format(SR.ReferenceEqualityNotDefined, p0, p1);
/// <summary>
/// A string like "The operands for operator '{0}' do not match the parameters of method '{1}'."
/// </summary>
internal static string OperandTypesDoNotMatchParameters(object p0, object p1) => SR.Format(SR.OperandTypesDoNotMatchParameters, p0, p1);
/// <summary>
/// A string like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'."
/// </summary>
internal static string OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) => SR.Format(SR.OverloadOperatorTypeDoesNotMatchConversionType, p0, p1);
/// <summary>
/// A string like "Conversion is not supported for arithmetic types without operator overloading."
/// </summary>
internal static string ConversionIsNotSupportedForArithmeticTypes => SR.ConversionIsNotSupportedForArithmeticTypes;
/// <summary>
/// A string like "Argument must be array"
/// </summary>
internal static string ArgumentMustBeArray => SR.ArgumentMustBeArray;
/// <summary>
/// A string like "Argument must be boolean"
/// </summary>
internal static string ArgumentMustBeBoolean => SR.ArgumentMustBeBoolean;
/// <summary>
/// A string like "The user-defined equality method '{0}' must return a boolean value."
/// </summary>
internal static string EqualityMustReturnBoolean(object p0) => SR.Format(SR.EqualityMustReturnBoolean, p0);
/// <summary>
/// A string like "Argument must be either a FieldInfo or PropertyInfo"
/// </summary>
internal static string ArgumentMustBeFieldInfoOrPropertyInfo => SR.ArgumentMustBeFieldInfoOrPropertyInfo;
/// <summary>
/// A string like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo"
/// </summary>
internal static string ArgumentMustBeFieldInfoOrPropertyInfoOrMethod => SR.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod;
/// <summary>
/// A string like "Argument must be an instance member"
/// </summary>
internal static string ArgumentMustBeInstanceMember => SR.ArgumentMustBeInstanceMember;
/// <summary>
/// A string like "Argument must be of an integer type"
/// </summary>
internal static string ArgumentMustBeInteger => SR.ArgumentMustBeInteger;
/// <summary>
/// A string like "Argument for array index must be of type Int32"
/// </summary>
internal static string ArgumentMustBeArrayIndexType => SR.ArgumentMustBeArrayIndexType;
/// <summary>
/// A string like "Argument must be single-dimensional, zero-based array type"
/// </summary>
internal static string ArgumentMustBeSingleDimensionalArrayType => SR.ArgumentMustBeSingleDimensionalArrayType;
/// <summary>
/// A string like "Argument types do not match"
/// </summary>
internal static string ArgumentTypesMustMatch => SR.ArgumentTypesMustMatch;
/// <summary>
/// A string like "Cannot auto initialize elements of value type through property '{0}', use assignment instead"
/// </summary>
internal static string CannotAutoInitializeValueTypeElementThroughProperty(object p0) => SR.Format(SR.CannotAutoInitializeValueTypeElementThroughProperty, p0);
/// <summary>
/// A string like "Cannot auto initialize members of value type through property '{0}', use assignment instead"
/// </summary>
internal static string CannotAutoInitializeValueTypeMemberThroughProperty(object p0) => SR.Format(SR.CannotAutoInitializeValueTypeMemberThroughProperty, p0);
/// <summary>
/// A string like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither"
/// </summary>
internal static string IncorrectTypeForTypeAs(object p0) => SR.Format(SR.IncorrectTypeForTypeAs, p0);
/// <summary>
/// A string like "Coalesce used with type that cannot be null"
/// </summary>
internal static string CoalesceUsedOnNonNullType => SR.CoalesceUsedOnNonNullType;
/// <summary>
/// A string like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'"
/// </summary>
internal static string ExpressionTypeCannotInitializeArrayType(object p0, object p1) => SR.Format(SR.ExpressionTypeCannotInitializeArrayType, p0, p1);
/// <summary>
/// A string like " Argument type '{0}' does not match the corresponding member type '{1}'"
/// </summary>
internal static string ArgumentTypeDoesNotMatchMember(object p0, object p1) => SR.Format(SR.ArgumentTypeDoesNotMatchMember, p0, p1);
/// <summary>
/// A string like " The member '{0}' is not declared on type '{1}' being created"
/// </summary>
internal static string ArgumentMemberNotDeclOnType(object p0, object p1) => SR.Format(SR.ArgumentMemberNotDeclOnType, p0, p1);
/// <summary>
/// A string like "Expression of type '{0}' cannot be used for return type '{1}'"
/// </summary>
internal static string ExpressionTypeDoesNotMatchReturn(object p0, object p1) => SR.Format(SR.ExpressionTypeDoesNotMatchReturn, p0, p1);
/// <summary>
/// A string like "Expression of type '{0}' cannot be used for assignment to type '{1}'"
/// </summary>
internal static string ExpressionTypeDoesNotMatchAssignment(object p0, object p1) => SR.Format(SR.ExpressionTypeDoesNotMatchAssignment, p0, p1);
/// <summary>
/// A string like "Expression of type '{0}' cannot be used for label of type '{1}'"
/// </summary>
internal static string ExpressionTypeDoesNotMatchLabel(object p0, object p1) => SR.Format(SR.ExpressionTypeDoesNotMatchLabel, p0, p1);
/// <summary>
/// A string like "Expression of type '{0}' cannot be invoked"
/// </summary>
internal static string ExpressionTypeNotInvocable(object p0) => SR.Format(SR.ExpressionTypeNotInvocable, p0);
/// <summary>
/// A string like "Field '{0}' is not defined for type '{1}'"
/// </summary>
internal static string FieldNotDefinedForType(object p0, object p1) => SR.Format(SR.FieldNotDefinedForType, p0, p1);
/// <summary>
/// A string like "Instance field '{0}' is not defined for type '{1}'"
/// </summary>
internal static string InstanceFieldNotDefinedForType(object p0, object p1) => SR.Format(SR.InstanceFieldNotDefinedForType, p0, p1);
/// <summary>
/// A string like "Field '{0}.{1}' is not defined for type '{2}'"
/// </summary>
internal static string FieldInfoNotDefinedForType(object p0, object p1, object p2) => SR.Format(SR.FieldInfoNotDefinedForType, p0, p1, p2);
/// <summary>
/// A string like "Incorrect number of indexes"
/// </summary>
internal static string IncorrectNumberOfIndexes => SR.IncorrectNumberOfIndexes;
/// <summary>
/// A string like "Incorrect number of parameters supplied for lambda declaration"
/// </summary>
internal static string IncorrectNumberOfLambdaDeclarationParameters => SR.IncorrectNumberOfLambdaDeclarationParameters;
/// <summary>
/// A string like " Incorrect number of members for constructor"
/// </summary>
internal static string IncorrectNumberOfMembersForGivenConstructor => SR.IncorrectNumberOfMembersForGivenConstructor;
/// <summary>
/// A string like "Incorrect number of arguments for the given members "
/// </summary>
internal static string IncorrectNumberOfArgumentsForMembers => SR.IncorrectNumberOfArgumentsForMembers;
/// <summary>
/// A string like "Lambda type parameter must be derived from System.MulticastDelegate"
/// </summary>
internal static string LambdaTypeMustBeDerivedFromSystemDelegate => SR.LambdaTypeMustBeDerivedFromSystemDelegate;
/// <summary>
/// A string like "Member '{0}' not field or property"
/// </summary>
internal static string MemberNotFieldOrProperty(object p0) => SR.Format(SR.MemberNotFieldOrProperty, p0);
/// <summary>
/// A string like "Method {0} contains generic parameters"
/// </summary>
internal static string MethodContainsGenericParameters(object p0) => SR.Format(SR.MethodContainsGenericParameters, p0);
/// <summary>
/// A string like "Method {0} is a generic method definition"
/// </summary>
internal static string MethodIsGeneric(object p0) => SR.Format(SR.MethodIsGeneric, p0);
/// <summary>
/// A string like "The method '{0}.{1}' is not a property accessor"
/// </summary>
internal static string MethodNotPropertyAccessor(object p0, object p1) => SR.Format(SR.MethodNotPropertyAccessor, p0, p1);
/// <summary>
/// A string like "The property '{0}' has no 'get' accessor"
/// </summary>
internal static string PropertyDoesNotHaveGetter(object p0) => SR.Format(SR.PropertyDoesNotHaveGetter, p0);
/// <summary>
/// A string like "The property '{0}' has no 'set' accessor"
/// </summary>
internal static string PropertyDoesNotHaveSetter(object p0) => SR.Format(SR.PropertyDoesNotHaveSetter, p0);
/// <summary>
/// A string like "The property '{0}' has no 'get' or 'set' accessors"
/// </summary>
internal static string PropertyDoesNotHaveAccessor(object p0) => SR.Format(SR.PropertyDoesNotHaveAccessor, p0);
/// <summary>
/// A string like "'{0}' is not a member of type '{1}'"
/// </summary>
internal static string NotAMemberOfType(object p0, object p1) => SR.Format(SR.NotAMemberOfType, p0, p1);
/// <summary>
/// A string like "'{0}' is not a member of any type"
/// </summary>
internal static string NotAMemberOfAnyType(object p0) => SR.Format(SR.NotAMemberOfAnyType, p0);
/// <summary>
/// A string like "The expression '{0}' is not supported for type '{1}'"
/// </summary>
internal static string ExpressionNotSupportedForType(object p0, object p1) => SR.Format(SR.ExpressionNotSupportedForType, p0, p1);
/// <summary>
/// A string like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'"
/// </summary>
internal static string ParameterExpressionNotValidAsDelegate(object p0, object p1) => SR.Format(SR.ParameterExpressionNotValidAsDelegate, p0, p1);
/// <summary>
/// A string like "Property '{0}' is not defined for type '{1}'"
/// </summary>
internal static string PropertyNotDefinedForType(object p0, object p1) => SR.Format(SR.PropertyNotDefinedForType, p0, p1);
/// <summary>
/// A string like "Instance property '{0}' is not defined for type '{1}'"
/// </summary>
internal static string InstancePropertyNotDefinedForType(object p0, object p1) => SR.Format(SR.InstancePropertyNotDefinedForType, p0, p1);
/// <summary>
/// A string like "Instance property '{0}' that takes no argument is not defined for type '{1}'"
/// </summary>
internal static string InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) => SR.Format(SR.InstancePropertyWithoutParameterNotDefinedForType, p0, p1);
/// <summary>
/// A string like "Instance property '{0}{1}' is not defined for type '{2}'"
/// </summary>
internal static string InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) => SR.Format(SR.InstancePropertyWithSpecifiedParametersNotDefinedForType, p0, p1, p2);
/// <summary>
/// A string like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'"
/// </summary>
internal static string InstanceAndMethodTypeMismatch(object p0, object p1, object p2) => SR.Format(SR.InstanceAndMethodTypeMismatch, p0, p1, p2);
/// <summary>
/// A string like "Type '{0}' does not have a default constructor"
/// </summary>
internal static string TypeMissingDefaultConstructor(object p0) => SR.Format(SR.TypeMissingDefaultConstructor, p0);
/// <summary>
/// A string like "Element initializer method must be named 'Add'"
/// </summary>
internal static string ElementInitializerMethodNotAdd => SR.ElementInitializerMethodNotAdd;
/// <summary>
/// A string like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter"
/// </summary>
internal static string ElementInitializerMethodNoRefOutParam(object p0, object p1) => SR.Format(SR.ElementInitializerMethodNoRefOutParam, p0, p1);
/// <summary>
/// A string like "Element initializer method must have at least 1 parameter"
/// </summary>
internal static string ElementInitializerMethodWithZeroArgs => SR.ElementInitializerMethodWithZeroArgs;
/// <summary>
/// A string like "Element initializer method must be an instance method"
/// </summary>
internal static string ElementInitializerMethodStatic => SR.ElementInitializerMethodStatic;
/// <summary>
/// A string like "Type '{0}' is not IEnumerable"
/// </summary>
internal static string TypeNotIEnumerable(object p0) => SR.Format(SR.TypeNotIEnumerable, p0);
/// <summary>
/// A string like "Unexpected coalesce operator."
/// </summary>
internal static string UnexpectedCoalesceOperator => SR.UnexpectedCoalesceOperator;
/// <summary>
/// A string like "Cannot cast from type '{0}' to type '{1}"
/// </summary>
internal static string InvalidCast(object p0, object p1) => SR.Format(SR.InvalidCast, p0, p1);
/// <summary>
/// A string like "Unhandled binary: {0}"
/// </summary>
internal static string UnhandledBinary(object p0) => SR.Format(SR.UnhandledBinary, p0);
/// <summary>
/// A string like "Unhandled binding "
/// </summary>
internal static string UnhandledBinding => SR.UnhandledBinding;
/// <summary>
/// A string like "Unhandled Binding Type: {0}"
/// </summary>
internal static string UnhandledBindingType(object p0) => SR.Format(SR.UnhandledBindingType, p0);
/// <summary>
/// A string like "Unhandled convert: {0}"
/// </summary>
internal static string UnhandledConvert(object p0) => SR.Format(SR.UnhandledConvert, p0);
/// <summary>
/// A string like "Unhandled unary: {0}"
/// </summary>
internal static string UnhandledUnary(object p0) => SR.Format(SR.UnhandledUnary, p0);
/// <summary>
/// A string like "Unknown binding type"
/// </summary>
internal static string UnknownBindingType => SR.UnknownBindingType;
/// <summary>
/// A string like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types."
/// </summary>
internal static string UserDefinedOpMustHaveConsistentTypes(object p0, object p1) => SR.Format(SR.UserDefinedOpMustHaveConsistentTypes, p0, p1);
/// <summary>
/// A string like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type."
/// </summary>
internal static string UserDefinedOpMustHaveValidReturnType(object p0, object p1) => SR.Format(SR.UserDefinedOpMustHaveValidReturnType, p0, p1);
/// <summary>
/// A string like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators."
/// </summary>
internal static string LogicalOperatorMustHaveBooleanOperators(object p0, object p1) => SR.Format(SR.LogicalOperatorMustHaveBooleanOperators, p0, p1);
/// <summary>
/// A string like "No method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static string MethodWithArgsDoesNotExistOnType(object p0, object p1) => SR.Format(SR.MethodWithArgsDoesNotExistOnType, p0, p1);
/// <summary>
/// A string like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. "
/// </summary>
internal static string GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) => SR.Format(SR.GenericMethodWithArgsDoesNotExistOnType, p0, p1);
/// <summary>
/// A string like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static string MethodWithMoreThanOneMatch(object p0, object p1) => SR.Format(SR.MethodWithMoreThanOneMatch, p0, p1);
/// <summary>
/// A string like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static string PropertyWithMoreThanOneMatch(object p0, object p1) => SR.Format(SR.PropertyWithMoreThanOneMatch, p0, p1);
/// <summary>
/// A string like "An incorrect number of type arguments were specified for the declaration of a Func type."
/// </summary>
internal static string IncorrectNumberOfTypeArgsForFunc => SR.IncorrectNumberOfTypeArgsForFunc;
/// <summary>
/// A string like "An incorrect number of type arguments were specified for the declaration of an Action type."
/// </summary>
internal static string IncorrectNumberOfTypeArgsForAction => SR.IncorrectNumberOfTypeArgsForAction;
/// <summary>
/// A string like "Argument type cannot be System.Void."
/// </summary>
internal static string ArgumentCannotBeOfTypeVoid => SR.ArgumentCannotBeOfTypeVoid;
/// <summary>
/// A string like "{0} must be greater than or equal to {1}"
/// </summary>
internal static string OutOfRange(object p0, object p1) => SR.Format(SR.OutOfRange, p0, p1);
/// <summary>
/// A string like "Cannot redefine label '{0}' in an inner block."
/// </summary>
internal static string LabelTargetAlreadyDefined(object p0) => SR.Format(SR.LabelTargetAlreadyDefined, p0);
/// <summary>
/// A string like "Cannot jump to undefined label '{0}'."
/// </summary>
internal static string LabelTargetUndefined(object p0) => SR.Format(SR.LabelTargetUndefined, p0);
/// <summary>
/// A string like "Control cannot leave a finally block."
/// </summary>
internal static string ControlCannotLeaveFinally => SR.ControlCannotLeaveFinally;
/// <summary>
/// A string like "Control cannot leave a filter test."
/// </summary>
internal static string ControlCannotLeaveFilterTest => SR.ControlCannotLeaveFilterTest;
/// <summary>
/// A string like "Cannot jump to ambiguous label '{0}'."
/// </summary>
internal static string AmbiguousJump(object p0) => SR.Format(SR.AmbiguousJump, p0);
/// <summary>
/// A string like "Control cannot enter a try block."
/// </summary>
internal static string ControlCannotEnterTry => SR.ControlCannotEnterTry;
/// <summary>
/// A string like "Control cannot enter an expression--only statements can be jumped into."
/// </summary>
internal static string ControlCannotEnterExpression => SR.ControlCannotEnterExpression;
/// <summary>
/// A string like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values."
/// </summary>
internal static string NonLocalJumpWithValue(object p0) => SR.Format(SR.NonLocalJumpWithValue, p0);
/// <summary>
/// A string like "Extension should have been reduced."
/// </summary>
internal static string ExtensionNotReduced => SR.ExtensionNotReduced;
#if FEATURE_COMPILE_TO_METHODBUILDER
/// <summary>
/// A string like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value."
/// </summary>
internal static string CannotCompileConstant(object p0) => SR.Format(SR.CannotCompileConstant, p0);
/// <summary>
/// A string like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite."
/// </summary>
internal static string CannotCompileDynamic => SR.CannotCompileDynamic;
/// <summary>
/// A string like "MethodBuilder does not have a valid TypeBuilder"
/// </summary>
internal static string MethodBuilderDoesNotHaveTypeBuilder => SR.MethodBuilderDoesNotHaveTypeBuilder;
#endif
/// <summary>
/// A string like "Invalid lvalue for assignment: {0}."
/// </summary>
internal static string InvalidLvalue(object p0) => SR.Format(SR.InvalidLvalue, p0);
/// <summary>
/// A string like "unknown lift type: '{0}'."
/// </summary>
internal static string UnknownLiftType(object p0) => SR.Format(SR.UnknownLiftType, p0);
/// <summary>
/// A string like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined"
/// </summary>
internal static string UndefinedVariable(object p0, object p1, object p2) => SR.Format(SR.UndefinedVariable, p0, p1, p2);
/// <summary>
/// A string like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'"
/// </summary>
internal static string CannotCloseOverByRef(object p0, object p1) => SR.Format(SR.CannotCloseOverByRef, p0, p1);
/// <summary>
/// A string like "Unexpected VarArgs call to method '{0}'"
/// </summary>
internal static string UnexpectedVarArgsCall(object p0) => SR.Format(SR.UnexpectedVarArgsCall, p0);
/// <summary>
/// A string like "Rethrow statement is valid only inside a Catch block."
/// </summary>
internal static string RethrowRequiresCatch => SR.RethrowRequiresCatch;
/// <summary>
/// A string like "Try expression is not allowed inside a filter body."
/// </summary>
internal static string TryNotAllowedInFilter => SR.TryNotAllowedInFilter;
/// <summary>
/// A string like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type."
/// </summary>
internal static string MustRewriteToSameNode(object p0, object p1, object p2) => SR.Format(SR.MustRewriteToSameNode, p0, p1, p2);
/// <summary>
/// A string like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite."
/// </summary>
internal static string MustRewriteChildToSameType(object p0, object p1, object p2) => SR.Format(SR.MustRewriteChildToSameType, p0, p1, p2);
/// <summary>
/// A string like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is intentional, override '{1}' and change it to allow this rewrite."
/// </summary>
internal static string MustRewriteWithoutMethod(object p0, object p1) => SR.Format(SR.MustRewriteWithoutMethod, p0, p1);
/// <summary>
/// A string like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static string TryNotSupportedForMethodsWithRefArgs(object p0) => SR.Format(SR.TryNotSupportedForMethodsWithRefArgs, p0);
/// <summary>
/// A string like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static string TryNotSupportedForValueTypeInstances(object p0) => SR.Format(SR.TryNotSupportedForValueTypeInstances, p0);
/// <summary>
/// A string like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static string TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) => SR.Format(SR.TestValueTypeDoesNotMatchComparisonMethodParameter, p0, p1);
/// <summary>
/// A string like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static string SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) => SR.Format(SR.SwitchValueTypeDoesNotMatchComparisonMethodParameter, p0, p1);
#if FEATURE_COMPILE_TO_METHODBUILDER && FEATURE_PDB_GENERATOR
/// <summary>
/// A string like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod."
/// </summary>
internal static string PdbGeneratorNeedsExpressionCompiler => SR.PdbGeneratorNeedsExpressionCompiler;
#endif
#if FEATURE_COMPILE
/// <summary>
/// A string like "The operator '{0}' is not implemented for type '{1}'"
/// </summary>
internal static string OperatorNotImplementedForType(object p0, object p1) => SR.Format(SR.OperatorNotImplementedForType, p0, p1);
#endif
/// <summary>
/// A string like "The constructor should not be static"
/// </summary>
internal static string NonStaticConstructorRequired => SR.NonStaticConstructorRequired;
/// <summary>
/// A string like "The constructor should not be declared on an abstract class"
/// </summary>
internal static string NonAbstractConstructorRequired => SR.NonAbstractConstructorRequired;
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Ecosim;
using Ecosim.SceneData;
using Ecosim.Render;
public class AnimalMgr : MonoBehaviour, NotifyTerrainChange
{
public class AnimalData
{
public AnimalData (int id, int x, int y)
{
this.id = id;
this.x = x;
this.y = y;
}
public readonly int id;
public int x;
public int y;
public Animal animal;
}
class AnimalCell
{
public AnimalCell (int cx, int cy)
{
this.cx = cx;
this.cy = cy;
animals = new List<AnimalData> ();
}
public readonly int cx;
public readonly int cy;
public bool isVisible = false;
public List<AnimalData> animals;
}
private int cWidth;
private int cHeight;
private AnimalCell[,] cells;
private Scene scene;
public bool editMode = false;
public static AnimalMgr self;
[System.NonSerialized] public bool doRefresh = false;
void Awake ()
{
self = this;
}
void Start ()
{
TerrainMgr.AddListener (this);
}
void Update ()
{
if (this.doRefresh) {
this.doRefresh = false;
Debug.LogWarning ("Forcing Refresh");
this.ForceRefresh ();
Debug.Log ("Refresh finished");
}
}
void OnDestroy ()
{
self = null;
TerrainMgr.RemoveListener (this);
}
public void ForceRefresh()
{
DeleteAnimals ();
TerrainMgr.RemoveListener (this);
SceneChanged (scene);
SuccessionCompleted ();
TerrainMgr.AddListener (this);
}
void DeleteAnimals ()
{
if (cells != null) {
foreach (AnimalCell cell in cells) {
foreach (AnimalData ad in cell.animals) {
if (ad.animal) {
Object.Destroy (ad.animal.gameObject);
ad.animal = null;
}
}
cell.animals.Clear ();
}
}
}
public void SceneChanged (Scene scene)
{
DeleteAnimals ();
cells = null;
this.scene = scene;
if (scene != null) {
if (!editMode && !scene.progression.HasData (Progression.ANIMAL_ID)) {
return; // no animals so don't bother...
}
cWidth = scene.width / TerrainMgr.CELL_SIZE;
cHeight = scene.height / TerrainMgr.CELL_SIZE;
cells = new AnimalCell[cHeight, cWidth];
for (int cy = 0; cy < cHeight; cy++) {
for (int cx = 0; cx < cWidth; cx++) {
cells [cy, cx] = new AnimalCell (cx, cy);
}
}
SuccessionCompleted ();
}
}
public void SuccessionCompleted ()
{
DeleteAnimals ();
if (!scene.progression.HasData (Progression.ANIMAL_ID)) {
return;
}
Data data = scene.progression.GetData (Progression.ANIMAL_ID);
int maxId = EcoTerrainElements.self.animals.Length;
// go over all defined animals
foreach (ValueCoordinate vc in data.EnumerateNotZero ()) {
int x = vc.x;
int y = vc.y;
int id = vc.v - 1;
if (id < maxId) {
// found an animal, id is valid (animal type exists in EcoTerrainElements)
AnimalData ad = new AnimalData (id, x, y);
int cx = x / TerrainMgr.CELL_SIZE;
int cy = y / TerrainMgr.CELL_SIZE;
cells [cy, cx].animals.Add (ad);
}
}
}
public void CellChangedToVisible (int cx, int cy, TerrainCell cell)
{
if (cells == null)
return;
AnimalCell aCell = cells [cy, cx];
aCell.isVisible = true;
foreach (AnimalData ad in aCell.animals) {
if (ad.animal == null) {
// animal needs to be created
CreateAnimal (ad);
}
}
}
public void CellChangedToInvisible (int cx, int cy)
{
if (cells == null)
return;
AnimalCell aCell = cells [cy, cx];
foreach (AnimalData ad in aCell.animals) {
if (ad.animal) {
Object.Destroy (ad.animal.gameObject);
ad.animal = null;
}
}
aCell.isVisible = false;
}
public void RemoveAnimalAt(int x, int y) {
int cx = x / TerrainMgr.CELL_SIZE;
int cy = y / TerrainMgr.CELL_SIZE;
if (isCellVisible(cx, cy)) {
AnimalCell cell = cells[cy, cx];
foreach (AnimalData ad in cell.animals) {
if ((ad.x == x) && (ad.y == y)) {
if (ad.animal) {
Destroy (ad.animal.gameObject);
}
cell.animals.Remove (ad);
break;
}
}
if (scene.progression.HasData (Progression.ANIMAL_ID)) {
Data map = scene.progression.GetData(Progression.ANIMAL_ID);
map.Set (x, y, 0);
}
}
}
public void AddAnimalAt(int id, int x, int y) {
int cx = x / TerrainMgr.CELL_SIZE;
int cy = y / TerrainMgr.CELL_SIZE;
if (isCellVisible(cx, cy)) {
AnimalCell cell = cells[cy, cx];
foreach (AnimalData ad in cell.animals) {
if ((ad.x == x) && (ad.y == y)) {
if (ad.animal) {
Destroy (ad.animal.gameObject);
}
cell.animals.Remove (ad);
break;
}
}
AnimalData newAd = new AnimalData(id, x, y);
cell.animals.Add (newAd);
CreateAnimal (newAd);
Data map;
if (!scene.progression.HasData (Progression.ANIMAL_ID)) {
scene.progression.AddData(Progression.ANIMAL_ID, new SparseBitMap8(scene));
}
map = scene.progression.GetData(Progression.ANIMAL_ID);
map.Set (x, y, id + 1);
}
}
public void CreateAnimal (AnimalData data)
{
EcoTerrainElements.AnimalPrototype[] animalPrototypes = EcoTerrainElements.self.animals;
Vector3 pos = new Vector3 ((0.5f + data.x) * TerrainMgr.TERRAIN_SCALE, 2000f, (0.5f + data.y) * TerrainMgr.TERRAIN_SCALE);
GameObject go = (GameObject)Instantiate (animalPrototypes [data.id].prefab);
go.transform.parent = transform;
go.transform.localPosition = pos;
go.transform.localRotation = Quaternion.Euler (0f, Random.Range (0f, 360f), 0f);
Animal animalScript = go.GetComponent<Animal> ();
animalScript.data = data;
if (editMode) {
go.transform.localScale *= 4f;
}
data.animal = animalScript;
}
public bool isCellVisible(int cx, int cy) {
if ((cx < 0) || (cx >= cWidth) || (cy < 0) || (cy >= cHeight)) {
return false; // outside scene!
}
return cells[cy, cx].isVisible;
}
public void AnimalMovesCell (AnimalData ad, int cx, int cy, int newCx, int newCy)
{
AnimalCell oldCell = cells[cy, cx];
oldCell.animals.Remove (ad);
AnimalCell newCell = cells[newCy, newCx];
newCell.animals.Add (ad);
if (!newCell.isVisible) {
Object.Destroy (ad.animal.gameObject);
ad.animal = null;
}
}
}
| |
// <copyright file="CollectionParser.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using BeanIO.Internal.Util;
namespace BeanIO.Internal.Parser
{
/// <summary>
/// A <see cref="CollectionParser" /> provides iteration support for a <see cref="Segment"/> or <see cref="Field"/>,
/// and is optionally bound to a <see cref="IList{T}"/> type property value.
/// </summary>
internal class CollectionParser : Aggregation
{
/// <summary>
/// the property value
/// </summary>
private readonly ParserLocal<object> _value = new ParserLocal<object>();
/// <summary>
/// Initializes a new instance of the <see cref="CollectionParser"/> class.
/// </summary>
public CollectionParser()
{
ElementType = typeof(object);
}
/// <summary>
/// Gets or sets the array element type
/// </summary>
public Type ElementType { get; set; }
/// <summary>
/// Gets a value indicating whether this aggregation is a property of its parent bean object.
/// </summary>
public override bool IsProperty => PropertyType != null;
/// <summary>
/// Gets the <see cref="IProperty"/> implementation type
/// </summary>
public override PropertyType Type => Internal.Parser.PropertyType.AggregationCollection;
/// <summary>
/// Gets the size of the components that make up a single iteration.
/// </summary>
public override int IterationSize => Size.GetValueOrDefault();
/// <summary>
/// Returns whether this parser and its children match a record being unmarshalled.
/// </summary>
/// <param name="context">The <see cref="UnmarshallingContext"/></param>
/// <returns>true if matched, false otherwise</returns>
public override bool Matches(UnmarshallingContext context)
{
// matching repeating fields is not supported
return true;
}
/// <summary>
/// Returns the length of aggregation
/// </summary>
/// <param name="value">the aggregation value</param>
/// <returns>the length</returns>
public override int Length(object value)
{
var collection = (ICollection)value;
return collection?.Count ?? 0;
}
/// <summary>
/// Creates the property value and returns it
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <returns>the property value</returns>
public override object CreateValue(ParsingContext context)
{
var value = _value.Get(context);
if (value == null)
{
value = CreateCollection();
_value.Set(context, value);
}
return GetValue(context);
}
public override bool Defines(object value)
{
// TODO: implement for arrays....
if (value == null || PropertyType == null)
return false;
if (value is ICollection)
{
// children of collections cannot be used to identify bean objects
// so we can immediately return true here
return true;
}
return false;
}
/// <summary>
/// Clears the current property value.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
public override void ClearValue(ParsingContext context)
{
_value.Set(context, null);
}
/// <summary>
/// Called by a stream to register variables stored in the parsing context.
/// </summary>
/// <remarks>
/// This method should be overridden by subclasses that need to register
/// one or more parser context variables.
/// </remarks>
/// <param name="locals">set of local variables</param>
public override void RegisterLocals(ISet<IParserLocal> locals)
{
if (locals.Add(_value))
base.RegisterLocals(locals);
}
/// <summary>
/// Returns whether this parser or any of its descendant have content for marshalling.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <returns>true if there is content for marshalling, false otherwise</returns>
public override bool HasContent(ParsingContext context)
{
var collection = GetCollection(context);
return collection != null && collection.Count > 0;
}
/// <summary>
/// Returns the unmarshalled property value.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <returns>the property value</returns>
public override object GetValue(ParsingContext context)
{
var value = _value.Get(context);
return value ?? Value.Missing;
}
/// <summary>
/// Sets the property value for marshaling.
/// </summary>
/// <param name="context">The <see cref="ParsingContext"/></param>
/// <param name="value">the property value</param>
public override void SetValue(ParsingContext context, object value)
{
// convert empty collections to null so that parent parsers
// will consider this property missing during marshalling
// ReSharper disable once UseNullPropagation
if (value != null)
{
var list = value.AsList();
if (list.Count == 0)
value = null;
}
_value.Set(context, value);
base.SetValue(context, value);
}
protected override bool Marshal(MarshallingContext context, IParser parser, int minOccurs, int? maxOccurs)
{
context.PushIteration(this);
try
{
var collection = GetCollection(context);
if (collection == null && minOccurs == 0)
return false;
var i = 0;
if (collection != null)
{
foreach (var value in collection)
{
if (maxOccurs != null && i >= maxOccurs)
return true;
SetIterationIndex(context, i);
parser.SetValue(context, value);
parser.Marshal(context);
i += 1;
}
}
if (i < minOccurs)
{
parser.SetValue(context, null);
while (i < minOccurs)
{
SetIterationIndex(context, i);
parser.Marshal(context);
i += 1;
}
}
return true;
}
finally
{
context.PopIteration();
}
}
protected override bool Unmarshal(UnmarshallingContext context, IParser parser, int minOccurs, int? maxOccurs)
{
var collection = IsLazy ? null : CreateCollection();
var invalid = false;
var count = 0;
try
{
context.PushIteration(this);
for (int i = 0; maxOccurs == null || i != maxOccurs; ++i)
{
SetIterationIndex(context, i);
// unmarshal the field
var found = parser.Unmarshal(context);
if (!found)
{
parser.ClearValue(context);
break;
}
// collect the field value and add it to our buffered list
object fieldValue = parser.GetValue(context);
if (ReferenceEquals(fieldValue, Value.Invalid))
{
invalid = true;
}
else if (!ReferenceEquals(fieldValue, Value.Missing))
{
// the field value may still be missing if 'optional' is true on a child segment
if (!IsLazy || StringUtil.HasValue(fieldValue))
{
if (collection == null)
collection = CreateCollection();
if (fieldValue == null)
{
var elementType = collection.GetElementType();
if (elementType.GetTypeInfo().IsPrimitive)
fieldValue = elementType.NewInstance();
}
collection.Add(fieldValue);
}
}
parser.ClearValue(context);
++count;
}
}
finally
{
context.PopIteration();
}
object value;
if (count < minOccurs)
{
context.AddFieldError(Name, null, "minOccurs", minOccurs, maxOccurs);
value = Value.Invalid;
}
else if (invalid)
{
value = Value.Invalid;
}
else
{
value = collection;
}
_value.Set(context, value);
return ReferenceEquals(value, Value.Invalid) || count > 0;
}
protected IList GetCollection(ParsingContext context)
{
var value = _value.Get(context);
if (ReferenceEquals(value, Value.Invalid))
return null;
return value.AsList();
}
protected virtual IList CreateCollection()
{
var propertyTypeInfo = PropertyType.GetTypeInfo();
Type type;
if (propertyTypeInfo.ContainsGenericParameters && !PropertyType.IsConstructedGenericType)
{
Type elementType = ElementType;
var elementTypeInfo = elementType.GetTypeInfo();
if (!elementType.IsConstructedGenericType && elementTypeInfo.ContainsGenericParameters)
elementType = typeof(object);
type = propertyTypeInfo.MakeGenericType(elementType);
}
else
{
type = PropertyType;
}
var result = type.NewInstance();
var resultAsList = result as IList;
if (resultAsList != null)
return resultAsList;
return new SetProxyList((IEnumerable)result);
}
/// <summary>
/// Returns a value indicating whether this iteration contained invalid values when last unmarshalled
/// </summary>
/// <param name="context">the <see cref="ParsingContext"/></param>
/// <returns>true if this iteration contained invalid values</returns>
protected virtual bool IsInvalid(ParsingContext context)
{
return ReferenceEquals(_value.Get(context), Value.Invalid);
}
/// <summary>
/// Called by <see cref="TreeNode{T}.ToString"/> to append node parameters to the output
/// </summary>
/// <param name="s">The output to append</param>
protected override void ToParamString(StringBuilder s)
{
base.ToParamString(s);
if (PropertyType != null)
s.AppendFormat(", type={0}", PropertyType.GetAssemblyQualifiedName());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using System.Threading;
using System.Diagnostics.Tracing;
using SdtEventSources;
namespace BasicEventSourceTests
{
public class TestsWriteEventToListener
{
[Fact]
[ActiveIssue("dotnet/corefx #19462", TargetFrameworkMonikers.NetFramework)]
public void Test_WriteEvent_ArgsBasicTypes()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new EventSourceTest())
{
using (var el = new LoudListener())
{
var sources = EventSource.GetSources();
Assert.True(sources.Contains(log));
Assert.NotNull(EventSource.GenerateManifest(typeof(SimpleEventSource), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration));
Assert.Null(EventSource.GenerateManifest(typeof(EventSourceTest), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration));
log.Event0();
Assert.Equal(1, LoudListener.t_lastEvent.EventId);
Assert.Equal(0, LoudListener.t_lastEvent.Payload.Count);
#region Validate "int" arguments
log.EventI(10);
Assert.Equal(2, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]);
log.EventII(10, 11);
Assert.Equal(3, LoudListener.t_lastEvent.EventId);
Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]);
log.EventIII(10, 11, 12);
Assert.Equal(4, LoudListener.t_lastEvent.EventId);
Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]);
Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]);
#endregion
#region Validate "long" arguments
log.EventL(10);
Assert.Equal(5, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]);
log.EventLL(10, 11);
Assert.Equal(6, LoudListener.t_lastEvent.EventId);
Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]);
log.EventLLL(10, 11, 12);
Assert.Equal(7, LoudListener.t_lastEvent.EventId);
Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]);
Assert.Equal(12, (long)LoudListener.t_lastEvent.Payload[2]);
#endregion
#region Validate "string" arguments
log.EventS("10");
Assert.Equal(8, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]);
log.EventSS("10", "11");
Assert.Equal(9, LoudListener.t_lastEvent.EventId);
Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]);
log.EventSSS("10", "11", "12");
Assert.Equal(10, LoudListener.t_lastEvent.EventId);
Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]);
Assert.Equal("12", (string)LoudListener.t_lastEvent.Payload[2]);
#endregion
#region Validate byte array arguments
byte[] arr = new byte[20];
log.EventWithByteArray(arr);
Assert.Equal(52, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(arr.Length, ((byte[])LoudListener.t_lastEvent.Payload[0]).Length);
#endregion
#region Validate mixed type arguments
log.EventSI("10", 11);
Assert.Equal(11, LoudListener.t_lastEvent.EventId);
Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]);
log.EventSL("10", 11);
Assert.Equal(12, LoudListener.t_lastEvent.EventId);
Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]);
log.EventSII("10", 11, 12);
Assert.Equal(13, LoudListener.t_lastEvent.EventId);
Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]);
Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]);
#endregion
#region Validate enums/flags
log.EventEnum(MyColor.Blue);
Assert.Equal(19, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(MyColor.Blue, (MyColor)LoudListener.t_lastEvent.Payload[0]);
log.EventEnum1(MyColor.Green);
Assert.Equal(20, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(MyColor.Green, (MyColor)LoudListener.t_lastEvent.Payload[0]);
log.EventFlags(MyFlags.Flag1);
Assert.Equal(21, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]);
log.EventFlags1(MyFlags.Flag1);
Assert.Equal(22, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]);
#endregion
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
#region Validate DateTime
DateTime now = DateTime.Now;
log.EventDateTime(now);
Assert.Equal(24, LoudListener.LastEvent.EventId);
Assert.Equal(1, LoudListener.LastEvent.Payload.Count);
Assert.Equal((DateTime)LoudListener.LastEvent.Payload[0], now);
#endregion
#endif // USE_ETW
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
[Fact]
[ActiveIssue("dotnet/corefx #19462", TargetFrameworkMonikers.NetFramework)]
public void Test_WriteEvent_ArgsCornerCases()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new EventSourceTest())
{
using (var el = new LoudListener())
{
// coverage for EventSource.SendCommand()
var options = new Dictionary<string, string>() { { "arg", "val" } };
EventSource.SendCommand(log, EventCommand.SendManifest, options);
Guid guid = Guid.NewGuid();
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
log.EventWithManyTypeArgs("Hello", 0, 0, 0, 'a', 0, 0, 0, 0, (float)10.0, (double)11.0, guid);
Assert.Equal(25, LoudListener.LastEvent.EventId);
Assert.Equal(12, LoudListener.LastEvent.Payload.Count);
Assert.Equal("Hello", (string)LoudListener.LastEvent.Payload[0]);
Assert.Equal(0, (long)LoudListener.LastEvent.Payload[1]);
Assert.Equal((uint)0, (uint)LoudListener.LastEvent.Payload[2]);
Assert.Equal((ulong)0, (ulong)LoudListener.LastEvent.Payload[3]);
Assert.Equal('a', (char)LoudListener.LastEvent.Payload[4]);
Assert.Equal((byte)0, (byte)LoudListener.LastEvent.Payload[5]);
Assert.Equal((sbyte)0, (sbyte)LoudListener.LastEvent.Payload[6]);
Assert.Equal((short)0, (short)LoudListener.LastEvent.Payload[7]);
Assert.Equal((ushort)0, (ushort)LoudListener.LastEvent.Payload[8]);
Assert.Equal((float)10.0, (float)LoudListener.LastEvent.Payload[9]);
Assert.Equal((double)11.0, (double)LoudListener.LastEvent.Payload[10]);
Assert.Equal(guid, (Guid)LoudListener.LastEvent.Payload[11]);
#endif // USE_ETW
log.EventWith7Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6");
Assert.Equal(26, LoudListener.t_lastEvent.EventId);
Assert.Equal(7, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("s0", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal("s6", (string)LoudListener.t_lastEvent.Payload[6]);
log.EventWith9Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8");
Assert.Equal(27, LoudListener.t_lastEvent.EventId);
Assert.Equal(9, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("s0", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal("s8", (string)LoudListener.t_lastEvent.Payload[8]);
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
log.EventWithWeirdArgs(IntPtr.Zero, true, MyLongEnum.LongVal1 /*, 9999999999999999999999999999m*/);
Assert.Equal(30, LoudListener.LastEvent.EventId);
Assert.Equal(3 /*4*/, LoudListener.LastEvent.Payload.Count);
Assert.Equal(IntPtr.Zero, (IntPtr)LoudListener.LastEvent.Payload[0]);
Assert.Equal(true, (bool)LoudListener.LastEvent.Payload[1]);
Assert.Equal(MyLongEnum.LongVal1, (MyLongEnum)LoudListener.LastEvent.Payload[2]);
// Assert.Equal(9999999999999999999999999999m, (decimal)LoudListener.LastEvent.Payload[3]);
#endif // USE_ETW
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
[Fact]
public void Test_WriteEvent_InvalidCalls()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new InvalidCallsToWriteEventEventSource())
{
using (var el = new LoudListener())
{
log.WriteTooManyArgs("Hello");
Assert.Equal(2, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); // Faked count (compat)
Assert.Equal("Hello", LoudListener.t_lastEvent.Payload[0]);
log.WriteTooFewArgs(10, 100);
Assert.Equal(1, LoudListener.t_lastEvent.EventId);
Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); // Real # of args passed to WriteEvent
Assert.Equal(10, LoudListener.t_lastEvent.Payload[0]);
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
[Fact]
public void Test_WriteEvent_ToChannel_Coverage()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var el = new LoudListener())
using (var log = new SimpleEventSource())
{
el.EnableEvents(log, EventLevel.Verbose);
log.WriteIntToAdmin(10);
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
[Fact]
public void Test_WriteEvent_TransferEvents()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new EventSourceTest())
{
using (var el = new LoudListener())
{
Guid actid = Guid.NewGuid();
log.LogTaskScheduled(actid, "Hello from a test");
Assert.Equal(17, LoudListener.LastEvent.EventId);
Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId);
Assert.Equal(1, LoudListener.LastEvent.Payload.Count);
Assert.Equal("Hello from a test", (string)LoudListener.LastEvent.Payload[0]);
actid = Guid.NewGuid();
log.LogTaskScheduledBad(actid, "Hello again");
Assert.Equal(23, LoudListener.LastEvent.EventId);
Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId);
Assert.Equal(1, LoudListener.LastEvent.Payload.Count);
Assert.Equal("Hello again", (string)LoudListener.LastEvent.Payload[0]);
actid = Guid.NewGuid();
Guid guid = Guid.NewGuid();
log.EventWithXferManyTypeArgs(actid, 0, 0, 0, 'a', 0, 0, 0, 0, (float)10.0, (double)11.0, guid);
Assert.Equal(29, LoudListener.LastEvent.EventId);
Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId);
Assert.Equal(11, LoudListener.LastEvent.Payload.Count);
Assert.Equal(0, (long)LoudListener.LastEvent.Payload[0]);
Assert.Equal((uint)0, (uint)LoudListener.LastEvent.Payload[1]);
Assert.Equal((ulong)0, (ulong)LoudListener.LastEvent.Payload[2]);
Assert.Equal('a', (char)LoudListener.LastEvent.Payload[3]);
Assert.Equal((byte)0, (byte)LoudListener.LastEvent.Payload[4]);
Assert.Equal((sbyte)0, (sbyte)LoudListener.LastEvent.Payload[5]);
Assert.Equal((short)0, (short)LoudListener.LastEvent.Payload[6]);
Assert.Equal((ushort)0, (ushort)LoudListener.LastEvent.Payload[7]);
Assert.Equal((float)10.0, (float)LoudListener.LastEvent.Payload[8]);
Assert.Equal((double)11.0, (double)LoudListener.LastEvent.Payload[9]);
Assert.Equal(guid, (Guid)LoudListener.LastEvent.Payload[10]);
actid = Guid.NewGuid();
log.EventWithXferWeirdArgs(actid, IntPtr.Zero, true, MyLongEnum.LongVal1 /*, 9999999999999999999999999999m*/);
Assert.Equal(31, LoudListener.LastEvent.EventId);
Assert.Equal(actid, LoudListener.LastEvent.RelatedActivityId);
Assert.Equal(3 /*4*/, LoudListener.LastEvent.Payload.Count);
Assert.Equal(IntPtr.Zero, (IntPtr)LoudListener.LastEvent.Payload[0]);
Assert.Equal(true, (bool)LoudListener.LastEvent.Payload[1]);
Assert.Equal(MyLongEnum.LongVal1, (MyLongEnum)LoudListener.LastEvent.Payload[2]);
// Assert.Equal(9999999999999999999999999999m, (decimal)LoudListener.LastEvent.Payload[3]);
actid = Guid.NewGuid();
Assert.Throws<EventSourceException>(() => log.LogTransferNoOpcode(actid));
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
#endif // USE_ETW
[Fact]
[ActiveIssue("dotnet/corefx #19462", TargetFrameworkMonikers.NetFramework)]
public void Test_WriteEvent_ZeroKwds()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new EventSourceTest())
{
using (var el = new LoudListener())
{
// match any kwds == 0
el.EnableEvents(log, 0, 0);
// Fire an event without a kwd: EventWithEscapingMessage
// 1. Validate that the event fires when ETW event method called unconditionally
log.EventWithEscapingMessage("Hello world!", 10);
Assert.NotNull(LoudListener.t_lastEvent);
Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("Hello world!", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[1]);
// reset LastEvent
LoudListener.t_lastEvent = null;
// 2. Validate that the event fires when ETW event method call is guarded by IsEnabled
if (log.IsEnabled(EventLevel.Informational, 0))
log.EventWithEscapingMessage("Goodbye skies!", 100);
Assert.NotNull(LoudListener.t_lastEvent);
Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count);
Assert.Equal("Goodbye skies!", (string)LoudListener.t_lastEvent.Payload[0]);
Assert.Equal(100, (int)LoudListener.t_lastEvent.Payload[1]);
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
#if FEATURE_ETLEVENTS
[Fact]
public void Test_EventSourceCreatedEvents_BeforeListener()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
EventSource log = null;
EventSource log2 = null;
EventListenerListener el = null;
try
{
string esName = "EventSourceName_HopefullyUnique";
string esName2 = "EventSourceName_HopefullyUnique2";
bool esNameHit = false;
bool esName2Hit = false;
log = new EventSource(esName);
log2 = new EventSource(esName2);
using (var listener = new EventListenerListener())
{
List<EventSource> eventSourceNotificationsReceived = new List<EventSource>();
listener.EventSourceCreated += (s, a) =>
{
if (a.EventSource.Name.Equals(esName))
{
esNameHit = true;
}
if (a.EventSource.Name.Equals(esName2))
{
esName2Hit = true;
}
};
Thread.Sleep(1000);
Assert.Equal(true, esNameHit);
Assert.Equal(true, esName2Hit);
}
}
finally
{
if (log != null)
{
log.Dispose();
}
if (log2 != null)
{
log2.Dispose();
}
if (el != null)
{
el.Dispose();
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
[Fact]
public void Test_EventSourceCreatedEvents_AfterListener()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
EventSource log = null;
EventSource log2 = null;
EventListenerListener el = null;
try
{
using (var listener = new EventListenerListener())
{
string esName = "EventSourceName_HopefullyUnique";
string esName2 = "EventSourceName_HopefullyUnique2";
bool esNameHit = false;
bool esName2Hit = false;
List<EventSource> eventSourceNotificationsReceived = new List<EventSource>();
listener.EventSourceCreated += (s, a) =>
{
if (a.EventSource.Name.Equals(esName))
{
esNameHit = true;
}
if (a.EventSource.Name.Equals(esName2))
{
esName2Hit = true;
}
};
log = new EventSource(esName);
log2 = new EventSource(esName2);
Thread.Sleep(1000);
Assert.Equal(true, esNameHit);
Assert.Equal(true, esName2Hit);
}
}
finally
{
if (log != null)
{
log.Dispose();
}
if (log2 != null)
{
log2.Dispose();
}
if (el != null)
{
el.Dispose();
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertSByte1()
{
var test = new InsertScalarTest__InsertSByte1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class InsertScalarTest__InsertSByte1
{
private struct TestStruct
{
public Vector128<SByte> _fld;
public SByte _scalarFldData;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
testStruct._scalarFldData = (sbyte)2;
return testStruct;
}
public void RunStructFldScenario(InsertScalarTest__InsertSByte1 testClass)
{
var result = Sse41.Insert(_fld, _scalarFldData, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, _scalarFldData, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data = new SByte[Op1ElementCount];
private static SByte _scalarClsData = (sbyte)2;
private static Vector128<SByte> _clsVar;
private Vector128<SByte> _fld;
private SByte _scalarFldData = (sbyte)2;
private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable;
static InsertScalarTest__InsertSByte1()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public InsertScalarTest__InsertSByte1()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
var result = Sse41.Insert(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr),
(sbyte)2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
SByte localData = (sbyte)2;
SByte* ptr = &localData;
var result = Sse41.Insert(
Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)),
*ptr,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public unsafe void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
SByte localData = (sbyte)2;
SByte* ptr = &localData;
var result = Sse41.Insert(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)),
*ptr,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, *ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr),
(sbyte)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr)),
(sbyte)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<SByte>), typeof(SByte), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr)),
(sbyte)2,
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, (sbyte)2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar,
_scalarClsData,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _scalarClsData,_dataTable.outArrayPtr);
}
public void RunLclVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario));
SByte localData = (sbyte)2;
var firstOp = Unsafe.Read<Vector128<SByte>>(_dataTable.inArrayPtr);
var result = Sse41.Insert(firstOp, localData, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
SByte localData = (sbyte)2;
var firstOp = Sse2.LoadVector128((SByte*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, localData, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
SByte localData = (sbyte)2;
var firstOp = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArrayPtr));
var result = Sse41.Insert(firstOp, localData, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, localData, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertScalarTest__InsertSByte1();
var result = Sse41.Insert(test._fld, test._scalarFldData, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld, _scalarFldData, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _scalarFldData, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld, test._scalarFldData, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, test._scalarFldData, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<SByte> firstOp, SByte scalarData, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray, scalarData, outArray, method);
}
private void ValidateResult(void* firstOp, SByte scalarData, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray, scalarData, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte scalarData, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if ((i == 1 ? result[i] != scalarData : result[i] != firstOp[i]))
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<SByte>(Vector128<SByte><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.IO;
using System.Text;
using Platform.IO;
namespace Platform.Text
{
/// <summary>
/// Provides useful methods for converting text.
/// </summary>
public class TextConversion
{
public static readonly char[] Base32Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
public static readonly char[] Base32AlphabetLowercase = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToLower().ToCharArray();
public static readonly char[] HexValues = "0123456789ABCDEF".ToCharArray();
public static readonly char[] HexValuesLowercase = "0123456789abcdef".ToCharArray();
/// <summary>
/// Decodes a string from an escaped hex string (URL encoded).
/// </summary>
/// <param name="s">The escaped hex encoded string</param>
/// <returns>The deocded string</returns>
public static string FromEscapedHexString(string s)
{
return Uri.UnescapeDataString(s);
}
public static readonly char[] SoundexValues =
{
//A B C D E F G H I J K L M
'0','1','2','3','0','1','2','0','0','2','2','4','5',
//N O P W R S T U V W X Y Z
'5','0','1','2','6','2','3','0','1','0','2','0','2'
};
public static void WriteSoundex(TextWriter writer, string value)
{
var length = 0;
var previousChar = '?';
if (value.Length > 0)
{
writer.Write(value[0]);
for (var i = 1; i < value.Length && length < 4; i++)
{
var currentChar = Char.ToUpper(value[i]);
if (currentChar >= 'A' && currentChar <= 'Z' && currentChar != previousChar)
{
var soundexChar = SoundexValues[currentChar - 'A'];
if (soundexChar != '0')
{
length++;
writer.Write(soundexChar);
}
previousChar = currentChar;
}
}
}
while (length < 4)
{
length++;
writer.Write('0');
}
}
public static string ToSoundex(string value)
{
var previousChar = '?';
var retval = new StringBuilder(4);
if (value.Length > 0)
{
retval.Append(value[0]);
for (var i = 1; i < value.Length && retval.Length < 4; i++)
{
var currentChar = Char.ToUpper(value[i]);
if (currentChar >= 'A' && currentChar <= 'Z' && currentChar != previousChar)
{
var soundexChar = SoundexValues[currentChar - 'A'];
if (soundexChar != '0')
{
retval.Append(soundexChar);
}
previousChar = currentChar;
}
}
}
while (retval.Length < 4)
{
retval.Append('0');
}
return retval.ToString();
}
public static TextWriter WriteUnescapedHexString(StringReader reader, StringWriter writer)
{
int x, y;
var bytes = new byte[1];
var chars = new char[1];
var decoder = Encoding.UTF8.GetDecoder();
while (true)
{
x = reader.Read();
if (x == -1)
{
break;
}
if (x != '%')
{
writer.Write((char)x);
continue;
}
x = reader.Read();
if (x == -1)
{
break;
}
if (!((char)x).IsHexDigit())
{
writer.Write('%');
writer.Write((char)x);
continue;
}
y = reader.Read();
if (y == -1)
{
break;
}
if (!((char)y).IsHexDigit())
{
writer.Write('%');
writer.Write((char)x);
writer.Write((char)y);
}
bytes[0] = (byte)(Int32Utils.FromHexNoCheck((char)x) * 0x10 + Int32Utils.FromHexNoCheck((char)y));
var charcount = decoder.GetChars(bytes, 0, 1, chars, 0);
if (charcount > 0)
{
writer.Write(chars[0]);
}
}
return writer;
}
private static readonly Predicate<char> isAsciiLetterOrDigit = PredicateUtils.Not<char>(CharUtils.IsAsciiLetterOrDigit);
public static string ToEscapedHexString(string s)
{
return ToEscapedHexString(s, isAsciiLetterOrDigit);
}
public static string ToEscapedHexString(string s, string charsToEscape)
{
var builder = new StringBuilder((int)(s.Length * 1.5));
foreach (char c in s)
{
if (c == '%' || charsToEscape.IndexOf(c) >= 0)
{
builder.Append('%');
builder.Append(HexValues[(c & '\x00f0') >> 4]);
builder.Append(HexValues[c & '\x000f']);
}
else
{
builder.Append(c);
}
}
return builder.ToString();
}
public static bool IsStandardUrlEscapedChar(char c)
{
return !IsStandardUrlUnEscapedChar(c);
}
public static bool IsStandardUrlUnEscapedChar(char c)
{
if (c == ' ' || c == '|' || c == '{' || c == '}' || c == '^'
|| c == '<' || c == '>' || c == '"' || c == '\\' || c == '%'
|| c == ';')
{
return false;
}
return ((int)c) >= 21 && ((int)c) <= 126;
}
public static string ToReEscapedHexString(string s, Predicate<char> shouldEscape)
{
var skip = 0;
return ToEscapedHexString
(
s,
context =>
{
if (skip > 0)
{
skip--;
return false;
}
var c = context.Left[context.Right];
if (Uri.IsHexEncoding(context.Left, context.Right))
{
skip = 2;
return false;
}
if (c == '%' || shouldEscape(c))
{
return true;
}
else
{
return false;
}
}
);
}
public static string ToEscapedHexString(string s, Predicate<Pair<string, int>> shouldEscapeChar)
{
var chars = new char[1];
var encoding = Encoding.UTF8;
var builder = new StringBuilder((int)(s.Length * 1.5));
var buffer = new byte[encoding.GetMaxByteCount(1)];
for (var i = 0; i < s.Length; i++)
{
if (shouldEscapeChar(new Pair<string, int>(s, i)))
{
chars[0] = s[i];
var bytecount = encoding.GetBytes(chars, 0, 1, buffer, 0);
for (int j = 0; j < bytecount; j++)
{
builder.Append('%');
builder.Append(HexValues[(buffer[j] & '\x00f0') >> 4]);
builder.Append(HexValues[buffer[j] & '\x000f']);
}
}
else
{
builder.Append(s[i]);
}
}
return builder.ToString();
}
public static string ToEscapedHexString(string s, Predicate<char> shouldEscapeChar)
{
return ToEscapedHexString
(
s,
stringInt => shouldEscapeChar(stringInt.Key[stringInt.Value])
);
}
public static TextWriter WriteEscapedHexString(TextReader reader, TextWriter writer)
{
return WriteEscapedHexString
(
reader,
writer,
isAsciiLetterOrDigit
);
}
public static TextWriter WriteEscapedHexString(TextReader reader, TextWriter writer, Predicate<char> shouldEscapeChar)
{
var chars = new char[1];
var encoding = Encoding.UTF8;
var buffer = new byte[encoding.GetMaxByteCount(1)];
return reader.ConvertAndDump(writer, (c, w) =>
{
if (c == '%' || shouldEscapeChar(c))
{
chars[0] = c;
var bytecount = encoding.GetBytes(chars, 0, 1, buffer, 0);
for (int j = 0; j < bytecount; j++)
{
w.Write('%');
w.Write(HexValues[(buffer[j] & '\x00f0') >> 4]);
w.Write(HexValues[(buffer[j] & '\x00f0') >> 4]);
}
}
else
{
w.Write(c);
}
});
}
public static bool IsHexChar(char c)
{
return (c >= 'A' && c <= 'Z')
|| (c >= 'a' && c <= 'z')
|| (c >= '0' && c <= '9');
}
public static int FromHex(char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
else if (c >= 'A' && c <= 'Z')
{
return c - 'A' + 10;
}
else if (c >= 'a' && c <= 'z')
{
return c - 'a' + 10;
}
else
{
throw new ArgumentException("Not a hex char", "c");
}
}
public static char ToHexChar(long x)
{
if (x > Int32.MaxValue || x < Int32.MinValue)
{
throw new ArgumentException("Not a hex char", "x");
}
return ToHexChar((int)x, false);
}
public static char ToHexChar(short x)
{
return ToHexChar((int)x, false);
}
public static char ToHexChar(byte x)
{
return ToHexChar((int)x, false);
}
public static char ToHexChar(int x)
{
return ToHexChar(x, false);
}
public static char ToHexChar(int x, bool lowercase)
{
return ToHexChar(x, lowercase ? HexValuesLowercase : HexValues);
}
private static char ToHexChar(int x, char[] hexValues)
{
if (x < 0 || x > 16)
{
throw new ArgumentException("Not a hex char", "c");
}
return hexValues[x];
}
public static byte[] FromHexString(string s)
{
var bytes = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
{
int x, y;
if (!IsHexChar(s[i]) || !IsHexChar(s[i + 1]))
{
throw new ArgumentException("Contains invlaid hexadecimal values", "s");
}
try
{
x = FromHex(s[i]);
y = FromHex(s[i + 1]);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
bytes[i / 2] = (byte)((x << 4) | y);
}
return bytes;
}
public static string ToHexString(long value)
{
var bytes = new byte[8];
bytes[7] = (byte)((value) >> 0 & 0xf);
bytes[6] = (byte)((value) >> 8 & 0xf);
bytes[5] = (byte)((value) >> 16 & 0xf);
bytes[4] = (byte)((value) >> 24 & 0xf);
bytes[3] = (byte)((value) >> 32 & 0xf);
bytes[2] = (byte)((value) >> 40 & 0xf);
bytes[1] = (byte)((value) >> 48 & 0xf);
bytes[0] = (byte)((value) >> 56 & 0xf);
return ToHexString(bytes);
}
public static string ToHexString(int value)
{
var bytes = new byte[4];
bytes[2] = (byte)((value >> 0) & 0xf);
bytes[3] = (byte)((value >> 8) & 0xf);
bytes[1] = (byte)((value >> 16) & 0xf);
bytes[0] = (byte)((value >> 24) & 0xf);
return ToHexString(bytes);
}
public static string ToHexString(byte[] bytes)
{
return ToHexString(bytes, false);
}
public static string ToHexString(byte[] bytes, bool lowercase)
{
return ToHexString(bytes, lowercase ? HexValuesLowercase : HexValues);
}
private static string ToHexString(byte[] bytes, char[] hexValues)
{
var builder = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
builder.Append(hexValues[((int)b >> 4)]);
builder.Append(hexValues[((int)b & 15)]);
}
return builder.ToString();
}
public static string ToBase32String(long x)
{
var data = new byte[8];
data[0] = (byte)((x & 0xff));
data[1] = (byte)((x >> 8) & 0xff);
data[2] = (byte)((x >> 16) & 0xff);
data[3] = (byte)((x >> 24) & 0xff);
data[4] = (byte)((x >> 32) & 0xff);
data[5] = (byte)((x >> 40) & 0xff);
data[6] = (byte)((x >> 48) & 0xff);
data[7] = (byte)((x >> 56) & 0xff);
return ToBase32String(data);
}
public static string ToBase32String(int x)
{
var out_block = new char[8];
var b0 = (byte)((x & 0xff));
var b1 = (byte)((x & 0xff00) >> 8);
var b2 = (byte)((x & 0xff0000) >> 16);
var b3 = (byte)((x & 0xff000000) >> 24);
var b4 = 0;
out_block[0] = Base32Alphabet[((b0 & 0xF8) >> 3)];
out_block[1] = Base32Alphabet[((b0 & 0x7) << 2) | ((b1 & 0xc0) >> 6)];
out_block[2] = Base32Alphabet[((b1 & 0x3e) >> 1)];
out_block[3] = Base32Alphabet[((b1 & 0x1) << 4) | ((b2 & 0xf0) >> 4)];
out_block[4] = Base32Alphabet[((b2 & 0xf) << 1) | ((b3 & 0x80) >> 7)];
out_block[5] = Base32Alphabet[((b3 & 0x7c) >> 2)];
out_block[6] = Base32Alphabet[((b3 & 0x3) << 3) | ((b4 & 0xe0) >> 5)];
out_block[7] = Base32Alphabet[((b4 & 0x1f))];
return new string(out_block);
}
public static byte[] FromBase64CharArray(char[] array, int offset, int length)
{
return Convert.FromBase64CharArray(array, offset, length);
}
public static byte[] FromBase64String(string s)
{
return Convert.FromBase64String(s);
}
public static string ToBase64String(byte[] input)
{
return Convert.ToBase64String(input, 0, input.Length);
}
public static string ToBase64String(byte[] input, int offset, int length)
{
return Convert.ToBase64String(input, offset, length);
}
public static int ToBase64CharArray(byte[] input, int offsetIn, int length, char[] outArray, int offsetOut)
{
return Convert.ToBase64CharArray(input, offsetIn, length, outArray, offsetOut);
}
public static int ToBase32CharArray(byte[] input, int offsetIn, int length, char[] outArray, int offsetOut)
{
var value = ToBase32String(input, offsetIn, length);
value.CopyTo(0, outArray, offsetOut, value.Length);
return value.Length;
}
public static string ToBase32String(byte[] input)
{
return ToBase32String(input, 0, input.Length);
}
public static string ToBase32String(byte[] input, int offset, int length)
{
var ex = -1;
byte b0, b1, b2, b3, b4;
var out_block = new char[8];
var buffer = new StringBuilder(input.Length * 2);
for (int i = offset; i < offset + input.Length; i += 5)
{
if (i + 4 < input.Length)
{
b0 = input[i];
b1 = input[i+1];
b2 = input[i+2];
b3 = input[i+3];
b4 = input[i+4];
out_block[0] = Base32Alphabet[((b0 & 0xF8) >> 3)];
out_block[1] = Base32Alphabet[((b0 & 0x7) << 2) | ((b1 & 0xc0) >> 6)];
out_block[2] = Base32Alphabet[((b1 & 0x3e) >> 1)];
out_block[3] = Base32Alphabet[((b1 & 0x1) << 4) | ((b2 & 0xf0) >> 4)];
out_block[4] = Base32Alphabet[((b2 & 0xf) << 1) | ((b3 & 0x80) >> 7)];
out_block[5] = Base32Alphabet[((b3 & 0x7c) >> 2)];
out_block[6] = Base32Alphabet[((b3 & 0x3) << 3) | ((b4 & 0xe0) >> 5)];
out_block[7] = Base32Alphabet[((b4 & 0x1f))];
}
else
{
b0 = b1 = b2 = b3 = b4 = 0;
if (i < input.Length)
{
b0 = input[i];
}
if (i + 1 < input.Length)
{
b1 = input[i+1];
}
if (i + 2 < input.Length)
{
b2 = input[i+2];
}
if (i + 3 < input.Length)
{
b3 = input[i+3];
}
if (i + 4 < input.Length)
{
b4 = input[i+4];
}
out_block[0] = Base32Alphabet[((b0 & 0xF8) >> 3)];
out_block[1] = Base32Alphabet[((b0 & 0x7) << 2) | ((b1 & 0xc0) >> 6)];
if (i + 1 >= input.Length)
{
ex = 2;
goto end;
}
out_block[2] = Base32Alphabet[((b1 & 0x3e) >> 1)];
out_block[3] = Base32Alphabet[((b1 & 0x1) << 4) | ((b2 & 0xf0) >> 4)];
if (i + 2 >= input.Length)
{
ex = 4;
goto end;
}
out_block[4] = Base32Alphabet[((b2 & 0xf) << 1) | ((b3 & 0x80) >> 7)];
if (i + 3 >= input.Length)
{
ex = 5;
goto end;
}
out_block[5] = Base32Alphabet[((b3 & 0x7c) >> 2)];
out_block[6] = Base32Alphabet[((b3 & 0x3) << 3) | ((b4 & 0xe0) >> 5)];
if (i + 4 >= input.Length)
{
ex = 7;
goto end;
}
out_block[7] = Base32Alphabet[((b4 & 0x1f))];
}
end:
if (ex > -1)
{
for (int j = ex; j < out_block.Length; j++)
{
out_block[j] = '=';
}
}
ex = -1;
buffer.Append(out_block);
}
return buffer.ToString();
}
}
}
| |
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using NMock2.Internal;
namespace NMock2.Monitoring
{
/// <summary>
/// Summary description for MockObjectFactory.
/// </summary>
internal class MockObjectFactory
{
private static readonly Hashtable createdTypes = new Hashtable();
private readonly ModuleBuilder moduleBuilder;
private class TypeId
{
private readonly Type[] types;
public TypeId(params Type[] types)
{
this.types = types;
}
private bool ContainsSameTypesAs(TypeId other)
{
if (other.types.Length !=
types.Length)
{
return false;
}
for (int num1 = 0; num1 < types.Length; num1++)
{
if (Array.IndexOf(other.types, types[num1]) < 0)
{
return false;
}
}
return true;
}
public override bool Equals(object obj)
{
return ((obj is TypeId) && ContainsSameTypesAs((TypeId) obj));
}
public override int GetHashCode()
{
int num1 = 0;
foreach (Type type1 in types)
{
num1 ^= type1.GetHashCode();
}
return num1;
}
}
public MockObjectFactory(string name)
{
AssemblyName name1 = new AssemblyName();
name1.Name = name;
moduleBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
name1, AssemblyBuilderAccess.Run).DefineDynamicModule(name);
}
private static bool AllTypes(Type type, object criteria)
{
return true;
}
private static void BuildAllInterfaceMethods(
Type mockedType, TypeBuilder typeBuilder)
{
Type[] typeArray1 = mockedType.FindInterfaces(new TypeFilter(AllTypes), null);
foreach (Type type1 in typeArray1)
{
BuildInterfaceMethods(typeBuilder, type1);
}
BuildInterfaceMethods(typeBuilder, mockedType);
}
private static void BuildConstructor(TypeBuilder typeBuilder)
{
Type[] typeArray1 =
new Type[] {typeof (Mockery), typeof (Type), typeof (string)};
ILGenerator generator1 =
typeBuilder.DefineConstructor(
MethodAttributes.Public, CallingConventions.HasThis, typeArray1).
GetILGenerator();
ConstructorInfo info1 =
typeof (MockObject).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance, null, typeArray1, null);
generator1.Emit(OpCodes.Ldarg_0);
generator1.Emit(OpCodes.Ldarg_1);
generator1.Emit(OpCodes.Ldarg_2);
generator1.Emit(OpCodes.Ldarg_3);
generator1.Emit(OpCodes.Call, info1);
generator1.Emit(OpCodes.Ret);
}
private static void BuildInterfaceMethods(
TypeBuilder typeBuilder, Type mockedType)
{
typeBuilder.AddInterfaceImplementation(mockedType);
MethodInfo[] infoArray1 = mockedType.GetMethods();
foreach (MethodInfo info1 in infoArray1)
{
GenerateMethodBody(typeBuilder, info1);
}
}
public MockObject CreateMockObject(
Mockery mockery, Type mockedType, string name)
{
return
(Activator.CreateInstance(
GetMockedType(
Id(new Type[] {mockedType, typeof (IMockObject)}), mockedType),
new object[] {mockery, mockedType, name})
as MockObject);
}
private Type GetMockedType(TypeId id1, Type mockedType)
{
Type type1;
if (createdTypes.ContainsKey(id1))
{
type1 = (Type) createdTypes[id1];
}
else
{
createdTypes[id1] =
type1 = CreateType("MockObjectType" + (createdTypes.Count + 1), mockedType);
}
return type1;
}
private Type CreateType(string typeName, Type mockedType)
{
TypeBuilder builder1 =
moduleBuilder.DefineType(
typeName,
TypeAttributes.Public,
typeof (MockObject),
new Type[] {mockedType});
BuildConstructor(builder1);
BuildAllInterfaceMethods(mockedType, builder1);
return builder1.CreateType();
}
private static void EmitReferenceMethodBody(ILGenerator gen)
{
gen.Emit(OpCodes.Ldnull);
gen.Emit(OpCodes.Ret);
}
private static void EmitValueMethodBody(MethodInfo method, ILGenerator gen)
{
gen.DeclareLocal(method.ReturnType);
gen.Emit(OpCodes.Ldloc_0);
gen.Emit(OpCodes.Ret);
}
private static void GenerateMethodBody(
TypeBuilder typeBuilder, MethodInfo method)
{
ILGenerator generator1 = PrepareMethodGenerator(typeBuilder, method);
generator1.Emit(OpCodes.Ldarg_0);
if (method.ReturnType == null)
{
generator1.Emit(OpCodes.Ret);
}
if (method.ReturnType.IsValueType)
{
EmitValueMethodBody(method, generator1);
}
else
{
EmitReferenceMethodBody(generator1);
}
}
private static TypeId Id(params Type[] types)
{
return new TypeId(types);
}
private static ILGenerator PrepareMethodGenerator(
TypeBuilder typeBuilder, MethodInfo method)
{
ParameterInfo[] infoArray1 = method.GetParameters();
Type[] typeArray1 = new Type[infoArray1.Length];
for (int num1 = 0; num1 < infoArray1.Length; num1++)
{
typeArray1[num1] = infoArray1[num1].ParameterType;
}
MethodBuilder builder1 =
typeBuilder.DefineMethod(
method.Name,
MethodAttributes.Virtual | MethodAttributes.Public,
method.CallingConvention,
method.ReturnType,
typeArray1);
builder1.InitLocals = true;
typeBuilder.DefineMethodOverride(builder1, method);
return builder1.GetILGenerator();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using GraphQL.Language.AST;
using GraphQL.Types;
using GraphQL.Utilities;
namespace GraphQL
{
public static class GraphQLExtensions
{
public static string TrimGraphQLTypes(this string name)
{
return Regex.Replace(name, "[\\[!\\]]", "").Trim();
}
public static bool IsCompositeType(this IGraphType type)
{
return type is IObjectGraphType ||
type is IInterfaceGraphType ||
type is UnionGraphType;
}
public static bool IsLeafType(this IGraphType type)
{
var namedType = type.GetNamedType();
return namedType is ScalarGraphType || namedType is EnumerationGraphType;
}
public static bool IsInputType(this IGraphType type)
{
var namedType = type.GetNamedType();
return namedType is ScalarGraphType ||
namedType is EnumerationGraphType ||
namedType is InputObjectGraphType;
}
public static IGraphType GetNamedType(this IGraphType type)
{
IGraphType unmodifiedType = type;
if (type is NonNullGraphType)
{
var nonNull = (NonNullGraphType) type;
return GetNamedType(nonNull.ResolvedType);
}
if (type is ListGraphType)
{
var list = (ListGraphType) type;
return GetNamedType(list.ResolvedType);
}
return unmodifiedType;
}
public static IGraphType BuildNamedType(this Type type, Func<Type, IGraphType> resolve = null)
{
if (resolve == null)
{
resolve = t => (IGraphType) Activator.CreateInstance(t);
}
if (type.GetTypeInfo().IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(NonNullGraphType<>))
{
var nonNull = (NonNullGraphType)Activator.CreateInstance(type);
nonNull.ResolvedType = BuildNamedType(type.GenericTypeArguments[0], resolve);
return nonNull;
}
if (type.GetGenericTypeDefinition() == typeof(ListGraphType<>))
{
var list = (ListGraphType)Activator.CreateInstance(type);
list.ResolvedType = BuildNamedType(type.GenericTypeArguments[0], resolve);
return list;
}
}
return resolve(type);
}
public static Type GetNamedType(this Type type)
{
if (type.GetTypeInfo().IsGenericType
&& (type.GetGenericTypeDefinition() == typeof(NonNullGraphType<>) ||
type.GetGenericTypeDefinition() == typeof(ListGraphType<>)))
{
return GetNamedType(type.GenericTypeArguments[0]);
}
return type;
}
public static IEnumerable<string> IsValidLiteralValue(this IGraphType type, IValue valueAst, ISchema schema)
{
if (type is NonNullGraphType)
{
var nonNull = (NonNullGraphType) type;
var ofType = nonNull.ResolvedType;
if (valueAst == null)
{
if (ofType != null)
{
return new[] { $"Expected \"{ofType.Name}!\", found null."};
}
return new[] { "Expected non-null value, found null"};
}
return IsValidLiteralValue(ofType, valueAst, schema);
}
if (valueAst == null)
{
return new string[] {};
}
// This function only tests literals, and assumes variables will provide
// values of the correct type.
if (valueAst is VariableReference)
{
return new string[] {};
}
if (type is ListGraphType)
{
var list = (ListGraphType)type;
var ofType = list.ResolvedType;
if (valueAst is ListValue)
{
var index = 0;
return ((ListValue) valueAst).Values.Aggregate(new string[] {}, (acc, value) =>
{
var errors = IsValidLiteralValue(ofType, value, schema);
var result = acc.Concat(errors.Map(err => $"In element #{index}: {err}")).ToArray();
index++;
return result;
});
}
return IsValidLiteralValue(ofType, valueAst, schema);
}
if (type is InputObjectGraphType)
{
if (!(valueAst is ObjectValue))
{
return new[] {$"Expected \"{type.Name}\", found not an object."};
}
var inputType = (InputObjectGraphType) type;
var fields = inputType.Fields.ToList();
var fieldAsts = ((ObjectValue) valueAst).ObjectFields.ToList();
var errors = new List<string>();
// ensure every provided field is defined
fieldAsts.Apply(providedFieldAst =>
{
var found = fields.FirstOrDefault(x => x.Name == providedFieldAst.Name);
if (found == null)
{
errors.Add($"In field \"{providedFieldAst.Name}\": Unknown field.");
}
});
// ensure every defined field is valid
fields.Apply(field =>
{
var fieldAst = fieldAsts.FirstOrDefault(x => x.Name == field.Name);
var result = IsValidLiteralValue(field.ResolvedType, fieldAst?.Value, schema);
errors.AddRange(result.Map(err=> $"In field \"{field.Name}\": {err}"));
});
return errors;
}
var scalar = (ScalarGraphType) type;
var parseResult = scalar.ParseLiteral(valueAst);
if (parseResult == null)
{
return new [] {$"Expected type \"{type.Name}\", found {AstPrinter.Print(valueAst)}."};
}
return new string[] {};
}
public static string NameOf<T, P>(this Expression<Func<T, P>> expression)
{
var member = (MemberExpression) expression.Body;
return member.Member.Name;
}
/// <summary>
/// Provided a type and a super type, return true if the first type is either
/// equal or a subset of the second super type (covariant).
/// </summary>
public static bool IsSubtypeOf(this IGraphType maybeSubType, IGraphType superType, ISchema schema)
{
if (maybeSubType.Equals(superType))
{
return true;
}
// If superType is non-null, maybeSubType must also be nullable.
if (superType is NonNullGraphType)
{
if (maybeSubType is NonNullGraphType)
{
var sub = (NonNullGraphType) maybeSubType;
var sup = (NonNullGraphType) superType;
return IsSubtypeOf(sub.ResolvedType, sup.ResolvedType, schema);
}
return false;
}
else if (maybeSubType is NonNullGraphType)
{
var sub = (NonNullGraphType) maybeSubType;
return IsSubtypeOf(sub.ResolvedType, superType, schema);
}
// If superType type is a list, maybeSubType type must also be a list.
if (superType is ListGraphType)
{
if (maybeSubType is ListGraphType)
{
var sub = (ListGraphType) maybeSubType;
var sup = (ListGraphType) superType;
return IsSubtypeOf(sub.ResolvedType, sup.ResolvedType, schema);
}
return false;
}
else if (maybeSubType is ListGraphType)
{
// If superType is not a list, maybeSubType must also be not a list.
return false;
}
// If superType type is an abstract type, maybeSubType type may be a currently
// possible object type.
if (superType is IAbstractGraphType &&
maybeSubType is IObjectGraphType)
{
return ((IAbstractGraphType) superType).IsPossibleType(maybeSubType);
}
return false;
}
/// <summary>
/// Provided two composite types, determine if they "overlap". Two composite
/// types overlap when the Sets of possible concrete types for each intersect.
///
/// This is often used to determine if a fragment of a given type could possibly
/// be visited in a context of another type.
///
/// This function is commutative.
/// </summary>
public static bool DoTypesOverlap(this ISchema schema, IGraphType typeA, IGraphType typeB)
{
if (typeA.Equals(typeB))
{
return true;
}
var a = typeA as IAbstractGraphType;
var b = typeB as IAbstractGraphType;
if (a != null)
{
if (b != null)
{
return a.PossibleTypes.Any(type => b.IsPossibleType(type));
}
return a.IsPossibleType(typeB);
}
if (b != null)
{
return b.IsPossibleType(typeA);
}
return false;
}
public static IValue AstFromValue(this object value, ISchema schema, IGraphType type)
{
if (type is NonNullGraphType)
{
var nonnull = (NonNullGraphType)type;
return AstFromValue(value, schema, nonnull.ResolvedType);
}
if (value == null || type == null)
{
return null;
}
// Convert IEnumerable to GraphQL list. If the GraphQLType is a list, but
// the value is not an IEnumerable, convert the value using the list's item type.
if (type is ListGraphType)
{
var listType = (ListGraphType) type;
var itemType = listType.ResolvedType;
if (!(value is string) && value is IEnumerable)
{
var list = (IEnumerable)value;
var values = list.Map(item => AstFromValue(item, schema, itemType));
return new ListValue(values);
}
return AstFromValue(value, schema, itemType);
}
// Populate the fields of the input object by creating ASTs from each value
// in the dictionary according to the fields in the input type.
if (type is InputObjectGraphType)
{
if (!(value is Dictionary<string, object>))
{
return null;
}
var input = (InputObjectGraphType) type;
var dict = (Dictionary<string, object>)value;
var fields = dict
.Select(pair =>
{
var field = input.Fields.FirstOrDefault(x => x.Name == pair.Key);
var fieldType = field?.ResolvedType;
return new ObjectField(pair.Key, AstFromValue(pair.Value, schema, fieldType));
})
.ToList();
return new ObjectValue(fields);
}
Invariant.Check(
type.IsInputType(),
$"Must provide Input Type, cannot use: {type}");
var inputType = type as ScalarGraphType;
// Since value is an internally represented value, it must be serialized
// to an externally represented value before converting into an AST.
var serialized = inputType.Serialize(value);
if (serialized == null)
{
return null;
}
if (serialized is bool)
{
return new BooleanValue((bool)serialized);
}
if (serialized is int)
{
return new IntValue((int)serialized);
}
if (serialized is long)
{
return new LongValue((long)serialized);
}
if (serialized is double)
{
return new FloatValue((double)serialized);
}
if (serialized is DateTime)
{
return new DateTimeValue((DateTime)serialized);
}
if (serialized is string)
{
if (type is EnumerationGraphType)
{
return new EnumValue(serialized.ToString());
}
return new StringValue(serialized.ToString());
}
throw new ExecutionError($"Cannot convert value to AST: {serialized}");
}
}
}
| |
// 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.Contracts;
using System.Linq;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Extensions.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Writers.CSharp
{
public partial class CSDeclarationWriter
{
private void WriteMethodDefinition(IMethodDefinition method)
{
if (method.IsPropertyOrEventAccessor())
return;
WriteMethodPseudoCustomAttributes(method);
WriteAttributes(method.Attributes);
WriteAttributes(method.SecurityAttributes);
if (method.IsDestructor())
{
// If platformNotSupportedExceptionMessage is != null we're generating a dummy assembly which means we don't need a destructor at all.
if(_platformNotSupportedExceptionMessage == null)
WriteDestructor(method);
return;
}
string name = method.GetMethodName();
if (!method.ContainingTypeDefinition.IsInterface)
{
if (!method.IsExplicitInterfaceMethod()) WriteVisibility(method.Visibility);
WriteMethodModifiers(method);
}
WriteInterfaceMethodModifiers(method);
WriteMethodDefinitionSignature(method, name);
WriteMethodBody(method);
}
private void WriteDestructor(IMethodDefinition method)
{
WriteSymbol("~");
WriteIdentifier(((INamedEntity)method.ContainingTypeDefinition).Name);
WriteSymbol("(");
WriteSymbol(")", false);
WriteEmptyBody();
}
private void WriteTypeName(ITypeReference type, ITypeReference containingType, bool isDynamic = false)
{
var useKeywords = containingType.GetTypeName() != type.GetTypeName();
WriteTypeName(type, isDynamic: isDynamic, useTypeKeywords: useKeywords);
}
private void WriteMethodDefinitionSignature(IMethodDefinition method, string name)
{
bool isOperator = method.IsConversionOperator();
if (!isOperator && !method.IsConstructor)
{
WriteAttributes(method.ReturnValueAttributes, true);
if (method.ReturnValueIsByRef)
{
WriteKeyword("ref");
if (method.ReturnValueAttributes.HasIsReadOnlyAttribute())
WriteKeyword("readonly");
}
// We are ignoring custom modifiers right now, we might need to add them later.
WriteTypeName(method.Type, method.ContainingType, isDynamic: IsDynamic(method.ReturnValueAttributes));
}
if (method.IsExplicitInterfaceMethod() && _forCompilationIncludeGlobalprefix)
Write("global::");
WriteIdentifier(name);
if (isOperator)
{
WriteSpace();
WriteTypeName(method.Type, method.ContainingType);
}
Contract.Assert(!(method is IGenericMethodInstance), "Currently don't support generic method instances");
if (method.IsGeneric)
WriteGenericParameters(method.GenericParameters);
WriteParameters(method.Parameters, method.ContainingType, extensionMethod: method.IsExtensionMethod(), acceptsExtraArguments: method.AcceptsExtraArguments);
if (method.IsGeneric && !method.IsOverride() && !method.IsExplicitInterfaceMethod())
WriteGenericContraints(method.GenericParameters);
}
private void WriteParameters(IEnumerable<IParameterDefinition> parameters, ITypeReference containingType, bool property = false, bool extensionMethod = false, bool acceptsExtraArguments = false)
{
string start = property ? "[" : "(";
string end = property ? "]" : ")";
WriteSymbol(start);
_writer.WriteList(parameters, p =>
{
WriteParameter(p, containingType, extensionMethod);
extensionMethod = false;
});
if (acceptsExtraArguments)
{
if (parameters.Any())
_writer.WriteSymbol(",");
_writer.WriteSpace();
_writer.Write("__arglist");
}
WriteSymbol(end);
}
private void WriteParameter(IParameterDefinition parameter, ITypeReference containingType, bool extensionMethod)
{
WriteAttributes(parameter.Attributes, true);
if (extensionMethod)
WriteKeyword("this");
if (parameter.IsParameterArray)
WriteKeyword("params");
if (parameter.IsOut && !parameter.IsIn && parameter.IsByReference)
{
WriteKeyword("out");
}
else
{
// For In/Out we should not emit them until we find a scenario that is needs thems.
//if (parameter.IsIn)
// WriteFakeAttribute("System.Runtime.InteropServices.In", writeInline: true);
//if (parameter.IsOut)
// WriteFakeAttribute("System.Runtime.InteropServices.Out", writeInline: true);
if (parameter.IsByReference)
{
if (parameter.Attributes.HasIsReadOnlyAttribute())
{
WriteKeyword("in");
}
else
{
WriteKeyword("ref");
}
}
}
WriteTypeName(parameter.Type, containingType, isDynamic: IsDynamic(parameter.Attributes));
WriteIdentifier(parameter.Name);
if (parameter.IsOptional && parameter.HasDefaultValue)
{
WriteSymbol(" = ");
WriteMetadataConstant(parameter.DefaultValue, parameter.Type);
}
}
private void WriteInterfaceMethodModifiers(IMethodDefinition method)
{
if (method.GetHiddenBaseMethod(_filter) != Dummy.Method)
WriteKeyword("new");
}
private void WriteMethodModifiers(IMethodDefinition method)
{
if (method.IsMethodUnsafe())
WriteKeyword("unsafe");
if (method.IsStatic)
WriteKeyword("static");
if (method.IsPlatformInvoke)
WriteKeyword("extern");
if (method.IsVirtual)
{
if (method.IsNewSlot)
{
if (method.IsAbstract)
WriteKeyword("abstract");
else if (!method.IsSealed) // non-virtual interfaces implementations are sealed virtual newslots
WriteKeyword("virtual");
}
else
{
if (method.IsAbstract)
WriteKeyword("abstract");
else if (method.IsSealed)
WriteKeyword("sealed");
WriteKeyword("override");
}
}
}
private void WriteMethodBody(IMethodDefinition method)
{
if (method.IsAbstract || !_forCompilation || method.IsPlatformInvoke)
{
WriteSymbol(";");
return;
}
if (method.IsConstructor)
WriteBaseConstructorCall(method.ContainingTypeDefinition);
// Write Dummy Body
WriteSpace();
WriteSymbol("{", true);
if (_platformNotSupportedExceptionMessage != null && !method.IsDispose())
{
Write("throw new ");
if (_forCompilationIncludeGlobalprefix)
Write("global::");
Write("System.PlatformNotSupportedException(");
if (_platformNotSupportedExceptionMessage.StartsWith("SR."))
{
if (_forCompilationIncludeGlobalprefix)
Write("global::");
Write($"System.{ _platformNotSupportedExceptionMessage}");
}
else if (_platformNotSupportedExceptionMessage.Length > 0)
Write($"\"{_platformNotSupportedExceptionMessage}\"");
Write(");");
}
else if (NeedsMethodBodyForCompilation(method))
{
Write("throw null; ");
}
WriteSymbol("}");
}
private bool NeedsMethodBodyForCompilation(IMethodDefinition method)
{
// Structs cannot have empty constructors so we need a body
if (method.ContainingTypeDefinition.IsValueType && method.IsConstructor)
return true;
// Compiler requires out parameters to be initialized
if (method.Parameters.Any(p => p.IsOut))
return true;
// For non-void returning methods we need a body.
if (!TypeHelper.TypesAreEquivalent(method.Type, method.ContainingTypeDefinition.PlatformType.SystemVoid))
return true;
return false;
}
private void WritePrivateConstructor(ITypeDefinition type)
{
if (!_forCompilation ||
type.IsInterface ||
type.IsEnum ||
type.IsDelegate ||
type.IsValueType ||
type.IsStatic)
return;
WriteVisibility(TypeMemberVisibility.Assembly);
WriteIdentifier(((INamedEntity)type).Name);
WriteSymbol("(");
WriteSymbol(")");
WriteBaseConstructorCall(type);
WriteEmptyBody();
}
private void WriteBaseConstructorCall(ITypeDefinition type)
{
if (!_forCompilation)
return;
ITypeDefinition baseType = type.BaseClasses.FirstOrDefault().GetDefinitionOrNull();
if (baseType == null)
return;
var ctors = baseType.Methods.Where(m => m.IsConstructor && _filter.Include(m) && !m.Attributes.Any(a => a.IsObsoleteWithUsageTreatedAsCompilationError()));
var defaultCtor = ctors.Where(c => c.ParameterCount == 0);
// Don't need a base call if we have a default constructor
if (defaultCtor.Any())
return;
var ctor = ctors.FirstOrDefault();
if (ctor == null)
return;
WriteSpace();
WriteSymbol(":", true);
WriteKeyword("base");
WriteSymbol("(");
_writer.WriteList(ctor.Parameters, p => WriteDefaultOf(p.Type));
WriteSymbol(")");
}
private void WriteEmptyBody()
{
if (!_forCompilation)
{
WriteSymbol(";");
}
else
{
WriteSpace();
WriteSymbol("{", true);
WriteSymbol("}");
}
}
private void WriteDefaultOf(ITypeReference type)
{
WriteKeyword("default", true);
WriteSymbol("(");
WriteTypeName(type, true);
WriteSymbol(")");
}
public static IDefinition GetDummyConstructor(ITypeDefinition type)
{
return new DummyInternalConstructor() { ContainingType = type };
}
private class DummyInternalConstructor : IDefinition
{
public ITypeDefinition ContainingType { get; set; }
public IEnumerable<ICustomAttribute> Attributes
{
get { throw new System.NotImplementedException(); }
}
public void Dispatch(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
public IEnumerable<ILocation> Locations
{
get { throw new System.NotImplementedException(); }
}
public void DispatchAsReference(IMetadataVisitor visitor)
{
throw new System.NotImplementedException();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Xml.Serialization;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.ApplicationPlugins.Rest.Regions
{
public partial class RestRegionPlugin : RestPlugin
{
#region GET methods
public string GetHandler(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// foreach (string h in httpRequest.Headers.AllKeys)
// foreach (string v in httpRequest.Headers.GetValues(h))
// m_log.DebugFormat("{0} IsGod: {1} -> {2}", MsgID, h, v);
MsgID = RequestID;
m_log.DebugFormat("{0} GET path {1} param {2}", MsgID, path, param);
try
{
// param empty: regions list
if (String.IsNullOrEmpty(param)) return GetHandlerRegions(httpResponse);
// param not empty: specific region
return GetHandlerRegion(httpResponse, param);
}
catch (Exception e)
{
return Failure(httpResponse, OSHttpStatusCode.ServerErrorInternalError, "GET", e);
}
}
public string GetHandlerRegions(OSHttpResponse httpResponse)
{
RestXmlWriter rxw = new RestXmlWriter(new StringWriter());
rxw.WriteStartElement(String.Empty, "regions", String.Empty);
foreach (Scene s in App.SceneManager.Scenes)
{
rxw.WriteStartElement(String.Empty, "uuid", String.Empty);
rxw.WriteString(s.RegionInfo.RegionID.ToString());
rxw.WriteEndElement();
}
rxw.WriteEndElement();
return rxw.ToString();
}
protected string ShortRegionInfo(string key, string value)
{
RestXmlWriter rxw = new RestXmlWriter(new StringWriter());
if (String.IsNullOrEmpty(value) ||
String.IsNullOrEmpty(key)) return null;
rxw.WriteStartElement(String.Empty, "region", String.Empty);
rxw.WriteStartElement(String.Empty, key, String.Empty);
rxw.WriteString(value);
rxw.WriteEndDocument();
return rxw.ToString();
}
public string GetHandlerRegion(OSHttpResponse httpResponse, string param)
{
// be resilient and don't get confused by a terminating '/'
param = param.TrimEnd(new char[]{'/'});
string[] comps = param.Split('/');
UUID regionID = (UUID)comps[0];
m_log.DebugFormat("{0} GET region UUID {1}", MsgID, regionID.ToString());
if (UUID.Zero == regionID) throw new Exception("missing region ID");
Scene scene = null;
App.SceneManager.TryGetScene(regionID, out scene);
if (null == scene) return Failure(httpResponse, OSHttpStatusCode.ClientErrorNotFound,
"GET", "cannot find region {0}", regionID.ToString());
RegionDetails details = new RegionDetails(scene.RegionInfo);
// m_log.DebugFormat("{0} GET comps {1}", MsgID, comps.Length);
// for (int i = 0; i < comps.Length; i++) m_log.DebugFormat("{0} GET comps[{1}] >{2}<", MsgID, i, comps[i]);
if (1 == comps.Length)
{
// complete region details requested
RestXmlWriter rxw = new RestXmlWriter(new StringWriter());
XmlSerializer xs = new XmlSerializer(typeof(RegionDetails));
xs.Serialize(rxw, details, _xmlNs);
return rxw.ToString();
}
if (2 == comps.Length)
{
string resp = ShortRegionInfo(comps[1], details[comps[1]]);
if (null != resp) return resp;
// m_log.DebugFormat("{0} GET comps advanced: >{1}<", MsgID, comps[1]);
// check for {terrain,stats,prims}
switch (comps[1].ToLower())
{
case "terrain":
return RegionTerrain(httpResponse, scene);
case "stats":
return RegionStats(httpResponse, scene);
case "prims":
return RegionPrims(httpResponse, scene, Vector3.Zero, Vector3.Zero);
}
}
if (3 == comps.Length)
{
switch (comps[1].ToLower())
{
case "prims":
string[] subregion = comps[2].Split(',');
if (subregion.Length == 6)
{
Vector3 min, max;
try
{
min = new Vector3((float)Double.Parse(subregion[0], Culture.NumberFormatInfo), (float)Double.Parse(subregion[1], Culture.NumberFormatInfo), (float)Double.Parse(subregion[2], Culture.NumberFormatInfo));
max = new Vector3((float)Double.Parse(subregion[3], Culture.NumberFormatInfo), (float)Double.Parse(subregion[4], Culture.NumberFormatInfo), (float)Double.Parse(subregion[5], Culture.NumberFormatInfo));
}
catch (Exception)
{
return Failure(httpResponse, OSHttpStatusCode.ClientErrorBadRequest,
"GET", "invalid subregion parameter");
}
return RegionPrims(httpResponse, scene, min, max);
}
else
{
return Failure(httpResponse, OSHttpStatusCode.ClientErrorBadRequest,
"GET", "invalid subregion parameter");
}
}
}
return Failure(httpResponse, OSHttpStatusCode.ClientErrorBadRequest,
"GET", "too many parameters {0}", param);
}
#endregion GET methods
protected string RegionTerrain(OSHttpResponse httpResponse, Scene scene)
{
httpResponse.SendChunked = true;
httpResponse.ContentType = "text/xml";
return scene.Heightmap.SaveToXmlString();
//return Failure(httpResponse, OSHttpStatusCode.ServerErrorNotImplemented,
// "GET", "terrain not implemented");
}
protected string RegionStats(OSHttpResponse httpResponse, Scene scene)
{
int users = scene.GetRootAgentCount();
int objects = scene.Entities.Count - users;
RestXmlWriter rxw = new RestXmlWriter(new StringWriter());
rxw.WriteStartElement(String.Empty, "region", String.Empty);
rxw.WriteStartElement(String.Empty, "stats", String.Empty);
rxw.WriteStartElement(String.Empty, "users", String.Empty);
rxw.WriteString(users.ToString());
rxw.WriteEndElement();
rxw.WriteStartElement(String.Empty, "objects", String.Empty);
rxw.WriteString(objects.ToString());
rxw.WriteEndElement();
rxw.WriteEndDocument();
return rxw.ToString();
}
protected string RegionPrims(OSHttpResponse httpResponse, Scene scene, Vector3 min, Vector3 max)
{
httpResponse.SendChunked = true;
httpResponse.ContentType = "text/xml";
IRegionSerialiserModule serialiser = scene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.SavePrimsToXml2(scene, new StreamWriter(httpResponse.OutputStream), min, max);
return "";
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type MessageExtensionsCollectionRequest.
/// </summary>
public partial class MessageExtensionsCollectionRequest : BaseRequest, IMessageExtensionsCollectionRequest
{
/// <summary>
/// Constructs a new MessageExtensionsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public MessageExtensionsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension)
{
return this.AddAsync(extension, CancellationToken.None);
}
/// <summary>
/// Adds the specified Extension to the collection via POST.
/// </summary>
/// <param name="extension">The Extension to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Extension.</returns>
public System.Threading.Tasks.Task<Extension> AddAsync(Extension extension, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
extension.ODataType = string.Concat("#", StringHelper.ConvertTypeToLowerCamelCase(extension.GetType().FullName));
return this.SendAsync<Extension>(extension, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IMessageExtensionsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IMessageExtensionsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<MessageExtensionsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Expand(Expression<Func<Extension, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Select(Expression<Func<Extension, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IMessageExtensionsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Buffers.Tests
{
public class MemoryTests
{
[Fact]
public void SimpleTests()
{
using(var owned = new OwnedNativeBuffer(1024)) {
var span = owned.AsSpan();
span[10] = 10;
unsafe { Assert.Equal(10, owned.Pointer[10]); }
var memory = owned.Buffer;
var array = memory.ToArray();
Assert.Equal(owned.Length, array.Length);
Assert.Equal(10, array[10]);
Span<byte> copy = new byte[20];
memory.Slice(10, 20).CopyTo(copy);
Assert.Equal(10, copy[0]);
}
using (OwnedPinnedBuffer<byte> owned = new byte[1024]) {
var span = owned.AsSpan();
span[10] = 10;
Assert.Equal(10, owned.Array[10]);
unsafe { Assert.Equal(10, owned.Pointer[10]); }
var memory = owned.Buffer;
var array = memory.ToArray();
Assert.Equal(owned.Length, array.Length);
Assert.Equal(10, array[10]);
Span<byte> copy = new byte[20];
memory.Slice(10, 20).CopyTo(copy);
Assert.Equal(10, copy[0]);
}
}
[Fact]
public void NativeMemoryLifetime()
{
var owner = new OwnedNativeBuffer(1024);
TestLifetime(owner);
}
[Fact]
public unsafe void PinnedArrayMemoryLifetime()
{
var bytes = new byte[1024];
fixed (byte* pBytes = bytes) {
var owner = new OwnedPinnedBuffer<byte>(bytes, pBytes);
TestLifetime(owner);
}
}
static void TestLifetime(OwnedBuffer<byte> owned)
{
Buffer<byte> copyStoredForLater;
try {
Buffer<byte> memory = owned.Buffer;
Buffer<byte> memorySlice = memory.Slice(10);
copyStoredForLater = memorySlice;
var r = memorySlice.Retain();
try {
Assert.Throws<InvalidOperationException>(() => { // memory is reserved; premature dispose check fires
owned.Dispose();
});
}
finally {
r.Dispose(); // release reservation
}
}
finally {
owned.Dispose(); // can finish dispose with no exception
}
Assert.Throws<ObjectDisposedException>(() => {
// memory is disposed; cannot use copy stored for later
var span = copyStoredForLater.Span;
});
}
[Fact]
public void AutoDispose()
{
OwnedBuffer<byte> owned = new AutoPooledBuffer(1000);
owned.Retain();
var memory = owned.Buffer;
Assert.Equal(false, owned.IsDisposed);
var reservation = memory.Retain();
Assert.Equal(false, owned.IsDisposed);
owned.Release();
Assert.Equal(false, owned.IsDisposed);
reservation.Dispose();
Assert.Equal(true, owned.IsDisposed);
}
[Fact]
public void OnNoReferencesTest()
{
var owned = new CustomBuffer<byte>(255);
var memory = owned.Buffer;
Assert.Equal(0, owned.OnNoRefencesCalledCount);
Assert.False(owned.IsRetained);
using (memory.Retain())
{
Assert.Equal(0, owned.OnNoRefencesCalledCount);
Assert.True(owned.IsRetained);
}
Assert.Equal(1, owned.OnNoRefencesCalledCount);
Assert.False(owned.IsRetained);
}
[Fact(Skip = "This needs to be fixed and re-enabled or removed.")]
public void RacyAccess()
{
for (int k = 0; k < 1000; k++)
{
var owners = new OwnedBuffer<byte>[128];
var memories = new Buffer<byte>[owners.Length];
var reserves = new BufferHandle[owners.Length];
var disposeSuccesses = new bool[owners.Length];
var reserveSuccesses = new bool[owners.Length];
for (int i = 0; i < owners.Length; i++)
{
var array = new byte[1024];
owners[i] = array;
memories[i] = owners[i].Buffer;
}
var dispose_task = Task.Run(() => {
for (int i = 0; i < owners.Length; i++)
{
try
{
owners[i].Dispose();
disposeSuccesses[i] = true;
}
catch (InvalidOperationException)
{
disposeSuccesses[i] = false;
}
}
});
var reserve_task = Task.Run(() => {
for (int i = owners.Length - 1; i >= 0; i--)
{
try
{
reserves[i] = memories[i].Retain();
reserveSuccesses[i] = true;
}
catch (ObjectDisposedException)
{
reserveSuccesses[i] = false;
}
}
});
Task.WaitAll(reserve_task, dispose_task);
for (int i = 0; i < owners.Length; i++)
{
Assert.False(disposeSuccesses[i] && reserveSuccesses[i]);
}
}
}
}
class CustomBuffer<T> : OwnedBuffer<T>
{
bool _disposed;
int _referenceCount;
int _noReferencesCalledCount;
T[] _array;
public CustomBuffer(int size)
{
_array = new T[size];
}
public int OnNoRefencesCalledCount => _noReferencesCalledCount;
public override int Length => _array.Length;
public override bool IsDisposed => _disposed;
public override bool IsRetained => _referenceCount > 0;
public override Span<T> AsSpan(int index, int length)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(CustomBuffer<T>));
return new Span<T>(_array, index, length);
}
public override Span<T> AsSpan()
{
if (IsDisposed) throw new ObjectDisposedException(nameof(CustomBuffer<T>));
return new Span<T>(_array, 0, _array.Length);
}
public override BufferHandle Pin(int index = 0)
{
unsafe
{
Retain();
var handle = GCHandle.Alloc(_array, GCHandleType.Pinned);
var pointer = Add((void*)handle.AddrOfPinnedObject(), index);
return new BufferHandle(this, pointer, handle);
}
}
protected override bool TryGetArray(out ArraySegment<T> arraySegment)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(CustomBuffer<T>));
arraySegment = new ArraySegment<T>(_array);
return true;
}
protected override void Dispose(bool disposing)
{
_disposed = true;
_array = null;
}
public override void Retain()
{
if (IsDisposed) throw new ObjectDisposedException(nameof(CustomBuffer<T>));
Interlocked.Increment(ref _referenceCount);
}
public override void Release()
{
if (!IsRetained) throw new InvalidOperationException();
if (Interlocked.Decrement(ref _referenceCount) == 0)
{
_noReferencesCalledCount++;
}
}
}
class AutoDisposeBuffer<T> : ReferenceCountedBuffer<T>
{
public AutoDisposeBuffer(T[] array)
{
_array = array;
}
public override int Length => _array.Length;
public override Span<T> AsSpan(int index, int length)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(AutoDisposeBuffer<T>));
return new Span<T>(_array, index, length);
}
protected override void Dispose(bool disposing)
{
_array = null;
base.Dispose(disposing);
}
protected override void OnNoReferences()
{
Dispose();
}
protected override bool TryGetArray(out ArraySegment<T> arraySegment)
{
if (IsDisposed) throw new ObjectDisposedException(nameof(AutoDisposeBuffer<T>));
arraySegment = new ArraySegment<T>(_array);
return true;
}
public override BufferHandle Pin(int index = 0)
{
unsafe
{
Retain();
var handle = GCHandle.Alloc(_array, GCHandleType.Pinned);
var pointer = Add((void*)handle.AddrOfPinnedObject(), index);
return new BufferHandle(this, pointer, handle);
}
}
protected T[] _array;
}
class AutoPooledBuffer : AutoDisposeBuffer<byte>
{
public AutoPooledBuffer(int length) : base(ArrayPool<byte>.Shared.Rent(length))
{
}
protected override void Dispose(bool disposing)
{
var array = _array;
if (array != null)
{
ArrayPool<byte>.Shared.Return(array);
}
_array = null;
base.Dispose(disposing);
}
}
}
| |
namespace Azure.Monitor.Query
{
public partial class LogsBatchQuery
{
public LogsBatchQuery() { }
public virtual string AddWorkspaceQuery(string workspaceId, string query, Azure.Monitor.Query.QueryTimeRange timeRange, Azure.Monitor.Query.LogsQueryOptions options = null) { throw null; }
}
public partial class LogsQueryClient
{
protected LogsQueryClient() { }
public LogsQueryClient(Azure.Core.TokenCredential credential) { }
public LogsQueryClient(Azure.Core.TokenCredential credential, Azure.Monitor.Query.LogsQueryClientOptions options) { }
public LogsQueryClient(System.Uri endpoint, Azure.Core.TokenCredential credential) { }
public LogsQueryClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Monitor.Query.LogsQueryClientOptions options) { }
public System.Uri Endpoint { get { throw null; } }
public static string CreateQuery(System.FormattableString query) { throw null; }
public virtual Azure.Response<Azure.Monitor.Query.Models.LogsBatchQueryResultCollection> QueryBatch(Azure.Monitor.Query.LogsBatchQuery batch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Monitor.Query.Models.LogsBatchQueryResultCollection>> QueryBatchAsync(Azure.Monitor.Query.LogsBatchQuery batch, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Monitor.Query.Models.LogsQueryResult> QueryWorkspace(string workspaceId, string query, Azure.Monitor.Query.QueryTimeRange timeRange, Azure.Monitor.Query.LogsQueryOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Monitor.Query.Models.LogsQueryResult>> QueryWorkspaceAsync(string workspaceId, string query, Azure.Monitor.Query.QueryTimeRange timeRange, Azure.Monitor.Query.LogsQueryOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IReadOnlyList<T>>> QueryWorkspaceAsync<T>(string workspaceId, string query, Azure.Monitor.Query.QueryTimeRange timeRange, Azure.Monitor.Query.LogsQueryOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<System.Collections.Generic.IReadOnlyList<T>> QueryWorkspace<T>(string workspaceId, string query, Azure.Monitor.Query.QueryTimeRange timeRange, Azure.Monitor.Query.LogsQueryOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class LogsQueryClientOptions : Azure.Core.ClientOptions
{
public LogsQueryClientOptions(Azure.Monitor.Query.LogsQueryClientOptions.ServiceVersion version = Azure.Monitor.Query.LogsQueryClientOptions.ServiceVersion.V1) { }
public enum ServiceVersion
{
V1 = 1,
}
}
public partial class LogsQueryOptions
{
public LogsQueryOptions() { }
public System.Collections.Generic.IList<string> AdditionalWorkspaces { get { throw null; } }
public bool AllowPartialErrors { get { throw null; } set { } }
public bool IncludeStatistics { get { throw null; } set { } }
public bool IncludeVisualization { get { throw null; } set { } }
public System.TimeSpan? ServerTimeout { get { throw null; } set { } }
}
public partial class MetricsQueryClient
{
protected MetricsQueryClient() { }
public MetricsQueryClient(Azure.Core.TokenCredential credential) { }
public MetricsQueryClient(Azure.Core.TokenCredential credential, Azure.Monitor.Query.MetricsQueryClientOptions options) { }
public MetricsQueryClient(System.Uri endpoint, Azure.Core.TokenCredential credential, Azure.Monitor.Query.MetricsQueryClientOptions options = null) { }
public System.Uri Endpoint { get { throw null; } }
public virtual Azure.Pageable<Azure.Monitor.Query.Models.MetricDefinition> GetMetricDefinitions(string resourceId, string metricsNamespace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Monitor.Query.Models.MetricDefinition> GetMetricDefinitionsAsync(string resourceId, string metricsNamespace, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.Monitor.Query.Models.MetricNamespace> GetMetricNamespaces(string resourceId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Monitor.Query.Models.MetricNamespace> GetMetricNamespacesAsync(string resourceId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Monitor.Query.Models.MetricsQueryResult> QueryResource(string resourceId, System.Collections.Generic.IEnumerable<string> metrics, Azure.Monitor.Query.MetricsQueryOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Monitor.Query.Models.MetricsQueryResult>> QueryResourceAsync(string resourceId, System.Collections.Generic.IEnumerable<string> metrics, Azure.Monitor.Query.MetricsQueryOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class MetricsQueryClientOptions : Azure.Core.ClientOptions
{
public MetricsQueryClientOptions(Azure.Monitor.Query.MetricsQueryClientOptions.ServiceVersion version = Azure.Monitor.Query.MetricsQueryClientOptions.ServiceVersion.V2018_01_01) { }
public enum ServiceVersion
{
V2018_01_01 = 1,
}
}
public partial class MetricsQueryOptions
{
public MetricsQueryOptions() { }
public System.Collections.Generic.IList<Azure.Monitor.Query.Models.MetricAggregationType> Aggregations { get { throw null; } }
public string Filter { get { throw null; } set { } }
public System.TimeSpan? Granularity { get { throw null; } set { } }
public string MetricNamespace { get { throw null; } set { } }
public string OrderBy { get { throw null; } set { } }
public int? Size { get { throw null; } set { } }
public Azure.Monitor.Query.QueryTimeRange? TimeRange { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct QueryTimeRange : System.IEquatable<Azure.Monitor.Query.QueryTimeRange>
{
public QueryTimeRange(System.DateTimeOffset start, System.DateTimeOffset end) { throw null; }
public QueryTimeRange(System.DateTimeOffset start, System.TimeSpan duration) { throw null; }
public QueryTimeRange(System.TimeSpan duration) { throw null; }
public QueryTimeRange(System.TimeSpan duration, System.DateTimeOffset end) { throw null; }
public static Azure.Monitor.Query.QueryTimeRange All { get { throw null; } }
public System.TimeSpan Duration { get { throw null; } }
public System.DateTimeOffset? End { get { throw null; } }
public System.DateTimeOffset? Start { get { throw null; } }
public bool Equals(Azure.Monitor.Query.QueryTimeRange other) { throw null; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Monitor.Query.QueryTimeRange left, Azure.Monitor.Query.QueryTimeRange right) { throw null; }
public static implicit operator Azure.Monitor.Query.QueryTimeRange (System.TimeSpan timeSpan) { throw null; }
public static bool operator !=(Azure.Monitor.Query.QueryTimeRange left, Azure.Monitor.Query.QueryTimeRange right) { throw null; }
public override string ToString() { throw null; }
}
}
namespace Azure.Monitor.Query.Models
{
public partial class LogsBatchQueryResult : Azure.Monitor.Query.Models.LogsQueryResult
{
internal LogsBatchQueryResult() { }
public string Id { get { throw null; } }
}
public partial class LogsBatchQueryResultCollection : System.Collections.ObjectModel.ReadOnlyCollection<Azure.Monitor.Query.Models.LogsBatchQueryResult>
{
internal LogsBatchQueryResultCollection() : base (default(System.Collections.Generic.IList<Azure.Monitor.Query.Models.LogsBatchQueryResult>)) { }
public Azure.Monitor.Query.Models.LogsBatchQueryResult GetResult(string queryId) { throw null; }
public System.Collections.Generic.IReadOnlyList<T> GetResult<T>(string queryId) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct LogsColumnType : System.IEquatable<Azure.Monitor.Query.Models.LogsColumnType>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public LogsColumnType(string value) { throw null; }
public static Azure.Monitor.Query.Models.LogsColumnType Bool { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Datetime { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Decimal { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Dynamic { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Guid { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Int { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Long { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Real { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType String { get { throw null; } }
public static Azure.Monitor.Query.Models.LogsColumnType Timespan { get { throw null; } }
public bool Equals(Azure.Monitor.Query.Models.LogsColumnType other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Monitor.Query.Models.LogsColumnType left, Azure.Monitor.Query.Models.LogsColumnType right) { throw null; }
public static implicit operator Azure.Monitor.Query.Models.LogsColumnType (string value) { throw null; }
public static bool operator !=(Azure.Monitor.Query.Models.LogsColumnType left, Azure.Monitor.Query.Models.LogsColumnType right) { throw null; }
public override string ToString() { throw null; }
}
public partial class LogsQueryResult
{
internal LogsQueryResult() { }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.LogsTable> AllTables { get { throw null; } }
public Azure.ResponseError Error { get { throw null; } }
public Azure.Monitor.Query.Models.LogsQueryResultStatus Status { get { throw null; } }
public Azure.Monitor.Query.Models.LogsTable Table { get { throw null; } }
public System.BinaryData GetStatistics() { throw null; }
public System.BinaryData GetVisualization() { throw null; }
}
public enum LogsQueryResultStatus
{
Success = 0,
PartialFailure = 1,
Failure = 2,
}
public partial class LogsTable
{
internal LogsTable() { }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.LogsTableColumn> Columns { get { throw null; } }
public string Name { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.LogsTableRow> Rows { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class LogsTableColumn
{
internal LogsTableColumn() { }
public string Name { get { throw null; } }
public Azure.Monitor.Query.Models.LogsColumnType Type { get { throw null; } }
public override string ToString() { throw null; }
}
public partial class LogsTableRow : System.Collections.Generic.IEnumerable<object>, System.Collections.Generic.IReadOnlyCollection<object>, System.Collections.Generic.IReadOnlyList<object>, System.Collections.IEnumerable
{
internal LogsTableRow() { }
public int Count { get { throw null; } }
public object this[int index] { get { throw null; } }
public object this[string name] { get { throw null; } }
public bool? GetBoolean(int index) { throw null; }
public bool? GetBoolean(string name) { throw null; }
public System.DateTimeOffset? GetDateTimeOffset(int index) { throw null; }
public System.DateTimeOffset? GetDateTimeOffset(string name) { throw null; }
public decimal? GetDecimal(int index) { throw null; }
public decimal? GetDecimal(string name) { throw null; }
public double? GetDouble(int index) { throw null; }
public double? GetDouble(string name) { throw null; }
public System.BinaryData GetDynamic(int index) { throw null; }
public System.BinaryData GetDynamic(string name) { throw null; }
public System.Guid? GetGuid(int index) { throw null; }
public System.Guid? GetGuid(string name) { throw null; }
public int? GetInt32(int index) { throw null; }
public int? GetInt32(string name) { throw null; }
public long? GetInt64(int index) { throw null; }
public long? GetInt64(string name) { throw null; }
public string GetString(int index) { throw null; }
public string GetString(string name) { throw null; }
public System.TimeSpan? GetTimeSpan(int index) { throw null; }
public System.TimeSpan? GetTimeSpan(string name) { throw null; }
System.Collections.Generic.IEnumerator<object> System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public override string ToString() { throw null; }
}
public enum MetricAggregationType
{
None = 0,
Average = 1,
Count = 2,
Minimum = 3,
Maximum = 4,
Total = 5,
}
public partial class MetricAvailability
{
internal MetricAvailability() { }
public System.TimeSpan? Granularity { get { throw null; } }
public System.TimeSpan? Retention { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct MetricClass : System.IEquatable<Azure.Monitor.Query.Models.MetricClass>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public MetricClass(string value) { throw null; }
public static Azure.Monitor.Query.Models.MetricClass Availability { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricClass Errors { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricClass Latency { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricClass Saturation { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricClass Transactions { get { throw null; } }
public bool Equals(Azure.Monitor.Query.Models.MetricClass other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Monitor.Query.Models.MetricClass left, Azure.Monitor.Query.Models.MetricClass right) { throw null; }
public static implicit operator Azure.Monitor.Query.Models.MetricClass (string value) { throw null; }
public static bool operator !=(Azure.Monitor.Query.Models.MetricClass left, Azure.Monitor.Query.Models.MetricClass right) { throw null; }
public override string ToString() { throw null; }
}
public partial class MetricDefinition
{
internal MetricDefinition() { }
public string Category { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<string> Dimensions { get { throw null; } }
public string DisplayDescription { get { throw null; } }
public string Id { get { throw null; } }
public bool? IsDimensionRequired { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.MetricAvailability> MetricAvailabilities { get { throw null; } }
public Azure.Monitor.Query.Models.MetricClass? MetricClass { get { throw null; } }
public string Name { get { throw null; } }
public string Namespace { get { throw null; } }
public Azure.Monitor.Query.Models.MetricAggregationType? PrimaryAggregationType { get { throw null; } }
public string ResourceId { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.MetricAggregationType> SupportedAggregationTypes { get { throw null; } }
public Azure.Monitor.Query.Models.MetricUnit? Unit { get { throw null; } }
}
public partial class MetricNamespace
{
internal MetricNamespace() { }
public Azure.Monitor.Query.Models.MetricNamespaceClassification? Classification { get { throw null; } }
public string FullyQualifiedName { get { throw null; } }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public string Type { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct MetricNamespaceClassification : System.IEquatable<Azure.Monitor.Query.Models.MetricNamespaceClassification>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public MetricNamespaceClassification(string value) { throw null; }
public static Azure.Monitor.Query.Models.MetricNamespaceClassification Custom { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricNamespaceClassification Platform { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricNamespaceClassification QualityOfService { get { throw null; } }
public bool Equals(Azure.Monitor.Query.Models.MetricNamespaceClassification other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Monitor.Query.Models.MetricNamespaceClassification left, Azure.Monitor.Query.Models.MetricNamespaceClassification right) { throw null; }
public static implicit operator Azure.Monitor.Query.Models.MetricNamespaceClassification (string value) { throw null; }
public static bool operator !=(Azure.Monitor.Query.Models.MetricNamespaceClassification left, Azure.Monitor.Query.Models.MetricNamespaceClassification right) { throw null; }
public override string ToString() { throw null; }
}
public partial class MetricResult
{
internal MetricResult() { }
public string Description { get { throw null; } }
public Azure.ResponseError Error { get { throw null; } }
public string Id { get { throw null; } }
public string Name { get { throw null; } }
public string ResourceType { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.MetricTimeSeriesElement> TimeSeries { get { throw null; } }
public Azure.Monitor.Query.Models.MetricUnit Unit { get { throw null; } }
}
public partial class MetricsQueryResult
{
internal MetricsQueryResult() { }
public int? Cost { get { throw null; } }
public System.TimeSpan? Granularity { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.MetricResult> Metrics { get { throw null; } }
public string Namespace { get { throw null; } }
public string ResourceRegion { get { throw null; } }
public Azure.Monitor.Query.QueryTimeRange TimeSpan { get { throw null; } }
public Azure.Monitor.Query.Models.MetricResult GetMetricByName(string name) { throw null; }
}
public partial class MetricTimeSeriesElement
{
internal MetricTimeSeriesElement() { }
public System.Collections.Generic.IReadOnlyDictionary<string, string> Metadata { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.MetricValue> Values { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct MetricUnit : System.IEquatable<Azure.Monitor.Query.Models.MetricUnit>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public MetricUnit(string value) { throw null; }
public static Azure.Monitor.Query.Models.MetricUnit BitsPerSecond { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit Bytes { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit ByteSeconds { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit BytesPerSecond { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit Cores { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit Count { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit CountPerSecond { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit MilliCores { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit MilliSeconds { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit NanoCores { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit Percent { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit Seconds { get { throw null; } }
public static Azure.Monitor.Query.Models.MetricUnit Unspecified { get { throw null; } }
public bool Equals(Azure.Monitor.Query.Models.MetricUnit other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Monitor.Query.Models.MetricUnit left, Azure.Monitor.Query.Models.MetricUnit right) { throw null; }
public static implicit operator Azure.Monitor.Query.Models.MetricUnit (string value) { throw null; }
public static bool operator !=(Azure.Monitor.Query.Models.MetricUnit left, Azure.Monitor.Query.Models.MetricUnit right) { throw null; }
public override string ToString() { throw null; }
}
public partial class MetricValue
{
internal MetricValue() { }
public double? Average { get { throw null; } }
public double? Count { get { throw null; } }
public double? Maximum { get { throw null; } }
public double? Minimum { get { throw null; } }
public System.DateTimeOffset TimeStamp { get { throw null; } }
public double? Total { get { throw null; } }
public override string ToString() { throw null; }
}
public static partial class MonitorQueryModelFactory
{
public static Azure.Monitor.Query.Models.LogsQueryResult LogsQueryResult(System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.LogsTable> allTables, System.BinaryData statistics, System.BinaryData visualization, System.BinaryData error) { throw null; }
public static Azure.Monitor.Query.Models.LogsTableColumn LogsTableColumn(string name = null, Azure.Monitor.Query.Models.LogsColumnType type = default(Azure.Monitor.Query.Models.LogsColumnType)) { throw null; }
public static Azure.Monitor.Query.Models.MetricAvailability MetricAvailability(System.TimeSpan? granularity = default(System.TimeSpan?), System.TimeSpan? retention = default(System.TimeSpan?)) { throw null; }
public static Azure.Monitor.Query.Models.MetricsQueryResult MetricsQueryResult(int? cost, string timespan, System.TimeSpan? granularity, string @namespace, string resourceRegion, System.Collections.Generic.IReadOnlyList<Azure.Monitor.Query.Models.MetricResult> metrics) { throw null; }
public static Azure.Monitor.Query.Models.MetricValue MetricValue(System.DateTimeOffset timeStamp = default(System.DateTimeOffset), double? average = default(double?), double? minimum = default(double?), double? maximum = default(double?), double? total = default(double?), double? count = default(double?)) { throw null; }
}
}
| |
using System;
using System.Drawing;
namespace GuruComponents.CodeEditor.Library.Drawing.Shapes
{
public class ShapeStar : ShapePolygon,IRectangle
{
private int _corners;
private float m_Width = 0;
private float m_Height = 0;
internal ShapeStar()
{
}
private static float ToRad(float deg)
{
return (float)(deg / 180 * Math.PI);
}
public ShapeStar(RectangleF ret, int corners,Pen pen,Brush brush)
{
_corners = corners;
this.Points = Star(ret, corners);
//this.Size = new SizeF(ret.Size.Width, ret.Size.Height);
this.Pen = pen;
this.Brush = brush;
UpdatePath();
}
public ShapeStar(RectangleF ret, int corners, float rotation, float diff, Pen pen, Brush brush)
{
_corners = corners;
this.Points = Star(ret, corners, ToRad(rotation), diff);
this.Rotation = rotation;
this.Pen = pen;
this.Brush = brush;
UpdatePath();
}
public ShapeStar(RectangleF ret, int corners, float rotation, Pen pen, Brush brush)
{
_corners = corners;
this.Points = Star(ret, corners, ToRad(rotation));
this.Rotation = rotation;
this.Pen = pen;
this.Brush = brush;
UpdatePath();
}
//***
public ShapeStar(PointF center, float Ir, float Er, int corners, Pen pen, Brush brush)
{
_corners = corners;
this.Points = Star(center, Ir, Er, corners);
this.Pen = pen;
this.Brush = brush;
UpdatePath();
}
//***
public ShapeStar(PointF Center, float radius, float internalRadius, int corners,float rotation, Pen pen, Brush brush)
{
_corners = corners;
this.Points = Star(Center,internalRadius,radius,corners);
this.Rotation = rotation;
this.Pen = pen;
this.Brush = brush;
UpdatePath();
}
//************************************************************
public PointF[] Star(RectangleF ret,int num)
{
PointF Center = new PointF(ret.Width / 2, ret.Height / 2);
int ir = (int)( ret.Width / 3);
int er=(int)ret.Width/2-2;
return Star(Center, ir, er, num);
}
public PointF[] Star(RectangleF ret, int num,float PH,float diff)
{
PointF Center = new PointF(ret.Width / 2, ret.Height / 2);
int er = (int)ret.Width / 2 - 2;
int ir = (int)(er *diff);
return Star(Center, ir, er, num, PH);
}
public PointF[] Star(RectangleF ret, int num, float PH)
{
PointF Center = new PointF(ret.Width / 2, ret.Height / 2);
int ir = (int)(ret.Width / 3);
int er = (int)ret.Width / 2 - 2;
return Star(Center, ir, er, num, PH);
}
public PointF[] Star(PointF center, int Ir, int Er, int num, float PH)
{
PointF[] Points = new PointF[num * 2];
float AngleStep = (float)(2 * Math.PI) / num;
float phase = AngleStep / 2;
float Angle = 0;
for (int i = 0; i < num * 2; i += 2)
{
Points[i].X = (int)(center.X + Er * Math.Cos(Angle + PH));
Points[i].Y = (int)(center.Y + Er * Math.Sin(Angle + PH));
Points[i + 1].X = (int)(center.X + Ir * Math.Cos(Angle + phase + PH));
Points[i + 1].Y = (int)(center.Y + Ir * Math.Sin(Angle + phase + PH));
Angle += AngleStep;
}
return Points;
}
//***
public PointF[] Star(PointF center ,float Ir,float Er, int num)
{
PointF[] Points = new PointF[num * 2];
float AngleStep = (float)(2 * Math.PI) / num;
float phase= AngleStep/2;
float Angle = 0;
for (int i = 0; i < num*2; i+=2)
{
Points[i].X = (float)(center.X + Er*Math.Cos(Angle));
Points[i].Y = (float)(center.Y + Er * Math.Sin(Angle));
Points[i + 1].X = (float)(center.X + Ir*Math.Cos(Angle + phase));
Points[i + 1].Y = (float)(center.Y + Ir*Math.Sin(Angle + phase));
Angle += AngleStep;
}
return Points;
}
public override void Update()
{
base.Update();
this.Points = Star(new RectangleF(this.Location.X,
this.Location.Y, m_Width, m_Height)
, _corners);
UpdatePath();
}
public override string ToString()
{
return "{GuruComponents.CodeEditor.Library.Drawing.Shapes.ShapeStar}";
}
#region IRectangle Members
public float Left
{
get
{
return this.Location.X;
}
set
{
this.Location = new PointF(value, this.Location.Y);
}
}
public float Top
{
get
{
return this.Location.Y;
}
set
{
this.Location = new PointF(this.Location.X, value);
}
}
public float Width
{
get
{
return m_Width;
}
set
{
m_Width = value;
}
}
public float Height
{
get
{
return m_Height;
}
set
{
m_Height = value;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Async;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Search;
using Extensions;
using Models;
namespace FileEnumerators
{
public static class FileEnumerators
{
#region Standard Enumeration using Recursion
public static IEnumerable<string> EnumerateDirectories(string parentDirectory, string searchPattern, SearchOption searchOpt)
{
try
{
var directories = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
directories = Directory.EnumerateDirectories(parentDirectory)
.SelectMany(x => EnumerateDirectories(x, searchPattern, searchOpt));
}
return directories.Concat(Directory.EnumerateDirectories(parentDirectory, searchPattern));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOpt)
{
try
{
var dirFiles = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
dirFiles = Directory.EnumerateDirectories(path)
.SelectMany(x => EnumerateFiles(x, searchPattern, searchOpt));
}
return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
#endregion
#region Standard Enumeration using Recursion and in Parallel & Async
public static IEnumerable<string> EnumerateFilesInParallel(string path, string searchPattern, SearchOption searchOpt)
{
try
{
var fileList = new ConcurrentBag<string>();
if (searchOpt == SearchOption.AllDirectories)
{
var dirFiles = Directory.EnumerateDirectories(path);
Parallel.ForEach(dirFiles, dir => {
fileList = new ConcurrentBag<string>(EnumerateFilesInParallel(dir, searchPattern, searchOpt));
});
}
return fileList.Concat(Directory.EnumerateFiles(path, searchPattern));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
public static async Task<IEnumerable<string>> EnumerateFilesAsync(string path, string searchPattern, SearchOption searchOpt)
{
var t = await Task.Run(() =>
{
try
{
var dirFiles = Enumerable.Empty<string>();
if (searchOpt == SearchOption.AllDirectories)
{
dirFiles = Directory.EnumerateDirectories(path)
.SelectMany(x => EnumerateFilesAsync(x, searchPattern, searchOpt).GetAwaiter().GetResult());
}
return dirFiles.Concat(Directory.EnumerateFiles(path, searchPattern));
}
catch (UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
});
return t;
}
#endregion
#region Parallel & Concurrent TreeTraverse
public static IEnumerable<string> GetFilesInParallel(string path, string searchPattern)
{
var bag = new ConcurrentBag<string>();
ParallelTreeTraverse(path, searchPattern, (f) => { bag.Add(f); });
return bag.ToList();
}
public static void ParallelTreeTraverse(string root, string searchPattern, Action<string> action)
{
//Count of files traversed and timer for diagnostic output
int fileCount = 0;
// Determine whether to parallelize file processing on each folder based on processor count.
int procCount = Environment.ProcessorCount;
// Data structure to hold names of subfolders to be examined for files.
Stack<string> dirs = new Stack<string>();
if (!Directory.Exists(root))
{
throw new ArgumentException();
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs = { };
string[] files = { };
try { subDirs = Directory.GetDirectories(currentDir); }
// Thrown if we do not have discovery permission on the directory.
catch (UnauthorizedAccessException) { continue; }
// Thrown if another process has deleted the directory after we retrieved its name.
catch (DirectoryNotFoundException) { continue; }
try { files = Directory.GetFiles(currentDir, searchPattern); }
catch (UnauthorizedAccessException) { continue; }
catch (DirectoryNotFoundException) { continue; }
catch (IOException) { continue; }
// Execute in parallel if there are enough files in the directory.
// Otherwise, execute sequentially.Files are opened and processed
// synchronously but this could be modified to perform async I/O.
try
{
if (files.Length < procCount)
{
foreach (var file in files)
{
action(file);
fileCount++;
}
}
else
{
Parallel.ForEach(files, () => 0, (file, loopState, localCount) =>
{
action(file);
return (int)++localCount;
},
(c) => {
Interlocked.Add(ref fileCount, c);
});
}
}
catch (AggregateException ae)
{
ae.Handle((ex) => {
if (ex is UnauthorizedAccessException)
{
return true;
}
// Handle other exceptions here if necessary...
return false;
});
}
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach (string str in subDirs)
dirs.Push(str);
}
}
public static async Task<IEnumerable<string>> GetFilesInParallelAsync(string path, string searchPattern)
{
var t = await Task.Run(() =>
{
var bag = new ConcurrentBag<string>();
ConcurrentParallelTreeTraverse(path, searchPattern, (f) => { bag.Add(f); });
return bag.ToList();
});
return t;
}
public static void ConcurrentParallelTreeTraverse(string root, string searchPattern, Action<string> action)
{
int fileCount = 0;
ConcurrentQueue<string> dirs = new ConcurrentQueue<string>();
dirs.Enqueue(root);
while (dirs.Count > 0)
{
string currentDir = string.Empty;
if (dirs.TryDequeue(out currentDir))
{
string[] subDirs = { };
string[] files = { };
try
{ subDirs = Directory.GetDirectories(currentDir); }
catch (UnauthorizedAccessException)
{ continue; }
catch (DirectoryNotFoundException)
{ continue; }
try
{ files = Directory.GetFiles(currentDir, searchPattern); }
catch (UnauthorizedAccessException)
{ continue; }
catch (DirectoryNotFoundException)
{ continue; }
catch (IOException)
{ continue; }
try
{
Parallel.ForEach(files, () => 0, (file, loopState, localCount) =>
{
action(file);
return ++localCount;
},
(c) => { Interlocked.Add(ref fileCount, c); });
}
catch (AggregateException ae)
{
ae.Handle((ex) =>
{
if (ex is UnauthorizedAccessException) { return true; }
return false;
});
}
Parallel.ForEach(subDirs, dir => { dirs.Enqueue(dir); });
}
}
}
#endregion
#region TreeTraverse Pseudo-Recursion & Async File Enumeration
public static async Task<IEnumerable<string>> GetFilesAsync(string path, string searchPattern)
{
return await GetFileNamesAsync(path, searchPattern);
}
public static async Task<IEnumerable<string>> GetAllFilesAsync(string path, string searchPattern)
{
return await TreeTraverseInParallelAsync(path, searchPattern);
}
// Fastest Method So Far
public static async Task<IEnumerable<string>> TreeTraverseAsync(string root, string searchPattern)
{
var taskBag = new ConcurrentBag<Task>();
var fileNameBags = new ConcurrentBag<ConcurrentBag<string>>();
var directories = new ConcurrentQueue<string>();
directories.Enqueue(root);
while (directories.Count > 0)
{
string currentDir = string.Empty;
if (directories.TryDequeue(out currentDir))
{
await GetDirectoriesAsync(currentDir, directories).ConfigureAwait(false);
taskBag.Add(GetFileNamesAsync(currentDir, searchPattern, fileNameBags));
}
}
await Task.WhenAll(taskBag);
return fileNameBags.AsParallel().SelectMany(f => f);
}
// Second Fastest Method
public static async Task<IEnumerable<string>> TreeTraverseInParallelAsync(string root, string searchPattern)
{
var taskBag = new ConcurrentBag<Task>();
var fileNameBags = new ConcurrentBag<ConcurrentBag<string>>();
var directoryQueue = new ConcurrentQueue<ConcurrentQueue<string>>();
var directory = new ConcurrentQueue<string>();
directory.Enqueue(root);
directoryQueue.Enqueue(directory);
while (directoryQueue.Count > 0)
{
if (directoryQueue.TryDequeue(out ConcurrentQueue<string> dirs))
{
await dirs.DequeueExisting().ParallelForEachAsync(async dir =>
{
await GetDirectoryQueuesAsync(dir, directoryQueue).ConfigureAwait(false);
taskBag.Add(GetFileNamesAsync(dir, searchPattern, fileNameBags));
});
}
}
await Task.WhenAll(taskBag);
return fileNameBags.AsParallel().SelectMany(f => f);
}
private static async Task GetDirectoriesAsync(string directory, ConcurrentQueue<string> directories)
{
await Task.Run(() =>
{
string[] subDirs = { };
try
{ subDirs = Directory.GetDirectories(directory); }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
foreach (var dir in subDirs) { directories.Enqueue(dir); };
});
}
private static async Task GetDirectoryQueuesAsync(string directory, ConcurrentQueue<ConcurrentQueue<string>> directoryQueue)
{
await Task.Run(() =>
{
string[] subDirs = { };
try
{ subDirs = Directory.GetDirectories(directory); }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
var dirs = new ConcurrentQueue<string>();
foreach (var dir in subDirs) { dirs.Enqueue(dir); };
directoryQueue.Enqueue(dirs);
});
}
private static async Task<IEnumerable<string>> GetFileNamesAsync(string directory, string searchPattern)
{
var t = await Task.Run(() =>
{
string[] files = { };
var fileNames = new ConcurrentBag<string>();
try
{ files = Directory.GetFiles(directory, searchPattern); }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
catch (IOException) { }
try
{
foreach (var file in files) { fileNames.Add(file); };
}
catch (AggregateException ae)
{
ae.Handle((ex) =>
{
if (ex is UnauthorizedAccessException) { return true; }
return false;
});
}
return fileNames;
});
return t;
}
private static async Task GetFileNamesAsync(string directory, string searchPattern, ConcurrentBag<ConcurrentBag<string>> fileNameBags)
{
await Task.Run(() =>
{
string[] files = { };
var fileNames = new ConcurrentBag<string>();
try
{ files = Directory.GetFiles(directory, searchPattern); }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
catch (IOException) { }
try
{
foreach (var file in files) { fileNames.Add(file); };
}
catch (AggregateException ae)
{
ae.Handle((ex) =>
{
if (ex is UnauthorizedAccessException) { return true; }
return false;
});
}
fileNameBags.Add(fileNames);
});
}
// Not Used At The Moment
private static async Task GetDirectoriesInParallelAsync(string directory, ConcurrentQueue<string> directories)
{
await Task.Run(() =>
{
string[] subDirs = { };
try
{ subDirs = Directory.GetDirectories(directory); }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
Parallel.ForEach(subDirs, dir => { directories.Enqueue(dir); });
});
}
// Not Used At The Moment
private static async Task GetFileNamesInParallelAsync(string directory, string searchPattern, ConcurrentBag<string> fileNames)
{
await Task.Run(() =>
{
string[] files = { };
try
{ files = Directory.GetFiles(directory, searchPattern); }
catch (UnauthorizedAccessException) { }
catch (DirectoryNotFoundException) { }
catch (IOException) { }
try
{
Parallel.ForEach(files, file => { fileNames.Add(file); });
}
catch (AggregateException ae)
{
ae.Handle((ex) =>
{
if (ex is UnauthorizedAccessException) { return true; }
return false;
});
}
return fileNames.ToList();
});
}
#endregion
#region UWP Query Based File Acquisition
public class SearchResult
{
public string FileName { get; set; }
public string FileExt { get; set; }
public string FilePath { get; set; }
}
public static async Task<List<SearchResult>> GetFilesByQueryAsync(string fileType, int resultCountToReturn, StorageFolder folder)
{
List<string> fileTypes = new List<string>();
if (!string.IsNullOrEmpty(fileType))
{ fileTypes.Add(fileType); }
else { fileTypes = null; }
var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileType)
{
IndexerOption = IndexerOption.UseIndexerWhenAvailable,
FolderDepth = FolderDepth.Deep
};
StorageFileQueryResult queryResults = folder.CreateFileQueryWithOptions(queryOptions);
//Paging
uint index = 0, stepSize = 50;
IReadOnlyList<StorageFile> files = await queryResults.GetFilesAsync(index, stepSize);
index += 50;
var results = new List<SearchResult>();
while (files.Count != 0)
{
// Only get this many results.
if (index >= resultCountToReturn)
{ break; }
var fileTask = queryResults.GetFilesAsync(index, stepSize).AsTask();
// While FileTask is running, create and store the last group results.
foreach (var file in files)
{
var searchResult = new SearchResult()
{
FilePath = file.Path,
FileName = file.DisplayName,
FileExt = file.DisplayType
};
results.Add(searchResult);
}
files = await fileTask;
index += 50;
}
return results.OrderBy(x => x.FilePath).ToList();
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Collections;
using System.IO;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>;
namespace System.Runtime.Serialization.Json
{
#if NET_NATIVE
public class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex
#elif MERGE_DCJS
internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex
#else
internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContext
#endif
{
private DataContractJsonSerializer _jsonSerializer;
#if !NET_NATIVE && !MERGE_DCJS
private bool _isSerializerKnownDataContractsSetExplicit;
#endif
#if NET_NATIVE || MERGE_DCJS
private EmitTypeInformation _emitXsiType;
private bool _perCallXsiTypeAlreadyEmitted;
private bool _useSimpleDictionaryFormat;
#endif
public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
: base(null, int.MaxValue, new StreamingContext(), true)
{
_jsonSerializer = serializer;
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
}
internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract)
{
return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract);
}
#if NET_NATIVE || MERGE_DCJS
internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
{
return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract);
}
internal XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract)
: base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false)
{
_emitXsiType = serializer.EmitTypeInformation;
this.rootTypeDataContract = rootTypeDataContract;
this.serializerKnownTypeList = serializer.knownTypeList;
this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
_useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat;
}
#endif
#if !NET_NATIVE && !MERGE_DCJS
internal override DataContractDictionary SerializerKnownDataContracts
{
get
{
// This field must be initialized during construction by serializers using data contracts.
if (!_isSerializerKnownDataContractsSetExplicit)
{
this.serializerKnownDataContracts = _jsonSerializer.KnownDataContracts;
_isSerializerKnownDataContractsSetExplicit = true;
}
return this.serializerKnownDataContracts;
}
}
#endif
internal IList<Type> SerializerKnownTypeList
{
get
{
return this.serializerKnownTypeList;
}
}
#if NET_NATIVE || MERGE_DCJS
public bool UseSimpleDictionaryFormat
{
get
{
return _useSimpleDictionaryFormat;
}
}
#endif
internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName)
{
return false;
}
internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
{
return false;
}
internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size)
{
//Noop
}
#if NET_NATIVE || MERGE_DCJS
protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
{
if (_emitXsiType != EmitTypeInformation.Never)
{
if (string.IsNullOrEmpty(dataContractNamespace))
{
WriteTypeInfo(writer, dataContractName);
}
else
{
WriteTypeInfo(writer, string.Concat(dataContractName, JsonGlobals.NameValueSeparatorString, TruncateDefaultDataContractNamespace(dataContractNamespace)));
}
}
}
#endif
internal static string TruncateDefaultDataContractNamespace(string dataContractNamespace)
{
if (!string.IsNullOrEmpty(dataContractNamespace))
{
if (dataContractNamespace[0] == '#')
{
return string.Concat("\\", dataContractNamespace);
}
else if (dataContractNamespace[0] == '\\')
{
return string.Concat("\\", dataContractNamespace);
}
else if (dataContractNamespace.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal))
{
return string.Concat("#", dataContractNamespace.Substring(JsonGlobals.DataContractXsdBaseNamespaceLength));
}
}
return dataContractNamespace;
}
protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
{
if (!((object.ReferenceEquals(contract.Name, declaredContract.Name) &&
object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) ||
(contract.Name.Value == declaredContract.Name.Value &&
contract.Namespace.Value == declaredContract.Namespace.Value)) &&
(contract.UnderlyingType != Globals.TypeOfObjectArray)
#if NET_NATIVE || MERGE_DCJS
&& (_emitXsiType != EmitTypeInformation.Never)
#endif
)
{
// We always deserialize collections assigned to System.Object as object[]
// Because of its common and JSON-specific nature,
// we don't want to validate known type information for object[]
#if NET_NATIVE || MERGE_DCJS
// Don't validate known type information when emitXsiType == Never because
// known types are not used without type information in the JSON
if (RequiresJsonTypeInfo(contract))
{
_perCallXsiTypeAlreadyEmitted = true;
WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value);
}
else
{
// check if the declared type is System.Enum and throw because
// __type information cannot be written for enums since it results in invalid JSON.
// Without __type, the resulting JSON cannot be deserialized since a number cannot be directly assigned to System.Enum.
if (declaredContract.UnderlyingType == typeof(Enum))
{
throw new SerializationException(SR.Format(SR.EnumTypeNotSupportedByDataContractJsonSerializer, declaredContract.UnderlyingType));
}
}
#endif
// Return true regardless of whether we actually wrote __type information
// E.g. We don't write __type information for enums, but we still want verifyKnownType
// to be true for them.
return true;
}
return false;
}
#if NET_NATIVE || MERGE_DCJS
private static bool RequiresJsonTypeInfo(DataContract contract)
{
return (contract is ClassDataContract);
}
private void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation)
{
writer.WriteAttributeString(null, JsonGlobals.serverTypeString, null, typeInformation);
}
#endif
protected override void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
#if NET_NATIVE || MERGE_DCJS
JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract);
if (_emitXsiType == EmitTypeInformation.Always && !_perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract))
{
WriteTypeInfo(xmlWriter, jsonDataContract.TypeName);
}
_perCallXsiTypeAlreadyEmitted = false;
DataContractJsonSerializerImpl.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle);
#else
_jsonSerializer.WriteObjectInternal(obj, dataContract, this, WriteTypeInfo(null, dataContract, DataContract.GetDataContract(declaredTypeHandle, obj.GetType())), declaredTypeHandle);
#endif
}
protected override void WriteNull(XmlWriterDelegator xmlWriter)
{
#if NET_NATIVE || MERGE_DCJS
DataContractJsonSerializerImpl.WriteJsonNull(xmlWriter);
#endif
}
#if NET_NATIVE || MERGE_DCJS
internal XmlDictionaryString CollectionItemName
{
get { return JsonGlobals.itemDictionaryString; }
}
protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
DataContract dataContract;
bool verifyKnownType = false;
bool isDeclaredTypeInterface = declaredType.GetTypeInfo().IsInterface;
if (isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
dataContract = GetDataContract(declaredTypeHandle, declaredType);
}
else if (declaredType.IsArray) // If declared type is array do not write __serverType. Instead write__serverType for each item
{
dataContract = GetDataContract(declaredTypeHandle, declaredType);
}
else
{
dataContract = GetDataContract(objectTypeHandle, objectType);
DataContract declaredTypeContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, declaredType);
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract);
HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType);
}
if (isDeclaredTypeInterface)
{
VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType);
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType);
}
private void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType)
{
if ((declaredType != dataContract.UnderlyingType) && (dataContract is CollectionDataContract))
{
if (verifyKnownType)
{
VerifyType(dataContract, declaredType);
verifyKnownType = false;
}
if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary)
{
// Convert non-generic dictionary to generic dictionary
IDictionary dictionaryObj = obj as IDictionary;
Dictionary<object, object> genericDictionaryObj = new Dictionary<object, object>();
foreach (DictionaryEntry entry in dictionaryObj)
{
genericDictionaryObj.Add(entry.Key, entry.Value);
}
obj = genericDictionaryObj;
}
dataContract = GetDataContract(Globals.TypeOfIEnumerable);
}
}
internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
{
bool verifyKnownType = false;
Type declaredType = rootTypeDataContract.UnderlyingType;
bool isDeclaredTypeInterface = declaredType.GetTypeInfo().IsInterface;
if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType))
&& !declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract);
HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType);
}
if (isDeclaredTypeInterface)
{
VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType);
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType);
}
private void VerifyType(DataContract dataContract, Type declaredType)
{
bool knownTypesAddedInCurrentScope = false;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
knownTypesAddedInCurrentScope = true;
}
if (!IsKnownType(dataContract, declaredType))
{
throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace));
}
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
}
internal static void WriteJsonNameWithMapping(XmlWriterDelegator xmlWriter, XmlDictionaryString[] memberNames, int index)
{
xmlWriter.WriteStartElement("a", JsonGlobals.itemString, JsonGlobals.itemString);
xmlWriter.WriteAttributeString(null, JsonGlobals.itemString, null, memberNames[index].Value);
}
#endif
internal static void VerifyObjectCompatibilityWithInterface(DataContract contract, object graph, Type declaredType)
{
Type contractType = contract.GetType();
if ((contractType == typeof(XmlDataContract)) && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(declaredType))
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlObjectAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
}
if ((contractType == typeof(CollectionDataContract)) && !CollectionDataContract.IsCollectionInterface(declaredType))
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CollectionAssignedToIncompatibleInterface, graph.GetType(), declaredType)));
}
}
internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract)
{
if (WriteTypeInfo(null, runtimeContract, declaredContract))
{
VerifyType(runtimeContract);
}
}
internal void VerifyType(DataContract dataContract)
{
bool knownTypesAddedInCurrentScope = false;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
knownTypesAddedInCurrentScope = true;
}
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
}
#if !NET_NATIVE && !MERGE_DCJS
private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack();
internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (obj.GetType().GetTypeInfo().IsValueType)
{
return false;
}
if (_byValObjectsInScope.Contains(obj))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType()))));
}
_byValObjectsInScope.Push(obj);
return false;
}
internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (!obj.GetType().GetTypeInfo().IsValueType)
_byValObjectsInScope.Pop(obj);
}
#endif
internal static DataContract GetRevisedItemContract(DataContract oldItemContract)
{
if ((oldItemContract != null) &&
oldItemContract.UnderlyingType.GetTypeInfo().IsGenericType &&
(oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue))
{
return ClassDataContract.CreateClassDataContractForKeyValue(oldItemContract.UnderlyingType, oldItemContract.Namespace, new string[] { JsonGlobals.KeyString, JsonGlobals.ValueString });
}
return oldItemContract;
}
internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContract(typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type)
{
DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle)
{
DataContract dataContract = base.GetDataContract(id, typeHandle);
DataContractJsonSerializer.CheckIfTypeIsReference(dataContract);
return dataContract;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using Castle.MicroKernel;
using Castle.Windsor;
using Rhino.ServiceBus.Castle;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Serializers;
using Xunit;
using Xunit.Extensions;
namespace Rhino.ServiceBus.Tests.Bugs
{
[CLSCompliant(false)]
public class Serialization_roundtrip
{
public class Foo
{
public string Name { get; set; }
public string UName
{
get
{
return Name.ToUpper();
}
}
}
public class Bar
{
public DateTime Date { get; set; }
}
public class ItemWithInitDictionary
{
public string Name { get; set; }
public Dictionary<string, string> Arguments { get; set; }
public ItemWithInitDictionary()
{
Arguments = new Dictionary<string, string>();
}
}
public class ItemWithoutInitDictionary
{
public string Name { get; set; }
public Dictionary<string, string> Arguments { get; set; }
}
public class ItemWithObjectDictionary
{
public string Name { get; set; }
public Dictionary<string, object> Arguments { get; set; }
}
[Fact]
public void Can_use_dictionaries_initialized()
{
var serializer = new XmlMessageSerializer(new DefaultReflection(),
new CastleServiceLocator(new WindsorContainer()));
var stream = new MemoryStream();
serializer.Serialize(new object[] { new ItemWithInitDictionary { Name = "abc", Arguments = new Dictionary<string, string>
{
{"abc","cdef"}
}} }, stream);
stream.Position = 0;
var foo = (ItemWithInitDictionary)serializer.Deserialize(stream)[0];
Assert.Equal("abc", foo.Name);
Assert.Equal("cdef", foo.Arguments["abc"]);
}
[Fact]
public void Can_use_dictionaries_uninitialized()
{
var serializer = new XmlMessageSerializer(new DefaultReflection(),
new CastleServiceLocator(new WindsorContainer()));
var stream = new MemoryStream();
serializer.Serialize(new object[] { new ItemWithoutInitDictionary { Name = "abc", Arguments = new Dictionary<string, string>
{
{"abc","cdef"}
}} }, stream);
stream.Position = 0;
stream.Position = 0;
var foo = (ItemWithoutInitDictionary)serializer.Deserialize(stream)[0];
Assert.Equal("abc", foo.Name);
Assert.Equal("cdef", foo.Arguments["abc"]);
}
[Fact]
public void Can_use_dictionaries_with_a_null_value()
{
var serializer = new XmlMessageSerializer(new DefaultReflection(),
new CastleServiceLocator(new WindsorContainer()));
var stream = new MemoryStream();
serializer.Serialize(new object[] { new ItemWithoutInitDictionary { Name = "abc", Arguments = new Dictionary<string, string>
{
{"abc",null}
}} }, stream);
stream.Position = 0;
stream.Position = 0;
var foo = (ItemWithoutInitDictionary)serializer.Deserialize(stream)[0];
Assert.Equal("abc", foo.Name);
Assert.Equal(null, foo.Arguments["abc"]);
}
public class Dog
{
public string Name { get; set; }
}
[Fact]
public void Can_handle_dictionaries_where_values_are_objects()
{
var serializer = new XmlMessageSerializer(new DefaultReflection(),
new CastleServiceLocator(new WindsorContainer()));
var stream = new MemoryStream();
serializer.Serialize(new object[] { new ItemWithObjectDictionary() { Name = "abc", Arguments = new Dictionary<string, object>
{
{"abc","cdef"},
{"def", 1},
{"123", new Dog{Name = "Oscar"}}
}} }, stream);
stream.Position = 0;
stream.Position = 0;
var foo = (ItemWithObjectDictionary)serializer.Deserialize(stream)[0];
Assert.Equal("abc", foo.Name);
Assert.Equal("cdef", foo.Arguments["abc"]);
Assert.Equal(1, (int)foo.Arguments["def"]);
Assert.Equal("Oscar", ((Dog)foo.Arguments["123"]).Name);
}
[Fact]
public void Can_roundtrip()
{
var serializer = new XmlMessageSerializer(new DefaultReflection(),
new CastleServiceLocator(new WindsorContainer()));
var stream = new MemoryStream();
serializer.Serialize(new object[] { new Foo { Name = "abc" } }, stream);
stream.Position = 0;
var foo = (Foo)serializer.Deserialize(stream)[0];
Assert.Equal("abc", foo.Name);
Assert.Equal("ABC", foo.UName);
}
[Theory]
[InlineData(DateTimeKind.Local)]
[InlineData(DateTimeKind.Unspecified)]
[InlineData(DateTimeKind.Utc)]
public void Roundtrip_with_datetime_should_preserved_DateTimeKind(DateTimeKind kind)
{
var serializer = new XmlMessageSerializer(new DefaultReflection(),
new CastleServiceLocator(new WindsorContainer()));
var stream = new MemoryStream();
var date = new DateTime(DateTime.Now.Ticks, kind);
serializer.Serialize(new object[] { new Bar { Date = date } }, stream);
stream.Position = 0;
var bar = (Bar)serializer.Deserialize(stream)[0];
Assert.Equal(date, bar.Date);
Assert.Equal(kind, bar.Date.Kind);
}
[Theory]
[InlineData("it-IT")]
[InlineData("mi-NZ")]
[InlineData("es-US")]
public void Can_roundtrip_with_datetime_on_non_english_culture(string cultureName)
{
var oldCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
try
{
var serializer = new XmlMessageSerializer(new DefaultReflection(),
new CastleServiceLocator(new WindsorContainer()));
var stream = new MemoryStream();
var date = DateTime.Now;
serializer.Serialize(new object[] { new Bar { Date = date } }, stream);
stream.Position = 0;
var bar = (Bar)serializer.Deserialize(stream)[0];
Assert.Equal(date, bar.Date);
}
finally
{
Thread.CurrentThread.CurrentCulture = oldCulture;
}
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public partial class BinaryFormatterTests : RemoteExecutorTestBase
{
[Theory]
[MemberData(nameof(BasicObjectsRoundtrip_MemberData))]
public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
object clone = FormatterClone(obj, null, assemblyFormat, filterLevel, typeFormat);
if (!ReferenceEquals(obj, string.Empty)) // "" is interned and will roundtrip as the same object
{
Assert.NotSame(obj, clone);
}
CheckForAnyEquals(obj, clone);
}
// Used for updating blobs in BinaryFormatterTestData.cs
//[Fact]
public void UpdateBlobs()
{
string testDataFilePath = GetTestDataFilePath();
IEnumerable<object[]> coreTypeRecords = GetCoreTypeRecords();
string[] coreTypeBlobs = GetCoreTypeBlobs(coreTypeRecords).ToArray();
UpdateCoreTypeBlobs(testDataFilePath, coreTypeBlobs);
}
[Theory]
[MemberData(nameof(SerializableObjects_MemberData))]
public void ValidateAgainstBlobs(object obj, string[] blobs)
{
if (blobs == null || blobs.Length == 0)
{
throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " +
SerializeObjectToBlob(obj));
}
foreach (string blob in blobs)
{
CheckForAnyEquals(obj, DeserializeBlobToObject(blob));
}
}
[Fact]
public void ArraySegmentDefaultCtor()
{
// This is workaround for Xunit bug which tries to pretty print test case name and enumerate this object.
// When inner array is not initialized it throws an exception when this happens.
object obj = new ArraySegment<int>();
string corefxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
string netfxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
CheckForAnyEquals(obj, DeserializeBlobToObject(corefxBlob));
CheckForAnyEquals(obj, DeserializeBlobToObject(netfxBlob));
}
[Fact]
public void ValidateDeserializationOfObjectWithDifferentAssemblyVersion()
{
// To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data)
// For this test 9.98.7.987 is being used
var obj = new SomeType() { SomeField = 7 };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAAA2U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlAQAAAAlTb21lRmllbGQACAIAAAAHAAAACw==";
var deserialized = (SomeType)DeserializeBlobToObject(serializedObj);
Assert.Equal(obj, deserialized);
}
[Fact]
public void ValidateDeserializationOfObjectWithGenericTypeWhichGenericArgumentHasDifferentAssemblyVersion()
{
// To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data)
// For this test 9.98.7.987 is being used
var obj = new GenericTypeWithArg<SomeType>() { Test = new SomeType() { SomeField = 9 } };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAADxAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HZW5lcmljVHlwZVdpdGhBcmdgMVtbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAABFRlc3QENlN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Tb21lVHlwZQIAAAACAAAACQMAAAAFAwAAADZTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuU29tZVR5cGUBAAAACVNvbWVGaWVsZAAIAgAAAAkAAAAL";
var deserialized = (GenericTypeWithArg<SomeType>)DeserializeBlobToObject(serializedObj);
Assert.Equal(obj, deserialized);
}
[Theory]
[MemberData(nameof(SerializableEqualityComparers_MemberData))]
public void ValidateDeserializationOfEqualityComparers(object obj, string[] blobs)
{
if (blobs == null || blobs.Length == 0)
{
throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " +
SerializeObjectToBlob(obj));
}
foreach (string base64Serialized in blobs)
{
object deserializedInstance = DeserializeBlobToObject(base64Serialized);
Type objType = deserializedInstance.GetType();
Assert.True(objType.IsGenericType, $"Type `{objType.FullName}` must be generic.");
Assert.Equal("System.Collections.Generic.ObjectEqualityComparer`1", objType.GetGenericTypeDefinition().FullName);
Assert.Equal(obj.GetType().GetGenericArguments()[0], objType.GetGenericArguments()[0]);
}
}
[Fact]
public void RoundtripManyObjectsInOneStream()
{
object[][] objects = SerializableObjects_MemberData().ToArray();
var s = new MemoryStream();
var f = new BinaryFormatter();
foreach (object[] obj in objects)
{
f.Serialize(s, obj[0]);
}
s.Position = 0;
foreach (object[] obj in objects)
{
object clone = f.Deserialize(s);
CheckForAnyEquals(obj[0], clone);
}
}
[Fact]
public void SameObjectRepeatedInArray()
{
object o = new object();
object[] arr = new[] { o, o, o, o, o };
object[] result = FormatterClone(arr);
Assert.Equal(arr.Length, result.Length);
Assert.NotSame(arr, result);
Assert.NotSame(arr[0], result[0]);
for (int i = 1; i < result.Length; i++)
{
Assert.Same(result[0], result[i]);
}
}
[Theory]
[MemberData(nameof(SerializableExceptions_MemberData))]
public void Roundtrip_Exceptions(Exception expected)
{
BinaryFormatterHelpers.AssertRoundtrips(expected);
}
[Theory]
[MemberData(nameof(NonSerializableTypes_MemberData))]
public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
var f = new BinaryFormatter()
{
AssemblyFormat = assemblyFormat,
FilterLevel = filterLevel,
TypeFormat = typeFormat
};
using (var s = new MemoryStream())
{
Assert.Throws<SerializationException>(() => f.Serialize(s, obj));
}
}
[Fact]
public void SerializeNonSerializableTypeWithSurrogate()
{
var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" };
Assert.False(p.GetType().IsSerializable);
Assert.Throws<SerializationException>(() => FormatterClone(p));
NonSerializablePair<int, string> result = FormatterClone(p, new NonSerializablePairSurrogate());
Assert.NotSame(p, result);
Assert.Equal(p.Value1, result.Value1);
Assert.Equal(p.Value2, result.Value2);
}
[Fact]
public void SerializationEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new IncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected()
{
var f = new BinaryFormatter();
var obj = new DerivedIncrementCountsDuringRoundtrip(null);
Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
using (var s = new MemoryStream())
{
f.Serialize(s, obj);
s.Position = 0;
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s);
Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.IncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.IncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod);
Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod);
Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod);
}
}
[Fact]
public void Properties_Roundtrip()
{
var f = new BinaryFormatter();
Assert.Null(f.Binder);
var binder = new DelegateBinder();
f.Binder = binder;
Assert.Same(binder, f.Binder);
Assert.NotNull(f.Context);
Assert.Null(f.Context.Context);
Assert.Equal(StreamingContextStates.All, f.Context.State);
var context = new StreamingContext(StreamingContextStates.Clone);
f.Context = context;
Assert.Equal(StreamingContextStates.Clone, f.Context.State);
Assert.Null(f.SurrogateSelector);
var selector = new SurrogateSelector();
f.SurrogateSelector = selector;
Assert.Same(selector, f.SurrogateSelector);
Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat);
f.AssemblyFormat = FormatterAssemblyStyle.Full;
Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat);
Assert.Equal(TypeFilterLevel.Full, f.FilterLevel);
f.FilterLevel = TypeFilterLevel.Low;
Assert.Equal(TypeFilterLevel.Low, f.FilterLevel);
Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat);
f.TypeFormat = FormatterTypeStyle.XsdString;
Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat);
}
[Fact]
public void SerializeDeserialize_InvalidArguments_ThrowsException()
{
var f = new BinaryFormatter();
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object()));
AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple, false)]
[InlineData(FormatterAssemblyStyle.Full, true)]
public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) };
if (exceptionExpected)
{
Assert.Throws<SerializationException>(() => f.Deserialize(s));
}
else
{
var result = (Version2ClassWithoutOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Equal(null, result.Value);
}
}
[Theory]
[InlineData(FormatterAssemblyStyle.Simple)]
[InlineData(FormatterAssemblyStyle.Full)]
public void OptionalField_Missing_Success(FormatterAssemblyStyle style)
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, new Version1ClassWithoutField());
s.Position = 0;
f = new BinaryFormatter() { AssemblyFormat = style };
f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) };
var result = (Version2ClassWithOptionalField)f.Deserialize(s);
Assert.NotNull(result);
Assert.Equal(null, result.Value);
}
[Fact]
public void ObjectReference_RealObjectSerialized()
{
var obj = new ObjRefReturnsObj { Real = 42 };
object real = FormatterClone<object>(obj);
Assert.Equal(42, real);
}
[OuterLoop]
[Theory]
[MemberData(nameof(FuzzInputs_MemberData))]
public void Deserialize_FuzzInput(object obj, Random rand)
{
// Get the serialized data for the object
byte[] data = SerializeObjectToRaw(obj);
// Make some "random" changes to it
for (int i = 1; i < rand.Next(1, 100); i++)
{
data[rand.Next(data.Length)] = (byte)rand.Next(256);
}
// Try to deserialize that.
try
{
DeserializeRawToObject(data);
// Since there's no checksum, it's possible we changed data that didn't corrupt the instance
}
catch (ArgumentOutOfRangeException) { }
catch (ArrayTypeMismatchException) { }
catch (DecoderFallbackException) { }
catch (FormatException) { }
catch (IndexOutOfRangeException) { }
catch (InvalidCastException) { }
catch (OutOfMemoryException) { }
catch (OverflowException) { }
catch (NullReferenceException) { }
catch (SerializationException) { }
catch (TargetInvocationException) { }
catch (ArgumentException) { }
catch (FileLoadException) { }
}
[Fact]
public void Deserialize_EndOfStream_ThrowsException()
{
var f = new BinaryFormatter();
var s = new MemoryStream();
f.Serialize(s, 1024);
for (long i = s.Length - 1; i >= 0; i--)
{
s.Position = 0;
var data = new byte[i];
Assert.Equal(data.Length, s.Read(data, 0, data.Length));
Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data)));
}
}
[Theory]
[MemberData(nameof(CrossProcessObjects_MemberData))]
public void Roundtrip_CrossProcess(object obj)
{
string outputPath = GetTestFilePath();
string inputPath = GetTestFilePath();
// Serialize out to a file
using (FileStream fs = File.OpenWrite(outputPath))
{
new BinaryFormatter().Serialize(fs, obj);
}
// In another process, deserialize from that file and serialize to another
RemoteInvoke((remoteInput, remoteOutput) =>
{
Assert.False(File.Exists(remoteOutput));
using (FileStream input = File.OpenRead(remoteInput))
using (FileStream output = File.OpenWrite(remoteOutput))
{
var b = new BinaryFormatter();
b.Serialize(output, b.Deserialize(input));
return SuccessExitCode;
}
}, $"\"{outputPath}\"", $"\"{inputPath}\"").Dispose();
// Deserialize what the other process serialized and compare it to the original
using (FileStream fs = File.OpenRead(inputPath))
{
object deserialized = new BinaryFormatter().Deserialize(fs);
Assert.Equal(obj, deserialized);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework fails when serializing arrays with non-zero lower bounds")]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "UAPAOT does not support non-zero lower bounds")]
public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound()
{
FormatterClone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 }));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Linq;
using Umbraco.Core.Configuration;
using System.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
namespace Umbraco.Core.Services
{
/// <summary>
/// A temporary interface until we are in v8, this is used to return a different result for the same method and this interface gets implemented
/// explicitly. These methods will replace the normal ones in IContentService in v8 and this will be removed.
/// </summary>
public interface IMediaServiceOperations
{
//TODO: Remove this class in v8
//TODO: There's probably more that needs to be added like the EmptyRecycleBin, etc...
/// <summary>
/// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
Attempt<OperationStatus> MoveToRecycleBin(IMedia media, int userId = 0);
/// <summary>
/// Moves an <see cref="IMedia"/> object to a new location
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to move</param>
/// <param name="parentId">Id of the Media's new Parent</param>
/// <param name="userId">Id of the User moving the Media</param>
/// <returns>True if moving succeeded, otherwise False</returns>
Attempt<OperationStatus> Move(IMedia media, int parentId, int userId = 0);
/// <summary>
/// Permanently deletes an <see cref="IMedia"/> object
/// </summary>
/// <remarks>
/// Please note that this method will completely remove the Media from the database,
/// but current not from the file system.
/// </remarks>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
Attempt<OperationStatus> Delete(IMedia media, int userId = 0);
/// <summary>
/// Saves a single <see cref="IMedia"/> object
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Media</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
Attempt<OperationStatus> Save(IMedia media, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves a collection of <see cref="IMedia"/> objects
/// </summary>
/// <param name="medias">Collection of <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Media</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
Attempt<OperationStatus> Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true);
}
/// <summary>
/// Defines the Media Service, which is an easy access to operations involving <see cref="IMedia"/>
/// </summary>
public interface IMediaService : IContentServiceBase
{
/// <summary>
/// Gets all XML entries found in the cmsContentXml table based on the given path
/// </summary>
/// <param name="path">Path starts with</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records the query would return without paging</param>
/// <returns>A paged enumerable of XML entries of media items</returns>
/// <remarks>
/// If -1 is passed, then this will return all media xml entries, otherwise will return all descendents from the path
/// </remarks>
IEnumerable<XElement> GetPagedXmlEntries(string path, long pageIndex, int pageSize, out long totalRecords);
/// <summary>
/// Rebuilds all xml content in the cmsContentXml table for all media
/// </summary>
/// <param name="contentTypeIds">
/// Only rebuild the xml structures for the content type ids passed in, if none then rebuilds the structures
/// for all media
/// </param>
void RebuildXmlStructures(params int[] contentTypeIds);
int CountNotTrashed(string contentTypeAlias = null);
int Count(string contentTypeAlias = null);
int CountChildren(int parentId, string contentTypeAlias = null);
int CountDescendants(int parentId, string contentTypeAlias = null);
IEnumerable<IMedia> GetByIds(IEnumerable<int> ids);
IEnumerable<IMedia> GetByIds(IEnumerable<Guid> ids);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMedia(string name, Guid parentId, string mediaTypeAlias, int userId = 0);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMedia(string name, int parentId, string mediaTypeAlias, int userId = 0);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// Note that using this method will simply return a new IMedia without any identity
/// as it has not yet been persisted. It is intended as a shortcut to creating new media objects
/// that does not invoke a save operation against the database.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMedia(string name, IMedia parent, string mediaTypeAlias, int userId = 0);
/// <summary>
/// Gets an <see cref="IMedia"/> object by Id
/// </summary>
/// <param name="id">Id of the Content to retrieve</param>
/// <returns><see cref="IMedia"/></returns>
IMedia GetById(int id);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetChildren(int id);
[Obsolete("Use the overload with 'long' parameter types instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
IEnumerable<IMedia> GetPagedChildren(int id, int pageIndex, int pageSize, out int totalRecords,
string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy = "SortOrder", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string filter);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Children from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter">Search text filter</param>
/// <param name="contentTypeFilter">A list of content type Ids to filter the list by</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IMedia> GetPagedChildren(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string filter, int[] contentTypeFilter);
[Obsolete("Use the overload with 'long' parameter types instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
IEnumerable<IMedia> GetPagedDescendants(int id, int pageIndex, int pageSize, out int totalRecords,
string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IMedia> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy = "path", Direction orderDirection = Direction.Ascending, string filter = "");
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Parent Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve Descendants from</param>
/// <param name="pageIndex">Page number</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalRecords">Total records query would return without paging</param>
/// <param name="orderBy">Field to order by</param>
/// <param name="orderDirection">Direction to order by</param>
/// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
/// <param name="filter">Search text filter</param>
/// <returns>An Enumerable list of <see cref="IContent"/> objects</returns>
IEnumerable<IMedia> GetPagedDescendants(int id, long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection, bool orderBySystemField, string filter);
/// <summary>
/// Gets descendants of a <see cref="IMedia"/> object by its Id
/// </summary>
/// <param name="id">Id of the Parent to retrieve descendants from</param>
/// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetDescendants(int id);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by the Id of the <see cref="IContentType"/>
/// </summary>
/// <param name="id">Id of the <see cref="IMediaType"/></param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetMediaOfMediaType(int id);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which reside at the first level / root
/// </summary>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetRootMedia();
/// <summary>
/// Gets a collection of an <see cref="IMedia"/> objects, which resides in the Recycle Bin
/// </summary>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetMediaInRecycleBin();
/// <summary>
/// Moves an <see cref="IMedia"/> object to a new location
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to move</param>
/// <param name="parentId">Id of the Media's new Parent</param>
/// <param name="userId">Id of the User moving the Media</param>
void Move(IMedia media, int parentId, int userId = 0);
/// <summary>
/// Deletes an <see cref="IMedia"/> object by moving it to the Recycle Bin
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
void MoveToRecycleBin(IMedia media, int userId = 0);
/// <summary>
/// Empties the Recycle Bin by deleting all <see cref="IMedia"/> that resides in the bin
/// </summary>
void EmptyRecycleBin();
/// <summary>
/// Deletes all media of specified type. All children of deleted media is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="mediaTypeId">Id of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional Id of the user deleting Media</param>
void DeleteMediaOfType(int mediaTypeId, int userId = 0);
/// <summary>
/// Deletes all media of the specified types. All Descendants of deleted media that is not of these types is moved to Recycle Bin.
/// </summary>
/// <remarks>This needs extra care and attention as its potentially a dangerous and extensive operation</remarks>
/// <param name="mediaTypeIds">Ids of the <see cref="IMediaType"/>s</param>
/// <param name="userId">Optional Id of the user issueing the delete operation</param>
void DeleteMediaOfTypes(IEnumerable<int> mediaTypeIds, int userId = 0);
/// <summary>
/// Permanently deletes an <see cref="IMedia"/> object
/// </summary>
/// <remarks>
/// Please note that this method will completely remove the Media from the database,
/// but current not from the file system.
/// </remarks>
/// <param name="media">The <see cref="IMedia"/> to delete</param>
/// <param name="userId">Id of the User deleting the Media</param>
void Delete(IMedia media, int userId = 0);
/// <summary>
/// Saves a single <see cref="IMedia"/> object
/// </summary>
/// <param name="media">The <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Media</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IMedia media, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Saves a collection of <see cref="IMedia"/> objects
/// </summary>
/// <param name="medias">Collection of <see cref="IMedia"/> to save</param>
/// <param name="userId">Id of the User saving the Media</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
void Save(IEnumerable<IMedia> medias, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Gets an <see cref="IMedia"/> object by its 'UniqueId'
/// </summary>
/// <param name="key">Guid key of the Media to retrieve</param>
/// <returns><see cref="IMedia"/></returns>
IMedia GetById(Guid key);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects by Level
/// </summary>
/// <param name="level">The level to retrieve Media from</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetByLevel(int level);
/// <summary>
/// Gets a specific version of an <see cref="IMedia"/> item.
/// </summary>
/// <param name="versionId">Id of the version to retrieve</param>
/// <returns>An <see cref="IMedia"/> item</returns>
IMedia GetByVersion(Guid versionId);
/// <summary>
/// Gets a collection of an <see cref="IMedia"/> objects versions by Id
/// </summary>
/// <param name="id"></param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetVersions(int id);
/// <summary>
/// Checks whether an <see cref="IMedia"/> item has any children
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/></param>
/// <returns>True if the media has any children otherwise False</returns>
bool HasChildren(int id);
/// <summary>
/// Permanently deletes versions from an <see cref="IMedia"/> object prior to a specific date.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> object to delete versions from</param>
/// <param name="versionDate">Latest version date</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersions(int id, DateTime versionDate, int userId = 0);
/// <summary>
/// Permanently deletes specific version(s) from an <see cref="IMedia"/> object.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> object to delete a version from</param>
/// <param name="versionId">Id of the version to delete</param>
/// <param name="deletePriorVersions">Boolean indicating whether to delete versions prior to the versionId</param>
/// <param name="userId">Optional Id of the User deleting versions of a Content object</param>
void DeleteVersion(int id, Guid versionId, bool deletePriorVersions, int userId = 0);
/// <summary>
/// Gets an <see cref="IMedia"/> object from the path stored in the 'umbracoFile' property.
/// </summary>
/// <param name="mediaPath">Path of the media item to retrieve (for example: /media/1024/koala_403x328.jpg)</param>
/// <returns><see cref="IMedia"/></returns>
IMedia GetMediaByPath(string mediaPath);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetAncestors(int id);
/// <summary>
/// Gets a collection of <see cref="IMedia"/> objects, which are ancestors of the current media.
/// </summary>
/// <param name="media"><see cref="IMedia"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetAncestors(IMedia media);
/// <summary>
/// Gets descendants of a <see cref="IMedia"/> object by its Id
/// </summary>
/// <param name="media">The Parent <see cref="IMedia"/> object to retrieve descendants from</param>
/// <returns>An Enumerable flat list of <see cref="IMedia"/> objects</returns>
IEnumerable<IMedia> GetDescendants(IMedia media);
/// <summary>
/// Gets the parent of the current media as an <see cref="IMedia"/> item.
/// </summary>
/// <param name="id">Id of the <see cref="IMedia"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IMedia"/> object</returns>
IMedia GetParent(int id);
/// <summary>
/// Gets the parent of the current media as an <see cref="IMedia"/> item.
/// </summary>
/// <param name="media"><see cref="IMedia"/> to retrieve the parent from</param>
/// <returns>Parent <see cref="IMedia"/> object</returns>
IMedia GetParent(IMedia media);
/// <summary>
/// Sorts a collection of <see cref="IMedia"/> objects by updating the SortOrder according
/// to the ordering of items in the passed in <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="items"></param>
/// <param name="userId"></param>
/// <param name="raiseEvents"></param>
/// <returns>True if sorting succeeded, otherwise False</returns>
bool Sort(IEnumerable<IMedia> items, int userId = 0, bool raiseEvents = true);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IMedia"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parent">Parent <see cref="IMedia"/> for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMediaWithIdentity(string name, IMedia parent, string mediaTypeAlias, int userId = 0);
/// <summary>
/// Creates an <see cref="IMedia"/> object using the alias of the <see cref="IMediaType"/>
/// that this Media should based on.
/// </summary>
/// <remarks>
/// This method returns an <see cref="IMedia"/> object that has been persisted to the database
/// and therefor has an identity.
/// </remarks>
/// <param name="name">Name of the Media object</param>
/// <param name="parentId">Id of Parent for the new Media item</param>
/// <param name="mediaTypeAlias">Alias of the <see cref="IMediaType"/></param>
/// <param name="userId">Optional id of the user creating the media item</param>
/// <returns><see cref="IMedia"/></returns>
IMedia CreateMediaWithIdentity(string name, int parentId, string mediaTypeAlias, int userId = 0);
/// <summary>
/// Gets the content of a media as a stream.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
/// <returns>The content of the media.</returns>
Stream GetMediaFileContentStream(string filepath);
/// <summary>
/// Sets the content of a media.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
/// <param name="content">The content of the media.</param>
void SetMediaFileContent(string filepath, Stream content);
/// <summary>
/// Gets the size of a media.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
/// <returns>The size of the media.</returns>
long GetMediaFileSize(string filepath);
/// <summary>
/// Deletes a media file and all thumbnails.
/// </summary>
/// <param name="filepath">The filesystem path to the media.</param>
void DeleteMediaFile(string filepath);
[Obsolete("This should no longer be used, thumbnail generation should be done via ImageProcessor, Umbraco no longer generates '_thumb' files for media")]
void GenerateThumbnails(string filepath, PropertyType propertyType);
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Reflection;
[CustomEditor(typeof(OVRManager))]
public class OVRManagerEditor : Editor
{
override public void OnInspectorGUI()
{
DrawDefaultInspector();
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
OVRManager manager = (OVRManager)target;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Mixed Reality Capture", EditorStyles.boldLabel);
SetupBoolField("Show Properties", ref manager.expandMixedRealityCapturePropertySheet);
if (manager.expandMixedRealityCapturePropertySheet)
{
string[] layerMaskOptions = new string[32];
for (int i=0; i<32; ++i)
{
layerMaskOptions[i] = LayerMask.LayerToName(i);
if (layerMaskOptions[i].Length == 0)
{
layerMaskOptions[i] = "<Layer " + i.ToString() + ">";
}
}
EditorGUI.indentLevel++;
EditorGUILayout.Space();
SetupBoolField("enableMixedReality", ref manager.enableMixedReality);
SetupCompositoinMethodField("compositionMethod", ref manager.compositionMethod);
SetupLayerMaskField("extraHiddenLayers", ref manager.extraHiddenLayers, layerMaskOptions);
if (manager.compositionMethod == OVRManager.CompositionMethod.Direct || manager.compositionMethod == OVRManager.CompositionMethod.Sandwich)
{
EditorGUILayout.Space();
if (manager.compositionMethod == OVRManager.CompositionMethod.Direct)
{
EditorGUILayout.LabelField("Direct Composition", EditorStyles.boldLabel);
}
else
{
EditorGUILayout.LabelField("Sandwich Composition", EditorStyles.boldLabel);
}
EditorGUI.indentLevel++;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Camera", EditorStyles.boldLabel);
SetupCameraDeviceField("capturingCameraDevice", ref manager.capturingCameraDevice);
SetupBoolField("flipCameraFrameHorizontally", ref manager.flipCameraFrameHorizontally);
SetupBoolField("flipCameraFrameVertically", ref manager.flipCameraFrameVertically);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Chroma Key", EditorStyles.boldLabel);
SetupColorField("chromaKeyColor", ref manager.chromaKeyColor);
SetupFloatField("chromaKeySimilarity", ref manager.chromaKeySimilarity);
SetupFloatField("chromaKeySmoothRange", ref manager.chromaKeySmoothRange);
SetupFloatField("chromaKeySpillRange", ref manager.chromaKeySpillRange);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Dynamic Lighting", EditorStyles.boldLabel);
SetupBoolField("useDynamicLighting", ref manager.useDynamicLighting);
SetupDepthQualityField("depthQuality", ref manager.depthQuality);
SetupFloatField("dynamicLightingSmoothFactor", ref manager.dynamicLightingSmoothFactor);
SetupFloatField("dynamicLightingDepthVariationClampingValue", ref manager.dynamicLightingDepthVariationClampingValue);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Virtual Green Screen", EditorStyles.boldLabel);
SetupVirtualGreenTypeField("virtualGreenScreenType", ref manager.virtualGreenScreenType);
SetupFloatField("virtualGreenScreenTopY", ref manager.virtualGreenScreenTopY);
SetupFloatField("virtualGreenScreenBottomY", ref manager.virtualGreenScreenBottomY);
SetupBoolField("virtualGreenScreenApplyDepthCulling", ref manager.virtualGreenScreenApplyDepthCulling);
SetupFloatField("virtualGreenScreenDepthTolerance", ref manager.virtualGreenScreenDepthTolerance);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Latency Control", EditorStyles.boldLabel);
SetupFloatField("handPoseStateLatency", ref manager.handPoseStateLatency);
if (manager.compositionMethod == OVRManager.CompositionMethod.Sandwich)
{
SetupFloatField("sandwichCompositionRenderLatency", ref manager.sandwichCompositionRenderLatency);
SetupIntField("sandwichCompositionBufferedFrames", ref manager.sandwichCompositionBufferedFrames);
}
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
#endif
}
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
void SetupBoolField(string name, ref bool member)
{
EditorGUI.BeginChangeCheck();
bool value = EditorGUILayout.Toggle(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupIntField(string name, ref int member)
{
EditorGUI.BeginChangeCheck();
int value = EditorGUILayout.IntField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupFloatField(string name, ref float member)
{
EditorGUI.BeginChangeCheck();
float value = EditorGUILayout.FloatField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupDoubleField(string name, ref double member)
{
EditorGUI.BeginChangeCheck();
double value = EditorGUILayout.DoubleField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupColorField(string name, ref Color member)
{
EditorGUI.BeginChangeCheck();
Color value = EditorGUILayout.ColorField(name, member);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
member = value;
}
}
void SetupLayerMaskField(string name, ref LayerMask layerMask, string[] layerMaskOptions)
{
EditorGUI.BeginChangeCheck();
int value = EditorGUILayout.MaskField(name, layerMask, layerMaskOptions);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
layerMask = value;
}
}
void SetupCompositoinMethodField(string name, ref OVRManager.CompositionMethod method)
{
EditorGUI.BeginChangeCheck();
OVRManager.CompositionMethod value = (OVRManager.CompositionMethod)EditorGUILayout.EnumPopup(name, method);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
method = value;
}
}
void SetupCameraDeviceField(string name, ref OVRManager.CameraDevice device)
{
EditorGUI.BeginChangeCheck();
OVRManager.CameraDevice value = (OVRManager.CameraDevice)EditorGUILayout.EnumPopup(name, device);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
device = value;
}
}
void SetupDepthQualityField(string name, ref OVRManager.DepthQuality depthQuality)
{
EditorGUI.BeginChangeCheck();
OVRManager.DepthQuality value = (OVRManager.DepthQuality)EditorGUILayout.EnumPopup(name, depthQuality);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
depthQuality = value;
}
}
void SetupVirtualGreenTypeField(string name, ref OVRManager.VirtualGreenScreenType virtualGreenScreenType)
{
EditorGUI.BeginChangeCheck();
OVRManager.VirtualGreenScreenType value = (OVRManager.VirtualGreenScreenType)EditorGUILayout.EnumPopup(name, virtualGreenScreenType);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changed " + name);
virtualGreenScreenType = value;
}
}
#endif
}
| |
/********************************************************************
*
* PropertyBag.cs
* --------------
* Derived from PropertyBag.cs by Tony Allowatt
* CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp
* Last Update: 04/05/2005
*
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Reflection;
using CslaGenerator.Attributes;
using CslaGenerator.Metadata;
namespace CslaGenerator.Util.PropertyBags
{
/// <summary>
/// Represents a collection of custom properties that can be selected into a
/// PropertyGrid to provide functionality beyond that of the simple reflection
/// normally used to query an object's properties.
/// </summary>
public class RuleBag : ICustomTypeDescriptor
{
#region PropertySpecCollection class definition
/// <summary>
/// Encapsulates a collection of PropertySpec objects.
/// </summary>
[Serializable]
public class PropertySpecCollection : IList
{
private readonly ArrayList _innerArray;
/// <summary>
/// Initializes a new instance of the PropertySpecCollection class.
/// </summary>
public PropertySpecCollection()
{
_innerArray = new ArrayList();
}
/// <summary>
/// Gets or sets the element at the specified index.
/// In C#, this property is the indexer for the PropertySpecCollection class.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <value>
/// The element at the specified index.
/// </value>
public PropertySpec this[int index]
{
get { return (PropertySpec) _innerArray[index]; }
set { _innerArray[index] = value; }
}
#region IList Members
/// <summary>
/// Gets the number of elements in the PropertySpecCollection.
/// </summary>
/// <value>
/// The number of elements contained in the PropertySpecCollection.
/// </value>
public int Count
{
get { return _innerArray.Count; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection has a fixed size.
/// </summary>
/// <value>
/// true if the PropertySpecCollection has a fixed size; otherwise, false.
/// </value>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection is read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>
/// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false.
/// </value>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the collection.
/// </value>
object ICollection.SyncRoot
{
get { return null; }
}
/// <summary>
/// Removes all elements from the PropertySpecCollection.
/// </summary>
public void Clear()
{
_innerArray.Clear();
}
/// <summary>
/// Returns an enumerator that can iterate through the PropertySpecCollection.
/// </summary>
/// <returns>An IEnumerator for the entire PropertySpecCollection.</returns>
public IEnumerator GetEnumerator()
{
return _innerArray.GetEnumerator();
}
/// <summary>
/// Removes the object at the specified index of the PropertySpecCollection.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
public void RemoveAt(int index)
{
_innerArray.RemoveAt(index);
}
#endregion
/// <summary>
/// Adds a PropertySpec to the end of the PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param>
/// <returns>The PropertySpecCollection index at which the value has been added.</returns>
public int Add(PropertySpec value)
{
int index = _innerArray.Add(value);
return index;
}
/// <summary>
/// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection.
/// </summary>
/// <param name="array">The PropertySpec array whose elements should be added to the end of the
/// PropertySpecCollection.</param>
public void AddRange(PropertySpec[] array)
{
_innerArray.AddRange(array);
}
/// <summary>
/// Determines whether a PropertySpec is in the PropertySpecCollection.
/// </summary>
/// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate
/// can be a null reference (Nothing in Visual Basic).</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(PropertySpec item)
{
return _innerArray.Contains(item);
}
/// <summary>
/// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(string name)
{
foreach (PropertySpec spec in _innerArray)
if (spec.Name == name)
return true;
return false;
}
/// <summary>
/// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the
/// beginning of the target array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from PropertySpecCollection. The Array must have zero-based indexing.</param>
public void CopyTo(PropertySpec[] array)
{
_innerArray.CopyTo(array);
}
/// <summary>
/// Copies the PropertySpecCollection or a portion of it to a one-dimensional array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from the collection.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(PropertySpec[] array, int index)
{
_innerArray.CopyTo(array, index);
}
/// <summary>
/// Searches for the specified PropertySpec and returns the zero-based index of the first
/// occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(PropertySpec value)
{
return _innerArray.IndexOf(value);
}
/// <summary>
/// Searches for the PropertySpec with the specified name and returns the zero-based index of
/// the first occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(string name)
{
int i = 0;
foreach (PropertySpec spec in _innerArray)
{
//if (spec.Name == name)
if (spec.TargetProperty == name)
return i;
i++;
}
return -1;
}
/// <summary>
/// Inserts a PropertySpec object into the PropertySpecCollection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The PropertySpec to insert.</param>
public void Insert(int index, PropertySpec value)
{
_innerArray.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the PropertySpecCollection.
/// </summary>
/// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(PropertySpec obj)
{
_innerArray.Remove(obj);
}
/// <summary>
/// Removes the property with the specified name from the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(string name)
{
int index = IndexOf(name);
RemoveAt(index);
}
/// <summary>
/// Copies the elements of the PropertySpecCollection to a new PropertySpec array.
/// </summary>
/// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns>
public PropertySpec[] ToArray()
{
return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec));
}
#region Explicit interface implementations for ICollection and IList
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
CopyTo((PropertySpec[]) array, index);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.Add(object value)
{
return Add((PropertySpec) value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
bool IList.Contains(object obj)
{
return Contains((PropertySpec) obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (PropertySpec) value; }
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.IndexOf(object obj)
{
return IndexOf((PropertySpec) obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Insert(int index, object value)
{
Insert(index, (PropertySpec) value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Remove(object value)
{
Remove((PropertySpec) value);
}
#endregion
}
#endregion
#region PropertySpecDescriptor class definition
private class PropertySpecDescriptor : PropertyDescriptor
{
private readonly RuleBag _bag;
private readonly PropertySpec _item;
public PropertySpecDescriptor(PropertySpec item, RuleBag bag, string name, Attribute[] attrs)
:
base(name, attrs)
{
_bag = bag;
_item = item;
}
public override Type ComponentType
{
get { return _item.GetType(); }
}
public override bool IsReadOnly
{
get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); }
}
public override Type PropertyType
{
get { return Type.GetType(_item.TypeName); }
}
public override bool CanResetValue(object component)
{
if (_item.DefaultValue == null)
return false;
return !GetValue(component).Equals(_item.DefaultValue);
}
public override object GetValue(object component)
{
// Have the property bag raise an event to get the current value
// of the property.
var e = new PropertySpecEventArgs(_item, null);
_bag.OnGetValue(e);
return e.Value;
}
public override void ResetValue(object component)
{
SetValue(component, _item.DefaultValue);
}
public override void SetValue(object component, object value)
{
// Have the property bag raise an event to set the current value
// of the property.
var e = new PropertySpecEventArgs(_item, value);
_bag.OnSetValue(e);
}
public override bool ShouldSerializeValue(object component)
{
object val = GetValue(component);
if (_item.DefaultValue == null && val == null)
return false;
return !val.Equals(_item.DefaultValue);
}
}
#endregion
#region Properties and Events
private readonly PropertySpecCollection _properties;
private string _defaultProperty;
private Rule[] _selectedObject;
/// <summary>
/// Initializes a new instance of the RuleBag class.
/// </summary>
public RuleBag()
{
_defaultProperty = null;
_properties = new PropertySpecCollection();
}
public RuleBag(Rule obj) : this(new[] {obj})
{
}
public RuleBag(Rule[] obj)
{
_defaultProperty = "Name";
_properties = new PropertySpecCollection();
_selectedObject = obj;
InitPropertyBag();
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public string DefaultProperty
{
get { return _defaultProperty; }
set { _defaultProperty = value; }
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public Rule[] SelectedObject
{
get { return _selectedObject; }
set
{
_selectedObject = value;
InitPropertyBag();
}
}
/// <summary>
/// Gets the collection of properties contained within this RuleBag.
/// </summary>
public PropertySpecCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Occurs when a PropertyGrid requests the value of a property.
/// </summary>
public event PropertySpecEventHandler GetValue;
/// <summary>
/// Occurs when the user changes the value of a property in a PropertyGrid.
/// </summary>
public event PropertySpecEventHandler SetValue;
/// <summary>
/// Raises the GetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnGetValue(PropertySpecEventArgs e)
{
if (e.Value != null)
GetValue(this, e);
e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue);
}
/// <summary>
/// Raises the SetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnSetValue(PropertySpecEventArgs e)
{
if (SetValue != null)
SetValue(this, e);
SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value);
}
#endregion
#region Initialize Propertybag
private void InitPropertyBag()
{
PropertyInfo pi;
Type t = typeof (Rule); // _selectedObject.GetType();
PropertyInfo[] props = t.GetProperties();
// Display information for all properties.
for (int i = 0; i < props.Length; i++)
{
pi = props[i];
object[] myAttributes = pi.GetCustomAttributes(true);
string category = "";
string description = "";
bool isreadonly = false;
bool isbrowsable = true;
object defaultvalue = null;
string userfriendlyname = "";
string typeconverter = "";
string designertypename = "";
string helptopic = "";
bool bindable = true;
string editor = "";
for (int n = 0; n < myAttributes.Length; n++)
{
var a = (Attribute) myAttributes[n];
switch (a.GetType().ToString())
{
case "System.ComponentModel.CategoryAttribute":
category = ((CategoryAttribute) a).Category;
break;
case "System.ComponentModel.DescriptionAttribute":
description = ((DescriptionAttribute) a).Description;
break;
case "System.ComponentModel.ReadOnlyAttribute":
isreadonly = ((ReadOnlyAttribute) a).IsReadOnly;
break;
case "System.ComponentModel.BrowsableAttribute":
isbrowsable = ((BrowsableAttribute) a).Browsable;
break;
case "System.ComponentModel.DefaultValueAttribute":
defaultvalue = ((DefaultValueAttribute) a).Value;
break;
case "CslaGenerator.Attributes.UserFriendlyNameAttribute":
userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName;
break;
case "CslaGenerator.Attributes.HelpTopicAttribute":
helptopic = ((HelpTopicAttribute) a).HelpTopic;
break;
case "System.ComponentModel.TypeConverterAttribute":
typeconverter = ((TypeConverterAttribute) a).ConverterTypeName;
break;
case "System.ComponentModel.DesignerAttribute":
designertypename = ((DesignerAttribute) a).DesignerTypeName;
break;
case "System.ComponentModel.BindableAttribute":
bindable = ((BindableAttribute) a).Bindable;
break;
case "System.ComponentModel.EditorAttribute":
editor = ((EditorAttribute) a).EditorTypeName;
break;
}
}
userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name;
var types = new List<string>();
foreach (var obj in _selectedObject)
{
if (!types.Contains(obj.Name))
types.Add(obj.Name);
}
// here get rid of ComponentName and Parent
bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent");
if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name))
{
// CR added missing parameters
//this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic));
Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category,
description, defaultvalue, editor, typeconverter, _selectedObject,
pi.Name, helptopic, isreadonly, isbrowsable, designertypename,
bindable));
}
}
}
#endregion
private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>();
private PropertyInfo GetPropertyInfoCache(string propertyName)
{
if (!propertyInfoCache.ContainsKey(propertyName))
{
propertyInfoCache.Add(propertyName, typeof (Rule).GetProperty(propertyName));
}
return propertyInfoCache[propertyName];
}
private bool IsEnumerable(PropertyInfo prop)
{
if (prop.PropertyType == typeof (string))
return false;
Type[] interfaces = prop.PropertyType.GetInterfaces();
foreach (Type typ in interfaces)
if (typ.Name.Contains("IEnumerable"))
return true;
return false;
}
#region IsBrowsable map objectType:propertyName -> true | false
private bool IsBrowsable(string[] objectType, string propertyName)
{
try
{
/*if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None ||
GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel) &&
(propertyName == "ReadRoles" ||
propertyName == "WriteRoles"))
return false;*/
if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName)))
return false;
return true;
}
catch //(Exception e)
{
Debug.WriteLine(objectType + ":" + propertyName);
return true;
}
}
#endregion
#region Reflection functions
private object GetField(Type t, string name, object target)
{
object obj = null;
Type tx;
FieldInfo[] fields;
//fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
fields = target.GetType().GetFields(BindingFlags.Public);
tx = target.GetType();
obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {});
return obj;
}
private object SetField(Type t, string name, object value, object target)
{
object obj;
obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value});
return obj;
}
private bool SetProperty(object obj, string propertyName, object val)
{
try
{
// get a reference to the PropertyInfo, exit if no property with that
// name
PropertyInfo pi = typeof (Rule).GetProperty(propertyName);
if (pi == null)
return false;
// convert the value to the expected type
val = Convert.ChangeType(val, pi.PropertyType);
// attempt the assignment
foreach (Rule bo in (Rule[]) obj)
pi.SetValue(bo, val, null);
return true;
}
catch
{
return false;
}
}
private object GetProperty(object obj, string propertyName, object defaultValue)
{
try
{
PropertyInfo pi = GetPropertyInfoCache(propertyName);
if (!(pi == null))
{
var objs = (Rule[]) obj;
var valueList = new ArrayList();
foreach (Rule bo in objs)
{
object value = pi.GetValue(bo, null);
if (!valueList.Contains(value))
{
valueList.Add(value);
}
}
switch (valueList.Count)
{
case 1:
return valueList[0];
default:
return string.Empty;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// if property doesn't exist or throws
return defaultValue;
}
#endregion
#region ICustomTypeDescriptor explicit interface definitions
// Most of the functions required by the ICustomTypeDescriptor are
// merely pssed on to the default TypeDescriptor for this type,
// which will do something appropriate. The exceptions are noted
// below.
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
// This function searches the property list for the property
// with the same name as the DefaultProperty specified, and
// returns a property descriptor for it. If no property is
// found that matches DefaultProperty, a null reference is
// returned instead.
PropertySpec propertySpec = null;
if (_defaultProperty != null)
{
int index = _properties.IndexOf(_defaultProperty);
propertySpec = _properties[index];
}
if (propertySpec != null)
return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null);
return null;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
// Rather than passing this function on to the default TypeDescriptor,
// which would return the actual properties of RuleBag, I construct
// a list here that contains property descriptors for the elements of the
// Properties list in the bag.
var props = new ArrayList();
foreach (PropertySpec property in _properties)
{
var attrs = new ArrayList();
// If a category, description, editor, or type converter are specified
// in the PropertySpec, create attributes to define that relationship.
if (property.Category != null)
attrs.Add(new CategoryAttribute(property.Category));
if (property.Description != null)
attrs.Add(new DescriptionAttribute(property.Description));
if (property.EditorTypeName != null)
attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor)));
if (property.ConverterTypeName != null)
attrs.Add(new TypeConverterAttribute(property.ConverterTypeName));
// Additionally, append the custom attributes associated with the
// PropertySpec, if any.
if (property.Attributes != null)
attrs.AddRange(property.Attributes);
if (property.DefaultValue != null)
attrs.Add(new DefaultValueAttribute(property.DefaultValue));
attrs.Add(new BrowsableAttribute(property.Browsable));
attrs.Add(new ReadOnlyAttribute(property.ReadOnly));
attrs.Add(new BindableAttribute(property.Bindable));
var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute));
// Create a new property descriptor for the property item, and add
// it to the list.
var pd = new PropertySpecDescriptor(property,
this, property.Name, attrArray);
props.Add(pd);
}
// Convert the list of PropertyDescriptors to a collection that the
// ICustomTypeDescriptor can use, and return it.
var propArray = (PropertyDescriptor[]) props.ToArray(
typeof (PropertyDescriptor));
return new PropertyDescriptorCollection(propArray);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
}
}
| |
// Copyright 2017, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Cloud.Spanner.V1;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Spanner.V1.Snippets
{
public class GeneratedSpannerClientSnippets
{
public async Task CreateSessionAsync()
{
// Snippet: CreateSessionAsync(DatabaseName,CallSettings)
// Additional: CreateSessionAsync(DatabaseName,CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
DatabaseName database = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]");
// Make the request
Session response = await spannerClient.CreateSessionAsync(database);
// End snippet
}
public void CreateSession()
{
// Snippet: CreateSession(DatabaseName,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
DatabaseName database = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]");
// Make the request
Session response = spannerClient.CreateSession(database);
// End snippet
}
public async Task CreateSessionAsync_RequestObject()
{
// Snippet: CreateSessionAsync(CreateSessionRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
CreateSessionRequest request = new CreateSessionRequest
{
DatabaseAsDatabaseName = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
};
// Make the request
Session response = await spannerClient.CreateSessionAsync(request);
// End snippet
}
public void CreateSession_RequestObject()
{
// Snippet: CreateSession(CreateSessionRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
CreateSessionRequest request = new CreateSessionRequest
{
DatabaseAsDatabaseName = new DatabaseName("[PROJECT]", "[INSTANCE]", "[DATABASE]"),
};
// Make the request
Session response = spannerClient.CreateSession(request);
// End snippet
}
public async Task GetSessionAsync()
{
// Snippet: GetSessionAsync(SessionName,CallSettings)
// Additional: GetSessionAsync(SessionName,CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
Session response = await spannerClient.GetSessionAsync(name);
// End snippet
}
public void GetSession()
{
// Snippet: GetSession(SessionName,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
Session response = spannerClient.GetSession(name);
// End snippet
}
public async Task GetSessionAsync_RequestObject()
{
// Snippet: GetSessionAsync(GetSessionRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
GetSessionRequest request = new GetSessionRequest
{
SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
Session response = await spannerClient.GetSessionAsync(request);
// End snippet
}
public void GetSession_RequestObject()
{
// Snippet: GetSession(GetSessionRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
GetSessionRequest request = new GetSessionRequest
{
SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
Session response = spannerClient.GetSession(request);
// End snippet
}
public async Task DeleteSessionAsync()
{
// Snippet: DeleteSessionAsync(SessionName,CallSettings)
// Additional: DeleteSessionAsync(SessionName,CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
await spannerClient.DeleteSessionAsync(name);
// End snippet
}
public void DeleteSession()
{
// Snippet: DeleteSession(SessionName,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName name = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
// Make the request
spannerClient.DeleteSession(name);
// End snippet
}
public async Task DeleteSessionAsync_RequestObject()
{
// Snippet: DeleteSessionAsync(DeleteSessionRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
DeleteSessionRequest request = new DeleteSessionRequest
{
SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
await spannerClient.DeleteSessionAsync(request);
// End snippet
}
public void DeleteSession_RequestObject()
{
// Snippet: DeleteSession(DeleteSessionRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
DeleteSessionRequest request = new DeleteSessionRequest
{
SessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
};
// Make the request
spannerClient.DeleteSession(request);
// End snippet
}
public async Task ExecuteSqlAsync_RequestObject()
{
// Snippet: ExecuteSqlAsync(ExecuteSqlRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
ExecuteSqlRequest request = new ExecuteSqlRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Sql = "",
};
// Make the request
ResultSet response = await spannerClient.ExecuteSqlAsync(request);
// End snippet
}
public void ExecuteSql_RequestObject()
{
// Snippet: ExecuteSql(ExecuteSqlRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ExecuteSqlRequest request = new ExecuteSqlRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Sql = "",
};
// Make the request
ResultSet response = spannerClient.ExecuteSql(request);
// End snippet
}
public async Task ReadAsync_RequestObject()
{
// Snippet: ReadAsync(ReadRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
ReadRequest request = new ReadRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Table = "",
Columns = { },
KeySet = new KeySet(),
};
// Make the request
ResultSet response = await spannerClient.ReadAsync(request);
// End snippet
}
public void Read_RequestObject()
{
// Snippet: Read(ReadRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
ReadRequest request = new ReadRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Table = "",
Columns = { },
KeySet = new KeySet(),
};
// Make the request
ResultSet response = spannerClient.Read(request);
// End snippet
}
public async Task BeginTransactionAsync()
{
// Snippet: BeginTransactionAsync(SessionName,TransactionOptions,CallSettings)
// Additional: BeginTransactionAsync(SessionName,TransactionOptions,CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = new TransactionOptions();
// Make the request
Transaction response = await spannerClient.BeginTransactionAsync(session, options);
// End snippet
}
public void BeginTransaction()
{
// Snippet: BeginTransaction(SessionName,TransactionOptions,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions options = new TransactionOptions();
// Make the request
Transaction response = spannerClient.BeginTransaction(session, options);
// End snippet
}
public async Task BeginTransactionAsync_RequestObject()
{
// Snippet: BeginTransactionAsync(BeginTransactionRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Options = new TransactionOptions(),
};
// Make the request
Transaction response = await spannerClient.BeginTransactionAsync(request);
// End snippet
}
public void BeginTransaction_RequestObject()
{
// Snippet: BeginTransaction(BeginTransactionRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Options = new TransactionOptions(),
};
// Make the request
Transaction response = spannerClient.BeginTransaction(request);
// End snippet
}
public async Task CommitAsync1()
{
// Snippet: CommitAsync(SessionName,ByteString,IEnumerable<Mutation>,CallSettings)
// Additional: CommitAsync(SessionName,ByteString,IEnumerable<Mutation>,CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.CopyFromUtf8("");
IEnumerable<Mutation> mutations = new List<Mutation>();
// Make the request
CommitResponse response = await spannerClient.CommitAsync(session, transactionId, mutations);
// End snippet
}
public void Commit1()
{
// Snippet: Commit(SessionName,ByteString,IEnumerable<Mutation>,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.CopyFromUtf8("");
IEnumerable<Mutation> mutations = new List<Mutation>();
// Make the request
CommitResponse response = spannerClient.Commit(session, transactionId, mutations);
// End snippet
}
public async Task CommitAsync2()
{
// Snippet: CommitAsync(SessionName,TransactionOptions,IEnumerable<Mutation>,CallSettings)
// Additional: CommitAsync(SessionName,TransactionOptions,IEnumerable<Mutation>,CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions singleUseTransaction = new TransactionOptions();
IEnumerable<Mutation> mutations = new List<Mutation>();
// Make the request
CommitResponse response = await spannerClient.CommitAsync(session, singleUseTransaction, mutations);
// End snippet
}
public void Commit2()
{
// Snippet: Commit(SessionName,TransactionOptions,IEnumerable<Mutation>,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
TransactionOptions singleUseTransaction = new TransactionOptions();
IEnumerable<Mutation> mutations = new List<Mutation>();
// Make the request
CommitResponse response = spannerClient.Commit(session, singleUseTransaction, mutations);
// End snippet
}
public async Task CommitAsync_RequestObject()
{
// Snippet: CommitAsync(CommitRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Mutations = { },
};
// Make the request
CommitResponse response = await spannerClient.CommitAsync(request);
// End snippet
}
public void Commit_RequestObject()
{
// Snippet: Commit(CommitRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
Mutations = { },
};
// Make the request
CommitResponse response = spannerClient.Commit(request);
// End snippet
}
public async Task RollbackAsync()
{
// Snippet: RollbackAsync(SessionName,ByteString,CallSettings)
// Additional: RollbackAsync(SessionName,ByteString,CancellationToken)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.CopyFromUtf8("");
// Make the request
await spannerClient.RollbackAsync(session, transactionId);
// End snippet
}
public void Rollback()
{
// Snippet: Rollback(SessionName,ByteString,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
SessionName session = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]");
ByteString transactionId = ByteString.CopyFromUtf8("");
// Make the request
spannerClient.Rollback(session, transactionId);
// End snippet
}
public async Task RollbackAsync_RequestObject()
{
// Snippet: RollbackAsync(RollbackRequest,CallSettings)
// Create client
SpannerClient spannerClient = await SpannerClient.CreateAsync();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
TransactionId = ByteString.CopyFromUtf8(""),
};
// Make the request
await spannerClient.RollbackAsync(request);
// End snippet
}
public void Rollback_RequestObject()
{
// Snippet: Rollback(RollbackRequest,CallSettings)
// Create client
SpannerClient spannerClient = SpannerClient.Create();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
SessionAsSessionName = new SessionName("[PROJECT]", "[INSTANCE]", "[DATABASE]", "[SESSION]"),
TransactionId = ByteString.CopyFromUtf8(""),
};
// Make the request
spannerClient.Rollback(request);
// End snippet
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators;
using CppSharp.Generators.AST;
using CppSharp.Generators.CLI;
using CppSharp.Generators.CSharp;
namespace CppSharp.Types.Std
{
[TypeMap("va_list")]
public class VaList : TypeMap
{
public override string CLISignature(TypePrinterContext ctx)
{
return "va_list";
}
public override string CSharpSignature(TypePrinterContext ctx)
{
return "va_list";
}
public override bool IsIgnored
{
get { return true; }
}
}
[TypeMap("basic_string<char, char_traits<char>, allocator<char>>")]
public class String : TypeMap
{
public override string CLISignature(TypePrinterContext ctx)
{
return "System::String^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.Parameter.Name);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF8>({0})",
ctx.ReturnVarName);
}
public override string CSharpSignature(TypePrinterContext ctx)
{
if (ctx.Kind == TypePrinterContextKind.Managed)
return "string";
ClassTemplateSpecialization basicString = GetBasicString(ctx.Type);
var typePrinter = new CSharpTypePrinter(null);
typePrinter.PushContext(TypePrinterContextKind.Native);
return basicString.Visit(typePrinter).Type;
}
public override void CSharpMarshalToNative(CSharpMarshalContext ctx)
{
var type = ctx.Parameter.Type.Desugar();
ClassTemplateSpecialization basicString = GetBasicString(type);
var typePrinter = new CSharpTypePrinter(ctx.Context);
if (!ctx.Parameter.Type.Desugar().IsAddress())
ctx.Return.Write($"*({typePrinter.PrintNative(basicString)}*) ");
var allocator = ctx.Context.ASTContext.FindClass("allocator", false, true).First(
a => a.IsDependent && a.TranslationUnit.IsSystemHeader);
var allocatorChar = allocator.Specializations.First(s => !s.Ignore);
string qualifiedBasicString = GetQualifiedBasicString(basicString);
if (type.IsPointer() || (type.IsReference() && ctx.Declaration is Field))
{
ctx.Return.Write($@"{qualifiedBasicString}Extensions.{basicString.Name}({
ctx.Parameter.Name}, new {allocatorChar.Visit(typePrinter)}()).{
Helpers.InstanceIdentifier}");
}
else
{
var varAllocator = $"__allocator{ctx.ParameterIndex}";
var varBasicString = $"__basicString{ctx.ParameterIndex}";
ctx.Before.WriteLine($@"var {varAllocator} = new {
allocatorChar.Visit(typePrinter)}();");
ctx.Before.WriteLine($@"var {varBasicString} = {
qualifiedBasicString}Extensions.{basicString.Name}({ctx.Parameter.Name}, {
varAllocator});");
ctx.Return.Write($"{varBasicString}.{Helpers.InstanceIdentifier}");
ctx.Cleanup.WriteLine($@"{varBasicString}.Dispose({
(type.IsPointer() ? "true" : "false")});");
ctx.Cleanup.WriteLine($"{varAllocator}.Dispose();");
}
}
public override void CSharpMarshalToManaged(CSharpMarshalContext ctx)
{
var type = ctx.ReturnType.Type.Desugar();
ClassTemplateSpecialization basicString = GetBasicString(type);
var c_str = basicString.Methods.First(m => m.OriginalName == "c_str");
var typePrinter = new CSharpTypePrinter(ctx.Context);
string qualifiedBasicString = GetQualifiedBasicString(basicString);
const string varBasicString = "__basicStringRet";
ctx.Before.WriteLine($@"var {varBasicString} = {
basicString.Visit(typePrinter)}.{Helpers.CreateInstanceIdentifier}({
ctx.ReturnVarName});");
if (type.IsAddress())
{
ctx.Return.Write($@"{qualifiedBasicString}Extensions.{c_str.Name}({
varBasicString})");
}
else
{
const string varString = "__stringRet";
ctx.Before.WriteLine($@"var {varString} = {
qualifiedBasicString}Extensions.{c_str.Name}({varBasicString});");
ctx.Before.WriteLine($"{varBasicString}.Dispose(false);");
ctx.Return.Write(varString);
}
}
private static string GetQualifiedBasicString(ClassTemplateSpecialization basicString)
{
var declContext = basicString.TemplatedDecl.TemplatedDecl;
var names = new Stack<string>();
while (!(declContext is TranslationUnit))
{
var isInlineNamespace = declContext is Namespace && ((Namespace)declContext).IsInline;
if (!isInlineNamespace)
names.Push(declContext.Name);
declContext = declContext.Namespace;
}
var qualifiedBasicString = string.Join(".", names);
return $"global::{qualifiedBasicString}";
}
private static ClassTemplateSpecialization GetBasicString(Type type)
{
var desugared = type.Desugar();
var template = (desugared.GetFinalPointee() ?? desugared).Desugar();
var templateSpecializationType = template as TemplateSpecializationType;
if (templateSpecializationType != null)
return templateSpecializationType.GetClassTemplateSpecialization();
return (ClassTemplateSpecialization) ((TagType) template).Declaration;
}
}
[TypeMap("std::wstring", GeneratorKind = GeneratorKind.CLI)]
public class WString : TypeMap
{
public override string CLISignature(TypePrinterContext ctx)
{
return "System::String^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF16>({0})",
ctx.Parameter.Name);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
ctx.Return.Write("clix::marshalString<clix::E_UTF16>({0})",
ctx.ReturnVarName);
}
public override string CSharpSignature(TypePrinterContext ctx)
{
return "string";
}
public override void CSharpMarshalToNative(CSharpMarshalContext ctx)
{
ctx.Return.Write("new Std.WString()");
}
public override void CSharpMarshalToManaged(CSharpMarshalContext ctx)
{
ctx.Return.Write(ctx.ReturnVarName);
}
}
[TypeMap("std::vector", GeneratorKind = GeneratorKind.CLI)]
public class Vector : TypeMap
{
public override bool IsIgnored
{
get
{
var finalType = Type.GetFinalPointee() ?? Type;
var type = finalType as TemplateSpecializationType;
if (type == null)
{
var injectedClassNameType = (InjectedClassNameType) finalType;
type = (TemplateSpecializationType) injectedClassNameType.InjectedSpecializationType.Type;
}
var checker = new TypeIgnoreChecker(TypeMapDatabase);
type.Arguments[0].Type.Visit(checker);
return checker.IsIgnored;
}
}
public override string CLISignature(TypePrinterContext ctx)
{
return string.Format("System::Collections::Generic::List<{0}>^",
ctx.GetTemplateParameterList());
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
var isPointerToPrimitive = type.Type.IsPointerToPrimitiveType();
var managedType = isPointerToPrimitive
? new CILType(typeof(System.IntPtr))
: type.Type;
var entryString = (ctx.Parameter != null) ? ctx.Parameter.Name
: ctx.ArgName;
var tmpVarName = "_tmp" + entryString;
var cppTypePrinter = new CppTypePrinter();
var nativeType = type.Type.Visit(cppTypePrinter);
ctx.Before.WriteLine("auto {0} = std::vector<{1}>();",
tmpVarName, nativeType);
ctx.Before.WriteLine("for each({0} _element in {1})",
managedType, entryString);
ctx.Before.WriteStartBraceIndent();
{
var param = new Parameter
{
Name = "_element",
QualifiedType = type
};
var elementCtx = new MarshalContext(ctx.Context)
{
Parameter = param,
ArgName = param.Name,
};
var marshal = new CLIMarshalManagedToNativePrinter(elementCtx);
type.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
ctx.Before.Write(marshal.Context.Before);
if (isPointerToPrimitive)
ctx.Before.WriteLine("auto _marshalElement = {0}.ToPointer();",
marshal.Context.Return);
else
ctx.Before.WriteLine("auto _marshalElement = {0};",
marshal.Context.Return);
ctx.Before.WriteLine("{0}.push_back(_marshalElement);",
tmpVarName);
}
ctx.Before.WriteCloseBraceIndent();
ctx.Return.Write(tmpVarName);
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
var isPointerToPrimitive = type.Type.IsPointerToPrimitiveType();
var managedType = isPointerToPrimitive
? new CILType(typeof(System.IntPtr))
: type.Type;
var tmpVarName = "_tmp" + ctx.ArgName;
ctx.Before.WriteLine(
"auto {0} = gcnew System::Collections::Generic::List<{1}>();",
tmpVarName, managedType);
ctx.Before.WriteLine("for(auto _element : {0})",
ctx.ReturnVarName);
ctx.Before.WriteStartBraceIndent();
{
var elementCtx = new MarshalContext(ctx.Context)
{
ReturnVarName = "_element",
ReturnType = type
};
var marshal = new CLIMarshalNativeToManagedPrinter(elementCtx);
type.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(marshal.Context.Before))
ctx.Before.Write(marshal.Context.Before);
ctx.Before.WriteLine("auto _marshalElement = {0};",
marshal.Context.Return);
if (isPointerToPrimitive)
ctx.Before.WriteLine("{0}->Add({1}(_marshalElement));",
tmpVarName, managedType);
else
ctx.Before.WriteLine("{0}->Add(_marshalElement);",
tmpVarName);
}
ctx.Before.WriteCloseBraceIndent();
ctx.Return.Write(tmpVarName);
}
public override string CSharpSignature(TypePrinterContext ctx)
{
if (ctx.Kind == TypePrinterContextKind.Native)
return "Std.Vector";
return string.Format("Std.Vector<{0}>", ctx.GetTemplateParameterList());
}
public override void CSharpMarshalToNative(CSharpMarshalContext ctx)
{
ctx.Return.Write("{0}.Internal", ctx.Parameter.Name);
}
public override void CSharpMarshalToManaged(CSharpMarshalContext ctx)
{
var templateType = Type as TemplateSpecializationType;
var type = templateType.Arguments[0].Type;
ctx.Return.Write("new Std.Vector<{0}>({1})", type,
ctx.ReturnVarName);
}
}
[TypeMap("std::map", GeneratorKind = GeneratorKind.CLI)]
public class Map : TypeMap
{
public override bool IsIgnored { get { return true; } }
public override string CLISignature(TypePrinterContext ctx)
{
var type = Type as TemplateSpecializationType;
return string.Format(
"System::Collections::Generic::Dictionary<{0}, {1}>^",
type.Arguments[0].Type, type.Arguments[1].Type);
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override string CSharpSignature(TypePrinterContext ctx)
{
if (ctx.Kind == TypePrinterContextKind.Native)
return "Std.Map";
var type = Type as TemplateSpecializationType;
return string.Format(
"System.Collections.Generic.Dictionary<{0}, {1}>",
type.Arguments[0].Type, type.Arguments[1].Type);
}
}
[TypeMap("std::list", GeneratorKind = GeneratorKind.CLI)]
public class List : TypeMap
{
public override bool IsIgnored { get { return true; } }
}
[TypeMap("std::shared_ptr", GeneratorKind = GeneratorKind.CLI)]
public class SharedPtr : TypeMap
{
public override bool IsIgnored { get { return true; } }
public override string CLISignature(TypePrinterContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
public override void CLIMarshalToManaged(MarshalContext ctx)
{
throw new System.NotImplementedException();
}
}
[TypeMap("std::ostream", GeneratorKind.CLI)]
public class OStream : TypeMap
{
public override string CLISignature(TypePrinterContext ctx)
{
return "System::IO::TextWriter^";
}
public override void CLIMarshalToNative(MarshalContext ctx)
{
var marshal = (CLIMarshalManagedToNativePrinter) ctx.MarshalToNative;
if (!ctx.Parameter.Type.Desugar().IsPointer())
marshal.ArgumentPrefix.Write("*");
var marshalCtxName = string.Format("ctx_{0}", ctx.Parameter.Name);
ctx.Before.WriteLine("msclr::interop::marshal_context {0};", marshalCtxName);
ctx.Return.Write("{0}.marshal_as<std::ostream*>({1})",
marshalCtxName, ctx.Parameter.Name);
}
}
[TypeMap("std::nullptr_t", GeneratorKind = GeneratorKind.CLI)]
public class NullPtr : TypeMap
{
public override bool DoesMarshalling { get { return false; } }
public override void CLITypeReference(CLITypeReferenceCollector collector,
ASTRecord<Declaration> loc)
{
var typeRef = collector.GetTypeReference(loc.Value);
var include = new Include
{
File = "cstddef",
Kind = Include.IncludeKind.Angled,
};
typeRef.Include = include;
}
}
[TypeMap("FILE", GeneratorKind = GeneratorKind.CSharp)]
public class FILE : TypeMap
{
public override string CSharpSignature(TypePrinterContext ctx)
{
return CSharpTypePrinter.IntPtrType;
}
public override void CSharpMarshalToNative(CSharpMarshalContext ctx)
{
ctx.Return.Write(ctx.Parameter.Name);
}
public override void CSharpMarshalToManaged(CSharpMarshalContext ctx)
{
ctx.Return.Write(ctx.ReturnVarName);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Format
{
using System;
using NPOI.SS.UserModel;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Drawing;
/**
* Format a value according to the standard Excel behavior. This "standard" is
* not explicitly documented by Microsoft, so the behavior is determined by
* experimentation; see the tests.
*
* An Excel format has up to four parts, Separated by semicolons. Each part
* specifies what to do with particular kinds of values, depending on the number
* of parts given:
*
* - One part (example: <c>[Green]#.##</c>)
* If the value is a number, display according to this one part (example: green text,
* with up to two decimal points). If the value is text, display it as is.
*
* - Two parts (example: <c>[Green]#.##;[Red]#.##</c>)
* If the value is a positive number or zero, display according to the first part (example: green
* text, with up to two decimal points); if it is a negative number, display
* according to the second part (example: red text, with up to two decimal
* points). If the value is text, display it as is.
*
* - Three parts (example: <c>[Green]#.##;[Black]#.##;[Red]#.##</c>)
* If the value is a positive number, display according to the first part (example: green text, with up to
* two decimal points); if it is zero, display according to the second part
* (example: black text, with up to two decimal points); if it is a negative
* number, display according to the third part (example: red text, with up to
* two decimal points). If the value is text, display it as is.
*
* - Four parts (example: <c>[Green]#.##;[Black]#.##;[Red]#.##;[@]</c>)
* If the value is a positive number, display according to the first part (example: green text,
* with up to two decimal points); if it is zero, display according to the
* second part (example: black text, with up to two decimal points); if it is a
* negative number, display according to the third part (example: red text, with
* up to two decimal points). If the value is text, display according to the
* fourth part (example: text in the cell's usual color, with the text value
* surround by brackets).
*
* In Addition to these, there is a general format that is used when no format
* is specified. This formatting is presented by the {@link #GENERAL_FORMAT}
* object.
*
* @author Ken Arnold, Industrious Media LLC
*/
public class CellFormat
{
private String format;
private CellFormatPart posNumFmt;
private CellFormatPart zeroNumFmt;
private CellFormatPart negNumFmt;
private CellFormatPart textFmt;
private int formatPartCount;
private static readonly Regex ONE_PART = new Regex(CellFormatPart.FORMAT_PAT.ToString() + "(;|$)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
private static readonly CellFormatPart DEFAULT_TEXT_FORMAT =
new CellFormatPart("@");
/*
* Cells that cannot be formatted, e.g. cells that have a date or time
* format and have an invalid date or time value, are displayed as 255
* pound signs ("#").
*/
private const string INVALID_VALUE_FOR_FORMAT =
"###################################################" +
"###################################################" +
"###################################################" +
"###################################################" +
"###################################################";
private const string QUOTE = "\"";
private static readonly CellFormat GENERAL_FORMAT = new GeneralCellFormat();
/**
* Format a value as it would be were no format specified. This is also
* used when the format specified is <tt>General</tt>.
*/
public class GeneralCellFormat : CellFormat
{
public GeneralCellFormat()
: base("General")
{
}
public override CellFormatResult Apply(Object value)
{
String text = (new CellGeneralFormatter()).Format(value);
return new CellFormatResult(true, text, Color.Empty);
}
}
/** Maps a format string to its Parsed version for efficiencies sake. */
private static Dictionary<String, CellFormat> formatCache =
new Dictionary<String, CellFormat>();
/**
* Returns a {@link CellFormat} that applies the given format. Two calls
* with the same format may or may not return the same object.
*
* @param format The format.
*
* @return A {@link CellFormat} that applies the given format.
*/
public static CellFormat GetInstance(String format)
{
CellFormat fmt = null;
if (formatCache.ContainsKey(format))
fmt = formatCache[format];
if (fmt == null)
{
if (format.Equals("General") || format.Equals("@"))
fmt = GENERAL_FORMAT;
else
fmt = new CellFormat(format);
formatCache.Add(format, fmt);
}
return fmt;
}
/**
* Creates a new object.
*
* @param format The format.
*/
private CellFormat(String format)
{
this.format = format;
MatchCollection mc = ONE_PART.Matches(format);
List<CellFormatPart> parts = new List<CellFormatPart>();
//while (m.Success)
foreach (Match m in mc)
{
try
{
String valueDesc = m.Groups[0].Value;
// Strip out the semicolon if it's there
if (valueDesc.EndsWith(";"))
valueDesc = valueDesc.Substring(0, valueDesc.Length - 1);
parts.Add(new CellFormatPart(valueDesc));
}
catch (Exception)
{
//CellFormatter.logger.Log(Level.WARNING,
// "Invalid format: " + CellFormatter.Quote(m.Group()), e);
parts.Add(null);
}
}
formatPartCount = parts.Count;
switch (formatPartCount)
{
case 1:
posNumFmt = parts[(0)];
negNumFmt = null;
zeroNumFmt = null;
textFmt = DEFAULT_TEXT_FORMAT;
break;
case 2:
posNumFmt = parts[0];
negNumFmt = parts[1];
zeroNumFmt = null;
textFmt = DEFAULT_TEXT_FORMAT;
break;
case 3:
posNumFmt = parts[0];
negNumFmt = parts[1];
zeroNumFmt = parts[2];
textFmt = DEFAULT_TEXT_FORMAT;
break;
case 4:
default:
posNumFmt = parts[0];
negNumFmt = parts[1];
zeroNumFmt = parts[2];
textFmt = parts[3];
break;
}
}
/**
* Returns the result of Applying the format to the given value. If the
* value is a number (a type of {@link Number} object), the correct number
* format type is chosen; otherwise it is considered a text object.
*
* @param value The value
*
* @return The result, in a {@link CellFormatResult}.
*/
public virtual CellFormatResult Apply(Object value)
{
//if (value is Number) {
if (NPOI.Util.Number.IsNumber(value))
{
double val ;
double.TryParse(value.ToString(), out val);
if (val < 0 &&
((formatPartCount == 2
&& !posNumFmt.HasCondition && !negNumFmt.HasCondition)
|| (formatPartCount == 3 && !negNumFmt.HasCondition)
|| (formatPartCount == 4 && !negNumFmt.HasCondition)))
{
// The negative number format has the negative formatting required,
// e.g. minus sign or brackets, so pass a positive value so that
// the default leading minus sign is not also output
return negNumFmt.Apply(-val);
}
else
{
return GetApplicableFormatPart(val).Apply(val);
}
}
else if (value is DateTime)
{
// Don't know (and can't get) the workbook date windowing (1900 or 1904)
// so assume 1900 date windowing
Double numericValue = DateUtil.GetExcelDate((DateTime)value);
if (DateUtil.IsValidExcelDate(numericValue))
{
return GetApplicableFormatPart(numericValue).Apply(value);
}
else
{
throw new ArgumentException("value not a valid Excel date");
}
}
else
{
return textFmt.Apply(value);
}
}
/**
* Returns the result of applying the format to the given date.
*
* @param date The date.
* @param numericValue The numeric value for the date.
*
* @return The result, in a {@link CellFormatResult}.
*/
private CellFormatResult Apply(DateTime date, double numericValue)
{
return GetApplicableFormatPart(numericValue).Apply(date);
}
/**
* Fetches the appropriate value from the cell, and returns the result of
* Applying it to the appropriate format. For formula cells, the computed
* value is what is used.
*
* @param c The cell.
*
* @return The result, in a {@link CellFormatResult}.
*/
public CellFormatResult Apply(ICell c)
{
switch (UltimateType(c))
{
case CellType.Blank:
return Apply("");
case CellType.Boolean:
return Apply(c.BooleanCellValue);
case CellType.Numeric:
Double value = c.NumericCellValue;
if (GetApplicableFormatPart(value).CellFormatType == CellFormatType.DATE)
{
if (DateUtil.IsValidExcelDate(value))
{
return Apply(c.DateCellValue, value);
}
else
{
return Apply(INVALID_VALUE_FOR_FORMAT);
}
}
else
{
return Apply(value);
}
case CellType.String:
return Apply(c.StringCellValue);
default:
return Apply("?");
}
}
/**
* Uses the result of Applying this format to the value, Setting the text
* and color of a label before returning the result.
*
* @param label The label to apply to.
* @param value The value to Process.
*
* @return The result, in a {@link CellFormatResult}.
*/
public CellFormatResult Apply(Label label, Object value)
{
CellFormatResult result = Apply(value);
label.Text = (/*setter*/result.Text);
if (result.TextColor != Color.Empty)
{
label.ForeColor = (/*setter*/result.TextColor);
}
return result;
}
/**
* Uses the result of applying this format to the given date, setting the text
* and color of a label before returning the result.
*
* @param label The label to apply to.
* @param date The date.
* @param numericValue The numeric value for the date.
*
* @return The result, in a {@link CellFormatResult}.
*/
private CellFormatResult Apply(Label label, DateTime date, double numericValue)
{
CellFormatResult result = Apply(date, numericValue);
label.Text = (result.Text);
if (result.TextColor != Color.Empty)
{
label.ForeColor = (result.TextColor);
}
return result;
}
/**
* Fetches the appropriate value from the cell, and uses the result, Setting
* the text and color of a label before returning the result.
*
* @param label The label to apply to.
* @param c The cell.
*
* @return The result, in a {@link CellFormatResult}.
*/
public CellFormatResult Apply(Label label, ICell c)
{
switch (UltimateType(c))
{
case CellType.Blank:
return Apply(label, "");
case CellType.Boolean:
return Apply(label, c.BooleanCellValue);
case CellType.Numeric:
Double value = c.NumericCellValue;
if (GetApplicableFormatPart(value).CellFormatType == CellFormatType.DATE)
{
if (DateUtil.IsValidExcelDate(value))
{
return Apply(label, c.DateCellValue, value);
}
else
{
return Apply(label, INVALID_VALUE_FOR_FORMAT);
}
}
else
{
return Apply(label, value);
}
case CellType.String:
return Apply(label, c.StringCellValue);
default:
return Apply(label, "?");
}
}
/**
* Returns the {@link CellFormatPart} that applies to the value. Result
* depends on how many parts the cell format has, the cell value and any
* conditions. The value must be a {@link Number}.
*
* @param value The value.
* @return The {@link CellFormatPart} that applies to the value.
*/
private CellFormatPart GetApplicableFormatPart(Object value)
{
//if (value is Number) {
if (NPOI.Util.Number.IsNumber(value))
{
double val;
double.TryParse(value.ToString(), out val);
if (formatPartCount == 1)
{
if (!posNumFmt.HasCondition
|| (posNumFmt.HasCondition && posNumFmt.Applies(val)))
{
return posNumFmt;
}
else
{
return new CellFormatPart("General");
}
}
else if (formatPartCount == 2)
{
if ((!posNumFmt.HasCondition && val >= 0)
|| (posNumFmt.HasCondition && posNumFmt.Applies(val)))
{
return posNumFmt;
}
else if (!negNumFmt.HasCondition
|| (negNumFmt.HasCondition && negNumFmt.Applies(val)))
{
return negNumFmt;
}
else
{
// Return ###...### (255 #s) to match Excel 2007 behaviour
return new CellFormatPart(QUOTE + INVALID_VALUE_FOR_FORMAT + QUOTE);
}
}
else
{
if ((!posNumFmt.HasCondition && val > 0)
|| (posNumFmt.HasCondition && posNumFmt.Applies(val)))
{
return posNumFmt;
}
else if ((!negNumFmt.HasCondition && val < 0)
|| (negNumFmt.HasCondition && negNumFmt.Applies(val)))
{
return negNumFmt;
// Only the first two format parts can have conditions
}
else
{
return zeroNumFmt;
}
}
}
else
{
throw new ArgumentException("value must be a Number");
}
}
/**
* Returns the ultimate cell type, following the results of formulas. If
* the cell is a {@link Cell#CELL_TYPE_FORMULA}, this returns the result of
* {@link Cell#getCachedFormulaResultType()}. Otherwise this returns the
* result of {@link Cell#getCellType()}.
*
* @param cell The cell.
*
* @return The ultimate type of this cell.
*/
public static CellType UltimateType(ICell cell)
{
CellType type = cell.CellType;
if (type == CellType.Formula)
return cell.CachedFormulaResultType;
else
return type;
}
/**
* Returns <tt>true</tt> if the other object is a {@link CellFormat} object
* with the same format.
*
* @param obj The other object.
*
* @return <tt>true</tt> if the two objects are Equal.
*/
public override bool Equals(Object obj)
{
if (this == obj)
return true;
if (obj is CellFormat)
{
CellFormat that = (CellFormat)obj;
return format.Equals(that.format);
}
return false;
}
/**
* Returns a hash code for the format.
*
* @return A hash code for the format.
*/
public override int GetHashCode()
{
return format.GetHashCode();
}
public override string ToString()
{
return format;
}
}
}
| |
// <copyright file="Ilutp.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2010 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// This class performs an Incomplete LU factorization with drop tolerance
/// and partial pivoting. The drop tolerance indicates which additional entries
/// will be dropped from the factorized LU matrices.
/// </summary>
/// <remarks>
/// The ILUTP-Mem algorithm was taken from: <br/>
/// ILUTP_Mem: a Space-Efficient Incomplete LU Preconditioner
/// <br/>
/// Tzu-Yi Chen, Department of Mathematics and Computer Science, <br/>
/// Pomona College, Claremont CA 91711, USA <br/>
/// Published in: <br/>
/// Lecture Notes in Computer Science <br/>
/// Volume 3046 / 2004 <br/>
/// pp. 20 - 28 <br/>
/// Algorithm is described in Section 2, page 22
/// </remarks>
public sealed class ILUTPPreconditioner : IPreconditioner<Complex>
{
/// <summary>
/// The default fill level.
/// </summary>
public const double DefaultFillLevel = 200.0;
/// <summary>
/// The default drop tolerance.
/// </summary>
public const double DefaultDropTolerance = 0.0001;
/// <summary>
/// The decomposed upper triangular matrix.
/// </summary>
SparseMatrix _upper;
/// <summary>
/// The decomposed lower triangular matrix.
/// </summary>
SparseMatrix _lower;
/// <summary>
/// The array containing the pivot values.
/// </summary>
int[] _pivots;
/// <summary>
/// The fill level.
/// </summary>
double _fillLevel = DefaultFillLevel;
/// <summary>
/// The drop tolerance.
/// </summary>
double _dropTolerance = DefaultDropTolerance;
/// <summary>
/// The pivot tolerance.
/// </summary>
double _pivotTolerance;
/// <summary>
/// Initializes a new instance of the <see cref="ILUTPPreconditioner"/> class with the default settings.
/// </summary>
public ILUTPPreconditioner()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ILUTPPreconditioner"/> class with the specified settings.
/// </summary>
/// <param name="fillLevel">
/// The amount of fill that is allowed in the matrix. The value is a fraction of
/// the number of non-zero entries in the original matrix. Values should be positive.
/// </param>
/// <param name="dropTolerance">
/// The absolute drop tolerance which indicates below what absolute value an entry
/// will be dropped from the matrix. A drop tolerance of 0.0 means that no values
/// will be dropped. Values should always be positive.
/// </param>
/// <param name="pivotTolerance">
/// The pivot tolerance which indicates at what level pivoting will take place. A
/// value of 0.0 means that no pivoting will take place.
/// </param>
public ILUTPPreconditioner(double fillLevel, double dropTolerance, double pivotTolerance)
{
if (fillLevel < 0)
{
throw new ArgumentOutOfRangeException("fillLevel");
}
if (dropTolerance < 0)
{
throw new ArgumentOutOfRangeException("dropTolerance");
}
if (pivotTolerance < 0)
{
throw new ArgumentOutOfRangeException("pivotTolerance");
}
_fillLevel = fillLevel;
_dropTolerance = dropTolerance;
_pivotTolerance = pivotTolerance;
}
/// <summary>
/// Gets or sets the amount of fill that is allowed in the matrix. The
/// value is a fraction of the number of non-zero entries in the original
/// matrix. The standard value is 200.
/// </summary>
/// <remarks>
/// <para>
/// Values should always be positive and can be higher than 1.0. A value lower
/// than 1.0 means that the eventual preconditioner matrix will have fewer
/// non-zero entries as the original matrix. A value higher than 1.0 means that
/// the eventual preconditioner can have more non-zero values than the original
/// matrix.
/// </para>
/// <para>
/// Note that any changes to the <b>FillLevel</b> after creating the preconditioner
/// will invalidate the created preconditioner and will require a re-initialization of
/// the preconditioner.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception>
public double FillLevel
{
get { return _fillLevel; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
_fillLevel = value;
}
}
/// <summary>
/// Gets or sets the absolute drop tolerance which indicates below what absolute value
/// an entry will be dropped from the matrix. The standard value is 0.0001.
/// </summary>
/// <remarks>
/// <para>
/// The values should always be positive and can be larger than 1.0. A low value will
/// keep more small numbers in the preconditioner matrix. A high value will remove
/// more small numbers from the preconditioner matrix.
/// </para>
/// <para>
/// Note that any changes to the <b>DropTolerance</b> after creating the preconditioner
/// will invalidate the created preconditioner and will require a re-initialization of
/// the preconditioner.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception>
public double DropTolerance
{
get { return _dropTolerance; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
_dropTolerance = value;
}
}
/// <summary>
/// Gets or sets the pivot tolerance which indicates at what level pivoting will
/// take place. The standard value is 0.0 which means pivoting will never take place.
/// </summary>
/// <remarks>
/// <para>
/// The pivot tolerance is used to calculate if pivoting is necessary. Pivoting
/// will take place if any of the values in a row is bigger than the
/// diagonal value of that row divided by the pivot tolerance, i.e. pivoting
/// will take place if <b>row(i,j) > row(i,i) / PivotTolerance</b> for
/// any <b>j</b> that is not equal to <b>i</b>.
/// </para>
/// <para>
/// Note that any changes to the <b>PivotTolerance</b> after creating the preconditioner
/// will invalidate the created preconditioner and will require a re-initialization of
/// the preconditioner.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception>
public double PivotTolerance
{
get { return _pivotTolerance; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value");
}
_pivotTolerance = value;
}
}
/// <summary>
/// Returns the upper triagonal matrix that was created during the LU decomposition.
/// </summary>
/// <remarks>
/// This method is used for debugging purposes only and should normally not be used.
/// </remarks>
/// <returns>A new matrix containing the upper triagonal elements.</returns>
internal Matrix<Complex> UpperTriangle()
{
return _upper.Clone();
}
/// <summary>
/// Returns the lower triagonal matrix that was created during the LU decomposition.
/// </summary>
/// <remarks>
/// This method is used for debugging purposes only and should normally not be used.
/// </remarks>
/// <returns>A new matrix containing the lower triagonal elements.</returns>
internal Matrix<Complex> LowerTriangle()
{
return _lower.Clone();
}
/// <summary>
/// Returns the pivot array. This array is not needed for normal use because
/// the preconditioner will return the solution vector values in the proper order.
/// </summary>
/// <remarks>
/// This method is used for debugging purposes only and should normally not be used.
/// </remarks>
/// <returns>The pivot array.</returns>
internal int[] Pivots()
{
var result = new int[_pivots.Length];
for (var i = 0; i < _pivots.Length; i++)
{
result[i] = _pivots[i];
}
return result;
}
/// <summary>
/// Initializes the preconditioner and loads the internal data structures.
/// </summary>
/// <param name="matrix">
/// The <see cref="Matrix"/> upon which this preconditioner is based. Note that the
/// method takes a general matrix type. However internally the data is stored
/// as a sparse matrix. Therefore it is not recommended to pass a dense matrix.
/// </param>
/// <exception cref="ArgumentNullException"> If <paramref name="matrix"/> is <see langword="null" />.</exception>
/// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception>
public void Initialize(Matrix<Complex> matrix)
{
if (matrix == null)
{
throw new ArgumentNullException("matrix");
}
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
var sparseMatrix = (matrix is SparseMatrix) ? matrix as SparseMatrix : SparseMatrix.OfMatrix(matrix);
// The creation of the preconditioner follows the following algorithm.
// spaceLeft = lfilNnz * nnz(A)
// for i = 1, .. , n
// {
// w = a(i,*)
// for j = 1, .. , i - 1
// {
// if (w(j) != 0)
// {
// w(j) = w(j) / a(j,j)
// if (w(j) < dropTol)
// {
// w(j) = 0;
// }
// if (w(j) != 0)
// {
// w = w - w(j) * U(j,*)
// }
// }
// }
//
// for j = i, .. ,n
// {
// if w(j) <= dropTol * ||A(i,*)||
// {
// w(j) = 0
// }
// }
//
// spaceRow = spaceLeft / (n - i + 1) // Determine the space for this row
// lfil = spaceRow / 2 // space for this row of L
// l(i,j) = w(j) for j = 1, .. , i -1 // only the largest lfil elements
//
// lfil = spaceRow - nnz(L(i,:)) // space for this row of U
// u(i,j) = w(j) for j = i, .. , n // only the largest lfil - 1 elements
// w = 0
//
// if max(U(i,i + 1: n)) > U(i,i) / pivTol then // pivot if necessary
// {
// pivot by swapping the max and the diagonal entries
// Update L, U
// Update P
// }
// spaceLeft = spaceLeft - nnz(L(i,:)) - nnz(U(i,:))
// }
// Create the lower triangular matrix
_lower = new SparseMatrix(sparseMatrix.RowCount);
// Create the upper triangular matrix and copy the values
_upper = new SparseMatrix(sparseMatrix.RowCount);
// Create the pivot array
_pivots = new int[sparseMatrix.RowCount];
for (var i = 0; i < _pivots.Length; i++)
{
_pivots[i] = i;
}
var workVector = new DenseVector(sparseMatrix.RowCount);
var rowVector = new DenseVector(sparseMatrix.ColumnCount);
var indexSorting = new int[sparseMatrix.RowCount];
// spaceLeft = lfilNnz * nnz(A)
var spaceLeft = (int) _fillLevel*sparseMatrix.NonZerosCount;
// for i = 1, .. , n
for (var i = 0; i < sparseMatrix.RowCount; i++)
{
// w = a(i,*)
sparseMatrix.Row(i, workVector);
// pivot the row
PivotRow(workVector);
var vectorNorm = workVector.InfinityNorm();
// for j = 1, .. , i - 1)
for (var j = 0; j < i; j++)
{
// if (w(j) != 0)
// {
// w(j) = w(j) / a(j,j)
// if (w(j) < dropTol)
// {
// w(j) = 0;
// }
// if (w(j) != 0)
// {
// w = w - w(j) * U(j,*)
// }
if (workVector[j] != 0.0)
{
// Calculate the multiplication factors that go into the L matrix
workVector[j] = workVector[j]/_upper[j, j];
if (workVector[j].Magnitude < _dropTolerance)
{
workVector[j] = 0.0;
}
// Calculate the addition factor
if (workVector[j] != 0.0)
{
// vector update all in one go
_upper.Row(j, rowVector);
// zero out columnVector[k] because we don't need that
// one anymore for k = 0 to k = j
for (var k = 0; k <= j; k++)
{
rowVector[k] = 0.0;
}
rowVector.Multiply(workVector[j], rowVector);
workVector.Subtract(rowVector, workVector);
}
}
}
// for j = i, .. ,n
for (var j = i; j < sparseMatrix.RowCount; j++)
{
// if w(j) <= dropTol * ||A(i,*)||
// {
// w(j) = 0
// }
if (workVector[j].Magnitude <= _dropTolerance*vectorNorm)
{
workVector[j] = 0.0;
}
}
// spaceRow = spaceLeft / (n - i + 1) // Determine the space for this row
var spaceRow = spaceLeft/(sparseMatrix.RowCount - i + 1);
// lfil = spaceRow / 2 // space for this row of L
var fillLevel = spaceRow/2;
FindLargestItems(0, i - 1, indexSorting, workVector);
// l(i,j) = w(j) for j = 1, .. , i -1 // only the largest lfil elements
var lowerNonZeroCount = 0;
var count = 0;
for (var j = 0; j < i; j++)
{
if ((count > fillLevel) || (indexSorting[j] == -1))
{
break;
}
_lower[i, indexSorting[j]] = workVector[indexSorting[j]];
count += 1;
lowerNonZeroCount += 1;
}
FindLargestItems(i + 1, sparseMatrix.RowCount - 1, indexSorting, workVector);
// lfil = spaceRow - nnz(L(i,:)) // space for this row of U
fillLevel = spaceRow - lowerNonZeroCount;
// u(i,j) = w(j) for j = i + 1, .. , n // only the largest lfil - 1 elements
var upperNonZeroCount = 0;
count = 0;
for (var j = 0; j < sparseMatrix.RowCount - i; j++)
{
if ((count > fillLevel - 1) || (indexSorting[j] == -1))
{
break;
}
_upper[i, indexSorting[j]] = workVector[indexSorting[j]];
count += 1;
upperNonZeroCount += 1;
}
// Simply copy the diagonal element. Next step is to see if we pivot
_upper[i, i] = workVector[i];
// if max(U(i,i + 1: n)) > U(i,i) / pivTol then // pivot if necessary
// {
// pivot by swapping the max and the diagonal entries
// Update L, U
// Update P
// }
// Check if we really need to pivot. If (i+1) >=(mCoefficientMatrix.Rows -1) then
// we are working on the last row. That means that there is only one number
// And pivoting is useless. Also the indexSorting array will only contain
// -1 values.
if ((i + 1) < (sparseMatrix.RowCount - 1))
{
if (workVector[i].Magnitude < _pivotTolerance*workVector[indexSorting[0]].Magnitude)
{
// swap columns of u (which holds the values of A in the
// sections that haven't been partitioned yet.
SwapColumns(_upper, i, indexSorting[0]);
// Update P
var temp = _pivots[i];
_pivots[i] = _pivots[indexSorting[0]];
_pivots[indexSorting[0]] = temp;
}
}
// spaceLeft = spaceLeft - nnz(L(i,:)) - nnz(U(i,:))
spaceLeft -= lowerNonZeroCount + upperNonZeroCount;
}
for (var i = 0; i < _lower.RowCount; i++)
{
_lower[i, i] = 1.0;
}
}
/// <summary>
/// Pivot elements in the <paramref name="row"/> according to internal pivot array
/// </summary>
/// <param name="row">Row <see cref="Vector"/> to pivot in</param>
void PivotRow(Vector<Complex> row)
{
var knownPivots = new Dictionary<int, int>();
// pivot the row
for (var i = 0; i < row.Count; i++)
{
if ((_pivots[i] != i) && (!PivotMapFound(knownPivots, i)))
{
// store the pivots in the hashtable
knownPivots.Add(_pivots[i], i);
var t = row[i];
row[i] = row[_pivots[i]];
row[_pivots[i]] = t;
}
}
}
/// <summary>
/// Was pivoting already performed
/// </summary>
/// <param name="knownPivots">Pivots already done</param>
/// <param name="currentItem">Current item to pivot</param>
/// <returns><c>true</c> if performed, otherwise <c>false</c></returns>
bool PivotMapFound(Dictionary<int, int> knownPivots, int currentItem)
{
if (knownPivots.ContainsKey(_pivots[currentItem]))
{
if (knownPivots[_pivots[currentItem]].Equals(currentItem))
{
return true;
}
}
if (knownPivots.ContainsKey(currentItem))
{
if (knownPivots[currentItem].Equals(_pivots[currentItem]))
{
return true;
}
}
return false;
}
/// <summary>
/// Swap columns in the <see cref="Matrix"/>
/// </summary>
/// <param name="matrix">Source <see cref="Matrix"/>.</param>
/// <param name="firstColumn">First column index to swap</param>
/// <param name="secondColumn">Second column index to swap</param>
static void SwapColumns(Matrix<Complex> matrix, int firstColumn, int secondColumn)
{
for (var i = 0; i < matrix.RowCount; i++)
{
var temp = matrix[i, firstColumn];
matrix[i, firstColumn] = matrix[i, secondColumn];
matrix[i, secondColumn] = temp;
}
}
/// <summary>
/// Sort vector descending, not changing vector but placing sorted indicies to <paramref name="sortedIndices"/>
/// </summary>
/// <param name="lowerBound">Start sort form</param>
/// <param name="upperBound">Sort till upper bound</param>
/// <param name="sortedIndices">Array with sorted vector indicies</param>
/// <param name="values">Source <see cref="Vector"/></param>
static void FindLargestItems(int lowerBound, int upperBound, int[] sortedIndices, Vector<Complex> values)
{
// Copy the indices for the values into the array
for (var i = 0; i < upperBound + 1 - lowerBound; i++)
{
sortedIndices[i] = lowerBound + i;
}
for (var i = upperBound + 1 - lowerBound; i < sortedIndices.Length; i++)
{
sortedIndices[i] = -1;
}
// Sort the first set of items.
// Sorting starts at index 0 because the index array
// starts at zero
// and ends at index upperBound - lowerBound
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, upperBound - lowerBound, sortedIndices, values);
}
/// <summary>
/// Approximates the solution to the matrix equation <b>Ax = b</b>.
/// </summary>
/// <param name="rhs">The right hand side vector.</param>
/// <param name="lhs">The left hand side vector. Also known as the result vector.</param>
public void Approximate(Vector<Complex> rhs, Vector<Complex> lhs)
{
if (_upper == null)
{
throw new ArgumentException(Resources.ArgumentMatrixDoesNotExist);
}
if ((lhs.Count != rhs.Count) || (lhs.Count != _upper.RowCount))
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength, "rhs");
}
// Solve equation here
// Pivot(vector, result);
// Solve L*Y = B(piv,:)
var rowValues = new DenseVector(_lower.RowCount);
for (var i = 0; i < _lower.RowCount; i++)
{
_lower.Row(i, rowValues);
var sum = Complex.Zero;
for (var j = 0; j < i; j++)
{
sum += rowValues[j]*lhs[j];
}
lhs[i] = rhs[i] - sum;
}
// Solve U*X = Y;
for (var i = _upper.RowCount - 1; i > -1; i--)
{
_upper.Row(i, rowValues);
var sum = Complex.Zero;
for (var j = _upper.RowCount - 1; j > i; j--)
{
sum += rowValues[j]*lhs[j];
}
lhs[i] = 1/rowValues[i]*(lhs[i] - sum);
}
// We have a column pivot so we only need to pivot the
// end result not the incoming right hand side vector
var temp = lhs.Clone();
Pivot(temp, lhs);
}
/// <summary>
/// Pivot elements in <see cref="Vector"/> according to internal pivot array
/// </summary>
/// <param name="vector">Source <see cref="Vector"/>.</param>
/// <param name="result">Result <see cref="Vector"/> after pivoting.</param>
void Pivot(Vector<Complex> vector, Vector<Complex> result)
{
for (var i = 0; i < _pivots.Length; i++)
{
result[i] = vector[_pivots[i]];
}
}
}
/// <summary>
/// An element sort algorithm for the <see cref="ILUTPPreconditioner"/> class.
/// </summary>
/// <remarks>
/// This sort algorithm is used to sort the columns in a sparse matrix based on
/// the value of the element on the diagonal of the matrix.
/// </remarks>
internal static class ILUTPElementSorter
{
/// <summary>
/// Sorts the elements of the <paramref name="values"/> vector in decreasing
/// fashion. The vector itself is not affected.
/// </summary>
/// <param name="lowerBound">The starting index.</param>
/// <param name="upperBound">The stopping index.</param>
/// <param name="sortedIndices">An array that will contain the sorted indices once the algorithm finishes.</param>
/// <param name="values">The <see cref="Vector{T}"/> that contains the values that need to be sorted.</param>
public static void SortDoubleIndicesDecreasing(int lowerBound, int upperBound, int[] sortedIndices, Vector<Complex> values)
{
// Move all the indices that we're interested in to the beginning of the
// array. Ignore the rest of the indices.
if (lowerBound > 0)
{
for (var i = 0; i < (upperBound - lowerBound + 1); i++)
{
Exchange(sortedIndices, i, i + lowerBound);
}
upperBound -= lowerBound;
lowerBound = 0;
}
HeapSortDoublesIndices(lowerBound, upperBound, sortedIndices, values);
}
/// <summary>
/// Sorts the elements of the <paramref name="values"/> vector in decreasing
/// fashion using heap sort algorithm. The vector itself is not affected.
/// </summary>
/// <param name="lowerBound">The starting index.</param>
/// <param name="upperBound">The stopping index.</param>
/// <param name="sortedIndices">An array that will contain the sorted indices once the algorithm finishes.</param>
/// <param name="values">The <see cref="Vector{T}"/> that contains the values that need to be sorted.</param>
private static void HeapSortDoublesIndices(int lowerBound, int upperBound, int[] sortedIndices, Vector<Complex> values)
{
var start = ((upperBound - lowerBound + 1) / 2) - 1 + lowerBound;
var end = (upperBound - lowerBound + 1) - 1 + lowerBound;
BuildDoubleIndexHeap(start, upperBound - lowerBound + 1, sortedIndices, values);
while (end >= lowerBound)
{
Exchange(sortedIndices, end, lowerBound);
SiftDoubleIndices(sortedIndices, values, lowerBound, end);
end -= 1;
}
}
/// <summary>
/// Build heap for double indicies
/// </summary>
/// <param name="start">Root position</param>
/// <param name="count">Length of <paramref name="values"/></param>
/// <param name="sortedIndices">Indicies of <paramref name="values"/></param>
/// <param name="values">Target <see cref="Vector{T}"/></param>
private static void BuildDoubleIndexHeap(int start, int count, int[] sortedIndices, Vector<Complex> values)
{
while (start >= 0)
{
SiftDoubleIndices(sortedIndices, values, start, count);
start -= 1;
}
}
/// <summary>
/// Sift double indicies
/// </summary>
/// <param name="sortedIndices">Indicies of <paramref name="values"/></param>
/// <param name="values">Target <see cref="Vector{T}"/></param>
/// <param name="begin">Root position</param>
/// <param name="count">Length of <paramref name="values"/></param>
private static void SiftDoubleIndices(int[] sortedIndices, Vector<Complex> values, int begin, int count)
{
var root = begin;
while (root * 2 < count)
{
var child = root * 2;
if ((child < count - 1) && (values[sortedIndices[child]].Magnitude > values[sortedIndices[child + 1]].Magnitude))
{
child += 1;
}
if (values[sortedIndices[root]].Magnitude <= values[sortedIndices[child]].Magnitude)
{
return;
}
Exchange(sortedIndices, root, child);
root = child;
}
}
/// <summary>
/// Sorts the given integers in a decreasing fashion.
/// </summary>
/// <param name="values">The values.</param>
public static void SortIntegersDecreasing(int[] values)
{
HeapSortIntegers(values, values.Length);
}
/// <summary>
/// Sort the given integers in a decreasing fashion using heapsort algorithm
/// </summary>
/// <param name="values">Array of values to sort</param>
/// <param name="count">Length of <paramref name="values"/></param>
private static void HeapSortIntegers(int[] values, int count)
{
var start = (count / 2) - 1;
var end = count - 1;
BuildHeap(values, start, count);
while (end >= 0)
{
Exchange(values, end, 0);
Sift(values, 0, end);
end -= 1;
}
}
/// <summary>
/// Build heap
/// </summary>
/// <param name="values">Target values array</param>
/// <param name="start">Root position</param>
/// <param name="count">Length of <paramref name="values"/></param>
private static void BuildHeap(int[] values, int start, int count)
{
while (start >= 0)
{
Sift(values, start, count);
start -= 1;
}
}
/// <summary>
/// Sift values
/// </summary>
/// <param name="values">Target value array</param>
/// <param name="start">Root position</param>
/// <param name="count">Length of <paramref name="values"/></param>
private static void Sift(int[] values, int start, int count)
{
var root = start;
while (root * 2 < count)
{
var child = root * 2;
if ((child < count - 1) && (values[child] > values[child + 1]))
{
child += 1;
}
if (values[root] > values[child])
{
Exchange(values, root, child);
root = child;
}
else
{
return;
}
}
}
/// <summary>
/// Exchange values in array
/// </summary>
/// <param name="values">Target values array</param>
/// <param name="first">First value to exchange</param>
/// <param name="second">Second value to exchange</param>
private static void Exchange(int[] values, int first, int second)
{
var t = values[first];
values[first] = values[second];
values[second] = t;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Contoso.API.Areas.HelpPage.ModelDescriptions;
using Contoso.API.Areas.HelpPage.Models;
namespace Contoso.API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Xml;
namespace System.Runtime.Serialization.Json
{
using System;
using System.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Xml;
internal delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames);
internal delegate void JsonFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract);
internal class JsonFormatWriterGenerator
{
private CriticalHelper _helper;
public JsonFormatWriterGenerator()
{
_helper = new CriticalHelper();
}
internal JsonFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
return _helper.GenerateClassWriter(classContract);
}
internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionWriter(collectionContract);
}
private class CriticalHelper
{
private CodeGenerator _ilg;
private ArgBuilder _xmlWriterArg;
private ArgBuilder _contextArg;
private ArgBuilder _dataContractArg;
private LocalBuilder _objectLocal;
// Used for classes
private ArgBuilder _memberNamesArg;
private int _typeIndex = 1;
private int _childElementIndex = 0;
internal JsonFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null);
try
{
BeginMethod(_ilg, "Write" + DataContract.SanitizeTypeName(classContract.StableName.Name) + "ToJson", typeof(JsonFormatClassWriterDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(classContract.UnderlyingType);
_memberNamesArg = _ilg.GetArg(4);
WriteClass(classContract);
return (JsonFormatClassWriterDelegate)_ilg.EndMethod();
}
internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null);
try
{
BeginMethod(_ilg, "Write" + DataContract.SanitizeTypeName(collectionContract.StableName.Name) + "ToJson", typeof(JsonFormatCollectionWriterDelegate), memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(collectionContract.UnderlyingType);
WriteCollection(collectionContract);
return (JsonFormatCollectionWriterDelegate)_ilg.EndMethod();
}
private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess)
{
#if USE_REFEMIT
ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess);
#else
MethodInfo signature = delegateType.GetMethod("Invoke");
ParameterInfo[] parameters = signature.GetParameters();
Type[] paramTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
paramTypes[i] = parameters[i].ParameterType;
DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatWriterGenerator).Module, allowPrivateMemberAccess);
ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess);
#endif
}
private void InitArgs(Type objType)
{
_xmlWriterArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(2);
_dataContractArg = _ilg.GetArg(3);
_objectLocal = _ilg.DeclareLocal(objType, "objSerialized");
ArgBuilder objectArg = _ilg.GetArg(1);
_ilg.Load(objectArg);
// Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter.
// DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (objType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod);
}
//Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>.
else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
{
ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType);
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments));
_ilg.New(dc.KeyValuePairAdapterConstructorInfo);
}
else
{
_ilg.ConvertValue(objectArg.ArgType, objType);
}
_ilg.Stloc(_objectLocal);
}
private void InvokeOnSerializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerializing(classContract.BaseContract);
if (classContract.OnSerializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerializing);
}
}
private void InvokeOnSerialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerialized(classContract.BaseContract);
if (classContract.OnSerialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerialized);
}
}
private void WriteClass(ClassDataContract classContract)
{
InvokeOnSerializing(classContract);
if (classContract.IsISerializable)
{
_ilg.Call(_contextArg, JsonFormatGeneratorStatics.WriteJsonISerializableMethod, _xmlWriterArg, _objectLocal);
}
else
{
if (classContract.HasExtensionData)
{
LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData");
_ilg.Load(_objectLocal);
_ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfIExtensibleDataObject);
_ilg.LoadMember(JsonFormatGeneratorStatics.ExtensionDataProperty);
_ilg.Store(extensionDataLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, -1);
WriteMembers(classContract, extensionDataLocal, classContract);
}
else
{
WriteMembers(classContract, null, classContract);
}
}
InvokeOnSerialized(classContract);
}
private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract)
{
int memberCount = (classContract.BaseContract == null) ? 0 :
WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract);
int classMemberCount = classContract.Members.Count;
_ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classMemberCount);
for (int i = 0; i < classMemberCount; i++, memberCount++)
{
DataMember member = classContract.Members[i];
Type memberType = member.MemberType;
LocalBuilder memberValue = null;
_ilg.Load(_contextArg);
_ilg.Call(methodInfo: member.IsGetOnlyCollection ?
XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod :
XmlFormatGeneratorStatics.ResetIsGetOnlyCollectionMethod);
if (!member.EmitDefaultValue)
{
memberValue = LoadMemberValue(member);
_ilg.IfNotDefaultValue(memberValue);
}
bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames[i]);
if (requiresNameAttribute || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, name: null, nameIndex: i + _childElementIndex))
{
// Note: DataContractSerializer has member-conflict logic here to deal with the schema export
// requirement that the same member can't be of two different types.
if (requiresNameAttribute)
{
_ilg.Call(thisObj: null, JsonFormatGeneratorStatics.WriteJsonNameWithMappingMethod, _xmlWriterArg, _memberNamesArg, i + _childElementIndex);
}
else
{
WriteStartElement(nameLocal: null, nameIndex: i + _childElementIndex);
}
if (memberValue == null)
memberValue = LoadMemberValue(member);
WriteValue(memberValue);
WriteEndElement();
}
if (classContract.HasExtensionData)
{
_ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, memberCount);
}
if (!member.EmitDefaultValue)
{
if (member.IsRequired)
{
_ilg.Else();
_ilg.Call(thisObj: null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType);
}
_ilg.EndIf();
}
}
_typeIndex++;
_childElementIndex += classMemberCount;
return memberCount;
}
private LocalBuilder LoadMemberValue(DataMember member)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(member.MemberInfo);
LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value");
_ilg.Stloc(memberValue);
return memberValue;
}
private void WriteCollection(CollectionDataContract collectionContract)
{
LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName");
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.CollectionItemNameProperty);
_ilg.Store(itemName);
if (collectionContract.Kind == CollectionKind.Array)
{
Type itemType = collectionContract.ItemType;
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal);
if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName))
{
WriteArrayAttribute();
_ilg.For(i, 0, _objectLocal);
if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemName, 0 /*nameIndex*/))
{
WriteStartElement(itemName, 0 /*nameIndex*/);
_ilg.LoadArrayElement(_objectLocal, i);
LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue");
_ilg.Stloc(memberValue);
WriteValue(memberValue);
WriteEndElement();
}
_ilg.EndFor();
}
}
else
{
MethodInfo incrementCollectionCountMethod = null;
switch (collectionContract.Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
break;
case CollectionKind.GenericDictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
break;
}
if (incrementCollectionCountMethod != null)
{
_ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal);
}
bool isDictionary = false, isGenericDictionary = false;
Type enumeratorType = null;
Type[] keyValueTypes = null;
if (collectionContract.Kind == CollectionKind.GenericDictionary)
{
isGenericDictionary = true;
keyValueTypes = collectionContract.ItemType.GetGenericArguments();
enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
}
else if (collectionContract.Kind == CollectionKind.Dictionary)
{
isDictionary = true;
keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
enumeratorType = Globals.TypeOfDictionaryEnumerator;
}
else
{
enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
}
MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (moveNextMethod == null || getCurrentMethod == null)
{
if (enumeratorType.IsInterface)
{
if (moveNextMethod == null)
moveNextMethod = JsonFormatGeneratorStatics.MoveNextMethod;
if (getCurrentMethod == null)
getCurrentMethod = JsonFormatGeneratorStatics.GetCurrentMethod;
}
else
{
Type ienumeratorInterface = Globals.TypeOfIEnumerator;
CollectionKind kind = collectionContract.Kind;
if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
{
Type[] interfaceTypes = enumeratorType.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType.IsGenericType
&& interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
&& interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
{
ienumeratorInterface = interfaceType;
break;
}
}
}
if (moveNextMethod == null)
moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
if (getCurrentMethod == null)
getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
}
}
Type elementType = getCurrentMethod.ReturnType;
LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue");
LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator");
_ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod);
if (isDictionary)
{
ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator });
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator);
_ilg.New(dictEnumCtor);
}
else if (isGenericDictionary)
{
Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam });
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam);
_ilg.New(dictEnumCtor);
}
_ilg.Stloc(enumerator);
bool canWriteSimpleDictionary = isDictionary || isGenericDictionary;
if (canWriteSimpleDictionary)
{
Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes);
PropertyInfo genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString);
PropertyInfo genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString);
_ilg.Load(_contextArg);
_ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatWriteProperty);
_ilg.If();
WriteObjectAttribute();
LocalBuilder pairKey = _ilg.DeclareLocal(Globals.TypeOfString, "key");
LocalBuilder pairValue = _ilg.DeclareLocal(keyValueTypes[1], "value");
_ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod);
_ilg.LoadAddress(currentValue);
_ilg.LoadMember(genericDictionaryKeyProperty);
_ilg.ToString(keyValueTypes[0]);
_ilg.Stloc(pairKey);
_ilg.LoadAddress(currentValue);
_ilg.LoadMember(genericDictionaryValueProperty);
_ilg.Stloc(pairValue);
WriteStartElement(pairKey, 0 /*nameIndex*/);
WriteValue(pairValue);
WriteEndElement();
_ilg.EndForEach(moveNextMethod);
_ilg.Else();
}
WriteArrayAttribute();
_ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod);
if (incrementCollectionCountMethod == null)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
}
if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemName, 0 /*nameIndex*/))
{
WriteStartElement(itemName, 0 /*nameIndex*/);
if (isGenericDictionary || isDictionary)
{
_ilg.Call(_dataContractArg, JsonFormatGeneratorStatics.GetItemContractMethod);
_ilg.Call(JsonFormatGeneratorStatics.GetRevisedItemContractMethod);
_ilg.Call(JsonFormatGeneratorStatics.GetJsonDataContractMethod);
_ilg.Load(_xmlWriterArg);
_ilg.Load(currentValue);
_ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject);
_ilg.Load(_contextArg);
_ilg.Load(currentValue.LocalType);
_ilg.LoadMember(JsonFormatGeneratorStatics.TypeHandleProperty);
_ilg.Call(JsonFormatGeneratorStatics.WriteJsonValueMethod);
}
else
{
WriteValue(currentValue);
}
WriteEndElement();
}
_ilg.EndForEach(moveNextMethod);
if (canWriteSimpleDictionary)
{
_ilg.EndIf();
}
}
}
private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder name, int nameIndex)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
return false;
// load writer
if (type.IsValueType)
{
_ilg.Load(_xmlWriterArg);
}
else
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
}
// load primitive value
if (value != null)
{
_ilg.Load(value);
}
else if (memberInfo != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(memberInfo);
}
else
{
_ilg.LoadArrayElement(_objectLocal, arrayItemIndex);
}
// load name
if (name != null)
{
_ilg.Load(name);
}
else
{
_ilg.LoadArrayElement(_memberNamesArg, nameIndex);
}
// load namespace
_ilg.Load(null);
// call method to write primitive
_ilg.Call(primitiveContract.XmlFormatWriterMethod);
return true;
}
private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string writeArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
writeArrayMethod = "WriteJsonBooleanArray";
break;
case TypeCode.DateTime:
writeArrayMethod = "WriteJsonDateTimeArray";
break;
case TypeCode.Decimal:
writeArrayMethod = "WriteJsonDecimalArray";
break;
case TypeCode.Int32:
writeArrayMethod = "WriteJsonInt32Array";
break;
case TypeCode.Int64:
writeArrayMethod = "WriteJsonInt64Array";
break;
case TypeCode.Single:
writeArrayMethod = "WriteJsonSingleArray";
break;
case TypeCode.Double:
writeArrayMethod = "WriteJsonDoubleArray";
break;
default:
break;
}
if (writeArrayMethod != null)
{
WriteArrayAttribute();
MethodInfo writeArrayMethodInfo = typeof(JsonWriterDelegator).GetMethod(
writeArrayMethod,
Globals.ScanAllMembers,
new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
_ilg.Call(_xmlWriterArg, writeArrayMethodInfo, value, itemName, null);
return true;
}
return false;
}
private void WriteArrayAttribute()
{
_ilg.Call(_xmlWriterArg, JsonFormatGeneratorStatics.WriteAttributeStringMethod,
null /* prefix */,
JsonGlobals.typeString /* local name */,
string.Empty /* namespace */,
JsonGlobals.arrayString /* value */);
}
private void WriteObjectAttribute()
{
_ilg.Call(_xmlWriterArg, JsonFormatGeneratorStatics.WriteAttributeStringMethod,
null /* prefix */,
JsonGlobals.typeString /* local name */,
null /* namespace */,
JsonGlobals.objectString /* value */);
}
private void WriteValue(LocalBuilder memberValue)
{
Type memberType = memberValue.LocalType;
bool isNullableOfT = (memberType.IsGenericType &&
memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
if (memberType.IsValueType && !isNullableOfT)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null)
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
else
InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, false /* writeXsiType */);
}
else
{
if (isNullableOfT)
{
memberValue = UnwrapNullableObject(memberValue); //Leaves !HasValue on stack
memberType = memberValue.LocalType;
}
else
{
_ilg.Load(memberValue);
_ilg.Load(null);
_ilg.Ceq();
}
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject)
{
if (isNullableOfT)
{
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
}
else
{
_ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue);
}
}
else
{
if (memberType == Globals.TypeOfObject || //boxed Nullable<T>
memberType == Globals.TypeOfValueType ||
((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType))
{
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue");
memberType = memberValue.LocalType;
_ilg.Stloc(memberValue);
_ilg.If(memberValue, Cmp.EqualTo, null);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
}
InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
memberValue, memberType, false /* writeXsiType */);
if (memberType == Globals.TypeOfObject) //boxed Nullable<T>
_ilg.EndIf();
}
_ilg.EndIf();
}
}
private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
LocalBuilder typeHandleValue = _ilg.DeclareLocal(typeof(RuntimeTypeHandle), "typeHandleValue");
_ilg.Call(memberValue, XmlFormatGeneratorStatics.GetTypeMethod);
_ilg.Call(XmlFormatGeneratorStatics.GetTypeHandleMethod);
_ilg.Stloc(typeHandleValue);
_ilg.LoadAddress(typeHandleValue);
_ilg.Ldtoken(memberType);
_ilg.Call(typeof(RuntimeTypeHandle).GetMethod("Equals", new Type[] { typeof(RuntimeTypeHandle) }));
_ilg.Load(writeXsiType);
_ilg.Load(DataContract.GetId(memberType.TypeHandle));
_ilg.Ldtoken(memberType);
_ilg.Call(methodInfo);
}
private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack
{
Type memberType = memberValue.LocalType;
Label onNull = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
_ilg.LoadAddress(memberValue);
while (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
Type innerType = memberType.GetGenericArguments()[0];
_ilg.Dup();
_ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_HasValue"));
_ilg.Brfalse(onNull);
_ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_Value"));
memberType = innerType;
}
memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue");
_ilg.Stloc(memberValue);
_ilg.Load(false); //isNull
_ilg.Br(end);
_ilg.MarkLabel(onNull);
_ilg.Pop();
_ilg.LoadAddress(memberValue);
_ilg.InitObj(memberType);
_ilg.Load(true); //isNull
_ilg.MarkLabel(end);
return memberValue;
}
private void WriteStartElement(LocalBuilder nameLocal, int nameIndex)
{
_ilg.Load(_xmlWriterArg);
// localName
if (nameLocal == null)
_ilg.LoadArrayElement(_memberNamesArg, nameIndex);
else
_ilg.Load(nameLocal);
// namespace
_ilg.Load(null);
if (nameLocal != null && nameLocal.LocalType == Globals.TypeOfString)
{
_ilg.Call(JsonFormatGeneratorStatics.WriteStartElementStringMethod);
}
else
{
_ilg.Call(JsonFormatGeneratorStatics.WriteStartElementMethod);
}
}
private void WriteEndElement()
{
_ilg.Call(_xmlWriterArg, JsonFormatGeneratorStatics.WriteEndElementMethod);
}
}
}
}
| |
//
// ILProcessor.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// 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 ScriptSharp.Collections.Generic;
namespace ScriptSharp.Importer.IL.Cil {
internal /* public */ sealed class ILProcessor {
readonly MethodBody body;
readonly Collection<Instruction> instructions;
public MethodBody Body {
get { return body; }
}
internal ILProcessor (MethodBody body)
{
this.body = body;
this.instructions = body.Instructions;
}
public Instruction Create (OpCode opcode)
{
return Instruction.Create (opcode);
}
public Instruction Create (OpCode opcode, TypeReference type)
{
return Instruction.Create (opcode, type);
}
public Instruction Create (OpCode opcode, CallSite site)
{
return Instruction.Create (opcode, site);
}
public Instruction Create (OpCode opcode, MethodReference method)
{
return Instruction.Create (opcode, method);
}
public Instruction Create (OpCode opcode, FieldReference field)
{
return Instruction.Create (opcode, field);
}
public Instruction Create (OpCode opcode, string value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, sbyte value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, byte value)
{
if (opcode.OperandType == OperandType.ShortInlineVar)
return Instruction.Create (opcode, body.Variables [value]);
if (opcode.OperandType == OperandType.ShortInlineArg)
return Instruction.Create (opcode, body.GetParameter (value));
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, int value)
{
if (opcode.OperandType == OperandType.InlineVar)
return Instruction.Create (opcode, body.Variables [value]);
if (opcode.OperandType == OperandType.InlineArg)
return Instruction.Create (opcode, body.GetParameter (value));
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, long value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, float value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, double value)
{
return Instruction.Create (opcode, value);
}
public Instruction Create (OpCode opcode, Instruction target)
{
return Instruction.Create (opcode, target);
}
public Instruction Create (OpCode opcode, Instruction [] targets)
{
return Instruction.Create (opcode, targets);
}
public Instruction Create (OpCode opcode, VariableDefinition variable)
{
return Instruction.Create (opcode, variable);
}
public Instruction Create (OpCode opcode, ParameterDefinition parameter)
{
return Instruction.Create (opcode, parameter);
}
public void Emit (OpCode opcode)
{
Append (Create (opcode));
}
public void Emit (OpCode opcode, TypeReference type)
{
Append (Create (opcode, type));
}
public void Emit (OpCode opcode, MethodReference method)
{
Append (Create (opcode, method));
}
public void Emit (OpCode opcode, CallSite site)
{
Append (Create (opcode, site));
}
public void Emit (OpCode opcode, FieldReference field)
{
Append (Create (opcode, field));
}
public void Emit (OpCode opcode, string value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, byte value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, sbyte value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, int value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, long value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, float value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, double value)
{
Append (Create (opcode, value));
}
public void Emit (OpCode opcode, Instruction target)
{
Append (Create (opcode, target));
}
public void Emit (OpCode opcode, Instruction [] targets)
{
Append (Create (opcode, targets));
}
public void Emit (OpCode opcode, VariableDefinition variable)
{
Append (Create (opcode, variable));
}
public void Emit (OpCode opcode, ParameterDefinition parameter)
{
Append (Create (opcode, parameter));
}
public void InsertBefore (Instruction target, Instruction instruction)
{
if (target == null)
throw new ArgumentNullException ("target");
if (instruction == null)
throw new ArgumentNullException ("instruction");
var index = instructions.IndexOf (target);
if (index == -1)
throw new ArgumentOutOfRangeException ("target");
instructions.Insert (index, instruction);
}
public void InsertAfter (Instruction target, Instruction instruction)
{
if (target == null)
throw new ArgumentNullException ("target");
if (instruction == null)
throw new ArgumentNullException ("instruction");
var index = instructions.IndexOf (target);
if (index == -1)
throw new ArgumentOutOfRangeException ("target");
instructions.Insert (index + 1, instruction);
}
public void Append (Instruction instruction)
{
if (instruction == null)
throw new ArgumentNullException ("instruction");
instructions.Add (instruction);
}
public void Replace (Instruction target, Instruction instruction)
{
if (target == null)
throw new ArgumentNullException ("target");
if (instruction == null)
throw new ArgumentNullException ("instruction");
InsertAfter (target, instruction);
Remove (target);
}
public void Remove (Instruction instruction)
{
if (instruction == null)
throw new ArgumentNullException ("instruction");
if (!instructions.Remove (instruction))
throw new ArgumentOutOfRangeException ("instruction");
}
}
}
| |
// 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 System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateMember.GenerateVariable
{
internal abstract partial class AbstractGenerateVariableService<TService, TSimpleNameSyntax, TExpressionSyntax>
{
private partial class GenerateVariableCodeAction : CodeAction
{
private readonly TService _service;
private readonly State _state;
private readonly bool _generateProperty;
private readonly bool _isReadonly;
private readonly bool _isConstant;
private readonly bool _returnsByRef;
private readonly SemanticDocument _document;
private readonly string _equivalenceKey;
public GenerateVariableCodeAction(
TService service,
SemanticDocument document,
State state,
bool generateProperty,
bool isReadonly,
bool isConstant,
bool returnsByRef)
{
_service = service;
_document = document;
_state = state;
_generateProperty = generateProperty;
_isReadonly = isReadonly;
_isConstant = isConstant;
_returnsByRef = returnsByRef;
_equivalenceKey = Title;
}
protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
var solution = _document.Project.Solution;
var syntaxTree = _document.SyntaxTree;
var generateUnsafe = _state.TypeMemberType.IsUnsafe() &&
!_state.IsContainedInUnsafeType;
var otions = new CodeGenerationOptions(
afterThisLocation: _state.AfterThisLocation,
beforeThisLocation: _state.BeforeThisLocation,
contextLocation: _state.IdentifierToken.GetLocation());
if (_generateProperty)
{
var getAccessor = CreateAccessor(DetermineMaximalAccessibility(_state), cancellationToken);
var setAccessor = _isReadonly || _returnsByRef
? null
: CreateAccessor(DetermineMinimalAccessibility(_state), cancellationToken);
var propertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: DetermineMaximalAccessibility(_state),
modifiers: new DeclarationModifiers(isStatic: _state.IsStatic, isUnsafe: generateUnsafe),
type: _state.TypeMemberType,
returnsByRef: _returnsByRef,
explicitInterfaceSymbol: null,
name: _state.IdentifierToken.ValueText,
isIndexer: _state.IsIndexer,
parameters: _state.Parameters,
getMethod: getAccessor,
setMethod: setAccessor);
return CodeGenerator.AddPropertyDeclarationAsync(
solution, _state.TypeToGenerateIn, propertySymbol, otions, cancellationToken);
}
else
{
var fieldSymbol = CodeGenerationSymbolFactory.CreateFieldSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: DetermineMinimalAccessibility(_state),
modifiers: _isConstant
? new DeclarationModifiers(isConst: true, isUnsafe: generateUnsafe)
: new DeclarationModifiers(isStatic: _state.IsStatic, isReadOnly: _isReadonly, isUnsafe: generateUnsafe),
type: _state.TypeMemberType,
name: _state.IdentifierToken.ValueText);
return CodeGenerator.AddFieldDeclarationAsync(
solution, _state.TypeToGenerateIn, fieldSymbol, otions, cancellationToken);
}
}
private IMethodSymbol CreateAccessor(
Accessibility accessibility, CancellationToken cancellationToken)
{
return CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: accessibility,
statements: GenerateStatements(cancellationToken));
}
private ImmutableArray<SyntaxNode> GenerateStatements(
CancellationToken cancellationToken)
{
var syntaxFactory = _document.Project.Solution.Workspace.Services.GetLanguageServices(_state.TypeToGenerateIn.Language).GetService<SyntaxGenerator>();
var throwStatement = CodeGenerationHelpers.GenerateThrowStatement(
syntaxFactory, this._document, "System.NotImplementedException", cancellationToken);
return _state.TypeToGenerateIn.TypeKind != TypeKind.Interface && _returnsByRef
? ImmutableArray.Create(throwStatement)
: default(ImmutableArray<SyntaxNode>);
}
private Accessibility DetermineMaximalAccessibility(State state)
{
if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface)
{
return Accessibility.NotApplicable;
}
var accessibility = Accessibility.Public;
// Ensure that we're not overly exposing a type.
var containingTypeAccessibility = state.TypeToGenerateIn.DetermineMinimalAccessibility();
var effectiveAccessibility = AccessibilityUtilities.Minimum(
containingTypeAccessibility, accessibility);
var returnTypeAccessibility = state.TypeMemberType.DetermineMinimalAccessibility();
if (AccessibilityUtilities.Minimum(effectiveAccessibility, returnTypeAccessibility) !=
effectiveAccessibility)
{
return returnTypeAccessibility;
}
return accessibility;
}
private Accessibility DetermineMinimalAccessibility(State state)
{
if (state.TypeToGenerateIn.TypeKind == TypeKind.Interface)
{
return Accessibility.NotApplicable;
}
// Otherwise, figure out what accessibility modifier to use and optionally mark
// it as static.
var syntaxFacts = _document.Document.GetLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsAttributeNamedArgumentIdentifier(state.SimpleNameOrMemberAccessExpressionOpt))
{
return Accessibility.Public;
}
else if (state.ContainingType.IsContainedWithin(state.TypeToGenerateIn))
{
return Accessibility.Private;
}
else if (DerivesFrom(state, state.ContainingType) && state.IsStatic)
{
// NOTE(cyrusn): We only generate protected in the case of statics. Consider
// the case where we're generating into one of our base types. i.e.:
//
// class B : A { void Foo() { A a; a.Foo(); }
//
// In this case we can *not* mark the method as protected. 'B' can only
// access protected members of 'A' through an instance of 'B' (or a subclass
// of B). It can not access protected members through an instance of the
// superclass. In this case we need to make the method public or internal.
//
// However, this does not apply if the method will be static. i.e.
//
// class B : A { void Foo() { A.Foo(); }
//
// B can access the protected statics of A, and so we generate 'Foo' as
// protected.
return Accessibility.Protected;
}
else if (state.ContainingType.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(state.TypeToGenerateIn.ContainingAssembly))
{
return Accessibility.Internal;
}
else
{
// TODO: Code coverage - we need a unit-test that generates across projects
return Accessibility.Public;
}
}
private bool DerivesFrom(State state, INamedTypeSymbol containingType)
{
return containingType.GetBaseTypes().Select(t => t.OriginalDefinition)
.Contains(state.TypeToGenerateIn);
}
public override string Title
{
get
{
var text = _isConstant
? FeaturesResources.Generate_constant_1_0
: _generateProperty
? _isReadonly ? FeaturesResources.Generate_read_only_property_1_0 : FeaturesResources.Generate_property_1_0
: _isReadonly ? FeaturesResources.Generate_read_only_field_1_0 : FeaturesResources.Generate_field_1_0;
return string.Format(
text,
_state.IdentifierToken.ValueText,
_state.TypeToGenerateIn.Name);
}
}
public override string EquivalenceKey => _equivalenceKey;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Tests.Collections;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
public abstract partial class KeyedCollectionTests<TKey, TValue>
where TValue : IComparable<TValue> where TKey : IEquatable<TKey>
{
private static readonly bool s_keyNullable = default(TKey)
== null;
private static int s_sometimesNullIndex;
public static Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
GetNeverNullKeyMethod
{
get
{
return
new Named
<KeyedCollectionGetKeyedValue<TKey, TValue>>(
"GetNeverNullKey",
GetNeverNullKey);
}
}
public static Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
GetSometimesNullKeyMethod
{
get
{
return
new Named
<KeyedCollectionGetKeyedValue<TKey, TValue>>(
"GetSometimesNullKey",
GetSometimesNullKey);
}
}
public static Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
GetAlwaysNullKeyMethod
{
get
{
return
new Named
<KeyedCollectionGetKeyedValue<TKey, TValue>>(
"GetAlwaysNullKey",
GetAlwaysNullKey);
}
}
public static IEnumerable<object[]> CollectionSizes
{
get
{
yield return new object[] {0};
yield return new object[] {33};
}
}
public static IEnumerable<object[]> ClassData2
{
get
{
yield return new object[] {0, GetNeverNullKeyMethod};
yield return new object[] {33, GetNeverNullKeyMethod};
}
}
public static IEnumerable<object[]> ClassData
{
get
{
yield return new object[] {0, GetNeverNullKeyMethod};
yield return new object[] {33, GetNeverNullKeyMethod};
if (s_keyNullable)
{
yield return
new object[] {0, GetSometimesNullKeyMethod};
yield return
new object[] {33, GetSometimesNullKeyMethod};
yield return
new object[] {0, GetAlwaysNullKeyMethod};
yield return
new object[] {33, GetAlwaysNullKeyMethod};
}
}
}
public static IEnumerable<object[]> ThresholdData
{
get
{
yield return
new object[]
{
32,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Add<T>",
Helper.AddItems)
};
yield return
new object[]
{
-1,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Add<T>",
Helper.AddItems)
};
yield return
new object[]
{
32,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Insert<T>",
Helper.InsertItems)
};
yield return
new object[]
{
-1,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Insert<T>",
Helper.InsertItems)
};
yield return
new object[]
{
32,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Add",
Helper.AddItemsObject)
};
yield return
new object[]
{
-1,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Add",
Helper.AddItemsObject)
};
yield return
new object[]
{
32,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Add",
Helper.InsertItemsObject)
};
yield return
new object[]
{
-1,
new Named
<
AddItemsFunc
<TKey, IKeyedItem<TKey, TValue>>>(
"Add",
Helper.InsertItemsObject)
};
}
}
public static IEnumerable<object[]> ContainsKeyData
{
get
{
var sizes = new[]
{
new object[] {0},
new object[] {1},
new object[] {16},
new object[] {33}
};
object[][] generatorMethods;
if (s_keyNullable)
{
generatorMethods = new[]
{
new object[] {GetNeverNullKeyMethod},
new object[] {GetSometimesNullKeyMethod},
new object[] {GetAlwaysNullKeyMethod}
};
}
else
{
generatorMethods = new[]
{
new object[] {GetNeverNullKeyMethod}
};
}
return from size in sizes
from method in generatorMethods
select size.Push(method);
}
}
public static IEnumerable<object[]> DictionaryData
{
get
{
yield return new object[] {10, 0, 0, 0, 0};
yield return new object[] {0, 10, 0, 0, 0};
yield return new object[] {10, 0, 5, 0, 0};
yield return new object[] {0, 10, 5, 0, 0};
yield return new object[] {10, 10, 10, 0, 0};
yield return new object[] {10, 0, 0, 5, 0};
yield return new object[] {0, 10, 0, 5, 0};
yield return new object[] {10, 10, 0, 10, 0};
yield return new object[] {10, 0, 3, 3, 0};
yield return new object[] {0, 10, 3, 3, 0};
yield return new object[] {10, 10, 5, 5, 0};
yield return new object[] {10, 0, 0, 0, 32};
yield return new object[] {0, 10, 0, 0, 32};
yield return new object[] {10, 0, 5, 0, 32};
yield return new object[] {0, 10, 5, 0, 32};
yield return new object[] {10, 10, 10, 0, 32};
yield return new object[] {10, 0, 0, 5, 32};
yield return new object[] {0, 10, 0, 5, 32};
yield return new object[] {10, 10, 0, 10, 32};
yield return new object[] {10, 0, 3, 3, 32};
yield return new object[] {0, 10, 3, 3, 32};
yield return new object[] {10, 10, 5, 5, 32};
}
}
public abstract TKey GetKeyForItem(TValue item);
public abstract TValue GenerateValue();
public object GenerateValueObject()
{
return GenerateValue();
}
private static IKeyedItem<TKey, TValue> GetNeverNullKey(
Func<TValue> getValue,
Func<TValue, TKey> getKeyForItem)
{
TValue item = getValue();
return new KeyedItem<TKey, TValue>(
getKeyForItem(item),
item);
}
private static IKeyedItem<TKey, TValue> GetSometimesNullKey(
Func<TValue> getValue,
Func<TValue, TKey> getKeyForItem)
{
TValue item = getValue();
return
new KeyedItem<TKey, TValue>(
(s_sometimesNullIndex++ & 1) == 0
? default(TKey)
: getKeyForItem(item),
item);
}
private static IKeyedItem<TKey, TValue> GetAlwaysNullKey(
Func<TValue> getValue,
Func<TValue, TKey> getKeyForItem)
{
return new KeyedItem<TKey, TValue>(
default(TKey),
getValue());
}
[Theory]
[MemberData(nameof(ClassData))]
public void AddNullKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TValue item1 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
// Verify Adding a value where the key is null
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tmpKeyedItem = new KeyedItem<TKey, TValue>(
default(TKey),
item3);
keys = keys.Push(key1);
items = items.Push(keyedItem1, tmpKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
collection.Add(keyedItem1);
collection.Add(tmpKeyedItem);
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void AddExistingKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TValue item1 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
//[] Verify setting a value where the key already exists in the collection
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tmpKeyedItem = new KeyedItem<TKey, TValue>(key1, item3);
keys = keys.Push(key1);
items = items.Push(keyedItem1);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
collection.Add(keyedItem1);
Assert.Throws<ArgumentException>(
() => { collection.Add(tmpKeyedItem); });
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void AddUniqueKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TValue item1 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
//[] Verify setting a value where the key is unique
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tmpKeyedItem = new KeyedItem<TKey, TValue>(key3, item3);
keys = keys.Push(key1, key3);
items = items.Push(keyedItem1, tmpKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1, tmpKeyedItem);
collection.Add(keyedItem1);
collection.Add(tmpKeyedItem);
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void NonGenericAddNullKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TValue item1 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
IList nonGenericCollection = collection;
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tmpKeyedItem = new KeyedItem<TKey, TValue>(
default(TKey),
item3);
keys = keys.Push(key1);
items = items.Push(keyedItem1, tmpKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
collection.Add(keyedItem1);
nonGenericCollection.Add(tmpKeyedItem);
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void NonGenericAddExistingKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TValue item1 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
IList nonGenericCollection = collection;
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tmpKeyedItem = new KeyedItem<TKey, TValue>(key1, item3);
keys = keys.Push(key1);
items = items.Push(keyedItem1);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
collection.Add(keyedItem1);
Assert.Throws<ArgumentException>(
() => { nonGenericCollection.Add(tmpKeyedItem); });
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void NonGenericAddUniqueKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TValue item1 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
IList nonGenericCollection = collection;
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tmpKeyedItem = new KeyedItem<TKey, TValue>(key3, item3);
keys = keys.Push(key1, key3);
items = items.Push(keyedItem1, tmpKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1, tmpKeyedItem);
collection.Add(keyedItem1);
nonGenericCollection.Add(tmpKeyedItem);
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void ChangeItemKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(key2, item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1, key2);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys =
itemsWithKeys.Push(
new[] {keyedItem1, keyedItem2}.Where(
ki => ki.Key != null)
.ToArray
<IKeyedItem<TKey, TValue>>());
collection.MyChangeItemKey(keyedItem2, key3);
keyedItem2.Key = key3;
keys[keys.Length - 1] = key3;
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void ChangeItemKeyThrowsPreexistingKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(key2, item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1, key2);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys =
itemsWithKeys.Push(
new[] {keyedItem1, keyedItem2}.Where(
ki => ki.Key != null)
.ToArray
<IKeyedItem<TKey, TValue>>());
Assert.Throws<ArgumentException>(
() => collection.MyChangeItemKey(keyedItem2, key1));
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void ChangeItemKeySameKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(key2, item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1, key2);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys =
itemsWithKeys.Push(
new[] {keyedItem1, keyedItem2}.Where(
ki => ki.Key != null)
.ToArray
<IKeyedItem<TKey, TValue>>());
collection.MyChangeItemKey(keyedItem2, key2);
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void ChangeItemDoesNotExistThrows(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(key2, item2);
var keyedItem3 = new KeyedItem<TKey, TValue>(key3, item3);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1, key2);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys =
itemsWithKeys.Push(
new[] {keyedItem1, keyedItem2}.Where(
ki => ki.Key != null)
.ToArray
<IKeyedItem<TKey, TValue>>());
Assert.Throws<ArgumentException>(
() => collection.MyChangeItemKey(keyedItem3, key3));
Assert.Throws<ArgumentException>(
() => collection.MyChangeItemKey(keyedItem3, key2));
var tempKeyedItem = new KeyedItem<TKey, TValue>(key1, item2);
Assert.Throws<ArgumentException>(
() => collection.MyChangeItemKey(tempKeyedItem, key2));
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData))]
public void ChangeItemKeyNullToNull(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
var tempKeyedItem =
new KeyedItem<TKey, TValue>(default(TKey), item2);
collection.Add(tempKeyedItem);
keys = keys.Push(key1);
items = items.Push(keyedItem1, tempKeyedItem);
itemsWithKeys =
itemsWithKeys.Push(
new[] {keyedItem1}.Where(ki => ki.Key != null)
.ToArray
<IKeyedItem<TKey, TValue>>());
collection.MyChangeItemKey(tempKeyedItem, default(TKey));
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData))]
public void ChangeItemKeyNullToNonNull(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
var tempKeyedItem =
new KeyedItem<TKey, TValue>(default(TKey), item2);
collection.Add(tempKeyedItem);
keys = keys.Push(key1);
items = items.Push(keyedItem1, tempKeyedItem);
itemsWithKeys =
itemsWithKeys.Push(
new[] {keyedItem1, tempKeyedItem}.Where(
ki => ki.Key != null)
.ToArray
<IKeyedItem<TKey, TValue>>());
collection.MyChangeItemKey(tempKeyedItem, key2);
tempKeyedItem.Key = key2;
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData))]
public void ChangeItemKeyNonNullToNull(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(
key2,
item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys =
itemsWithKeys.Push(
new[] {keyedItem1}.Where(ki => ki.Key != null)
.ToArray
<IKeyedItem<TKey, TValue>>());
collection.MyChangeItemKey(keyedItem2, default(TKey));
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(CollectionSizes))]
public void ChangeItemKeyNullItemNotPresent(int collectionSize)
{
if (default(TKey) == null)
{
TKey[] keys;
TValue[] items;
TValue[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var collection =
new TestKeyedCollection<TKey, TValue>(GetKeyForItem);
collection.AddItems(
GenerateValue,
GetKeyForItem,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(item1);
Assert.Throws<ArgumentException>(
() =>
collection.MyChangeItemKey(default(TValue), key2));
collection.Verify(
keys.Push(key1),
items.Push(item1),
itemsWithKeys.Push(item1));
}
}
[Theory]
[MemberData(nameof(CollectionSizes))]
public void ChangeItemKeyNullItemPresent(int collectionSize)
{
if (default(TKey) == null)
{
TKey[] keys;
TValue[] items;
TValue[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var collection =
new TestKeyedCollection<TKey, TValue>(GetKeyForItem);
collection.AddItems(
GenerateValue,
GetKeyForItem,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(item1);
collection.Add(default(TValue));
collection.MyChangeItemKey(default(TValue), key2);
collection.Verify(
keys.Push(key1),
items.Push(item1, default(TValue)),
itemsWithKeys.Push(item1));
}
}
[Theory]
[MemberData(nameof(CollectionSizes))]
public void ChangeItemKeyNullKeyNotPresent(int collectionSize)
{
if (default(TKey) == null)
{
TKey[] keys;
TValue[] items;
TValue[] itemsWithKeys;
TValue item1 = GenerateValue();
var collection =
new TestKeyedCollection<TKey, TValue>(GetKeyForItem);
collection.AddItems(
GenerateValue,
GetKeyForItem,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(item1);
collection.MyChangeItemKey(item1, default(TKey));
collection.Verify(
keys,
items.Push(item1),
itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(CollectionSizes))]
public void ChangeItemKeyNullKeyPresent(int collectionSize)
{
if (default(TKey) == null)
{
TKey[] keys;
TValue[] items;
TValue[] itemsWithKeys;
TValue item1 = GenerateValue();
var collection =
new TestKeyedCollection<TKey, TValue>(GetKeyForItem);
collection.AddItems(
GenerateValue,
GetKeyForItem,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(item1);
collection.Add(default(TValue));
collection.MyChangeItemKey(item1, default(TKey));
collection.Verify(
keys,
items.Push(item1, default(TValue)),
itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(CollectionSizes))]
public void ChangeItemKeyNullItemNullKeyPresent(
int collectionSize)
{
if (default(TKey) == null)
{
TKey[] keys;
TValue[] items;
TValue[] itemsWithKeys;
TValue item1 = GenerateValue();
var collection =
new TestKeyedCollection<TKey, TValue>(GetKeyForItem);
collection.AddItems(
GenerateValue,
GetKeyForItem,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(item1);
collection.Add(default(TValue));
collection.MyChangeItemKey(
default(TValue),
default(TKey));
collection.Verify(
keys,
items.Push(item1, default(TValue)),
itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeyKeyAlreadyChanged(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(key2, item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1, collectionSize >= 32 ? key2 : key3);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys = itemsWithKeys.Push(keyedItem1, keyedItem2);
keyedItem2.Key = key3;
if (collectionSize >= 32)
{
Assert.Throws<ArgumentException>(
() => collection.MyChangeItemKey(keyedItem2, key3));
}
else
{
collection.MyChangeItemKey(keyedItem2, key3);
}
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeyKeyAlreadyChangedNewKeyIsOldKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(key2, item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1, collectionSize >= 32 ? key2 : key3);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys = itemsWithKeys.Push(keyedItem1, keyedItem2);
keyedItem2.Key = key3;
if (collectionSize >= 32)
{
Assert.Throws<ArgumentException>(
() => collection.MyChangeItemKey(keyedItem2, key2));
}
else
{
collection.MyChangeItemKey(keyedItem2, key2);
}
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeyKeyAlreadyChangedNewKeyIsDifferent(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TValue item4 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
TKey key3 = GetKeyForItem(item3);
TKey key4 = GetKeyForItem(item4);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(key2, item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1, collectionSize >= 32 ? key2 : key3);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys = itemsWithKeys.Push(keyedItem1, keyedItem2);
keyedItem2.Key = key3;
if (collectionSize >= 32)
{
Assert.Throws<ArgumentException>(
() => collection.MyChangeItemKey(keyedItem2, key4));
}
else
{
collection.MyChangeItemKey(keyedItem2, key4);
}
collection.Verify(keys, items, itemsWithKeys);
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeyNullToNewKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
var tempKeyedItem =
new KeyedItem<TKey, TValue>(default(TKey), item2);
collection.Add(tempKeyedItem);
keys = keys.Push(key1);
if (collectionSize < 32)
{
keys = keys.Push(key3);
}
items = items.Push(keyedItem1, tempKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
if (collectionSize < 32)
{
itemsWithKeys = itemsWithKeys.Push(tempKeyedItem);
}
tempKeyedItem.Key = key3;
if (collectionSize >= 32)
{
Assert.Throws<ArgumentException>(
() =>
collection.MyChangeItemKey(tempKeyedItem, key3));
}
else
{
collection.MyChangeItemKey(tempKeyedItem, key3);
}
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeyNullToOldKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
var tempKeyedItem =
new KeyedItem<TKey, TValue>(default(TKey), item2);
collection.Add(tempKeyedItem);
keys = keys.Push(key1);
if (collectionSize < 32)
{
keys = keys.Push(key3);
}
items = items.Push(keyedItem1, tempKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
if (collectionSize < 32)
{
itemsWithKeys = itemsWithKeys.Push(tempKeyedItem);
}
tempKeyedItem.Key = key3;
if (collectionSize >= 32)
{
Assert.Throws<ArgumentException>(
() =>
collection.MyChangeItemKey(
tempKeyedItem,
default(TKey)));
}
else
{
collection.MyChangeItemKey(
tempKeyedItem,
default(TKey));
}
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeyNullToOtherKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item3 = GenerateValue();
TValue item4 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key3 = GetKeyForItem(item3);
TKey key4 = GetKeyForItem(item4);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
var tempKeyedItem =
new KeyedItem<TKey, TValue>(default(TKey), item2);
collection.Add(tempKeyedItem);
keys = keys.Push(key1);
if (collectionSize < 32)
{
keys = keys.Push(key3);
}
items = items.Push(keyedItem1, tempKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
if (collectionSize < 32)
{
itemsWithKeys = itemsWithKeys.Push(tempKeyedItem);
}
tempKeyedItem.Key = key3;
if (collectionSize >= 32)
{
Assert.Throws<ArgumentException>(
() =>
collection.MyChangeItemKey(tempKeyedItem, key4));
}
else
{
collection.MyChangeItemKey(tempKeyedItem, key4);
}
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeySetKeyNonNullToNull(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(
key2,
item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
keyedItem2.Key = default(TKey);
collection.MyChangeItemKey(keyedItem2, default(TKey));
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData2))]
public void ChangeItemKeySetKeyNonNullToNullChangeKeyNonNull(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(
key2,
item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
keyedItem2.Key = default(TKey);
if (collectionSize >= 32)
{
Assert.Throws<ArgumentException>(
() =>
collection.MyChangeItemKey(keyedItem2, key2));
}
else
{
collection.MyChangeItemKey(keyedItem2, key2);
}
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ClassData2))]
public void
ChangeItemKeySetKeyNonNullToNullChangeKeySomethingElse(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
if (default(TKey) == null)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
TValue item1 = GenerateValue();
TValue item2 = GenerateValue();
TValue item4 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key2 = GetKeyForItem(item2);
TKey key4 = GetKeyForItem(item4);
var keyedItem1 = new KeyedItem<TKey, TValue>(
key1,
item1);
var keyedItem2 = new KeyedItem<TKey, TValue>(
key2,
item2);
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Add(keyedItem1);
collection.Add(keyedItem2);
keys = keys.Push(key1);
items = items.Push(keyedItem1, keyedItem2);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
keyedItem2.Key = default(TKey);
if (collectionSize >= 32 && keyedItem2.Key != null)
{
Assert.Throws<ArgumentException>(
() =>
collection.MyChangeItemKey(keyedItem2, key4));
}
else
{
collection.MyChangeItemKey(keyedItem2, key4);
}
collection.Verify(keys, items, itemsWithKeys);
}
}
[Theory]
[InlineData(0)]
[InlineData(4)]
[InlineData(25)]
[InlineData(33)]
public void Clear(int collectionSize)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
GetNeverNullKeyMethod.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
bool haveDict = collection.GetDictionary() != null;
collection.Clear();
collection.Verify(
new TKey[0],
new IKeyedItem<TKey, TValue>[0],
new IKeyedItem<TKey, TValue>[0]);
Assert.Equal(haveDict, collection.GetDictionary() != null);
}
[Theory]
[MemberData(nameof(ClassData))]
public void Contains(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
if (s_keyNullable)
{
Assert.Throws<ArgumentNullException>(
() => collection.Contains(default(TKey)));
}
else
{
Assert.False(collection.Contains(default(TKey)));
}
}
private void VerifyDictionary(
KeyedCollection<TKey, IKeyedItem<TKey, TValue>> dictionary,
TKey[] expectedKeys,
IKeyedItem<TKey, TValue>[] expectedItems)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
if (expectedKeys.Length != expectedItems.Length)
{
throw new ArgumentException(
"Expected keys length and expected items length must be the same.");
}
Assert.Equal(expectedItems.Length, dictionary.Count);
for (var i = 0; i < expectedKeys.Length; ++i)
{
Assert.Equal(
expectedItems[i],
dictionary[expectedKeys[i]]);
}
}
[Theory]
[MemberData(nameof(ThresholdData))]
public void Threshold(
int collectionDictionaryThreshold,
Named<AddItemsFunc<TKey, IKeyedItem<TKey, TValue>>> addItems)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
if (collectionDictionaryThreshold >= 0)
{
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>(
collectionDictionaryThreshold);
// dictionary is created when the threshold is exceeded
addItems.Value(
collection,
GetNeverNullKeyMethod.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionDictionaryThreshold,
out keys,
out items,
out itemsWithKeys);
Assert.Null(collection.GetDictionary());
collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>(
collectionDictionaryThreshold);
addItems.Value(
collection,
GetNeverNullKeyMethod.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionDictionaryThreshold + 1,
out keys,
out items,
out itemsWithKeys);
Assert.NotNull(collection.GetDictionary());
VerifyDictionary(collection, keys, itemsWithKeys);
}
else
{
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>(
collectionDictionaryThreshold);
// dictionary is created when the threshold is exceeded
addItems.Value(
collection,
GetNeverNullKeyMethod.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
1024,
out keys,
out items,
out itemsWithKeys);
Assert.Null(collection.GetDictionary());
collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>(
collectionDictionaryThreshold);
addItems.Value(
collection,
GetNeverNullKeyMethod.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
2048,
out keys,
out items,
out itemsWithKeys);
Assert.Null(collection.GetDictionary());
}
}
[Theory]
[MemberData(nameof(ContainsKeyData))]
public void ContainsKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
IKeyedItem<TKey, TValue> itemNotIn =
generateKeyedItem.Value(GenerateValue, GetKeyForItem);
// this is to make overload resolution pick the correct Contains function. replacing keyNotIn with null causes the Contains<TValue> overload to be used. We want the Contains<TKey> version.
TKey keyNotIn = itemNotIn.Key;
if (keyNotIn == null)
{
Assert.Throws<ArgumentNullException>(
() => collection.Contains(keyNotIn));
}
else
{
Assert.False(collection.Contains(keyNotIn));
}
foreach (TKey k in keys)
{
TKey key = k;
if (key == null)
{
Assert.Throws<ArgumentNullException>(
() => collection.Contains(key));
continue;
}
Assert.True(collection.Contains(key));
}
}
[Theory]
[MemberData(nameof(ContainsKeyData))]
public void RemoveKey(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
collection.Verify(keys, items, itemsWithKeys);
IKeyedItem<TKey, TValue> itemNotIn =
generateKeyedItem.Value(GenerateValue, GetKeyForItem);
// this is to make overload resolution pick the correct Contains function. replacing keyNotIn with null causes the Contains<TValue> overload to be used. We want the Contains<TKey> version.
TKey keyNotIn = itemNotIn.Key;
if (keyNotIn == null)
{
Assert.Throws<ArgumentNullException>(
() => collection.Remove(keyNotIn));
}
else
{
Assert.False(collection.Remove(keyNotIn));
}
collection.Verify(keys, items, itemsWithKeys);
var tempKeys = (TKey[]) keys.Clone();
var tempItems = (IKeyedItem<TKey, TValue>[]) items.Clone();
var tempItemsWithKeys =
(IKeyedItem<TKey, TValue>[]) itemsWithKeys.Clone();
for (var i = 0; i < itemsWithKeys.Length; i++)
{
TKey key = keys[i];
if (key == null)
{
Assert.Throws<ArgumentNullException>(
() => collection.Remove(key));
}
else
{
Assert.True(collection.Remove(key));
tempItems =
tempItems.RemoveAt(
Array.IndexOf(tempItems, itemsWithKeys[i]));
tempItemsWithKeys = itemsWithKeys.Slice(
i + 1,
itemsWithKeys.Length - i - 1);
tempKeys = keys.Slice(i + 1, keys.Length - i - 1);
}
collection.Verify(
tempKeys,
tempItems,
tempItemsWithKeys);
}
}
[Theory]
[MemberData(nameof(ContainsKeyData))]
public void KeyIndexer(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
IKeyedItem<TKey, TValue> itemNotIn =
generateKeyedItem.Value(GenerateValue, GetKeyForItem);
// this is to make overload resolution pick the correct Contains function. replacing keyNotIn with null causes the Contains<TValue> overload to be used. We want the Contains<TKey> version.
TKey keyNotIn = itemNotIn.Key;
if (keyNotIn == null)
{
Assert.Throws<ArgumentNullException>(
() => collection[keyNotIn]);
}
else
{
Assert.Throws<KeyNotFoundException>(
() => collection[keyNotIn]);
}
foreach (TKey k in keys)
{
TKey key = k;
if (key == null)
{
Assert.Throws<ArgumentNullException>(
() => collection[key]);
continue;
}
IKeyedItem<TKey, TValue> tmp = collection[key];
}
}
[Theory]
[MemberData(nameof(CollectionSizes))]
public void KeyIndexerSet(int collectionSize)
{
TKey[] keys;
TValue[] items;
TValue[] itemsWithKeys;
var collection =
new TestKeyedCollection<TKey, TValue>(GetKeyForItem);
collection.AddItems(
GenerateValue,
GetKeyForItem,
collectionSize,
out keys,
out items,
out itemsWithKeys);
foreach (TValue item in itemsWithKeys)
{
collection[collection.IndexOf(item)] = item;
}
}
[Theory]
[MemberData(nameof(DictionaryData))]
public void Dictionary(
int addCount,
int insertCount,
int removeCount,
int removeKeyCount,
int collectionDictionaryThreshold)
{
var collection =
new TestKeyedCollectionOfIKeyedItem<TKey, TValue>(
collectionDictionaryThreshold);
TKey[] tempKeys;
IKeyedItem<TKey, TValue>[] tempItems;
IKeyedItem<TKey, TValue>[] tempItemsWithKeys;
var keys = new TKey[0];
var itemsWithKeys = new IKeyedItem<TKey, TValue>[0];
if (addCount > 0)
{
collection.AddItems(
GetNeverNullKeyMethod.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
addCount,
out tempKeys,
out tempItems,
out tempItemsWithKeys);
keys = keys.Push(tempKeys);
itemsWithKeys = itemsWithKeys.Push(tempItemsWithKeys);
VerifyDictionary(collection, keys, itemsWithKeys);
}
if (insertCount > 0)
{
collection.InsertItems(
GetNeverNullKeyMethod.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
insertCount,
out tempKeys,
out tempItems,
out tempItemsWithKeys);
keys = keys.Push(tempKeys);
itemsWithKeys = itemsWithKeys.Push(tempItemsWithKeys);
VerifyDictionary(collection, keys, itemsWithKeys);
}
if (removeCount > 0)
{
for (var i = 0; i < removeCount; i++)
{
int index = (((i*43691 << 2)/7 >> 1)*5039)
%collection.Count;
collection.RemoveAt(index);
keys = keys.RemoveAt(index);
itemsWithKeys = itemsWithKeys.RemoveAt(index);
VerifyDictionary(collection, keys, itemsWithKeys);
}
}
if (removeKeyCount > 0)
{
for (var i = 0; i < removeCount; i++)
{
int index = (((i*127 << 2)/7 >> 1)*5039)
%collection.Count;
IKeyedItem<TKey, TValue> item = collection[index];
collection.Remove(item.Key);
keys = keys.RemoveAt(index);
itemsWithKeys = itemsWithKeys.RemoveAt(index);
VerifyDictionary(collection, keys, itemsWithKeys);
}
}
}
[Theory]
[MemberData(nameof(ClassData))]
public void Insert(
int collectionSize,
Named<KeyedCollectionGetKeyedValue<TKey, TValue>>
generateKeyedItem)
{
TValue item1 = GenerateValue();
TValue item3 = GenerateValue();
TKey key1 = GetKeyForItem(item1);
TKey key3 = GetKeyForItem(item3);
var keyedItem1 = new KeyedItem<TKey, TValue>(key1, item1);
var inserts =
new Action
<KeyedCollection<TKey, IKeyedItem<TKey, TValue>>,
int, IKeyedItem<TKey, TValue>>[]
{
(c, i, item) => c.Insert(i, item),
(c, i, item) => ((IList) c).Insert(i, item)
};
foreach (
Action
<KeyedCollection<TKey, IKeyedItem<TKey, TValue>>,
int, IKeyedItem<TKey, TValue>> i in inserts)
{
Action
<KeyedCollection<TKey, IKeyedItem<TKey, TValue>>,
int, IKeyedItem<TKey, TValue>> insert = i;
{
// Insert key is null
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
var collection =
new TestKeyedCollectionOfIKeyedItem
<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tempKeyedItem =
new KeyedItem<TKey, TValue>(
default(TKey),
item3);
keys = keys.Push(key1);
items = items.Push(keyedItem1, tempKeyedItem);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
insert(collection, collection.Count, keyedItem1);
insert(collection, collection.Count, tempKeyedItem);
collection.Verify(keys, items, itemsWithKeys);
}
{
// Insert key already exists
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
var collection =
new TestKeyedCollectionOfIKeyedItem
<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tempKeyedItem = new KeyedItem<TKey, TValue>(
key1,
item3);
keys = keys.Push(key1);
items = items.Push(keyedItem1);
itemsWithKeys = itemsWithKeys.Push(keyedItem1);
insert(collection, collection.Count, keyedItem1);
Assert.Throws<ArgumentException>(
() =>
insert(
collection,
collection.Count,
tempKeyedItem));
collection.Verify(keys, items, itemsWithKeys);
}
{
// Insert key is unique
TKey[] keys;
IKeyedItem<TKey, TValue>[] items;
IKeyedItem<TKey, TValue>[] itemsWithKeys;
var collection =
new TestKeyedCollectionOfIKeyedItem
<TKey, TValue>();
collection.AddItems(
generateKeyedItem.Value.Bind(
GenerateValue,
GetKeyForItem),
ki => ki.Key,
collectionSize,
out keys,
out items,
out itemsWithKeys);
var tempKeyedItem = new KeyedItem<TKey, TValue>(
key3,
item3);
keys = keys.Push(key1, key3);
items = items.Push(keyedItem1, tempKeyedItem);
itemsWithKeys = itemsWithKeys.Push(
keyedItem1,
tempKeyedItem);
insert(collection, collection.Count, keyedItem1);
insert(collection, collection.Count, tempKeyedItem);
collection.Verify(keys, items, itemsWithKeys);
}
}
}
}
public abstract class IListTestKeyedCollection<TKey, TValue> :
IListTest<KeyedCollection<TKey, TValue>, TValue>
{
protected IListTestKeyedCollection()
: base(false, false, false, false, true, true)
{
}
protected abstract TKey GetKeyForItem(TValue item);
/// <summary>
/// When overridden in a derived class, Gets an instance of the list under test containing the given items.
/// </summary>
/// <param name="items">The items to initialize the list with.</param>
/// <returns>An instance of the list under test containing the given items.</returns>
protected override KeyedCollection<TKey, TValue> CreateList(
IEnumerable<TValue> items)
{
var ret =
new TestKeyedCollection<TKey, TValue>(GetKeyForItem);
if (items == null)
{
return ret;
}
foreach (TValue item in items)
{
ret.Add(item);
}
return ret;
}
/// <summary>
/// When overridden in a derived class, invalidates any enumerators for the given list.
/// </summary>
/// <param name="list">The list to invalidate enumerators for.</param>
/// <returns>The new contents of the list.</returns>
protected override IEnumerable<TValue> InvalidateEnumerator(
KeyedCollection<TKey, TValue> list)
{
TValue item = CreateItem();
list.Add(item);
return list;
}
}
public abstract class IListTestKeyedCollectionBadKey<TKey, TValue> :
IListTest<KeyedCollection<BadKey<TKey>, TValue>, TValue>
where TKey : IEquatable<TKey>
{
protected IListTestKeyedCollectionBadKey()
: base(false, false, false, false, true, true)
{
}
/// <summary>
/// When overridden in a derived class, Gets an instance of the list under test containing the given items.
/// </summary>
/// <param name="items">The items to initialize the list with.</param>
/// <returns>An instance of the list under test containing the given items.</returns>
protected override KeyedCollection<BadKey<TKey>, TValue>
CreateList(IEnumerable<TValue> items)
{
var ret =
new TestKeyedCollection<BadKey<TKey>, TValue>(
item => new BadKey<TKey>(GetKeyForItem(item)),
new BadKeyComparer<TKey>());
if (items == null)
{
return ret;
}
foreach (TValue item in items)
{
ret.Add(item);
}
return ret;
}
/// <summary>
/// When overridden in a derived class, invalidates any enumerators for the given list.
/// </summary>
/// <param name="list">The list to invalidate enumerators for.</param>
/// <returns>The new contents of the list.</returns>
protected override IEnumerable<TValue> InvalidateEnumerator(
KeyedCollection<BadKey<TKey>, TValue> list)
{
TValue item = CreateItem();
list.Add(item);
return list;
}
protected abstract TKey GetKeyForItem(TValue item);
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Project.Automation;
using System.Runtime.Versioning;
namespace Microsoft.VisualStudio.Project.Samples.NestedProject.UnitTests
{
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class BaseAccessor
{
protected Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject m_privateObject;
protected BaseAccessor(object target, Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType type)
{
m_privateObject = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject(target, type);
}
protected BaseAccessor(Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType type)
:
this(null, type)
{
}
internal virtual object Target
{
get
{
return m_privateObject.Target;
}
}
public override string ToString()
{
return this.Target.ToString();
}
public override bool Equals(object obj)
{
if(typeof(BaseAccessor).IsInstanceOfType(obj))
{
obj = ((BaseAccessor)(obj)).Target;
}
return this.Target.Equals(obj);
}
public override int GetHashCode()
{
return this.Target.GetHashCode();
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_GeneralPropertyPageAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(GeneralPropertyPage));
internal VisualStudio_Project_Samples_GeneralPropertyPageAccessor(GeneralPropertyPage target)
:
base(target, m_privateType)
{
}
internal string assemblyName
{
get
{
string ret = ((string)(m_privateObject.GetField("assemblyName")));
return ret;
}
set
{
m_privateObject.SetField("assemblyName", value);
}
}
internal OutputType outputType
{
get
{
OutputType ret = ((OutputType)(m_privateObject.GetField("outputType")));
return ret;
}
set
{
m_privateObject.SetField("outputType", value);
}
}
internal string defaultNamespace
{
get
{
string ret = ((string)(m_privateObject.GetField("defaultNamespace")));
return ret;
}
set
{
m_privateObject.SetField("defaultNamespace", value);
}
}
internal string startupObject
{
get
{
string ret = ((string)(m_privateObject.GetField("startupObject")));
return ret;
}
set
{
m_privateObject.SetField("startupObject", value);
}
}
internal string applicationIcon
{
get
{
string ret = ((string)(m_privateObject.GetField("applicationIcon")));
return ret;
}
set
{
m_privateObject.SetField("applicationIcon", value);
}
}
internal FrameworkName targetFrameworkMoniker
{
get
{
FrameworkName ret = ((FrameworkName)(m_privateObject.GetField("targetFrameworkMoniker")));
return ret;
}
set
{
m_privateObject.SetField("targetFrameworkMoniker", value);
}
}
internal void BindProperties()
{
object[] args = new object[0];
m_privateObject.Invoke("BindProperties", new System.Type[0], args);
}
internal int ApplyChanges()
{
object[] args = new object[0];
int ret = ((int)(m_privateObject.Invoke("ApplyChanges", new System.Type[0], args)));
return ret;
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_NestedProjectPackageAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(NestedProjectPackage));
internal VisualStudio_Project_Samples_NestedProjectPackageAccessor(NestedProjectPackage target)
:
base(target, m_privateType)
{
}
internal void Initialize()
{
object[] args = new object[0];
m_privateObject.Invoke("Initialize", new System.Type[0], args);
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_OANestedProjectPropertyAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(OANestedProjectProperty));
internal VisualStudio_Project_Samples_OANestedProjectPropertyAccessor(OANestedProjectProperty target)
:
base(target, m_privateType)
{
}
internal OAProperties parent
{
get
{
OAProperties ret = ((OAProperties)(m_privateObject.GetField("parent")));
return ret;
}
set
{
m_privateObject.SetField("parent", value);
}
}
internal string name
{
get
{
string ret = ((string)(m_privateObject.GetField("name")));
return ret;
}
set
{
m_privateObject.SetField("name", value);
}
}
internal static OANestedProjectProperty CreatePrivate(OANestedProjectProperties parent, string name)
{
object[] args = new object[] {
parent,
name};
Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject priv_obj = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject(typeof(OANestedProjectProperty), new System.Type[] {
typeof(OANestedProjectProperties),
typeof(string)}, args);
return ((OANestedProjectProperty)(priv_obj.Target));
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_ResourcesDescriptionAttributeAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType("Microsoft.VisualStudio.Project.Samples.NestedProject", "Microsoft.VisualStudio.Project.Samples.NestedProject.ResourcesDescriptionAttribute");
internal VisualStudio_Project_Samples_ResourcesDescriptionAttributeAccessor(object target) :
base(target, m_privateType)
{
}
internal bool replaced
{
get
{
bool ret = ((bool)(m_privateObject.GetField("replaced")));
return ret;
}
set
{
m_privateObject.SetField("replaced", value);
}
}
internal string Description
{
get
{
string ret = ((string)(m_privateObject.GetProperty("Description")));
return ret;
}
}
internal static global::System.ComponentModel.DescriptionAttribute CreatePrivate(string description)
{
object[] args = new object[] {
description};
Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject priv_obj = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject("Microsoft.VisualStudio.Project.Samples.NestedProject", "Microsoft.VisualStudio.Project.Samples.NestedProject.ResourcesDescriptionAttribute", new System.Type[] {
typeof(string)}, args);
return ((global::System.ComponentModel.DescriptionAttribute)(priv_obj.Target));
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_ResourcesCategoryAttributeAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType("Microsoft.VisualStudio.Project.Samples.NestedProject", "Microsoft.VisualStudio.Project.Samples.NestedProject.ResourcesCategoryAttribute");
internal VisualStudio_Project_Samples_ResourcesCategoryAttributeAccessor(object target) :
base(target, m_privateType)
{
}
internal static global::System.ComponentModel.CategoryAttribute CreatePrivate(string category)
{
object[] args = new object[] {
category};
Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject priv_obj = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject("Microsoft.VisualStudio.Project.Samples.NestedProject", "Microsoft.VisualStudio.Project.Samples.NestedProject.ResourcesCategoryAttribute", new System.Type[] {
typeof(string)}, args);
return ((global::System.ComponentModel.CategoryAttribute)(priv_obj.Target));
}
internal string GetLocalizedString(string value)
{
object[] args = new object[] {
value};
string ret = ((string)(m_privateObject.Invoke("GetLocalizedString", new System.Type[] {
typeof(string)}, args)));
return ret;
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_LocDisplayNameAttributeAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType("Microsoft.VisualStudio.Project.Samples.NestedProject", "Microsoft.VisualStudio.Project.Samples.NestedProject.LocDisplayNameAttribute");
internal VisualStudio_Project_Samples_LocDisplayNameAttributeAccessor(object target) :
base(target, m_privateType)
{
}
internal string name
{
get
{
string ret = ((string)(m_privateObject.GetField("name")));
return ret;
}
set
{
m_privateObject.SetField("name", value);
}
}
internal string DisplayName
{
get
{
string ret = ((string)(m_privateObject.GetProperty("DisplayName")));
return ret;
}
}
internal static global::System.ComponentModel.DisplayNameAttribute CreatePrivate(string name)
{
object[] args = new object[] {
name};
Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject priv_obj = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject("Microsoft.VisualStudio.Project.Samples.NestedProject", "Microsoft.VisualStudio.Project.Samples.NestedProject.LocDisplayNameAttribute", new System.Type[] {
typeof(string)}, args);
return ((global::System.ComponentModel.DisplayNameAttribute)(priv_obj.Target));
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_NestedProjectFactoryAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(NestedProjectFactory));
internal VisualStudio_Project_Samples_NestedProjectFactoryAccessor(NestedProjectFactory target) :
base(target, m_privateType)
{
}
internal ProjectNode CreateProject()
{
object[] args = new object[0];
ProjectNode ret = ((ProjectNode)(m_privateObject.Invoke("CreateProject", new System.Type[0], args)));
return ret;
}
}
[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class VisualStudio_Project_Samples_NestedProjectNodeAccessor : BaseAccessor
{
protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(NestedProjectNode));
internal VisualStudio_Project_Samples_NestedProjectNodeAccessor(NestedProjectNode target) :
base(target, m_privateType)
{
}
internal object Object
{
get
{
object ret = ((object)(m_privateObject.GetProperty("Object")));
return ret;
}
}
internal global::System.Guid[] GetConfigurationIndependentPropertyPages()
{
object[] args = new object[0];
global::System.Guid[] ret = ((global::System.Guid[])(m_privateObject.Invoke("GetConfigurationIndependentPropertyPages", new System.Type[0], args)));
return ret;
}
internal global::System.Guid[] GetPriorityProjectDesignerPages()
{
object[] args = new object[0];
global::System.Guid[] ret = ((global::System.Guid[])(m_privateObject.Invoke("GetPriorityProjectDesignerPages", new System.Type[0], args)));
return ret;
}
internal global::System.Guid[] GetConfigurationDependentPropertyPages()
{
object[] args = new object[0];
global::System.Guid[] ret = ((global::System.Guid[])(m_privateObject.Invoke("GetConfigurationDependentPropertyPages", new System.Type[0], args)));
return ret;
}
}
}
| |
//Contributor: Nicholas Mayne
using System;
using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Localization;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Localization;
using Nop.Services.Logging;
using Nop.Services.Messages;
using Nop.Services.Orders;
namespace Nop.Services.Authentication.External
{
/// <summary>
/// External authorizer
/// </summary>
public partial class ExternalAuthorizer : IExternalAuthorizer
{
#region Fields
private readonly IAuthenticationService _authenticationService;
private readonly IOpenAuthenticationService _openAuthenticationService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly ICustomerRegistrationService _customerRegistrationService;
private readonly ICustomerActivityService _customerActivityService;
private readonly ILocalizationService _localizationService;
private readonly IWorkContext _workContext;
private readonly CustomerSettings _customerSettings;
private readonly ExternalAuthenticationSettings _externalAuthenticationSettings;
private readonly IShoppingCartService _shoppingCartService;
private readonly IWorkflowMessageService _workflowMessageService;
private readonly LocalizationSettings _localizationSettings;
#endregion
#region Ctor
public ExternalAuthorizer(IAuthenticationService authenticationService,
IOpenAuthenticationService openAuthenticationService,
IGenericAttributeService genericAttributeService,
ICustomerRegistrationService customerRegistrationService,
ICustomerActivityService customerActivityService, ILocalizationService localizationService,
IWorkContext workContext, CustomerSettings customerSettings,
ExternalAuthenticationSettings externalAuthenticationSettings,
IShoppingCartService shoppingCartService,
IWorkflowMessageService workflowMessageService, LocalizationSettings localizationSettings)
{
this._authenticationService = authenticationService;
this._openAuthenticationService = openAuthenticationService;
this._genericAttributeService = genericAttributeService;
this._customerRegistrationService = customerRegistrationService;
this._customerActivityService = customerActivityService;
this._localizationService = localizationService;
this._workContext = workContext;
this._customerSettings = customerSettings;
this._externalAuthenticationSettings = externalAuthenticationSettings;
this._shoppingCartService = shoppingCartService;
this._workflowMessageService = workflowMessageService;
this._localizationSettings = localizationSettings;
}
#endregion
#region Utilities
private bool RegistrationIsEnabled()
{
return _customerSettings.UserRegistrationType != UserRegistrationType.Disabled && !_externalAuthenticationSettings.AutoRegisterEnabled;
}
private bool AutoRegistrationIsEnabled()
{
return _customerSettings.UserRegistrationType != UserRegistrationType.Disabled && _externalAuthenticationSettings.AutoRegisterEnabled;
}
private bool AccountDoesNotExistAndUserIsNotLoggedOn(Customer userFound, Customer userLoggedIn)
{
return userFound == null && userLoggedIn == null;
}
private bool AccountIsAssignedToLoggedOnAccount(Customer userFound, Customer userLoggedIn)
{
return userFound.Id.Equals(userLoggedIn.Id);
}
private bool AccountAlreadyExists(Customer userFound, Customer userLoggedIn)
{
return userFound != null && userLoggedIn != null;
}
#endregion
#region Methods
public virtual AuthorizationResult Authorize(OpenAuthenticationParameters parameters)
{
var userFound = _openAuthenticationService.GetUser(parameters);
var userLoggedIn = _workContext.CurrentCustomer.IsRegistered() ? _workContext.CurrentCustomer : null;
if (AccountAlreadyExists(userFound, userLoggedIn))
{
if (AccountIsAssignedToLoggedOnAccount(userFound, userLoggedIn))
{
// The person is trying to log in as himself.. bit weird
return new AuthorizationResult(OpenAuthenticationStatus.Authenticated);
}
var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
result.AddError("Account is already assigned");
return result;
}
if (AccountDoesNotExistAndUserIsNotLoggedOn(userFound, userLoggedIn))
{
ExternalAuthorizerHelper.StoreParametersForRoundTrip(parameters);
if (AutoRegistrationIsEnabled())
{
#region Register user
var currentCustomer = _workContext.CurrentCustomer;
var details = new RegistrationDetails(parameters);
var randomPassword = CommonHelper.GenerateRandomDigitCode(20);
bool isApproved = _customerSettings.UserRegistrationType == UserRegistrationType.Standard;
var registrationRequest = new CustomerRegistrationRequest(currentCustomer, details.EmailAddress,
_customerSettings.UsernamesEnabled ? details.UserName : details.EmailAddress, randomPassword, PasswordFormat.Clear, isApproved);
var registrationResult = _customerRegistrationService.RegisterCustomer(registrationRequest);
if (registrationResult.Success)
{
//store other parameters (form fields)
if (!String.IsNullOrEmpty(details.FirstName))
_genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.FirstName, details.FirstName);
if (!String.IsNullOrEmpty(details.LastName))
_genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.LastName, details.LastName);
userFound = currentCustomer;
_openAuthenticationService.AssociateExternalAccountWithUser(currentCustomer, parameters);
ExternalAuthorizerHelper.RemoveParameters();
//code below is copied from CustomerController.Register method
//authenticate
if (isApproved)
_authenticationService.SignIn(userFound ?? userLoggedIn, false);
//notifications
if (_customerSettings.NotifyNewCustomerRegistration)
_workflowMessageService.SendCustomerRegisteredNotificationMessage(currentCustomer, _localizationSettings.DefaultAdminLanguageId);
switch (_customerSettings.UserRegistrationType)
{
case UserRegistrationType.EmailValidation:
{
//email validation message
_genericAttributeService.SaveAttribute(currentCustomer, SystemCustomerAttributeNames.AccountActivationToken, Guid.NewGuid().ToString());
_workflowMessageService.SendCustomerEmailValidationMessage(currentCustomer, _workContext.WorkingLanguage.Id);
//result
return new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredEmailValidation);
}
case UserRegistrationType.AdminApproval:
{
//result
return new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredAdminApproval);
}
case UserRegistrationType.Standard:
{
//send customer welcome message
_workflowMessageService.SendCustomerWelcomeMessage(currentCustomer, _workContext.WorkingLanguage.Id);
//result
return new AuthorizationResult(OpenAuthenticationStatus.AutoRegisteredStandard);
}
default:
break;
}
}
else
{
ExternalAuthorizerHelper.RemoveParameters();
var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
foreach (var error in registrationResult.Errors)
result.AddError(string.Format(error));
return result;
}
#endregion
}
else if (RegistrationIsEnabled())
{
return new AuthorizationResult(OpenAuthenticationStatus.AssociateOnLogon);
}
else
{
ExternalAuthorizerHelper.RemoveParameters();
var result = new AuthorizationResult(OpenAuthenticationStatus.Error);
result.AddError("Registration is disabled");
return result;
}
}
if (userFound == null)
{
_openAuthenticationService.AssociateExternalAccountWithUser(userLoggedIn, parameters);
}
//migrate shopping cart
_shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, userFound ?? userLoggedIn, true);
//authenticate
_authenticationService.SignIn(userFound ?? userLoggedIn, false);
//activity log
_customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"),
userFound ?? userLoggedIn);
return new AuthorizationResult(OpenAuthenticationStatus.Authenticated);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
using System.Text.RegularExpressions;
namespace OpenQA.Selenium
{
[TestFixture]
public class TextHandlingTest : DriverTestFixture
{
private string newLine = "\r\n";
[Test]
public void ShouldReturnTheTextContentOfASingleElementWithNoChildren()
{
driver.Url = simpleTestPage;
string selectText = driver.FindElement(By.Id("oneline")).Text;
Assert.AreEqual(selectText, "A single line of text");
string getText = driver.FindElement(By.Id("oneline")).Text;
Assert.AreEqual(getText, "A single line of text");
}
[Test]
public void ShouldReturnTheEntireTextContentOfChildElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("multiline")).Text;
Assert.IsTrue(text.Contains("A div containing"));
Assert.IsTrue(text.Contains("More than one line of text"));
Assert.IsTrue(text.Contains("and block level elements"));
}
[Test]
public void ShouldIgnoreScriptElements()
{
driver.Url = javascriptEnhancedForm;
IWebElement labelForUsername = driver.FindElement(By.Id("labelforusername"));
string text = labelForUsername.Text;
Assert.AreEqual(labelForUsername.FindElements(By.TagName("script")).Count, 1);
Assert.IsFalse(text.Contains("document.getElementById"));
Assert.AreEqual(text, "Username:");
}
[Test]
public void ShouldRepresentABlockLevelElementAsANewline()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("multiline")).Text;
Assert.IsTrue(text.StartsWith("A div containing" + newLine));
Assert.IsTrue(text.Contains("More than one line of text" + newLine));
Assert.IsTrue(text.EndsWith("and block level elements"));
}
[Test]
public void ShouldCollapseMultipleWhitespaceCharactersIntoASingleSpace()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("lotsofspaces")).Text;
Assert.AreEqual(text, "This line has lots of spaces.");
}
[Test]
public void ShouldTrimText()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("multiline")).Text;
Assert.IsTrue(text.StartsWith("A div containing"));
Assert.IsTrue(text.EndsWith("block level elements"));
}
[Test]
public void ShouldConvertANonBreakingSpaceIntoANormalSpaceCharacter()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("nbsp")).Text;
Assert.AreEqual(text, "This line has a non-breaking space");
}
[Test]
public void ShouldTreatANonBreakingSpaceAsAnyOtherWhitespaceCharacterWhenCollapsingWhitespace()
{
driver.Url = (simpleTestPage);
IWebElement element = driver.FindElement(By.Id("nbspandspaces"));
string text = element.Text;
Assert.AreEqual(text, "This line has a non-breaking space and spaces");
}
[Test]
public void HavingInlineElementsShouldNotAffectHowTextIsReturned()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("inline")).Text;
Assert.AreEqual(text, "This line has text within elements that are meant to be displayed inline");
}
[Test]
public void ShouldReturnTheEntireTextOfInlineElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("span")).Text;
Assert.AreEqual(text, "An inline element");
}
//[Test]
//public void ShouldRetainTheFormatingOfTextWithinAPreElement()
//{
// driver.Url = simpleTestPage;
// string text = driver.FindElement(By.Id("preformatted")).Text;
// Assert.AreEqual(text, "This section has a\npreformatted\n text block\n" +
// " within in\n" +
// " ");
//}
[Test]
public void ShouldBeAbleToSetMoreThanOneLineOfTextInATextArea()
{
driver.Url = formsPage;
IWebElement textarea = driver.FindElement(By.Id("withText"));
textarea.Clear();
string expectedText = "I like cheese" + newLine + newLine + "It's really nice";
textarea.SendKeys(expectedText);
string seenText = textarea.Value;
Assert.AreEqual(seenText, expectedText);
}
[Test]
public void ShouldBeAbleToEnterDatesAfterFillingInOtherValuesFirst()
{
driver.Url = formsPage;
IWebElement input = driver.FindElement(By.Id("working"));
string expectedValue = "10/03/2007 to 30/07/1993";
input.SendKeys(expectedValue);
string seenValue = input.Value;
Assert.AreEqual(seenValue, expectedValue);
}
[Test]
public void ShouldReturnEmptystringWhenTextIsOnlySpaces()
{
driver.Url = (xhtmlTestPage);
string text = driver.FindElement(By.Id("spaces")).Text;
Assert.AreEqual(text, string.Empty);
}
[Test]
public void ShouldReturnEmptystringWhenTextIsEmpty()
{
driver.Url = (xhtmlTestPage);
string text = driver.FindElement(By.Id("empty")).Text;
Assert.AreEqual(text, string.Empty);
}
[Test]
public void ShouldReturnEmptystringWhenTagIsSelfClosing()
{
driver.Url = (xhtmlTestPage);
string text = driver.FindElement(By.Id("self-closed")).Text;
Assert.AreEqual(text, string.Empty);
}
[Test]
public void ShouldHandleSiblingBlockLevelElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("twoblocks")).Text;
Assert.AreEqual(text, "Some text" + newLine + "Some more text");
}
[Test]
[IgnoreBrowser(Browser.Firefox, "Difference in DOM rendering engines. Firefox places new line characters for paragraph elements only after the element.")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.IE, "Difference in DOM rendering engines. IE preserves trailing space on first line")]
[IgnoreBrowser(Browser.Chrome)]
public void ShouldHandleNestedBlockLevelElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("nestedblocks")).Text;
Assert.AreEqual("Cheese" + newLine + "Some text" + newLine + "Some more text" + newLine
+ "and also" + newLine + "Brie", text);
}
[Test]
public void ShouldHandleWhitespaceInInlineElements()
{
driver.Url = (simpleTestPage);
string text = driver.FindElement(By.Id("inlinespan")).Text;
Assert.AreEqual(text, "line has text");
}
[Test]
public void ReadALargeAmountOfData()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("macbeth.html");
string source = driver.PageSource.Trim().ToLower();
Assert.IsTrue(source.EndsWith("</html>"));
}
[Test]
public void GetTextWithLineBreakForInlineElement()
{
driver.Url = (simpleTestPage);
IWebElement label = driver.FindElement(By.Id("label1"));
string labelText = label.Text;
Assert.IsTrue(new Regex("foo[\\n\\r]+bar").IsMatch(labelText));
}
[Test]
[Category("Javascript")]
public void ShouldOnlyIncludeVisibleText()
{
driver.Url = javascriptPage;
string empty = driver.FindElement(By.Id("suppressedParagraph")).Text;
string explicitText = driver.FindElement(By.Id("outer")).Text;
Assert.AreEqual(string.Empty, empty);
Assert.AreEqual("sub-element that is explicitly visible", explicitText);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
** Purpose: Implements a generic, dynamically sized list as an
** array.
**
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
//
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>
{
private const int _defaultCapacity = 4;
private T[] _items; // Do not rename (binary serialization)
[ContractPublicPropertyName("Count")]
private int _size; // Do not rename (binary serialization)
private int _version; // Do not rename (binary serialization)
[NonSerialized]
private Object _syncRoot;
private static readonly T[] _emptyArray = new T[0];
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to _defaultCapacity, and then increased in multiples of two
// as required.
public List()
{
_items = _emptyArray;
}
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
public List(int capacity)
{
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (capacity == 0)
_items = _emptyArray;
else
_items = new T[capacity];
}
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
public List(IEnumerable<T> collection)
{
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else
{
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
else
{
_size = 0;
_items = _emptyArray;
AddEnumerable(collection);
}
}
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
public int Capacity
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
set
{
if (value < _size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
if (value != _items.Length)
{
if (value > 0)
{
T[] newItems = new T[value];
if (_size > 0)
{
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
else
{
_items = _emptyArray;
}
}
}
}
// Read-only property describing how many elements are in the List.
public int Count
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
bool System.Collections.IList.IsFixedSize
{
get { return false; }
}
// Is this List read-only?
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
bool System.Collections.IList.IsReadOnly
{
get { return false; }
}
// Is this List synchronized (thread-safe)?
bool System.Collections.ICollection.IsSynchronized
{
get { return false; }
}
// Synchronization root for this object.
Object System.Collections.ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Sets or Gets the element at the given index.
//
public T this[int index]
{
get
{
// Following trick can reduce the range check by one
if ((uint)index >= (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
return _items[index];
}
set
{
if ((uint)index >= (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
private static bool IsCompatibleObject(object value)
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
Object System.Collections.IList.this[int index]
{
get
{
return this[index];
}
set
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
try
{
this[index] = (T)value;
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
}
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
var array = _items;
var size = _size;
_version++;
if ((uint)size < (uint)array.Length)
{
_size = size + 1;
array[size] = item;
}
else
{
AddWithResize(item);
}
}
// Non-inline from List.Add to improve its code quality as uncommon path
[MethodImpl(MethodImplOptions.NoInlining)]
private void AddWithResize(T item)
{
var size = _size;
EnsureCapacity(size + 1);
_size = size + 1;
_items[size] = item;
}
int System.Collections.IList.Add(Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try
{
Add((T)item);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
return Count - 1;
}
// Adds the elements of the given collection to the end of this list. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
//
public void AddRange(IEnumerable<T> collection)
{
Contract.Ensures(Count >= Contract.OldValue(Count));
InsertRange(_size, collection);
}
public ReadOnlyCollection<T> AsReadOnly()
{
Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
return new ReadOnlyCollection<T>(this);
}
// Searches a section of the list for a given element using a binary search
// algorithm. Elements of the list are compared to the search value using
// the given IComparer interface. If comparer is null, elements of
// the list are compared to the search value using the IComparable
// interface, which in that case must be implemented by all elements of the
// list and the given search value. This method assumes that the given
// section of the list is already sorted; if this is not the case, the
// result will be incorrect.
//
// The method returns the index of the given value in the list. If the
// list does not contain the given value, the method returns a negative
// integer. The bitwise complement operator (~) can be applied to a
// negative result to produce the index of the first element (if any) that
// is larger than the given search value. This is also the index at which
// the search value should be inserted into the list in order for the list
// to remain sorted.
//
// The method uses the Array.BinarySearch method to perform the
// search.
//
public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
{
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (count < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() <= index + count);
Contract.EndContractBlock();
return Array.BinarySearch<T>(_items, index, count, item, comparer);
}
public int BinarySearch(T item)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, null);
}
public int BinarySearch(T item, IComparer<T> comparer)
{
Contract.Ensures(Contract.Result<int>() <= Count);
return BinarySearch(0, Count, item, comparer);
}
// Clears the contents of List.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
int size = _size;
_size = 0;
_version++;
if (size > 0)
{
Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references.
}
}
else
{
_size = 0;
_version++;
}
}
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// EqualityComparer<T>.Default.Equals().
public bool Contains(T item)
{
// PERF: IndexOf calls Array.IndexOf, which internally
// calls EqualityComparer<T>.Default.IndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.IndexOf.
return _size != 0 && IndexOf(item) != -1;
}
bool System.Collections.IList.Contains(Object item)
{
if (IsCompatibleObject(item))
{
return Contains((T)item);
}
return false;
}
public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
{
if (converter == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
Contract.EndContractBlock();
List<TOutput> list = new List<TOutput>(_size);
for (int i = 0; i < _size; i++)
{
list._items[i] = converter(_items[i]);
}
list._size = _size;
return list;
}
// Copies this List into array, which must be of a
// compatible array type.
//
public void CopyTo(T[] array)
{
CopyTo(array, 0);
}
// Copies this List into array, which must be of a
// compatible array type.
//
void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
{
if ((array != null) && (array.Rank != 1))
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
Contract.EndContractBlock();
try
{
// Array.Copy will check for NULL.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
//
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
if (_size - index < count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
public void CopyTo(T[] array, int arrayIndex)
{
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
// Ensures that the capacity of this list is at least the given minimum
// value. If the current capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min)
{
if (_items.Length < min)
{
int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
public bool Exists(Predicate<T> match)
{
return FindIndex(match) != -1;
}
public T Find(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for (int i = 0; i < _size; i++)
{
if (match(_items[i]))
{
return _items[i];
}
}
return default(T);
}
public List<T> FindAll(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
List<T> list = new List<T>();
for (int i = 0; i < _size; i++)
{
if (match(_items[i]))
{
list.Add(_items[i]);
}
}
return list;
}
public int FindIndex(Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindIndex(0, _size, match);
}
public int FindIndex(int startIndex, Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + Count);
return FindIndex(startIndex, _size - startIndex, match);
}
public int FindIndex(int startIndex, int count, Predicate<T> match)
{
if ((uint)startIndex > (uint)_size)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
if (count < 0 || startIndex > _size - count)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + count);
Contract.EndContractBlock();
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
if (match(_items[i])) return i;
}
return -1;
}
public T FindLast(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for (int i = _size - 1; i >= 0; i--)
{
if (match(_items[i]))
{
return _items[i];
}
}
return default(T);
}
public int FindLastIndex(Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindLastIndex(_size - 1, _size, match);
}
public int FindLastIndex(int startIndex, Predicate<T> match)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
return FindLastIndex(startIndex, startIndex + 1, match);
}
public int FindLastIndex(int startIndex, int count, Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
Contract.EndContractBlock();
if (_size == 0)
{
// Special case for 0 length List
if (startIndex != -1)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
else
{
// Make sure we're not out of range
if ((uint)startIndex >= (uint)_size)
{
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
{
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
int endIndex = startIndex - count;
for (int i = startIndex; i > endIndex; i--)
{
if (match(_items[i]))
{
return i;
}
}
return -1;
}
public void ForEach(Action<T> action)
{
if (action == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
Contract.EndContractBlock();
int version = _version;
for (int i = 0; i < _size; i++)
{
if (version != _version)
{
break;
}
action(_items[i]);
}
if (version != _version)
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Returns an enumerator for this list with the given
// permission for removal of elements. If modifications made to the list
// while an enumeration is in progress, the MoveNext and
// GetObject methods of the enumerator will throw an exception.
//
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public List<T> GetRange(int index, int count)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.Ensures(Contract.Result<List<T>>() != null);
Contract.EndContractBlock();
List<T> list = new List<T>(count);
Array.Copy(_items, index, list._items, 0, count);
list._size = count;
return list;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
}
int System.Collections.IList.IndexOf(Object item)
{
if (IsCompatibleObject(item))
{
return IndexOf((T)item);
}
return -1;
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and ending at count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index)
{
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, _size - index);
}
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards, starting at index
// index and upto count number of elements. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.IndexOf method to perform the
// search.
//
public int IndexOf(T item, int index, int count)
{
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
if (count < 0 || index > _size - count) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, count);
}
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
public void Insert(int index, T item)
{
// Note that insertions at the end are legal.
if ((uint)index > (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
_size++;
_version++;
}
void System.Collections.IList.Insert(int index, Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
try
{
Insert(index, (T)item);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
}
// Inserts the elements of the given collection at a given index. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the List's size.
//
public void InsertRange(int index, IEnumerable<T> collection)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
if ((uint)index > (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
if (c != null)
{ // if collection is ICollection<T>
int count = c.Count;
if (count > 0)
{
EnsureCapacity(_size + count);
if (index < _size)
{
Array.Copy(_items, index, _items, index + count, _size - index);
}
// If we're inserting a List into itself, we want to be able to deal with that.
if (this == c)
{
// Copy first part of _items to insert location
Array.Copy(_items, 0, _items, index, index);
// Copy last part of _items back to inserted location
Array.Copy(_items, index + count, _items, index * 2, _size - index);
}
else
{
c.CopyTo(_items, index);
}
_size += count;
}
}
else if (index < _size)
{
// We're inserting a lazy enumerable. Call Insert on each of the constituent items.
using (IEnumerator<T> en = collection.GetEnumerator())
{
while (en.MoveNext())
{
Insert(index++, en.Current);
}
}
}
else
{
// We're adding a lazy enumerable because the index is at the end of this list.
AddEnumerable(collection);
}
_version++;
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at the end
// and ending at the first element in the list. The elements of the list
// are compared to the given value using the Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item)
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
if (_size == 0)
{ // Special case for empty list
return -1;
}
else
{
return LastIndexOf(item, _size - 1, _size);
}
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and ending at the first element in the list. The
// elements of the list are compared to the given value using the
// Object.Equals method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index)
{
if (index >= _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
return LastIndexOf(item, index, index + 1);
}
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at index
// index and upto count elements. The elements of
// the list are compared to the given value using the Object.Equals
// method.
//
// This method uses the Array.LastIndexOf method to perform the
// search.
//
public int LastIndexOf(T item, int index, int count)
{
if ((Count != 0) && (index < 0))
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if ((Count != 0) && (count < 0))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
if (_size == 0)
{ // Special case for empty list
return -1;
}
if (index >= _size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
if (count > index + 1)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
return Array.LastIndexOf(_items, item, index, count);
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
void System.Collections.IList.Remove(Object item)
{
if (IsCompatibleObject(item))
{
Remove((T)item);
}
}
// This method removes all items which matches the predicate.
// The complexity is O(n).
public int RemoveAll(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
Contract.EndContractBlock();
int freeIndex = 0; // the first free slot in items array
// Find the first item which needs to be removed.
while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
if (freeIndex >= _size) return 0;
int current = freeIndex + 1;
while (current < _size)
{
// Find the first item which needs to be kept.
while (current < _size && match(_items[current])) current++;
if (current < _size)
{
// copy item to the free slot.
_items[freeIndex++] = _items[current++];
}
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_items, freeIndex, _size - freeIndex); // Clear the elements so that the gc can reclaim the references.
}
int result = _size - freeIndex;
_size = freeIndex;
_version++;
return result;
}
// Removes the element at the given index. The size of the list is
// decreased by one.
//
public void RemoveAt(int index)
{
if ((uint)index >= (uint)_size)
{
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
_size--;
if (index < _size)
{
Array.Copy(_items, index + 1, _items, index, _size - index);
}
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
_items[_size] = default(T);
}
_version++;
}
// Removes a range of elements from this list.
//
public void RemoveRange(int index, int count)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count > 0)
{
int i = _size;
_size -= count;
if (index < _size)
{
Array.Copy(_items, index + count, _items, index, _size - index);
}
_version++;
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_items, _size, count);
}
}
}
// Reverses the elements in this list.
public void Reverse()
{
Reverse(0, Count);
}
// Reverses the elements in a range of this list. Following a call to this
// method, an element in the range given by index and count
// which was previously located at index i will now be located at
// index index + (index + count - i - 1).
//
public void Reverse(int index, int count)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count > 1)
{
Array.Reverse(_items, index, count);
}
_version++;
}
// Sorts the elements in this list. Uses the default comparer and
// Array.Sort.
public void Sort()
{
Sort(0, Count, null);
}
// Sorts the elements in this list. Uses Array.Sort with the
// provided comparer.
public void Sort(IComparer<T> comparer)
{
Sort(0, Count, comparer);
}
// Sorts the elements in a section of this list. The sort compares the
// elements to each other using the given IComparer interface. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented by all
// elements of the list.
//
// This method uses the Array.Sort method to sort the elements.
//
public void Sort(int index, int count, IComparer<T> comparer)
{
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (count < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count > 1)
{
Array.Sort<T>(_items, index, count, comparer);
}
_version++;
}
public void Sort(Comparison<T> comparison)
{
if (comparison == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
Contract.EndContractBlock();
if (_size > 1)
{
ArraySortHelper<T>.Sort(_items, 0, _size, comparison);
}
_version++;
}
// ToArray returns an array containing the contents of the List.
// This requires copying the List, which is an O(n) operation.
public T[] ToArray()
{
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
if (_size == 0)
{
return _emptyArray;
}
T[] array = new T[_size];
Array.Copy(_items, 0, array, 0, _size);
return array;
}
// Sets the capacity of this list to the size of the list. This method can
// be used to minimize a list's memory overhead once it is known that no
// new elements will be added to the list. To completely clear a list and
// release all memory referenced by the list, execute the following
// statements:
//
// list.Clear();
// list.TrimExcess();
//
public void TrimExcess()
{
int threshold = (int)(((double)_items.Length) * 0.9);
if (_size < threshold)
{
Capacity = _size;
}
}
public bool TrueForAll(Predicate<T> match)
{
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
for (int i = 0; i < _size; i++)
{
if (!match(_items[i]))
{
return false;
}
}
return true;
}
private void AddEnumerable(IEnumerable<T> enumerable)
{
Debug.Assert(enumerable != null);
Debug.Assert(!(enumerable is ICollection<T>), "We should have optimized for this beforehand.");
using (IEnumerator<T> en = enumerable.GetEnumerator())
{
_version++; // Even if the enumerable has no items, we can update _version.
while (en.MoveNext())
{
// Capture Current before doing anything else. If this throws
// an exception, we want to make a clean break.
T current = en.Current;
if (_size == _items.Length)
{
EnsureCapacity(_size + 1);
}
_items[_size++] = current;
}
}
}
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private List<T> list;
private int index;
private int version;
private T current;
internal Enumerator(List<T> list)
{
this.list = list;
index = 0;
version = list._version;
current = default(T);
}
public void Dispose()
{
}
public bool MoveNext()
{
List<T> localList = list;
if (version == localList._version && ((uint)index < (uint)localList._size))
{
current = localList._items[index];
index++;
return true;
}
return MoveNextRare();
}
private bool MoveNextRare()
{
if (version != list._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = list._size + 1;
current = default(T);
return false;
}
public T Current
{
get
{
return current;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (index == 0 || index == list._size + 1)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return Current;
}
}
void System.Collections.IEnumerator.Reset()
{
if (version != list._version)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
current = default(T);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BoundColumn.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.UI.WebControls {
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Web;
using System.Web.UI;
using System.Web.Util;
/// <devdoc>
/// <para>Creates a column bounded to a data field in a <see cref='System.Web.UI.WebControls.DataGrid'/>.</para>
/// </devdoc>
public class BoundColumn : DataGridColumn {
/// <devdoc>
/// <para>Specifies a string that represents "this". This field is read-only. </para>
/// </devdoc>
public static readonly string thisExpr = "!";
private PropertyDescriptor boundFieldDesc;
private bool boundFieldDescValid;
private string boundField;
private string formatting;
/// <devdoc>
/// <para>Initializes a new instance of a <see cref='System.Web.UI.WebControls.BoundColumn'/> class.</para>
/// </devdoc>
public BoundColumn() {
}
/// <devdoc>
/// <para> Gets or sets the field name from the data model bound to this column.</para>
/// </devdoc>
[
WebCategory("Data"),
DefaultValue(""),
WebSysDescription(SR.BoundColumn_DataField)
]
public virtual string DataField {
get {
object o = ViewState["DataField"];
if (o != null)
return (string)o;
return String.Empty;
}
set {
ViewState["DataField"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the display format of data in this
/// column.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(""),
WebSysDescription(SR.BoundColumn_DataFormatString)
]
public virtual string DataFormatString {
get {
object o = ViewState["DataFormatString"];
if (o != null)
return (string)o;
return String.Empty;
}
set {
ViewState["DataFormatString"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// <para>Gets or sets the property that prevents modification to data
/// in this column.</para>
/// </devdoc>
[
WebCategory("Behavior"),
DefaultValue(false),
WebSysDescription(SR.BoundColumn_ReadOnly)
]
public virtual bool ReadOnly {
get {
object o = ViewState["ReadOnly"];
if (o != null)
return (bool)o;
return false;
}
set {
ViewState["ReadOnly"] = value;
OnColumnChanged();
}
}
/// <devdoc>
/// </devdoc>
protected virtual string FormatDataValue(object dataValue) {
string formattedValue = String.Empty;
if (!DataBinder.IsNull(dataValue)) {
if (formatting.Length == 0) {
formattedValue = dataValue.ToString();
}
else {
formattedValue = String.Format(CultureInfo.CurrentCulture, formatting, dataValue);
}
}
return formattedValue;
}
/// <devdoc>
/// </devdoc>
public override void Initialize() {
base.Initialize();
boundFieldDesc = null;
boundFieldDescValid = false;
boundField = DataField;
formatting = DataFormatString;
}
/// <devdoc>
/// <para>Initializes a cell in the DataGridColumn.</para>
/// </devdoc>
public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType) {
base.InitializeCell(cell, columnIndex, itemType);
Control childControl = null;
Control boundControl = null;
switch (itemType) {
case ListItemType.Header:
case ListItemType.Footer:
break;
case ListItemType.Item:
case ListItemType.AlternatingItem:
case ListItemType.SelectedItem:
if (DataField.Length != 0) {
boundControl = cell;
}
break;
case ListItemType.EditItem:
if (ReadOnly == true) {
goto case ListItemType.Item;
}
else {
//
TextBox editor = new TextBox();
childControl = editor;
if (boundField.Length != 0) {
boundControl = editor;
}
}
break;
}
if (childControl != null) {
cell.Controls.Add(childControl);
}
if (boundControl != null) {
boundControl.DataBinding += new EventHandler(this.OnDataBindColumn);
}
}
/// <devdoc>
/// </devdoc>
private void OnDataBindColumn(object sender, EventArgs e) {
Debug.Assert(DataField.Length != 0, "Shouldn't be DataBinding without a DataField");
Control boundControl = (Control)sender;
DataGridItem item = (DataGridItem)boundControl.NamingContainer;
object dataItem = item.DataItem;
if (boundFieldDescValid == false) {
if (!boundField.Equals(thisExpr)) {
boundFieldDesc = TypeDescriptor.GetProperties(dataItem).Find(boundField, true);
if ((boundFieldDesc == null) && !DesignMode) {
throw new HttpException(SR.GetString(SR.Field_Not_Found, boundField));
}
}
boundFieldDescValid = true;
}
object data = dataItem;
string dataValue;
if ((boundFieldDesc == null) && DesignMode) {
dataValue = SR.GetString(SR.Sample_Databound_Text);
}
else {
if (boundFieldDesc != null) {
data = boundFieldDesc.GetValue(dataItem);
}
dataValue = FormatDataValue(data);
}
if (boundControl is TableCell) {
if (dataValue.Length == 0) {
dataValue = " ";
}
((TableCell)boundControl).Text = dataValue;
}
else {
Debug.Assert(boundControl is TextBox, "Expected the bound control to be a TextBox");
((TextBox)boundControl).Text = dataValue;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Linq;
using Crestron;
using Crestron.Logos.SplusLibrary;
using Crestron.Logos.SplusObjects;
using Crestron.SimplSharp;
namespace UserModule_BSS_SOUNDWEB_LONDON_MATRIX_MIXER
{
public class UserModuleClass_BSS_SOUNDWEB_LONDON_MATRIX_MIXER : SplusObject
{
static CCriticalSection g_criticalSection = new CCriticalSection();
Crestron.Logos.SplusObjects.DigitalInput SUBSCRIBE__DOLLAR__;
Crestron.Logos.SplusObjects.DigitalInput UNSUBSCRIBE__DOLLAR__;
InOutArray<Crestron.Logos.SplusObjects.DigitalInput> OUTPUT_MUTE__DOLLAR__;
Crestron.Logos.SplusObjects.AnalogInput INPUT__DOLLAR__;
Crestron.Logos.SplusObjects.BufferInput RX__DOLLAR__;
InOutArray<Crestron.Logos.SplusObjects.AnalogInput> OUTPUT_GAIN__DOLLAR__;
InOutArray<Crestron.Logos.SplusObjects.DigitalOutput> OUTPUT_MUTE_FB__DOLLAR__;
Crestron.Logos.SplusObjects.StringOutput TX__DOLLAR__;
InOutArray<Crestron.Logos.SplusObjects.AnalogOutput> OUTPUT_GAIN_FB__DOLLAR__;
StringParameter OBJECTID__DOLLAR__;
UShortParameter IMAXOUTPUT;
private CrestronString ITOVOLUMEPERCENT ( SplusExecutionContext __context__, ushort INT )
{
__context__.SourceCodeLine = 168;
_SplusNVRAM.VOLUME = (ushort) ( ((INT * 100) / 65535) ) ;
__context__.SourceCodeLine = 169;
_SplusNVRAM.RETURNSTRING .UpdateValue ( "\u0000" + Functions.Chr ( (int) ( _SplusNVRAM.VOLUME ) ) + "\u0000\u0000" ) ;
__context__.SourceCodeLine = 170;
return ( _SplusNVRAM.RETURNSTRING ) ;
}
private ushort VOLUMEPERCENTTOI ( SplusExecutionContext __context__, CrestronString STR )
{
ushort FRACTION = 0;
__context__.SourceCodeLine = 178;
FRACTION = (ushort) ( ((Byte( STR , (int)( 3 ) ) * 256) + Byte( STR , (int)( 4 ) )) ) ;
__context__.SourceCodeLine = 179;
if ( Functions.TestForTrue ( ( Functions.BoolToInt ( FRACTION > 32767 )) ) )
{
__context__.SourceCodeLine = 180;
_SplusNVRAM.VOLUME = (ushort) ( (((Byte( STR , (int)( 2 ) ) + 1) * 65535) / 100) ) ;
}
else
{
__context__.SourceCodeLine = 183;
_SplusNVRAM.VOLUME = (ushort) ( ((Byte( STR , (int)( 2 ) ) * 65535) / 100) ) ;
}
__context__.SourceCodeLine = 185;
_SplusNVRAM.RETURNI = (ushort) ( _SplusNVRAM.VOLUME ) ;
__context__.SourceCodeLine = 187;
return (ushort)( _SplusNVRAM.RETURNI) ;
}
object OUTPUT_MUTE__DOLLAR___OnPush_0 ( Object __EventInfo__ )
{
Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__;
try
{
SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__);
__context__.SourceCodeLine = 199;
_SplusNVRAM.STATEVARONOFF = (ushort) ( Functions.GetLastModifiedArrayIndex( __SignalEventArg__ ) ) ;
__context__.SourceCodeLine = 200;
_SplusNVRAM.STATEVARONOFF = (ushort) ( (((_SplusNVRAM.STATEVARONOFF - 1) * 128) + (_SplusNVRAM.INPUT - 1)) ) ;
__context__.SourceCodeLine = 201;
MakeString ( TX__DOLLAR__ , "\u0088\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0001\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ;
__context__.SourceCodeLine = 203;
if ( Functions.TestForTrue ( ( _SplusNVRAM.SUBSCRIBE) ) )
{
__context__.SourceCodeLine = 205;
MakeString ( TX__DOLLAR__ , "\u0089\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ;
__context__.SourceCodeLine = 206;
Functions.ProcessLogic ( ) ;
}
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler( __SignalEventArg__ ); }
return this;
}
object OUTPUT_MUTE__DOLLAR___OnRelease_1 ( Object __EventInfo__ )
{
Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__;
try
{
SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__);
__context__.SourceCodeLine = 211;
_SplusNVRAM.STATEVARONOFF = (ushort) ( Functions.GetLastModifiedArrayIndex( __SignalEventArg__ ) ) ;
__context__.SourceCodeLine = 212;
_SplusNVRAM.STATEVARONOFF = (ushort) ( (((_SplusNVRAM.STATEVARONOFF - 1) * 128) + (_SplusNVRAM.INPUT - 1)) ) ;
__context__.SourceCodeLine = 213;
MakeString ( TX__DOLLAR__ , "\u0088\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ;
__context__.SourceCodeLine = 215;
if ( Functions.TestForTrue ( ( _SplusNVRAM.SUBSCRIBE) ) )
{
__context__.SourceCodeLine = 217;
MakeString ( TX__DOLLAR__ , "\u0089\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARONOFF ) ) ) ) ;
__context__.SourceCodeLine = 218;
Functions.ProcessLogic ( ) ;
}
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler( __SignalEventArg__ ); }
return this;
}
object OUTPUT_GAIN__DOLLAR___OnChange_2 ( Object __EventInfo__ )
{
Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__;
try
{
SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__);
__context__.SourceCodeLine = 225;
_SplusNVRAM.X = (ushort) ( Functions.GetLastModifiedArrayIndex( __SignalEventArg__ ) ) ;
__context__.SourceCodeLine = 227;
if ( Functions.TestForTrue ( ( Functions.BoolToInt (_SplusNVRAM.VOLUMEOUTPUT[ _SplusNVRAM.X ] != OUTPUT_GAIN__DOLLAR__[ _SplusNVRAM.X ] .UshortValue)) ) )
{
__context__.SourceCodeLine = 229;
if ( Functions.TestForTrue ( ( _SplusNVRAM.XOKGAIN[ _SplusNVRAM.X ]) ) )
{
__context__.SourceCodeLine = 231;
_SplusNVRAM.XOKGAIN [ _SplusNVRAM.X] = (ushort) ( 0 ) ;
__context__.SourceCodeLine = 232;
_SplusNVRAM.STATEVARGAIN = (ushort) ( (16384 + (((_SplusNVRAM.X - 1) * 128) + (_SplusNVRAM.INPUT - 1))) ) ;
__context__.SourceCodeLine = 234;
_SplusNVRAM.VOLUMEOUTPUT [ _SplusNVRAM.X] = (ushort) ( OUTPUT_GAIN__DOLLAR__[ _SplusNVRAM.X ] .UshortValue ) ;
__context__.SourceCodeLine = 235;
OUTPUT_GAIN_FB__DOLLAR__ [ _SplusNVRAM.X] .Value = (ushort) ( OUTPUT_GAIN__DOLLAR__[ _SplusNVRAM.X ] .UshortValue ) ;
__context__.SourceCodeLine = 237;
MakeString ( TX__DOLLAR__ , "\u008D\u0000\u0000\u0003{0}{1}{2}{3}\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARGAIN ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARGAIN ) ) ) , ITOVOLUMEPERCENT ( __context__ , (ushort)( OUTPUT_GAIN__DOLLAR__[ _SplusNVRAM.X ] .UshortValue )) ) ;
__context__.SourceCodeLine = 238;
_SplusNVRAM.XOKGAIN [ _SplusNVRAM.X] = (ushort) ( 1 ) ;
}
}
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler( __SignalEventArg__ ); }
return this;
}
object SUBSCRIBE__DOLLAR___OnPush_3 ( Object __EventInfo__ )
{
Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__;
try
{
SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__);
__context__.SourceCodeLine = 246;
CreateWait ( "__SPLS_TMPVAR__WAITLABEL_0__" , 20 , __SPLS_TMPVAR__WAITLABEL_0___Callback ) ;
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler( __SignalEventArg__ ); }
return this;
}
public void __SPLS_TMPVAR__WAITLABEL_0___CallbackFn( object stateInfo )
{
try
{
Wait __LocalWait__ = (Wait)stateInfo;
SplusExecutionContext __context__ = SplusThreadStartCode(__LocalWait__);
__LocalWait__.RemoveFromList();
__context__.SourceCodeLine = 248;
if ( Functions.TestForTrue ( ( _SplusNVRAM.XOKSUBSCRIBE) ) )
{
__context__.SourceCodeLine = 250;
_SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 0 ) ;
__context__.SourceCodeLine = 251;
_SplusNVRAM.STATEVARSUB = (ushort) ( (_SplusNVRAM.INPUT - 1) ) ;
__context__.SourceCodeLine = 252;
ushort __FN_FORSTART_VAL__1 = (ushort) ( 1 ) ;
ushort __FN_FOREND_VAL__1 = (ushort)IMAXOUTPUT .Value;
int __FN_FORSTEP_VAL__1 = (int)1;
for ( _SplusNVRAM.I = __FN_FORSTART_VAL__1; (__FN_FORSTEP_VAL__1 > 0) ? ( (_SplusNVRAM.I >= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I <= __FN_FOREND_VAL__1) ) : ( (_SplusNVRAM.I <= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I >= __FN_FOREND_VAL__1) ) ; _SplusNVRAM.I += (ushort)__FN_FORSTEP_VAL__1)
{
__context__.SourceCodeLine = 254;
_SplusNVRAM.STATEVARSUB = (ushort) ( ((_SplusNVRAM.INPUT - 1) + ((_SplusNVRAM.I - 1) * 128)) ) ;
__context__.SourceCodeLine = 255;
MakeString ( TX__DOLLAR__ , "\u0089\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) ) ;
__context__.SourceCodeLine = 256;
Functions.ProcessLogic ( ) ;
__context__.SourceCodeLine = 258;
_SplusNVRAM.STATEVARSUB = (ushort) ( (_SplusNVRAM.STATEVARSUB + 16384) ) ;
__context__.SourceCodeLine = 259;
MakeString ( TX__DOLLAR__ , "\u008E\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) ) ;
__context__.SourceCodeLine = 260;
Functions.ProcessLogic ( ) ;
__context__.SourceCodeLine = 261;
Functions.Delay ( (int) ( 5 ) ) ;
__context__.SourceCodeLine = 252;
}
__context__.SourceCodeLine = 263;
_SplusNVRAM.SUBSCRIBE = (ushort) ( 1 ) ;
__context__.SourceCodeLine = 264;
_SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 1 ) ;
}
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler(); }
}
object UNSUBSCRIBE__DOLLAR___OnPush_4 ( Object __EventInfo__ )
{
Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__;
try
{
SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__);
__context__.SourceCodeLine = 272;
if ( Functions.TestForTrue ( ( _SplusNVRAM.XOKSUBSCRIBE) ) )
{
__context__.SourceCodeLine = 274;
_SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 0 ) ;
__context__.SourceCodeLine = 275;
_SplusNVRAM.STATEVARSUB = (ushort) ( (_SplusNVRAM.INPUT - 1) ) ;
__context__.SourceCodeLine = 276;
ushort __FN_FORSTART_VAL__1 = (ushort) ( 1 ) ;
ushort __FN_FOREND_VAL__1 = (ushort)IMAXOUTPUT .Value;
int __FN_FORSTEP_VAL__1 = (int)1;
for ( _SplusNVRAM.I = __FN_FORSTART_VAL__1; (__FN_FORSTEP_VAL__1 > 0) ? ( (_SplusNVRAM.I >= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I <= __FN_FOREND_VAL__1) ) : ( (_SplusNVRAM.I <= __FN_FORSTART_VAL__1) && (_SplusNVRAM.I >= __FN_FOREND_VAL__1) ) ; _SplusNVRAM.I += (ushort)__FN_FORSTEP_VAL__1)
{
__context__.SourceCodeLine = 278;
_SplusNVRAM.STATEVARSUB = (ushort) ( ((_SplusNVRAM.INPUT - 1) + ((_SplusNVRAM.I - 1) * 128)) ) ;
__context__.SourceCodeLine = 279;
MakeString ( TX__DOLLAR__ , "\u008A\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) ) ;
__context__.SourceCodeLine = 280;
Functions.ProcessLogic ( ) ;
__context__.SourceCodeLine = 282;
_SplusNVRAM.STATEVARSUB = (ushort) ( (_SplusNVRAM.STATEVARSUB + 16384) ) ;
__context__.SourceCodeLine = 283;
MakeString ( TX__DOLLAR__ , "\u008F\u0000\u0000\u0003{0}{1}{2}\u0000\u0000\u0000\u0000\u0003\u0003\u0003\u0003\u0003", OBJECTID__DOLLAR__ , Functions.Chr ( (int) ( Functions.High( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) , Functions.Chr ( (int) ( Functions.Low( (ushort) _SplusNVRAM.STATEVARSUB ) ) ) ) ;
__context__.SourceCodeLine = 284;
Functions.ProcessLogic ( ) ;
__context__.SourceCodeLine = 285;
Functions.Delay ( (int) ( 5 ) ) ;
__context__.SourceCodeLine = 276;
}
__context__.SourceCodeLine = 287;
_SplusNVRAM.SUBSCRIBE = (ushort) ( 0 ) ;
__context__.SourceCodeLine = 288;
_SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 1 ) ;
}
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler( __SignalEventArg__ ); }
return this;
}
object INPUT__DOLLAR___OnChange_5 ( Object __EventInfo__ )
{
Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__;
try
{
SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__);
__context__.SourceCodeLine = 296;
if ( Functions.TestForTrue ( ( Functions.BoolToInt ( INPUT__DOLLAR__ .UshortValue > 0 )) ) )
{
__context__.SourceCodeLine = 297;
_SplusNVRAM.INPUT = (ushort) ( INPUT__DOLLAR__ .UshortValue ) ;
}
else
{
__context__.SourceCodeLine = 300;
_SplusNVRAM.INPUT = (ushort) ( 1 ) ;
__context__.SourceCodeLine = 301;
Print( "error input for the automixer cannot be 0. set to default of 1") ;
}
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler( __SignalEventArg__ ); }
return this;
}
object RX__DOLLAR___OnChange_6 ( Object __EventInfo__ )
{
Crestron.Logos.SplusObjects.SignalEventArgs __SignalEventArg__ = (Crestron.Logos.SplusObjects.SignalEventArgs)__EventInfo__;
try
{
SplusExecutionContext __context__ = SplusThreadStartCode(__SignalEventArg__);
__context__.SourceCodeLine = 315;
if ( Functions.TestForTrue ( ( _SplusNVRAM.XOK) ) )
{
__context__.SourceCodeLine = 317;
_SplusNVRAM.XOK = (ushort) ( 0 ) ;
__context__.SourceCodeLine = 318;
while ( Functions.TestForTrue ( ( Functions.Length( RX__DOLLAR__ )) ) )
{
__context__.SourceCodeLine = 320;
if ( Functions.TestForTrue ( ( Functions.Find( "\u0003\u0003\u0003\u0003\u0003" , RX__DOLLAR__ )) ) )
{
__context__.SourceCodeLine = 322;
_SplusNVRAM.TEMPSTRING .UpdateValue ( Functions.Remove ( "\u0003\u0003\u0003\u0003\u0003" , RX__DOLLAR__ ) ) ;
__context__.SourceCodeLine = 323;
if ( Functions.TestForTrue ( ( Functions.BoolToInt ( (Functions.TestForTrue ( Functions.BoolToInt (Functions.Mid( _SplusNVRAM.TEMPSTRING , (int)( 6 ) , (int)( 3 ) ) == "\u0000\u0000\u0000") ) || Functions.TestForTrue ( Functions.BoolToInt (Functions.Mid( _SplusNVRAM.TEMPSTRING , (int)( 6 ) , (int)( 3 ) ) == OBJECTID__DOLLAR__ ) )) )) ) )
{
__context__.SourceCodeLine = 325;
_SplusNVRAM.STATEVARRECEIVE = (ushort) ( ((Byte( _SplusNVRAM.TEMPSTRING , (int)( 9 ) ) * 256) + Byte( _SplusNVRAM.TEMPSTRING , (int)( 10 ) )) ) ;
__context__.SourceCodeLine = 326;
if ( Functions.TestForTrue ( ( Functions.BoolToInt (Mod( _SplusNVRAM.STATEVARRECEIVE , 128 ) == (_SplusNVRAM.INPUT - 1))) ) )
{
__context__.SourceCodeLine = 328;
if ( Functions.TestForTrue ( ( Functions.BoolToInt ( _SplusNVRAM.STATEVARRECEIVE < 16384 )) ) )
{
__context__.SourceCodeLine = 330;
if ( Functions.TestForTrue ( ( Byte( _SplusNVRAM.TEMPSTRING , (int)( 14 ) )) ) )
{
__context__.SourceCodeLine = 333;
OUTPUT_MUTE_FB__DOLLAR__ [ ((_SplusNVRAM.STATEVARRECEIVE / 128) + 1)] .Value = (ushort) ( 1 ) ;
}
else
{
__context__.SourceCodeLine = 337;
OUTPUT_MUTE_FB__DOLLAR__ [ ((_SplusNVRAM.STATEVARRECEIVE / 128) + 1)] .Value = (ushort) ( 0 ) ;
}
}
else
{
__context__.SourceCodeLine = 343;
_SplusNVRAM.STATEVARRECEIVE = (ushort) ( (((_SplusNVRAM.STATEVARRECEIVE - 16384) / 128) + 1) ) ;
__context__.SourceCodeLine = 344;
_SplusNVRAM.VOLUMEOUTPUT [ _SplusNVRAM.X] = (ushort) ( VOLUMEPERCENTTOI( __context__ , Functions.Mid( _SplusNVRAM.TEMPSTRING , (int)( 11 ) , (int)( 4 ) ) ) ) ;
__context__.SourceCodeLine = 345;
OUTPUT_GAIN_FB__DOLLAR__ [ _SplusNVRAM.STATEVARRECEIVE] .Value = (ushort) ( _SplusNVRAM.VOLUMEOUTPUT[ _SplusNVRAM.X ] ) ;
}
}
}
__context__.SourceCodeLine = 349;
Functions.ClearBuffer ( _SplusNVRAM.TEMPSTRING ) ;
}
__context__.SourceCodeLine = 318;
}
__context__.SourceCodeLine = 353;
_SplusNVRAM.XOK = (ushort) ( 1 ) ;
}
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler( __SignalEventArg__ ); }
return this;
}
public override object FunctionMain ( object __obj__ )
{
ushort I = 0;
try
{
SplusExecutionContext __context__ = SplusFunctionMainStartCode();
__context__.SourceCodeLine = 374;
_SplusNVRAM.XOK = (ushort) ( 1 ) ;
__context__.SourceCodeLine = 375;
_SplusNVRAM.SUBSCRIBE = (ushort) ( 0 ) ;
__context__.SourceCodeLine = 376;
ushort __FN_FORSTART_VAL__1 = (ushort) ( 1 ) ;
ushort __FN_FOREND_VAL__1 = (ushort)48;
int __FN_FORSTEP_VAL__1 = (int)1;
for ( I = __FN_FORSTART_VAL__1; (__FN_FORSTEP_VAL__1 > 0) ? ( (I >= __FN_FORSTART_VAL__1) && (I <= __FN_FOREND_VAL__1) ) : ( (I <= __FN_FORSTART_VAL__1) && (I >= __FN_FOREND_VAL__1) ) ; I += (ushort)__FN_FORSTEP_VAL__1)
{
__context__.SourceCodeLine = 378;
_SplusNVRAM.XOKGAIN [ I] = (ushort) ( 1 ) ;
__context__.SourceCodeLine = 376;
}
__context__.SourceCodeLine = 380;
_SplusNVRAM.XOKSUBSCRIBE = (ushort) ( 1 ) ;
}
catch(Exception e) { ObjectCatchHandler(e); }
finally { ObjectFinallyHandler(); }
return __obj__;
}
public override void LogosSplusInitialize()
{
SocketInfo __socketinfo__ = new SocketInfo( 1, this );
InitialParametersClass.ResolveHostName = __socketinfo__.ResolveHostName;
_SplusNVRAM = new SplusNVRAM( this );
_SplusNVRAM.VOLUMEOUTPUT = new ushort[ 49 ];
_SplusNVRAM.XOKGAIN = new ushort[ 49 ];
_SplusNVRAM.RETURNSTRING = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 4, this );
_SplusNVRAM.TEMPSTRING = new CrestronString( Crestron.Logos.SplusObjects.CrestronStringEncoding.eEncodingASCII, 40, this );
SUBSCRIBE__DOLLAR__ = new Crestron.Logos.SplusObjects.DigitalInput( SUBSCRIBE__DOLLAR____DigitalInput__, this );
m_DigitalInputList.Add( SUBSCRIBE__DOLLAR____DigitalInput__, SUBSCRIBE__DOLLAR__ );
UNSUBSCRIBE__DOLLAR__ = new Crestron.Logos.SplusObjects.DigitalInput( UNSUBSCRIBE__DOLLAR____DigitalInput__, this );
m_DigitalInputList.Add( UNSUBSCRIBE__DOLLAR____DigitalInput__, UNSUBSCRIBE__DOLLAR__ );
OUTPUT_MUTE__DOLLAR__ = new InOutArray<DigitalInput>( 48, this );
for( uint i = 0; i < 48; i++ )
{
OUTPUT_MUTE__DOLLAR__[i+1] = new Crestron.Logos.SplusObjects.DigitalInput( OUTPUT_MUTE__DOLLAR____DigitalInput__ + i, OUTPUT_MUTE__DOLLAR____DigitalInput__, this );
m_DigitalInputList.Add( OUTPUT_MUTE__DOLLAR____DigitalInput__ + i, OUTPUT_MUTE__DOLLAR__[i+1] );
}
OUTPUT_MUTE_FB__DOLLAR__ = new InOutArray<DigitalOutput>( 48, this );
for( uint i = 0; i < 48; i++ )
{
OUTPUT_MUTE_FB__DOLLAR__[i+1] = new Crestron.Logos.SplusObjects.DigitalOutput( OUTPUT_MUTE_FB__DOLLAR____DigitalOutput__ + i, this );
m_DigitalOutputList.Add( OUTPUT_MUTE_FB__DOLLAR____DigitalOutput__ + i, OUTPUT_MUTE_FB__DOLLAR__[i+1] );
}
INPUT__DOLLAR__ = new Crestron.Logos.SplusObjects.AnalogInput( INPUT__DOLLAR____AnalogSerialInput__, this );
m_AnalogInputList.Add( INPUT__DOLLAR____AnalogSerialInput__, INPUT__DOLLAR__ );
OUTPUT_GAIN__DOLLAR__ = new InOutArray<AnalogInput>( 48, this );
for( uint i = 0; i < 48; i++ )
{
OUTPUT_GAIN__DOLLAR__[i+1] = new Crestron.Logos.SplusObjects.AnalogInput( OUTPUT_GAIN__DOLLAR____AnalogSerialInput__ + i, OUTPUT_GAIN__DOLLAR____AnalogSerialInput__, this );
m_AnalogInputList.Add( OUTPUT_GAIN__DOLLAR____AnalogSerialInput__ + i, OUTPUT_GAIN__DOLLAR__[i+1] );
}
OUTPUT_GAIN_FB__DOLLAR__ = new InOutArray<AnalogOutput>( 48, this );
for( uint i = 0; i < 48; i++ )
{
OUTPUT_GAIN_FB__DOLLAR__[i+1] = new Crestron.Logos.SplusObjects.AnalogOutput( OUTPUT_GAIN_FB__DOLLAR____AnalogSerialOutput__ + i, this );
m_AnalogOutputList.Add( OUTPUT_GAIN_FB__DOLLAR____AnalogSerialOutput__ + i, OUTPUT_GAIN_FB__DOLLAR__[i+1] );
}
TX__DOLLAR__ = new Crestron.Logos.SplusObjects.StringOutput( TX__DOLLAR____AnalogSerialOutput__, this );
m_StringOutputList.Add( TX__DOLLAR____AnalogSerialOutput__, TX__DOLLAR__ );
RX__DOLLAR__ = new Crestron.Logos.SplusObjects.BufferInput( RX__DOLLAR____AnalogSerialInput__, 400, this );
m_StringInputList.Add( RX__DOLLAR____AnalogSerialInput__, RX__DOLLAR__ );
IMAXOUTPUT = new UShortParameter( IMAXOUTPUT__Parameter__, this );
m_ParameterList.Add( IMAXOUTPUT__Parameter__, IMAXOUTPUT );
OBJECTID__DOLLAR__ = new StringParameter( OBJECTID__DOLLAR____Parameter__, this );
m_ParameterList.Add( OBJECTID__DOLLAR____Parameter__, OBJECTID__DOLLAR__ );
__SPLS_TMPVAR__WAITLABEL_0___Callback = new WaitFunction( __SPLS_TMPVAR__WAITLABEL_0___CallbackFn );
for( uint i = 0; i < 48; i++ )
OUTPUT_MUTE__DOLLAR__[i+1].OnDigitalPush.Add( new InputChangeHandlerWrapper( OUTPUT_MUTE__DOLLAR___OnPush_0, false ) );
for( uint i = 0; i < 48; i++ )
OUTPUT_MUTE__DOLLAR__[i+1].OnDigitalRelease.Add( new InputChangeHandlerWrapper( OUTPUT_MUTE__DOLLAR___OnRelease_1, false ) );
for( uint i = 0; i < 48; i++ )
OUTPUT_GAIN__DOLLAR__[i+1].OnAnalogChange.Add( new InputChangeHandlerWrapper( OUTPUT_GAIN__DOLLAR___OnChange_2, false ) );
SUBSCRIBE__DOLLAR__.OnDigitalPush.Add( new InputChangeHandlerWrapper( SUBSCRIBE__DOLLAR___OnPush_3, false ) );
UNSUBSCRIBE__DOLLAR__.OnDigitalPush.Add( new InputChangeHandlerWrapper( UNSUBSCRIBE__DOLLAR___OnPush_4, false ) );
INPUT__DOLLAR__.OnAnalogChange.Add( new InputChangeHandlerWrapper( INPUT__DOLLAR___OnChange_5, false ) );
RX__DOLLAR__.OnSerialChange.Add( new InputChangeHandlerWrapper( RX__DOLLAR___OnChange_6, false ) );
_SplusNVRAM.PopulateCustomAttributeList( true );
NVRAM = _SplusNVRAM;
}
public override void LogosSimplSharpInitialize()
{
}
public UserModuleClass_BSS_SOUNDWEB_LONDON_MATRIX_MIXER ( string InstanceName, string ReferenceID, Crestron.Logos.SplusObjects.CrestronStringEncoding nEncodingType ) : base( InstanceName, ReferenceID, nEncodingType ) {}
private WaitFunction __SPLS_TMPVAR__WAITLABEL_0___Callback;
const uint SUBSCRIBE__DOLLAR____DigitalInput__ = 0;
const uint UNSUBSCRIBE__DOLLAR____DigitalInput__ = 1;
const uint OUTPUT_MUTE__DOLLAR____DigitalInput__ = 2;
const uint INPUT__DOLLAR____AnalogSerialInput__ = 0;
const uint RX__DOLLAR____AnalogSerialInput__ = 1;
const uint OUTPUT_GAIN__DOLLAR____AnalogSerialInput__ = 2;
const uint OUTPUT_MUTE_FB__DOLLAR____DigitalOutput__ = 0;
const uint TX__DOLLAR____AnalogSerialOutput__ = 0;
const uint OUTPUT_GAIN_FB__DOLLAR____AnalogSerialOutput__ = 1;
const uint OBJECTID__DOLLAR____Parameter__ = 10;
const uint IMAXOUTPUT__Parameter__ = 11;
[SplusStructAttribute(-1, true, false)]
public class SplusNVRAM : SplusStructureBase
{
public SplusNVRAM( SplusObject __caller__ ) : base( __caller__ ) {}
[SplusStructAttribute(0, false, true)]
public ushort I = 0;
[SplusStructAttribute(1, false, true)]
public ushort [] VOLUMEOUTPUT;
[SplusStructAttribute(2, false, true)]
public ushort VOLUME = 0;
[SplusStructAttribute(3, false, true)]
public ushort INPUT = 0;
[SplusStructAttribute(4, false, true)]
public CrestronString RETURNSTRING;
[SplusStructAttribute(5, false, true)]
public ushort RETURNI = 0;
[SplusStructAttribute(6, false, true)]
public ushort SUBSCRIBE = 0;
[SplusStructAttribute(7, false, true)]
public ushort XOK = 0;
[SplusStructAttribute(8, false, true)]
public ushort [] XOKGAIN;
[SplusStructAttribute(9, false, true)]
public ushort XOKSUBSCRIBE = 0;
[SplusStructAttribute(10, false, true)]
public CrestronString TEMPSTRING;
[SplusStructAttribute(11, false, true)]
public ushort STATEVARONOFF = 0;
[SplusStructAttribute(12, false, true)]
public ushort STATEVARGAIN = 0;
[SplusStructAttribute(13, false, true)]
public ushort STATEVARSUB = 0;
[SplusStructAttribute(14, false, true)]
public ushort STATEVARRECEIVE = 0;
[SplusStructAttribute(15, false, true)]
public ushort X = 0;
}
SplusNVRAM _SplusNVRAM = null;
public class __CEvent__ : CEvent
{
public __CEvent__() {}
public void Close() { base.Close(); }
public int Reset() { return base.Reset() ? 1 : 0; }
public int Set() { return base.Set() ? 1 : 0; }
public int Wait( int timeOutInMs ) { return base.Wait( timeOutInMs ) ? 1 : 0; }
}
public class __CMutex__ : CMutex
{
public __CMutex__() {}
public void Close() { base.Close(); }
public void ReleaseMutex() { base.ReleaseMutex(); }
public int WaitForMutex() { return base.WaitForMutex() ? 1 : 0; }
}
public int IsNull( object obj ){ return (obj == null) ? 1 : 0; }
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="DataPortal.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Implements the server-side DataPortal </summary>
//-----------------------------------------------------------------------
using System;
#if !NETFX_CORE
using System.Configuration;
#endif
#if NETFX_CORE
using System.Reflection;
using Csla.Reflection;
#endif
using System.Security.Principal;
using System.Threading.Tasks;
using Csla.Properties;
using System.Collections.Generic;
namespace Csla.Server
{
/// <summary>
/// Implements the server-side DataPortal
/// message router as discussed
/// in Chapter 4.
/// </summary>
public class DataPortal : IDataPortalServer
{
#region Constructors
/// <summary>
/// Default constructor
/// </summary>
public DataPortal()
: this("CslaAuthorizationProvider")
{
}
/// <summary>
/// This construcor accepts the App Setting name for the Csla Authorization Provider,
/// therefore getting the provider type from configuration file
/// </summary>
/// <param name="cslaAuthorizationProviderAppSettingName"></param>
protected DataPortal(string cslaAuthorizationProviderAppSettingName)
: this(GetAuthProviderType(cslaAuthorizationProviderAppSettingName))
{
}
/// <summary>
/// This constructor accepts the Authorization Provider Type as a parameter.
/// </summary>
/// <param name="authProviderType"></param>
protected DataPortal(Type authProviderType)
{
if (null == authProviderType)
throw new ArgumentNullException("authProviderType", Resources.CslaAuthenticationProviderNotSet);
if (!typeof(IAuthorizeDataPortal).IsAssignableFrom(authProviderType))
throw new ArgumentException(Resources.AuthenticationProviderDoesNotImplementIAuthorizeDataPortal, "authProviderType");
//only construct the type if it was not constructed already
if (null == _authorizer)
{
lock (_syncRoot)
{
if (null == _authorizer)
_authorizer = (IAuthorizeDataPortal)Activator.CreateInstance(authProviderType);
}
}
if (InterceptorType != null)
{
if (_interceptor == null)
{
lock (_syncRoot)
{
if (_interceptor == null)
_interceptor = (IInterceptDataPortal)Activator.CreateInstance(InterceptorType);
}
}
}
}
private static Type GetAuthProviderType(string cslaAuthorizationProviderAppSettingName)
{
if (cslaAuthorizationProviderAppSettingName == null)
throw new ArgumentNullException("cslaAuthorizationProviderAppSettingName", Resources.AuthorizationProviderNameNotSpecified);
if (null == _authorizer)//not yet instantiated
{
#if (ANDROID || IOS) || NETFX_CORE
string authProvider = string.Empty;
#else
var authProvider = ConfigurationManager.AppSettings[cslaAuthorizationProviderAppSettingName];
#endif
return string.IsNullOrEmpty(authProvider) ?
typeof(NullAuthorizer) :
Type.GetType(authProvider, true);
}
else
return _authorizer.GetType();
}
#endregion
#region Data Access
#if !(ANDROID || IOS) && !NETFX_CORE && !MONO
private IDataPortalServer GetServicedComponentPortal(TransactionalAttribute transactionalAttribute)
{
switch (transactionalAttribute.TransactionIsolationLevel)
{
case TransactionIsolationLevel.Serializable:
return new ServicedDataPortalSerializable();
case TransactionIsolationLevel.RepeatableRead:
return new ServicedDataPortalRepeatableRead();
case TransactionIsolationLevel.ReadCommitted:
return new ServicedDataPortalReadCommitted();
case TransactionIsolationLevel.ReadUncommitted:
return new ServicedDataPortalReadUncommitted();
default:
throw new ArgumentOutOfRangeException("transactionalAttribute");
}
}
#endif
/// <summary>
/// Create a new business object.
/// </summary>
/// <param name="objectType">Type of business object to create.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
public async Task<DataPortalResult> Create(
Type objectType, object criteria, DataPortalContext context, bool isSync)
{
try
{
SetContext(context);
Initialize(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Operation = DataPortalOperations.Create, IsSync = isSync });
AuthorizeRequest(new AuthorizeRequest(objectType, criteria, DataPortalOperations.Create));
DataPortalResult result;
DataPortalMethodInfo method = DataPortalMethodCache.GetCreateMethod(objectType, criteria);
IDataPortalServer portal;
#if !(ANDROID || IOS) && !NETFX_CORE
switch (method.TransactionalAttribute.TransactionType)
{
#if !MONO
case TransactionalTypes.EnterpriseServices:
portal = GetServicedComponentPortal(method.TransactionalAttribute);
try
{
result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false);
}
finally
{
((System.EnterpriseServices.ServicedComponent)portal).Dispose();
}
break;
#endif
case TransactionalTypes.TransactionScope:
portal = new TransactionalDataPortal(method.TransactionalAttribute);
result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false);
break;
default:
portal = new DataPortalBroker();
result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false);
break;
}
#else
portal = new DataPortalBroker();
result = await portal.Create(objectType, criteria, context, isSync).ConfigureAwait(false);
#endif
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Result = result, Operation = DataPortalOperations.Create, IsSync = isSync });
return result;
}
catch (Csla.Server.DataPortalException ex)
{
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = ex, Operation = DataPortalOperations.Create, IsSync = isSync });
throw;
}
catch (AggregateException ex)
{
Exception error = null;
if (ex.InnerExceptions.Count > 0)
error = ex.InnerExceptions[0].InnerException;
else
error = ex;
var fex = DataPortal.NewDataPortalException(
"DataPortal.Create " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Create", error),
null);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Create, IsSync = isSync });
throw fex;
}
catch (Exception ex)
{
var fex = DataPortal.NewDataPortalException(
"DataPortal.Create " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Create", ex),
null);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Create, IsSync = isSync });
throw fex;
}
finally
{
ClearContext(context);
}
}
/// <summary>
/// Get an existing business object.
/// </summary>
/// <param name="objectType">Type of business object to retrieve.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
public async Task<DataPortalResult> Fetch(Type objectType, object criteria, DataPortalContext context, bool isSync)
{
try
{
SetContext(context);
Initialize(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Operation = DataPortalOperations.Fetch, IsSync = isSync });
AuthorizeRequest(new AuthorizeRequest(objectType, criteria, DataPortalOperations.Fetch));
DataPortalResult result;
DataPortalMethodInfo method = DataPortalMethodCache.GetFetchMethod(objectType, criteria);
IDataPortalServer portal;
#if !(ANDROID || IOS) && !NETFX_CORE
switch (method.TransactionalAttribute.TransactionType)
{
#if !MONO
case TransactionalTypes.EnterpriseServices:
portal = GetServicedComponentPortal(method.TransactionalAttribute);
try
{
result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false);
}
finally
{
((System.EnterpriseServices.ServicedComponent)portal).Dispose();
}
break;
#endif
case TransactionalTypes.TransactionScope:
portal = new TransactionalDataPortal(method.TransactionalAttribute);
result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false);
break;
default:
portal = new DataPortalBroker();
result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false);
break;
}
#else
portal = new DataPortalBroker();
result = await portal.Fetch(objectType, criteria, context, isSync).ConfigureAwait(false);
#endif
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Result = result, Operation = DataPortalOperations.Fetch, IsSync = isSync });
return result;
}
catch (Csla.Server.DataPortalException ex)
{
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = ex, Operation = DataPortalOperations.Fetch, IsSync = isSync });
throw;
}
catch (AggregateException ex)
{
Exception error = null;
if (ex.InnerExceptions.Count > 0)
error = ex.InnerExceptions[0].InnerException;
else
error = ex;
var fex = DataPortal.NewDataPortalException(
"DataPortal.Fetch " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Fetch", error),
null);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Fetch, IsSync = isSync });
throw fex;
}
catch (Exception ex)
{
var fex = DataPortal.NewDataPortalException(
"DataPortal.Fetch " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Fetch", ex),
null);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Fetch, IsSync = isSync });
throw fex;
}
finally
{
ClearContext(context);
}
}
/// <summary>
/// Update a business object.
/// </summary>
/// <param name="obj">Business object to update.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public async Task<DataPortalResult> Update(object obj, DataPortalContext context, bool isSync)
{
Type objectType = null;
DataPortalOperations operation = DataPortalOperations.Update;
try
{
SetContext(context);
objectType = obj.GetType();
if (obj is Core.ICommandObject)
operation = DataPortalOperations.Execute;
Initialize(new InterceptArgs { ObjectType = objectType, Parameter = obj, Operation = operation, IsSync = isSync });
AuthorizeRequest(new AuthorizeRequest(objectType, obj, operation));
DataPortalResult result;
DataPortalMethodInfo method;
var factoryInfo = ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType);
if (factoryInfo != null)
{
string methodName;
var factoryType = FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName);
var bbase = obj as Core.BusinessBase;
if (bbase != null)
{
if (bbase.IsDeleted)
methodName = factoryInfo.DeleteMethodName;
else
methodName = factoryInfo.UpdateMethodName;
}
else if (obj is Core.ICommandObject)
methodName = factoryInfo.ExecuteMethodName;
else
methodName = factoryInfo.UpdateMethodName;
method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, methodName, new object[] { obj });
}
else
{
string methodName;
var bbase = obj as Core.BusinessBase;
if (bbase != null)
{
if (bbase.IsDeleted)
methodName = "DataPortal_DeleteSelf";
else
if (bbase.IsNew)
methodName = "DataPortal_Insert";
else
methodName = "DataPortal_Update";
}
else if (obj is Core.ICommandObject)
methodName = "DataPortal_Execute";
else
methodName = "DataPortal_Update";
method = DataPortalMethodCache.GetMethodInfo(obj.GetType(), methodName);
}
#if !(ANDROID || IOS) && !NETFX_CORE
context.TransactionalType = method.TransactionalAttribute.TransactionType;
#else
context.TransactionalType = method.TransactionalType;
#endif
IDataPortalServer portal;
#if !(ANDROID || IOS) && !NETFX_CORE
switch (method.TransactionalAttribute.TransactionType)
{
#if !MONO
case TransactionalTypes.EnterpriseServices:
portal = GetServicedComponentPortal(method.TransactionalAttribute);
try
{
result = await portal.Update(obj, context, isSync).ConfigureAwait(false);
}
finally
{
((System.EnterpriseServices.ServicedComponent)portal).Dispose();
}
break;
#endif
case TransactionalTypes.TransactionScope:
portal = new TransactionalDataPortal(method.TransactionalAttribute);
result = await portal.Update(obj, context, isSync).ConfigureAwait(false);
break;
default:
portal = new DataPortalBroker();
result = await portal.Update(obj, context, isSync).ConfigureAwait(false);
break;
}
#else
portal = new DataPortalBroker();
result = await portal.Update(obj, context, isSync).ConfigureAwait(false);
#endif
Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Result = result, Operation = operation, IsSync = isSync });
return result;
}
catch (Csla.Server.DataPortalException ex)
{
Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Exception = ex, Operation = operation, IsSync = isSync });
throw;
}
catch (AggregateException ex)
{
Exception error = null;
if (ex.InnerExceptions.Count > 0)
error = ex.InnerExceptions[0].InnerException;
else
error = ex;
var fex = DataPortal.NewDataPortalException(
"DataPortal.Update " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(obj.GetType(), obj, null, "DataPortal.Update", error),
obj);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Exception = fex, Operation = operation, IsSync = isSync });
throw fex;
}
catch (Exception ex)
{
var fex = DataPortal.NewDataPortalException(
"DataPortal.Update " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(obj.GetType(), obj, null, "DataPortal.Update", ex),
obj);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = obj, Exception = fex, Operation = operation, IsSync = isSync });
throw fex;
}
finally
{
ClearContext(context);
}
}
/// <summary>
/// Delete a business object.
/// </summary>
/// <param name="objectType">Type of business object to create.</param>
/// <param name="criteria">Criteria object describing business object.</param>
/// <param name="context">
/// <see cref="Server.DataPortalContext" /> object passed to the server.
/// </param>
/// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param>
public async Task<DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync)
{
try
{
SetContext(context);
Initialize(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Operation = DataPortalOperations.Delete, IsSync = isSync });
AuthorizeRequest(new AuthorizeRequest(objectType, criteria, DataPortalOperations.Delete));
DataPortalResult result;
DataPortalMethodInfo method;
var factoryInfo = ObjectFactoryAttribute.GetObjectFactoryAttribute(objectType);
if (factoryInfo != null)
{
var factoryType = FactoryDataPortal.FactoryLoader.GetFactoryType(factoryInfo.FactoryTypeName);
string methodName = factoryInfo.DeleteMethodName;
method = Server.DataPortalMethodCache.GetMethodInfo(factoryType, methodName, criteria);
}
else
{
method = DataPortalMethodCache.GetMethodInfo(objectType, "DataPortal_Delete", criteria);
}
IDataPortalServer portal;
#if !(ANDROID || IOS) && !NETFX_CORE
switch (method.TransactionalAttribute.TransactionType)
{
#if !MONO
case TransactionalTypes.EnterpriseServices:
portal = GetServicedComponentPortal(method.TransactionalAttribute);
try
{
result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false);
}
finally
{
((System.EnterpriseServices.ServicedComponent)portal).Dispose();
}
break;
#endif
case TransactionalTypes.TransactionScope:
portal = new TransactionalDataPortal(method.TransactionalAttribute);
result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false);
break;
default:
portal = new DataPortalBroker();
result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false);
break;
}
#else
portal = new DataPortalBroker();
result = await portal.Delete(objectType, criteria, context, isSync).ConfigureAwait(false);
#endif
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Result = result, Operation = DataPortalOperations.Delete, IsSync = isSync });
return result;
}
catch (Csla.Server.DataPortalException ex)
{
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = ex, Operation = DataPortalOperations.Delete, IsSync = isSync });
throw;
}
catch (AggregateException ex)
{
Exception error = null;
if (ex.InnerExceptions.Count > 0)
error = ex.InnerExceptions[0].InnerException;
else
error = ex;
var fex = DataPortal.NewDataPortalException(
"DataPortal.Delete " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Delete", error),
null);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Delete, IsSync = isSync });
throw fex;
}
catch (Exception ex)
{
var fex = DataPortal.NewDataPortalException(
"DataPortal.Delete " + Resources.FailedOnServer,
new DataPortalExceptionHandler().InspectException(objectType, criteria, "DataPortal.Delete", ex),
null);
Complete(new InterceptArgs { ObjectType = objectType, Parameter = criteria, Exception = fex, Operation = DataPortalOperations.Delete, IsSync = isSync });
throw fex;
}
finally
{
ClearContext(context);
}
}
private IInterceptDataPortal _interceptor = null;
private static Type _interceptorType = null;
private static bool _InterceptorTypeSet = false;
/// <summary>
/// Gets or sets the type of interceptor invoked
/// by the data portal for pre- and post-processing
/// of each data portal invocation.
/// </summary>
public static Type InterceptorType
{
get
{
if (!_InterceptorTypeSet)
{
#if !(ANDROID || IOS) && !NETFX_CORE
var typeName = ConfigurationManager.AppSettings["CslaDataPortalInterceptor"];
if (!string.IsNullOrWhiteSpace(typeName))
InterceptorType = Type.GetType(typeName);
#endif
_InterceptorTypeSet = true;
}
return _interceptorType;
}
set
{
_interceptorType = value;
_InterceptorTypeSet = true;
}
}
internal void Complete(InterceptArgs e)
{
if (_interceptor != null)
_interceptor.Complete(e);
}
internal void Initialize(InterceptArgs e)
{
if (_interceptor != null)
_interceptor.Initialize(e);
}
#endregion
#region Context
ApplicationContext.LogicalExecutionLocations _oldLocation;
private void SetContext(DataPortalContext context)
{
_oldLocation = Csla.ApplicationContext.LogicalExecutionLocation;
ApplicationContext.SetLogicalExecutionLocation(ApplicationContext.LogicalExecutionLocations.Server);
// if the dataportal is not remote then
// do nothing
if (!context.IsRemotePortal) return;
// set the context value so everyone knows the
// code is running on the server
ApplicationContext.SetExecutionLocation(ApplicationContext.ExecutionLocations.Server);
// set the app context to the value we got from the
// client
ApplicationContext.SetContext(context.ClientContext, context.GlobalContext);
// set the thread's culture to match the client
#if !PCL46 // rely on NuGet bait-and-switch for actual implementation
#if NETCORE
System.Globalization.CultureInfo.CurrentCulture =
new System.Globalization.CultureInfo(context.ClientCulture);
System.Globalization.CultureInfo.CurrentUICulture =
new System.Globalization.CultureInfo(context.ClientUICulture);
#elif NETFX_CORE
var list = new System.Collections.ObjectModel.ReadOnlyCollection<string>(new List<string> { context.ClientUICulture });
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Languages = list;
list = new System.Collections.ObjectModel.ReadOnlyCollection<string>(new List<string> { context.ClientCulture });
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Languages = list;
#else
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo(context.ClientCulture);
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo(context.ClientUICulture);
#endif
#endif
if (ApplicationContext.AuthenticationType == "Windows")
{
// When using integrated security, Principal must be null
if (context.Principal != null)
{
Csla.Security.SecurityException ex =
new Csla.Security.SecurityException(Resources.NoPrincipalAllowedException);
//ex.Action = System.Security.Permissions.SecurityAction.Deny;
throw ex;
}
#if !(ANDROID || IOS) && !NETFX_CORE
// Set .NET to use integrated security
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
#endif
}
else
{
// We expect the some Principal object
if (context.Principal == null)
{
Csla.Security.SecurityException ex =
new Csla.Security.SecurityException(
Resources.BusinessPrincipalException + " Nothing");
//ex.Action = System.Security.Permissions.SecurityAction.Deny;
throw ex;
}
ApplicationContext.User = context.Principal;
}
}
private void ClearContext(DataPortalContext context)
{
ApplicationContext.SetLogicalExecutionLocation(_oldLocation);
// if the dataportal is not remote then
// do nothing
if (!context.IsRemotePortal) return;
ApplicationContext.Clear();
if (ApplicationContext.AuthenticationType != "Windows")
ApplicationContext.User = null;
}
#endregion
#region Authorize
private static object _syncRoot = new object();
private static IAuthorizeDataPortal _authorizer = null;
/// <summary>
/// Gets or sets a reference to the current authorizer.
/// </summary>
protected static IAuthorizeDataPortal Authorizer
{
get { return _authorizer; }
set { _authorizer = value; }
}
internal void Authorize(AuthorizeRequest clientRequest)
{
AuthorizeRequest(clientRequest);
}
private static void AuthorizeRequest(AuthorizeRequest clientRequest)
{
_authorizer.Authorize(clientRequest);
}
/// <summary>
/// Default implementation of the authorizer that
/// allows all data portal calls to pass.
/// </summary>
protected class NullAuthorizer : IAuthorizeDataPortal
{
/// <summary>
/// Creates an instance of the type.
/// </summary>
/// <param name="clientRequest">
/// Client request information.
/// </param>
public void Authorize(AuthorizeRequest clientRequest)
{ /* default is to allow all requests */ }
}
#endregion
internal static DataPortalException NewDataPortalException(string message, Exception innerException, object businessObject)
{
if (!ApplicationContext.DataPortalReturnObjectOnException)
businessObject = null;
throw new DataPortalException(
message,
innerException, new DataPortalResult(businessObject));
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Cci.MutableCodeModel;
using Microsoft.Cci;
namespace CCDoc {
[ContractVerification(true)]
internal static class BooleanExpressionHelper
{
#region Code to negate predicates in bool expression strings
// Recognize some common predicate forms, and negate them. Also, fall back to a correct default.
public static String NegatePredicate(String predicate) {
if (String.IsNullOrEmpty(predicate)) return "";
if (predicate.Length < 2) return "!" + predicate;
// "(p)", but avoiding stuff like "(p && q) || (!p)"
if (predicate[0] == '(' && predicate[predicate.Length - 1] == ')') {
if (predicate.IndexOf('(', 1) == -1)
return '(' + NegatePredicate(predicate.Substring(1, predicate.Length - 2)) + ')';
}
// "!p"
if (predicate[0] == '!' && (ContainsNoOperators(predicate, 1, predicate.Length - 1) || IsSimpleFunctionCall(predicate, 1, predicate.Length - 1)))
return predicate.Substring(1);
// "a < b" or "a <= b"
int ltIndex = predicate.IndexOf('<');
if (ltIndex >= 0) {
int aStart = 0, aEnd, bStart, bEnd = predicate.Length;
bool ltOrEquals = ltIndex < bEnd - 1 ? predicate[ltIndex + 1] == '=' : false;
aEnd = ltIndex;
bStart = ltOrEquals ? ltIndex + 2 : ltIndex + 1;
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
if (ContainsNoOperators(a) && ContainsNoOperators(b))
return a + (ltOrEquals ? ">" : ">=") + b;
}
// "a > b" or "a >= b"
int gtIndex = predicate.IndexOf('>');
if (gtIndex >= 0) {
int aStart = 0, aEnd, bStart, bEnd = predicate.Length;
bool gtOrEquals = gtIndex < bEnd - 1 ? predicate[gtIndex + 1] == '=' : false;
aEnd = gtIndex;
bStart = gtOrEquals ? gtIndex + 2 : gtIndex + 1;
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
if (ContainsNoOperators(a) && ContainsNoOperators(b))
return a + (gtOrEquals ? "<" : "<=") + b;
}
// "a == b" or "a != b"
int eqIndex = predicate.IndexOf('=');
if (eqIndex >= 0) {
int aStart = 0, aEnd = -1, bStart = -1, bEnd = predicate.Length;
bool skip = false;
bool equalsOperator = false;
if (eqIndex > 0 && predicate[eqIndex - 1] == '!') {
aEnd = eqIndex - 1;
bStart = eqIndex + 1;
equalsOperator = false;
} else if (eqIndex < bEnd - 1 && predicate[eqIndex + 1] == '=') {
aEnd = eqIndex;
bStart = eqIndex + 2;
equalsOperator = true;
} else
skip = true;
if (!skip) {
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
if (ContainsNoOperators(a) && ContainsNoOperators(b))
return a + (equalsOperator ? "!=" : "==") + b;
}
}
return NegateConjunctsAndDisjuncts(predicate);
}
[ContractVerification(true)]
private static string NegateConjunctsAndDisjuncts(String predicate)
{
Contract.Requires(predicate != null);
if (predicate.Contains("&&") || predicate.Contains("||"))
{
// Consider predicates like "(P) && (Q)", "P || Q", "(P || Q) && R", etc.
// Apply DeMorgan's law, and recurse to negate both sides of the binary operator.
int aStart = 0, aEnd, bEnd = predicate.Length;
int parenCount = 0;
bool skip = false;
bool foundAnd = false, foundOr = false;
aEnd = 0;
while (aEnd < predicate.Length && ((predicate[aEnd] != '&' && predicate[aEnd] != '|') || parenCount > 0))
{
if (predicate[aEnd] == '(')
parenCount++;
else if (predicate[aEnd] == ')')
parenCount--;
aEnd++;
}
if (aEnd >= predicate.Length - 1)
skip = true;
else
{
if (aEnd + 1 < predicate.Length && predicate[aEnd] == '&' && predicate[aEnd + 1] == '&')
foundAnd = true;
else if (aEnd + 1 < predicate.Length && predicate[aEnd] == '|' && predicate[aEnd + 1] == '|')
foundOr = true;
if (!foundAnd && !foundOr)
skip = true;
}
if (!skip)
{
var bStart = aEnd + 2;
Contract.Assert(bStart <= bEnd);
while (aEnd > 0 && Char.IsWhiteSpace(predicate[aEnd - 1]))
aEnd--;
while (bStart < bEnd && Char.IsWhiteSpace(predicate[bStart]))
bStart++;
String a = predicate.Substring(aStart, aEnd - aStart);
String b = predicate.Substring(bStart, bEnd - bStart);
String op = foundAnd ? " || " : " && ";
return NegatePredicate(a) + op + NegatePredicate(b);
}
}
return String.Format("!({0})", predicate);
}
private static bool ContainsNoOperators(String s) {
Contract.Requires(s != null);
return ContainsNoOperators(s, 0, s.Length);
}
// These aren't operators like + per se, but ones that will cause evaluation order to possibly change,
// or alter the semantics of what might be in a predicate.
// @TODO: Consider adding '~'
static readonly String[] Operators = new String[] { "==", "!=", "=", "<", ">", "(", ")", "//", "/*", "*/" };
private static bool ContainsNoOperators(String s, int start, int end) {
Contract.Requires(s != null);
foreach (String op in Operators) {
Contract.Assume(op != null, "lack of contract support for collections");
if (s.IndexOf(op) >= 0)
return false;
}
return true;
}
private static bool ArrayContains<T>(T[] array, T item) {
Contract.Requires(array != null);
foreach (T x in array)
if (item.Equals(x))
return true;
return false;
}
// Recognize only SIMPLE method calls, like "System.String.Equals("", "")".
private static bool IsSimpleFunctionCall(String s, int start, int end) {
Contract.Requires(s != null);
Contract.Requires(start >= 0);
Contract.Requires(end <= s.Length);
Contract.Requires(end >= 0);
char[] badChars = { '+', '-', '*', '/', '~', '<', '=', '>', ';', '?', ':' };
int parenCount = 0;
int index = start;
bool foundMethod = false;
for (; index < end; index++) {
if (s[index] == '(')
{
parenCount++;
if (parenCount > 1)
return false;
if (foundMethod == true)
return false;
foundMethod = true;
} else if (s[index] == ')') {
parenCount--;
if (index != end - 1)
return false;
} else if (ArrayContains(badChars, s[index]))
return false;
}
return foundMethod;
}
#endregion Code from BrianGru to negate predicates coming from if-then-throw preconditions
public static IExpression Normalize(IExpression expression) {
LogicalNot/*?*/ logicalNot = expression as LogicalNot;
if (logicalNot != null) {
IExpression operand = logicalNot.Operand;
#region LogicalNot: !
LogicalNot/*?*/ operandAsLogicalNot = operand as LogicalNot;
if (operandAsLogicalNot != null) {
return Normalize(operandAsLogicalNot.Operand);
}
#endregion
#region BinaryOperations: ==, !=, <, <=, >, >=
BinaryOperation/*?*/ binOp = operand as BinaryOperation;
if (binOp != null) {
BinaryOperation/*?*/ result = null;
if (binOp is IEquality)
result = new NotEquality();
else if (binOp is INotEquality)
result = new Equality();
else if (binOp is ILessThan)
result = new GreaterThanOrEqual();
else if (binOp is ILessThanOrEqual)
result = new GreaterThan();
else if (binOp is IGreaterThan)
result = new LessThanOrEqual();
else if (binOp is IGreaterThanOrEqual)
result = new LessThan();
if (result != null) {
result.LeftOperand = Normalize(binOp.LeftOperand);
result.RightOperand = Normalize(binOp.RightOperand);
return result;
}
}
#endregion
#region Conditionals: &&, ||
Conditional/*?*/ conditional = operand as Conditional;
if (conditional != null) {
if (ExpressionHelper.IsIntegralNonzero(conditional.ResultIfTrue) ||
ExpressionHelper.IsIntegralZero(conditional.ResultIfFalse)) {
Conditional result = new Conditional();
LogicalNot not;
//invert condition
not = new LogicalNot();
not.Operand = conditional.Condition;
result.Condition = Normalize(not);
//invert false branch and switch with true branch
not = new LogicalNot();
not.Operand = conditional.ResultIfFalse;
result.ResultIfTrue = Normalize(not);
//invert true branch and switch with false branch
not = new LogicalNot();
not.Operand = conditional.ResultIfTrue;
result.ResultIfFalse = Normalize(not);
//return
result.Type = conditional.Type;
return result;
}
}
#endregion
#region Constants: true, false
CompileTimeConstant/*?*/ ctc = operand as CompileTimeConstant;
if (ctc != null) {
if (ExpressionHelper.IsIntegralNonzero(ctc)) { //Is true
var val = SetBooleanFalse(ctc);
if (val != null)
return val;
else
return expression;
} else if (ExpressionHelper.IsIntegralZero(ctc)) { //Is false
var val = SetBooleanTrue(ctc);
if (val != null)
return val;
else
return expression;
}
}
#endregion
}
return expression;
}
public static CompileTimeConstant/*?*/ SetBooleanFalse(ICompileTimeConstant constExpression) {
Contract.Requires(constExpression != null);
IConvertible/*?*/ ic = constExpression.Value as IConvertible;
if (ic == null) return null;
CompileTimeConstant result = new CompileTimeConstant(constExpression);
switch (ic.GetTypeCode()) {
case System.TypeCode.SByte: result.Value = (SByte)0; break;
case System.TypeCode.Int16: result.Value = (Int16)0; break;
case System.TypeCode.Int32: result.Value = (Int32)0; break;
case System.TypeCode.Int64: result.Value = (Int64)0; break;
case System.TypeCode.Byte: result.Value = (Byte)0; break;
case System.TypeCode.UInt16: result.Value = (UInt16)0; break;
case System.TypeCode.UInt32: result.Value = (UInt32)0; break;
case System.TypeCode.UInt64: result.Value = (UInt64)0; break;
default: return null;
}
return result;
}
public static CompileTimeConstant/*?*/ SetBooleanTrue(ICompileTimeConstant constExpression) {
Contract.Requires(constExpression != null);
IConvertible/*?*/ ic = constExpression.Value as IConvertible;
if (ic == null) return null;
CompileTimeConstant result = new CompileTimeConstant(constExpression);
switch (ic.GetTypeCode()) {
case System.TypeCode.SByte: result.Value = (SByte)1; break;
case System.TypeCode.Int16: result.Value = (Int16)1; break;
case System.TypeCode.Int32: result.Value = (Int32)1; break;
case System.TypeCode.Int64: result.Value = (Int64)1; break;
case System.TypeCode.Byte: result.Value = (Byte)1; break;
case System.TypeCode.UInt16: result.Value = (UInt16)1; break;
case System.TypeCode.UInt32: result.Value = (UInt32)1; break;
case System.TypeCode.UInt64: result.Value = (UInt64)1; break;
default: return null;
}
return result;
}
}
[ContractVerification(true)]
internal class ExpressionSimplifier : CodeRewriter {
public ExpressionSimplifier() : base(Dummy.CompilationHostEnvironment) { }
public override IExpression Rewrite(ILogicalNot logicalNot) {
var result = base.Rewrite(logicalNot);
return BooleanExpressionHelper.Normalize(result);
}
public override IExpression Rewrite(IConditional conditional) {
if (conditional.Type.TypeCode == PrimitiveTypeCode.Boolean && ExpressionHelper.IsIntegralZero(conditional.ResultIfTrue)) {
var not = new LogicalNot() { Operand = conditional.Condition, };
var c = new Conditional() {
Condition = BooleanExpressionHelper.Normalize(not),
ResultIfTrue = conditional.ResultIfFalse,
ResultIfFalse = new CompileTimeConstant() { Type = conditional.Type, Value = false, },
Type = conditional.Type,
};
return c;
}
return base.Rewrite(conditional);
}
public override IExpression Rewrite(IGreaterThan greaterThan)
{
// Catch use of the x > null idiom used by Roslyn as generated
// code for x != null statements.
if (ExpressionHelper.IsNullLiteral(greaterThan.RightOperand))
{
var c = new NotEquality
{
LeftOperand = greaterThan.LeftOperand,
RightOperand = greaterThan.RightOperand,
Type = greaterThan.Type
};
return c;
}
return base.Rewrite(greaterThan);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using LSL_Float = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLFloat;
using LSL_Integer = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLInteger;
using LSL_Key = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_List = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.list;
using LSL_Rotation = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Quaternion;
using LSL_String = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.LSLString;
using LSL_Vector = Aurora.ScriptEngine.AuroraDotNetEngine.LSL_Types.Vector3;
namespace Aurora.ScriptEngine.AuroraDotNetEngine.APIs.Interfaces
{
public interface ILSL_Api
{
void state(string newState);
LSL_Integer llAbs(int i);
LSL_Float llAcos(double val);
void llAddToLandBanList(string avatar, double hours);
void llAddToLandPassList(string avatar, double hours);
void llAdjustSoundVolume(double volume);
void llAllowInventoryDrop(int add);
LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b);
void llApplyImpulse(LSL_Vector force, int local);
void llApplyRotationalImpulse(LSL_Vector force, int local);
LSL_Float llAsin(double val);
LSL_Float llAtan2(double x, double y);
void llAttachToAvatar(int attachment);
LSL_Key llAvatarOnSitTarget();
LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up);
LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle);
LSL_Integer llBase64ToInteger(string str);
LSL_String llBase64ToString(string str);
void llBreakAllLinks();
void llBreakLink(int linknum);
LSL_Integer llCeil(double f);
void llClearCameraParams();
void llCloseRemoteDataChannel(object channel);
LSL_Float llCloud(LSL_Vector offset);
void llCollisionFilter(string name, string id, int accept);
void llCollisionSound(string impact_sound, double impact_volume);
void llCollisionSprite(string impact_sprite);
LSL_Float llCos(double f);
void llCreateLink(string target, int parent);
LSL_List llCSV2List(string src);
LSL_List llDeleteSubList(LSL_List src, int start, int end);
LSL_String llDeleteSubString(string src, int start, int end);
void llDetachFromAvatar();
LSL_Vector llDetectedGrab(int number);
LSL_Integer llDetectedGroup(int number);
LSL_Key llDetectedKey(int number);
LSL_Integer llDetectedLinkNumber(int number);
LSL_String llDetectedName(int number);
LSL_Key llDetectedOwner(int number);
LSL_Vector llDetectedPos(int number);
LSL_Rotation llDetectedRot(int number);
LSL_Integer llDetectedType(int number);
LSL_Vector llDetectedTouchBinormal(int index);
LSL_Integer llDetectedTouchFace(int index);
LSL_Vector llDetectedTouchNormal(int index);
LSL_Vector llDetectedTouchPos(int index);
LSL_Vector llDetectedTouchST(int index);
LSL_Vector llDetectedTouchUV(int index);
LSL_Vector llDetectedVel(int number);
void llDialog(string avatar, string message, LSL_List buttons, int chat_channel);
void llDie();
LSL_String llDumpList2String(LSL_List src, string seperator);
LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir);
void llEjectFromLand(string pest);
void llEmail(string address, string subject, string message);
LSL_String llEscapeURL(string url);
LSL_Rotation llEuler2Rot(LSL_Vector v);
LSL_Float llFabs(double f);
LSL_Integer llFloor(double f);
void llForceMouselook(int mouselook);
LSL_Float llFrand(double mag);
LSL_Vector llGetAccel();
LSL_Integer llGetAgentInfo(string id);
LSL_String llGetAgentLanguage(string id);
LSL_Vector llGetAgentSize(string id);
LSL_Float llGetAlpha(int face);
LSL_Float llGetAndResetTime();
LSL_String llGetAnimation(string id);
LSL_List llGetAnimationList(string id);
LSL_Integer llGetAttached();
LSL_List llGetBoundingBox(string obj);
LSL_Vector llGetCameraPos();
LSL_Rotation llGetCameraRot();
LSL_Vector llGetCenterOfMass();
LSL_Vector llGetColor(int face);
LSL_String llGetCreator();
LSL_String llGetDate();
LSL_Float llGetEnergy();
LSL_Vector llGetForce();
LSL_Integer llGetFreeMemory();
LSL_Integer llGetFreeURLs();
LSL_Vector llGetGeometricCenter();
LSL_Float llGetGMTclock();
LSL_String llGetHTTPHeader(LSL_Key request_id, string header);
LSL_Key llGetInventoryCreator(string item);
LSL_Key llGetInventoryKey(string name);
LSL_String llGetInventoryName(int type, int number);
LSL_Integer llGetInventoryNumber(int type);
LSL_Integer llGetInventoryPermMask(string item, int mask);
LSL_Integer llGetInventoryType(string name);
LSL_Key llGetKey();
LSL_Key llGetLandOwnerAt(LSL_Vector pos);
LSL_Key llGetLinkKey(int linknum);
LSL_String llGetLinkName(int linknum);
LSL_Integer llGetLinkNumber();
LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules);
LSL_Integer llGetListEntryType(LSL_List src, int index);
LSL_Integer llGetListLength(LSL_List src);
LSL_Vector llGetLocalPos();
LSL_Rotation llGetLocalRot();
LSL_Float llGetMass();
void llGetNextEmail(string address, string subject);
LSL_Key llGetNotecardLine(string name, int line);
LSL_Key llGetNumberOfNotecardLines(string name);
LSL_Integer llGetNumberOfPrims();
LSL_Integer llGetNumberOfSides();
LSL_String llGetObjectDesc();
LSL_List llGetObjectDetails(string id, LSL_List args);
LSL_Float llGetObjectMass(string id);
LSL_String llGetObjectName();
LSL_Integer llGetObjectPermMask(int mask);
LSL_Integer llGetObjectPrimCount(string object_id);
LSL_Vector llGetOmega();
LSL_Key llGetOwner();
LSL_Key llGetOwnerKey(string id);
LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param);
LSL_Integer llGetParcelFlags(LSL_Vector pos);
LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide);
LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide);
LSL_List llGetParcelPrimOwners(LSL_Vector pos);
LSL_Integer llGetPermissions();
LSL_Key llGetPermissionsKey();
LSL_Vector llGetPos();
LSL_List llGetPrimitiveParams(LSL_List rules);
LSL_Integer llGetRegionAgentCount();
LSL_Vector llGetRegionCorner();
LSL_Integer llGetRegionFlags();
LSL_Float llGetRegionFPS();
LSL_String llGetRegionName();
LSL_Float llGetRegionTimeDilation();
LSL_Vector llGetRootPosition();
LSL_Rotation llGetRootRotation();
LSL_Rotation llGetRot();
LSL_Vector llGetScale();
LSL_String llGetScriptName();
LSL_Integer llGetScriptState(string name);
LSL_String llGetSimulatorHostname();
LSL_Integer llGetStartParameter();
LSL_Integer llGetStatus(int status);
LSL_String llGetSubString(string src, int start, int end);
LSL_Vector llGetSunDirection();
LSL_String llGetTexture(int face);
LSL_Vector llGetTextureOffset(int face);
LSL_Float llGetTextureRot(int side);
LSL_Vector llGetTextureScale(int side);
LSL_Float llGetTime();
LSL_Float llGetTimeOfDay();
LSL_String llGetTimestamp();
LSL_Vector llGetTorque();
LSL_Integer llGetUnixTime();
LSL_Vector llGetVel();
LSL_Float llGetWallclock();
void llGiveInventory(string destination, string inventory);
void llGiveInventoryList(string destination, string category, LSL_List inventory);
LSL_Integer llGiveMoney(string destination, int amount);
void llGodLikeRezObject(string inventory, LSL_Vector pos);
LSL_Float llGround(LSL_Vector offset);
LSL_Vector llGroundContour(LSL_Vector offset);
LSL_Vector llGroundNormal(LSL_Vector offset);
void llGroundRepel(double height, int water, double tau);
LSL_Vector llGroundSlope(LSL_Vector offset);
LSL_String llHTTPRequest(string url, LSL_List parameters, string body);
void llHTTPResponse(LSL_Key id, int status, string body);
LSL_String llInsertString(string dst, int position, string src);
void llInstantMessage(string user, string message);
LSL_String llIntegerToBase64(int number);
LSL_String llKey2Name(string id);
void llLinkParticleSystem(int linknum, LSL_List rules);
LSL_String llList2CSV(LSL_List src);
LSL_Float llList2Float(LSL_List src, int index);
LSL_Integer llList2Integer(LSL_List src, int index);
LSL_Key llList2Key(LSL_List src, int index);
LSL_List llList2List(LSL_List src, int start, int end);
LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride);
LSL_Rotation llList2Rot(LSL_List src, int index);
LSL_String llList2String(LSL_List src, int index);
LSL_Vector llList2Vector(LSL_List src, int index);
LSL_Integer llListen(int channelID, string name, string ID, string msg);
void llListenControl(int number, int active);
void llListenRemove(int number);
LSL_Integer llListFindList(LSL_List src, LSL_List test);
LSL_List llListInsertList(LSL_List dest, LSL_List src, int start);
LSL_List llListRandomize(LSL_List src, int stride);
LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end);
LSL_List llListSort(LSL_List src, int stride, int ascending);
LSL_Float llListStatistics(int operation, LSL_List src);
void llLoadURL(string avatar_id, string message, string url);
LSL_Float llLog(double val);
LSL_Float llLog10(double val);
void llLookAt(LSL_Vector target, double strength, double damping);
void llLoopSound(string sound, double volume);
void llLoopSoundMaster(string sound, double volume);
void llLoopSoundSlave(string sound, double volume);
void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset);
void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at);
LSL_String llMD5String(string src, int nonce);
LSL_String llSHA1String(string src);
void llMessageLinked(int linknum, int num, string str, string id);
void llMinEventDelay(double delay);
void llModifyLand(int action, int brush);
LSL_Integer llModPow(int a, int b, int c);
void llMoveToTarget(LSL_Vector target, double tau);
void llOffsetTexture(double u, double v, int face);
void llOpenRemoteDataChannel();
LSL_Integer llOverMyLand(string id);
void llOwnerSay(string msg);
void llParcelMediaCommandList(LSL_List commandList);
LSL_List llParcelMediaQuery(LSL_List aList);
LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers);
LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers);
void llParticleSystem(LSL_List rules);
void llPassCollisions(int pass);
void llPassTouches(int pass);
void llPlaySound(string sound, double volume);
void llPlaySoundSlave(string sound, double volume);
void llPointAt(LSL_Vector pos);
LSL_Float llPow(double fbase, double fexponent);
void llPreloadSound(string sound);
void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local);
void llRefreshPrimURL();
void llRegionSay(int channelID, string text);
void llReleaseCamera(string avatar);
void llReleaseControls();
void llReleaseURL(string url);
void llRemoteDataReply(string channel, string message_id, string sdata, int idata);
void llRemoteDataSetRegion();
void llRemoteLoadScript(string target, string name, int running, int start_param);
void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param);
void llRemoveFromLandBanList(string avatar);
void llRemoveFromLandPassList(string avatar);
void llRemoveInventory(string item);
void llRemoveVehicleFlags(int flags);
LSL_String llRequestAgentData(string id, int data);
LSL_Key llRequestInventoryData(string name);
void llRequestPermissions(string agent, int perm);
LSL_String llRequestSecureURL();
LSL_Key llRequestSimulatorData(string simulator, int data);
LSL_Key llRequestURL();
void llResetLandBanList();
void llResetLandPassList();
void llResetOtherScript(string name);
void llResetScript();
void llResetTime();
void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param);
void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param);
LSL_Float llRot2Angle(LSL_Rotation rot);
LSL_Vector llRot2Axis(LSL_Rotation rot);
LSL_Vector llRot2Euler(LSL_Rotation r);
LSL_Vector llRot2Fwd(LSL_Rotation r);
LSL_Vector llRot2Left(LSL_Rotation r);
LSL_Vector llRot2Up(LSL_Rotation r);
void llRotateTexture(double rotation, int face);
LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end);
void llRotLookAt(LSL_Rotation target, double strength, double damping);
LSL_Integer llRotTarget(LSL_Rotation rot, double error);
void llRotTargetRemove(int number);
LSL_Integer llRound(double f);
LSL_Integer llSameGroup(string agent);
void llSay(int channelID, object text);
void llScaleTexture(double u, double v, int face);
LSL_Integer llScriptDanger(LSL_Vector pos);
LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata);
void llSensor(string name, string id, int type, double range, double arc);
void llSensorRemove();
void llSensorRepeat(string name, string id, int type, double range, double arc, double rate);
void llSetAlpha(double alpha, int face);
void llSetBuoyancy(double buoyancy);
void llSetCameraAtOffset(LSL_Vector offset);
void llSetCameraEyeOffset(LSL_Vector offset);
void llSetCameraParams(LSL_List rules);
void llSetClickAction(int action);
void llSetColor(LSL_Vector color, int face);
void llSetDamage(double damage);
void llSetForce(LSL_Vector force, int local);
void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local);
void llSetHoverHeight(double height, int water, double tau);
void llSetInventoryPermMask(string item, int mask, int value);
void llSetLinkAlpha(int linknumber, double alpha, int face);
void llSetLinkColor(int linknumber, LSL_Vector color, int face);
void llSetLinkPrimitiveParams(int linknumber, LSL_List rules);
void llSetLinkTexture(int linknumber, string texture, int face);
void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetLocalRot(LSL_Rotation rot);
void llSetObjectDesc(string desc);
void llSetObjectName(string name);
void llSetObjectPermMask(int mask, int value);
void llSetParcelMusicURL(string url);
void llSetPayPrice(int price, LSL_List quick_pay_buttons);
void llSetPos(LSL_Vector pos);
void llSetPrimitiveParams(LSL_List rules);
void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules);
void llSetPrimURL(string url);
void llSetRemoteScriptAccessPin(int pin);
void llSetRot(LSL_Rotation rot);
void llSetScale(LSL_Vector scale);
void llSetScriptState(string name, int run);
void llSetSitText(string text);
void llSetSoundQueueing(int queue);
void llSetSoundRadius(double radius);
void llSetStatus(int status, int value);
void llSetText(string text, LSL_Vector color, LSL_Float alpha);
void llSetTexture(string texture, int face);
void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetTimerEvent(double sec);
void llSetTorque(LSL_Vector torque, int local);
void llSetTouchText(string text);
void llSetVehicleFlags(int flags);
void llSetVehicleFloatParam(int param, LSL_Float value);
void llSetVehicleRotationParam(int param, LSL_Rotation rot);
void llSetVehicleType(int type);
void llSetVehicleVectorParam(int param, LSL_Vector vec);
void llShout(int channelID, string text);
LSL_Float llSin(double f);
void llSitTarget(LSL_Vector offset, LSL_Rotation rot);
void llSleep(double sec);
void llSound(string sound, double volume, int queue, int loop);
void llSoundPreload(string sound);
LSL_Float llSqrt(double f);
void llStartAnimation(string anim);
void llStopAnimation(string anim);
void llStopHover();
void llStopLookAt();
void llStopMoveToTarget();
void llStopPointAt();
void llStopSound();
LSL_Integer llStringLength(string str);
LSL_String llStringToBase64(string str);
LSL_String llStringTrim(string src, int type);
LSL_Integer llSubStringIndex(string source, string pattern);
void llTakeCamera(string avatar);
void llTakeControls(int controls, int accept, int pass_on);
LSL_Float llTan(double f);
LSL_Integer llTarget(LSL_Vector position, double range);
void llTargetOmega(LSL_Vector axis, double spinrate, double gain);
void llTargetRemove(int number);
void llTeleportAgentHome(LSL_Key agent);
void llTextBox(string avatar, string message, int chat_channel);
LSL_String llToLower(string source);
LSL_String llToUpper(string source);
void llTriggerSound(string sound, double volume);
void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west);
LSL_String llUnescapeURL(string url);
void llUnSit(string id);
LSL_Float llVecDist(LSL_Vector a, LSL_Vector b);
LSL_Float llVecMag(LSL_Vector v);
LSL_Vector llVecNorm(LSL_Vector v);
void llVolumeDetect(int detect);
LSL_Float llWater(LSL_Vector offset);
void llWhisper(int channelID, string text);
LSL_Vector llWind(LSL_Vector offset);
LSL_String llXorBase64Strings(string str1, string str2);
LSL_String llXorBase64StringsCorrect(string str1, string str2);
void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
LSL_List GetLinkPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
LSL_Integer llSetPrimMediaParams(LSL_Integer face, LSL_List commandList);
LSL_Integer llClearPrimMedia(LSL_Integer face);
LSL_List llGetPrimMediaParams(LSL_Integer face, LSL_List aList);
LSL_Integer llGetLinkNumberOfSides(int LinkNum);
void llRezPrim(string inventory, LSL_Types.Vector3 pos, LSL_Types.Vector3 vel, LSL_Types.Quaternion rot, int param, bool isRezAtRoot, bool doRecoil, bool SetDieAtEdge, bool CheckPos);
void print(string str);
LSL_String llGetDisplayName(string id);
LSL_String llGetUsername(string id);
LSL_String llGetEnv(LSL_String name);
LSL_Key llRequestDisplayName(LSL_Key uuid);
LSL_Key llRequestUsername(LSL_Key uuid);
LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options);
}
}
| |
// 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.Globalization;
using Xunit;
namespace System.Globalization.CalendarTests
{
// GregorianCalendar.IsLeapMonth(Int32, Int32, Int32, Int32)
public class GregorianCalendarIsLeapMonth
{
private const int c_DAYS_IN_LEAP_YEAR = 366;
private const int c_DAYS_IN_COMMON_YEAR = 365;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
#region Positive tests
// PosTest1: February in leap year
[Fact]
public void PosTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
bool expectedValue;
bool actualValue;
year = GetALeapYear(myCalendar);
month = 2;
expectedValue = false;
actualValue = myCalendar.IsLeapMonth(year, month, 1);
Assert.Equal(expectedValue, actualValue);
}
// PosTest2: february in common year
[Fact]
public void PosTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
bool expectedValue;
bool actualValue;
year = GetACommonYear(myCalendar);
month = 2;
expectedValue = false;
actualValue = myCalendar.IsLeapMonth(year, month, 1);
Assert.Equal(expectedValue, actualValue);
}
// PosTest3: any month, any year
[Fact]
public void PosTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
bool expectedValue;
bool actualValue;
year = GetAYear(myCalendar);
month = _generator.GetInt32(-55) % 12 + 1;
expectedValue = false;
actualValue = myCalendar.IsLeapMonth(year, month, 1);
Assert.Equal(expectedValue, actualValue);
}
// PosTest4: any month in maximum supported year
[Fact]
public void PosTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
bool expectedValue;
bool actualValue;
year = myCalendar.MaxSupportedDateTime.Year;
month = _generator.GetInt32(-55) % 12 + 1;
expectedValue = false;
actualValue = myCalendar.IsLeapMonth(year, month, 1);
Assert.Equal(expectedValue, actualValue);
}
// PosTest5: any month in minimum supported year
[Fact]
public void PosTest5()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
bool expectedValue;
bool actualValue;
year = myCalendar.MinSupportedDateTime.Year;
month = _generator.GetInt32(-55) % 12 + 1;
expectedValue = false;
actualValue = myCalendar.IsLeapMonth(year, month, 1);
Assert.Equal(expectedValue, actualValue);
}
#endregion
#region Negative Tests
// NegTest1: year is greater than maximum supported value
[Fact]
public void NegTest1()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
year = myCalendar.MaxSupportedDateTime.Year + 100;
month = _generator.GetInt32(-55) % 12 + 1;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.IsLeapMonth(year, month, 1);
});
}
// NegTest2: year is less than minimum supported value
[Fact]
public void NegTest2()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
year = myCalendar.MinSupportedDateTime.Year - 100;
month = _generator.GetInt32(-55) % 12 + 1;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.IsLeapMonth(year, month, 1);
});
}
// NegTest3: era is outside the range supported by the calendar
[Fact]
public void NegTest3()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int era;
year = this.GetAYear(myCalendar);
month = _generator.GetInt32(-55) % 12 + 1;
era = 2 + _generator.GetInt32(-55) % (int.MaxValue - 1);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.IsLeapMonth(year, month, era);
});
}
// NegTest4: month is less than the minimum value supported by the calendar
[Fact]
public void NegTest4()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int era;
year = this.GetAYear(myCalendar);
month = -1 * _generator.GetInt32(-55);
era = _generator.GetInt32(-55) & 1;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.IsLeapMonth(year, month, era);
});
}
// NegTest5: month is greater than the maximum value supported by the calendar
[Fact]
public void NegTest5()
{
System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
int year, month;
int era;
year = this.GetAYear(myCalendar);
month = 13 + _generator.GetInt32(-55) % (int.MaxValue - 12);
era = _generator.GetInt32(-55) & 1;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
myCalendar.IsLeapMonth(year, month, era);
});
}
#endregion
#region Helper methods for all the tests
//Get a random year beween minmum supported year and maximum supported year of the specified calendar
private int GetAYear(Calendar calendar)
{
int retVal;
int maxYear, minYear;
maxYear = calendar.MaxSupportedDateTime.Year;
minYear = calendar.MinSupportedDateTime.Year;
retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear);
return retVal;
}
//Get a leap year of the specified calendar
private int GetALeapYear(Calendar calendar)
{
int retVal;
// A leap year is any year divisible by 4 except for centennial years(those ending in 00)
// which are only leap years if they are divisible by 400.
retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0
retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400
// if retVal was 100, 200, or 300 the above logic will result in 0
if (0 == retVal)
{
retVal = 400;
}
return retVal;
}
//Get a common year of the specified calendar
private int GetACommonYear(Calendar calendar)
{
int retVal;
do
{
retVal = GetAYear(calendar);
}
while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400);
return retVal;
}
//Get text represntation of the input parmeters
private string GetParamsInfo(int year, int month)
{
string str;
str = string.Format("\nThe specified date is {0:04}-{1:02} (yyyy-mm).", year, month);
return str;
}
#endregion
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Using directives
#define USE_TRACING
using System;
using System.Xml;
using System.Globalization;
using System.ComponentModel;
using System.Runtime.InteropServices;
#endregion
//////////////////////////////////////////////////////////////////////
// <summary>Handles atom:person element.</summary>
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
//////////////////////////////////////////////////////////////////////
/// <summary>TypeConverter, so that AtomHead shows up in the property pages
/// </summary>
//////////////////////////////////////////////////////////////////////
[ComVisible(false)]
public class AtomPersonConverter : ExpandableObjectConverter
{
///<summary>Standard type converter method</summary>
public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType)
{
if (destinationType == typeof(AtomPerson))
return true;
return base.CanConvertTo(context, destinationType);
}
///<summary>Standard type converter method</summary>
public override object ConvertTo(ITypeDescriptorContext context,CultureInfo culture, object value, System.Type destinationType)
{
AtomPerson person = value as AtomPerson;
if (destinationType == typeof(System.String) && person != null)
{
return "Person: " + person.Name;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>enum to describe the different person types
/// </summary>
//////////////////////////////////////////////////////////////////////
public enum AtomPersonType
{
/// <summary>is an author</summary>
Author,
/// <summary>is an contributor</summary>
Contributor, ///
/// <summary>parsing error</summary>
Unknown
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>generic Person object, used for the feed and for the entry
/// </summary>
//////////////////////////////////////////////////////////////////////
[TypeConverterAttribute(typeof(AtomPersonConverter)), DescriptionAttribute("Expand to see the person object for the feed/entry.")]
public class AtomPerson : AtomBase
{
/// <summary>name holds the Name property as a string</summary>
private string name;
/// <summary>email holds the email property as a string</summary>
private string email;
/// <summary>link holds an Uri, representing the link atribute</summary>
private AtomUri uri;
/// <summary>holds the type for persistence</summary>
private AtomPersonType type;
/// <summary>public default constructor, usefull only for property pages</summary>
public AtomPerson()
{
this.type = AtomPersonType.Author;
}
//////////////////////////////////////////////////////////////////////
/// <summary>Constructor taking a type to indicate whether person is author or contributor.</summary>
/// <param name="type">indicates if author or contributor</param>
//////////////////////////////////////////////////////////////////////
public AtomPerson(AtomPersonType type)
{
this.type = type;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Constructor taking a type to indicate whether person is author or contributor, plus the person's name</summary>
/// <param name="type">indicates if author or contributor</param>
/// <param name="name">person's name</param>
//////////////////////////////////////////////////////////////////////
public AtomPerson(AtomPersonType type, string name) : this(type)
{
this.name = name;
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Name</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Name
{
get {return this.name;}
set {this.Dirty =true; this.name = value;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public Uri Uri</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomUri Uri
{
get
{
if (this.uri == null)
{
this.uri = new AtomUri("");
}
return this.uri;
}
set {this.Dirty = true; this.uri = value;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public Uri Email</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Email
{
get {return this.email;}
set {this.Dirty = true; this.email = value;}
}
/////////////////////////////////////////////////////////////////////////////
#region Persistence overloads
//////////////////////////////////////////////////////////////////////
/// <summary>Just returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public override string XmlName
{
get { return this.type == AtomPersonType.Author ? AtomParserNameTable.XmlAuthorElement : AtomParserNameTable.XmlContributorElement; }
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>saves the inner state of the element</summary>
/// <param name="writer">the xmlWriter to save into </param>
//////////////////////////////////////////////////////////////////////
protected override void SaveInnerXml(XmlWriter writer)
{
base.SaveInnerXml(writer);
// now save our state...
WriteEncodedElementString(writer, BaseNameTable.XmlName, this.Name);
WriteEncodedElementString(writer, AtomParserNameTable.XmlEmailElement, this.Email);
WriteEncodedElementString(writer, AtomParserNameTable.XmlUriElement, this.Uri);
}
//////////////////////////////////////////////////////////////////////
/// <summary>figures out if this object should be persisted</summary>
/// <returns> true, if it's worth saving</returns>
//////////////////////////////////////////////////////////////////////
public override bool ShouldBePersisted()
{
if (!base.ShouldBePersisted())
{
if (Utilities.IsPersistable(this.name))
{
return true;
}
if (Utilities.IsPersistable(this.email))
{
return true;
}
if (Utilities.IsPersistable(this.uri))
{
return true;
}
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#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.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Runtime.Assemblies;
using Internal.LowLevelLinq;
using Internal.Reflection.Core;
using Internal.Runtime.Augments;
using Internal.Metadata.NativeFormat;
using NativeFormatAssemblyFlags = global::Internal.Metadata.NativeFormat.AssemblyFlags;
namespace System.Reflection.Runtime.General
{
//
// Collect various metadata reading tasks for better chunking...
//
internal static class NativeFormatMetadataReaderExtensions
{
public static bool StringOrNullEquals(this ConstantStringValueHandle handle, String valueOrNull, MetadataReader reader)
{
if (valueOrNull == null)
return handle.IsNull(reader);
if (handle.IsNull(reader))
return false;
return handle.StringEquals(valueOrNull, reader);
}
// Needed for RuntimeMappingTable access
public static int AsInt(this TypeDefinitionHandle typeDefinitionHandle)
{
unsafe
{
return *(int*)&typeDefinitionHandle;
}
}
public static TypeDefinitionHandle AsTypeDefinitionHandle(this int i)
{
unsafe
{
return *(TypeDefinitionHandle*)&i;
}
}
public static int AsInt(this MethodHandle methodHandle)
{
unsafe
{
return *(int*)&methodHandle;
}
}
public static MethodHandle AsMethodHandle(this int i)
{
unsafe
{
return *(MethodHandle*)&i;
}
}
public static int AsInt(this FieldHandle fieldHandle)
{
unsafe
{
return *(int*)&fieldHandle;
}
}
public static FieldHandle AsFieldHandle(this int i)
{
unsafe
{
return *(FieldHandle*)&i;
}
}
public static bool IsNamespaceDefinitionHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceDefinition;
}
public static bool IsNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
return handleType == HandleType.NamespaceReference;
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static ScopeReferenceHandle ToExpectedScopeReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToScopeReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static NamespaceReferenceHandle ToExpectedNamespaceReferenceHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToNamespaceReferenceHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller.
public static TypeDefinitionHandle ToExpectedTypeDefinitionHandle(this Handle handle, MetadataReader reader)
{
try
{
return handle.ToTypeDefinitionHandle(reader);
}
catch (ArgumentException)
{
throw new BadImageFormatException();
}
}
// Return any custom modifiers modifying the passed-in type and whose required/optional bit matches the passed in boolean.
// Because this is intended to service the GetCustomModifiers() apis, this helper will always return a freshly allocated array
// safe for returning to api callers.
public static Type[] GetCustomModifiers(this Handle handle, MetadataReader reader, TypeContext typeContext, bool optional)
{
HandleType handleType = handle.HandleType;
Debug.Assert(handleType == HandleType.TypeDefinition || handleType == HandleType.TypeReference || handleType == HandleType.TypeSpecification || handleType == HandleType.ModifiedType);
if (handleType != HandleType.ModifiedType)
return Array.Empty<Type>();
LowLevelList<Type> customModifiers = new LowLevelList<Type>();
do
{
ModifiedType modifiedType = handle.ToModifiedTypeHandle(reader).GetModifiedType(reader);
if (optional == modifiedType.IsOptional)
{
Type customModifier = modifiedType.ModifierType.Resolve(reader, typeContext);
customModifiers.Insert(0, customModifier);
}
handle = modifiedType.Type;
handleType = handle.HandleType;
}
while (handleType == HandleType.ModifiedType);
return customModifiers.ToArray();
}
public static Handle SkipCustomModifiers(this Handle handle, MetadataReader reader)
{
HandleType handleType = handle.HandleType;
Debug.Assert(handleType == HandleType.TypeDefinition || handleType == HandleType.TypeReference || handleType == HandleType.TypeSpecification || handleType == HandleType.ModifiedType);
if (handleType != HandleType.ModifiedType)
return handle;
do
{
ModifiedType modifiedType = handle.ToModifiedTypeHandle(reader).GetModifiedType(reader);
handle = modifiedType.Type;
handleType = handle.HandleType;
}
while (handleType == HandleType.ModifiedType);
return handle;
}
public static MethodSignature ParseMethodSignature(this Handle handle, MetadataReader reader)
{
return handle.ToMethodSignatureHandle(reader).GetMethodSignature(reader);
}
public static FieldSignature ParseFieldSignature(this Handle handle, MetadataReader reader)
{
return handle.ToFieldSignatureHandle(reader).GetFieldSignature(reader);
}
public static PropertySignature ParsePropertySignature(this Handle handle, MetadataReader reader)
{
return handle.ToPropertySignatureHandle(reader).GetPropertySignature(reader);
}
//
// Used to split methods between DeclaredMethods and DeclaredConstructors.
//
public static bool IsConstructor(this MethodHandle methodHandle, MetadataReader reader)
{
Method method = methodHandle.GetMethod(reader);
return IsConstructor(ref method, reader);
}
// This is specially designed for a hot path so we make some compromises in the signature:
//
// - "method" is passed by reference even though no side-effects are intended.
//
public static bool IsConstructor(ref Method method, MetadataReader reader)
{
if ((method.Flags & (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName)) != (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName))
return false;
ConstantStringValueHandle nameHandle = method.Name;
return nameHandle.StringEquals(ConstructorInfo.ConstructorName, reader) || nameHandle.StringEquals(ConstructorInfo.TypeConstructorName, reader);
}
private static Exception ParseBoxedEnumConstantValue(this ConstantBoxedEnumValueHandle handle, MetadataReader reader, out Object value)
{
ConstantBoxedEnumValue record = handle.GetConstantBoxedEnumValue(reader);
Exception exception = null;
Type enumType = record.Type.TryResolve(reader, new TypeContext(null, null), ref exception);
if (enumType == null)
{
value = null;
return exception;
}
if (!enumType.IsEnum)
throw new BadImageFormatException();
Type underlyingType = Enum.GetUnderlyingType(enumType);
// Now box the value as the specified enum type.
unsafe
{
switch (record.Value.HandleType)
{
case HandleType.ConstantByteValue:
{
if (underlyingType != CommonRuntimeTypes.Byte)
throw new BadImageFormatException();
byte v = record.Value.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantSByteValue:
{
if (underlyingType != CommonRuntimeTypes.SByte)
throw new BadImageFormatException();
sbyte v = record.Value.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt16Value:
{
if (underlyingType != CommonRuntimeTypes.Int16)
throw new BadImageFormatException();
short v = record.Value.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt16Value:
{
if (underlyingType != CommonRuntimeTypes.UInt16)
throw new BadImageFormatException();
ushort v = record.Value.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt32Value:
{
if (underlyingType != CommonRuntimeTypes.Int32)
throw new BadImageFormatException();
int v = record.Value.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt32Value:
{
if (underlyingType != CommonRuntimeTypes.UInt32)
throw new BadImageFormatException();
uint v = record.Value.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantInt64Value:
{
if (underlyingType != CommonRuntimeTypes.Int64)
throw new BadImageFormatException();
long v = record.Value.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
case HandleType.ConstantUInt64Value:
{
if (underlyingType != CommonRuntimeTypes.UInt64)
throw new BadImageFormatException();
ulong v = record.Value.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v));
return null;
}
default:
throw new BadImageFormatException();
}
}
}
public static Object ParseConstantValue(this Handle handle, MetadataReader reader)
{
Object value;
Exception exception = handle.TryParseConstantValue(reader, out value);
if (exception != null)
throw exception;
return value;
}
public static Exception TryParseConstantValue(this Handle handle, MetadataReader reader, out Object value)
{
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanValue:
value = handle.ToConstantBooleanValueHandle(reader).GetConstantBooleanValue(reader).Value;
return null;
case HandleType.ConstantStringValue:
value = handle.ToConstantStringValueHandle(reader).GetConstantStringValue(reader).Value;
return null;
case HandleType.ConstantCharValue:
value = handle.ToConstantCharValueHandle(reader).GetConstantCharValue(reader).Value;
return null;
case HandleType.ConstantByteValue:
value = handle.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value;
return null;
case HandleType.ConstantSByteValue:
value = handle.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value;
return null;
case HandleType.ConstantInt16Value:
value = handle.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value;
return null;
case HandleType.ConstantUInt16Value:
value = handle.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value;
return null;
case HandleType.ConstantInt32Value:
value = handle.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value;
return null;
case HandleType.ConstantUInt32Value:
value = handle.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value;
return null;
case HandleType.ConstantInt64Value:
value = handle.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value;
return null;
case HandleType.ConstantUInt64Value:
value = handle.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value;
return null;
case HandleType.ConstantSingleValue:
value = handle.ToConstantSingleValueHandle(reader).GetConstantSingleValue(reader).Value;
return null;
case HandleType.ConstantDoubleValue:
value = handle.ToConstantDoubleValueHandle(reader).GetConstantDoubleValue(reader).Value;
return null;
case HandleType.TypeDefinition:
case HandleType.TypeReference:
case HandleType.TypeSpecification:
{
Exception exception = null;
Type type = handle.TryResolve(reader, new TypeContext(null, null), ref exception);
value = type;
return (value == null) ? exception : null;
}
case HandleType.ConstantReferenceValue:
value = null;
return null;
case HandleType.ConstantBoxedEnumValue:
{
return handle.ToConstantBoxedEnumValueHandle(reader).ParseBoxedEnumConstantValue(reader, out value);
}
default:
{
Exception exception;
value = handle.TryParseConstantArray(reader, out exception);
if (value == null)
return exception;
return null;
}
}
}
private static Array TryParseConstantArray(this Handle handle, MetadataReader reader, out Exception exception)
{
exception = null;
HandleType handleType = handle.HandleType;
switch (handleType)
{
case HandleType.ConstantBooleanArray:
return handle.ToConstantBooleanArrayHandle(reader).GetConstantBooleanArray(reader).Value.ToArray();
case HandleType.ConstantCharArray:
return handle.ToConstantCharArrayHandle(reader).GetConstantCharArray(reader).Value.ToArray();
case HandleType.ConstantByteArray:
return handle.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value.ToArray();
case HandleType.ConstantSByteArray:
return handle.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value.ToArray();
case HandleType.ConstantInt16Array:
return handle.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value.ToArray();
case HandleType.ConstantUInt16Array:
return handle.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value.ToArray();
case HandleType.ConstantInt32Array:
return handle.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value.ToArray();
case HandleType.ConstantUInt32Array:
return handle.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value.ToArray();
case HandleType.ConstantInt64Array:
return handle.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value.ToArray();
case HandleType.ConstantUInt64Array:
return handle.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value.ToArray();
case HandleType.ConstantSingleArray:
return handle.ToConstantSingleArrayHandle(reader).GetConstantSingleArray(reader).Value.ToArray();
case HandleType.ConstantDoubleArray:
return handle.ToConstantDoubleArrayHandle(reader).GetConstantDoubleArray(reader).Value.ToArray();
case HandleType.ConstantEnumArray:
return TryParseConstantEnumArray(handle.ToConstantEnumArrayHandle(reader), reader, out exception);
case HandleType.ConstantStringArray:
{
HandleCollection constantHandles = handle.ToConstantStringArrayHandle(reader).GetConstantStringArray(reader).Value;
string[] elements = new string[constantHandles.Count];
int i = 0;
foreach (Handle constantHandle in constantHandles)
{
object elementValue;
exception = constantHandle.TryParseConstantValue(reader, out elementValue);
if (exception != null)
return null;
elements[i] = (string)elementValue;
i++;
}
return elements;
}
case HandleType.ConstantHandleArray:
{
HandleCollection constantHandles = handle.ToConstantHandleArrayHandle(reader).GetConstantHandleArray(reader).Value;
object[] elements = new object[constantHandles.Count];
int i = 0;
foreach (Handle constantHandle in constantHandles)
{
exception = constantHandle.TryParseConstantValue(reader, out elements[i]);
if (exception != null)
return null;
i++;
}
return elements;
}
default:
throw new BadImageFormatException();
}
}
private static Array TryParseConstantEnumArray(this ConstantEnumArrayHandle handle, MetadataReader reader, out Exception exception)
{
exception = null;
ConstantEnumArray enumArray = handle.GetConstantEnumArray(reader);
Type elementType = enumArray.ElementType.TryResolve(reader, new TypeContext(null, null), ref exception);
if (exception != null)
return null;
switch (enumArray.Value.HandleType)
{
case HandleType.ConstantByteArray:
return enumArray.Value.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value.ToArray(elementType);
case HandleType.ConstantSByteArray:
return enumArray.Value.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value.ToArray(elementType);
case HandleType.ConstantInt16Array:
return enumArray.Value.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value.ToArray(elementType);
case HandleType.ConstantUInt16Array:
return enumArray.Value.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value.ToArray(elementType);
case HandleType.ConstantInt32Array:
return enumArray.Value.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value.ToArray(elementType);
case HandleType.ConstantUInt32Array:
return enumArray.Value.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value.ToArray(elementType);
case HandleType.ConstantInt64Array:
return enumArray.Value.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value.ToArray(elementType);
case HandleType.ConstantUInt64Array:
return enumArray.Value.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value.ToArray(elementType);
default:
throw new BadImageFormatException();
}
}
public static Handle GetAttributeTypeHandle(this CustomAttribute customAttribute,
MetadataReader reader)
{
HandleType constructorHandleType = customAttribute.Constructor.HandleType;
if (constructorHandleType == HandleType.QualifiedMethod)
return customAttribute.Constructor.ToQualifiedMethodHandle(reader).GetQualifiedMethod(reader).EnclosingType;
else if (constructorHandleType == HandleType.MemberReference)
return customAttribute.Constructor.ToMemberReferenceHandle(reader).GetMemberReference(reader).Parent;
else
throw new BadImageFormatException();
}
//
// Lightweight check to see if a custom attribute's is of a well-known type.
//
// This check performs without instantating the Type object and bloating memory usage. On the flip side,
// it doesn't check on whether the type is defined in a paricular assembly. The desktop CLR typically doesn't
// check this either so this is useful from a compat perspective as well.
//
public static bool IsCustomAttributeOfType(this CustomAttributeHandle customAttributeHandle,
MetadataReader reader,
String ns,
String name)
{
String[] namespaceParts = ns.Split('.');
Handle typeHandle = customAttributeHandle.GetCustomAttribute(reader).GetAttributeTypeHandle(reader);
HandleType handleType = typeHandle.HandleType;
if (handleType == HandleType.TypeDefinition)
{
TypeDefinition typeDefinition = typeHandle.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader);
if (!typeDefinition.Name.StringEquals(name, reader))
return false;
NamespaceDefinitionHandle nsHandle = typeDefinition.NamespaceDefinition;
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceDefinition namespaceDefinition = nsHandle.GetNamespaceDefinition(reader);
if (!namespaceDefinition.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceDefinition.ParentScopeOrNamespace.IsNamespaceDefinitionHandle(reader))
return false;
nsHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader);
}
if (!nsHandle.GetNamespaceDefinition(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else if (handleType == HandleType.TypeReference)
{
TypeReference typeReference = typeHandle.ToTypeReferenceHandle(reader).GetTypeReference(reader);
if (!typeReference.TypeName.StringEquals(name, reader))
return false;
if (!typeReference.ParentNamespaceOrType.IsNamespaceReferenceHandle(reader))
return false;
NamespaceReferenceHandle nsHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(reader);
int idx = namespaceParts.Length;
while (idx-- != 0)
{
String namespacePart = namespaceParts[idx];
NamespaceReference namespaceReference = nsHandle.GetNamespaceReference(reader);
if (!namespaceReference.Name.StringOrNullEquals(namespacePart, reader))
return false;
if (!namespaceReference.ParentScopeOrNamespace.IsNamespaceReferenceHandle(reader))
return false;
nsHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader);
}
if (!nsHandle.GetNamespaceReference(reader).Name.StringOrNullEquals(null, reader))
return false;
return true;
}
else
throw new NotSupportedException();
}
public static String ToNamespaceName(this NamespaceDefinitionHandle namespaceDefinitionHandle, MetadataReader reader)
{
String ns = "";
for (;;)
{
NamespaceDefinition currentNamespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(reader);
String name = currentNamespaceDefinition.Name.GetStringOrNull(reader);
if (name != null)
{
if (ns.Length != 0)
ns = "." + ns;
ns = name + ns;
}
Handle nextHandle = currentNamespaceDefinition.ParentScopeOrNamespace;
HandleType handleType = nextHandle.HandleType;
if (handleType == HandleType.ScopeDefinition)
break;
if (handleType == HandleType.NamespaceDefinition)
{
namespaceDefinitionHandle = nextHandle.ToNamespaceDefinitionHandle(reader);
continue;
}
throw new BadImageFormatException(SR.Bif_InvalidMetadata);
}
return ns;
}
public static IEnumerable<NamespaceDefinitionHandle> GetTransitiveNamespaces(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
yield return namespaceHandle;
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (NamespaceDefinitionHandle childNamespaceHandle in GetTransitiveNamespaces(reader, namespaceDefinition.NamespaceDefinitions.AsEnumerable()))
yield return childNamespaceHandle;
}
}
public static IEnumerable<TypeDefinitionHandle> GetTopLevelTypes(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles)
{
foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles)
{
NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader);
foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions)
{
yield return typeDefinitionHandle;
}
}
}
public static IEnumerable<TypeDefinitionHandle> GetTransitiveTypes(this MetadataReader reader, IEnumerable<TypeDefinitionHandle> typeDefinitionHandles, bool publicOnly)
{
foreach (TypeDefinitionHandle typeDefinitionHandle in typeDefinitionHandles)
{
TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader);
if (publicOnly)
{
TypeAttributes visibility = typeDefinition.Flags & TypeAttributes.VisibilityMask;
if (visibility != TypeAttributes.Public && visibility != TypeAttributes.NestedPublic)
continue;
}
yield return typeDefinitionHandle;
foreach (TypeDefinitionHandle nestedTypeDefinitionHandle in GetTransitiveTypes(reader, typeDefinition.NestedTypes.AsEnumerable(), publicOnly))
yield return nestedTypeDefinitionHandle;
}
}
/// <summary>
/// Reverse len characters in a StringBuilder starting at offset index
/// </summary>
private static void ReverseStringInStringBuilder(StringBuilder builder, int index, int len)
{
int back = index + len - 1;
int front = index;
while (front < back)
{
char temp = builder[front];
builder[front] = builder[back];
builder[back] = temp;
front++;
back--;
}
}
public static string ToFullyQualifiedTypeName(this NamespaceReferenceHandle namespaceReferenceHandle, string typeName, MetadataReader reader)
{
StringBuilder fullName = new StringBuilder(64);
NamespaceReference namespaceReference;
for (;;)
{
namespaceReference = namespaceReferenceHandle.GetNamespaceReference(reader);
String namespacePart = namespaceReference.Name.GetStringOrNull(reader);
if (namespacePart == null)
break;
fullName.Append('.');
int index = fullName.Length;
fullName.Append(namespacePart);
ReverseStringInStringBuilder(fullName, index, namespacePart.Length);
namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToExpectedNamespaceReferenceHandle(reader);
}
ReverseStringInStringBuilder(fullName, 0, fullName.Length);
fullName.Append(typeName);
return fullName.ToString();
}
public static IEnumerable<NamespaceDefinitionHandle> AsEnumerable(this NamespaceDefinitionHandleCollection collection)
{
foreach (NamespaceDefinitionHandle handle in collection)
yield return handle;
}
public static IEnumerable<TypeDefinitionHandle> AsEnumerable(this TypeDefinitionHandleCollection collection)
{
foreach (TypeDefinitionHandle handle in collection)
yield return handle;
}
public static Handle[] ToArray(this HandleCollection collection)
{
int count = collection.Count;
Handle[] result = new Handle[count];
int i = 0;
foreach (Handle element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static bool[] ToArray(this BooleanCollection collection)
{
int count = collection.Count;
bool[] result = new bool[count];
int i = 0;
foreach (bool element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static char[] ToArray(this CharCollection collection)
{
int count = collection.Count;
char[] result = new char[count];
int i = 0;
foreach (char element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static float[] ToArray(this SingleCollection collection)
{
int count = collection.Count;
float[] result = new float[count];
int i = 0;
foreach (float element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static double[] ToArray(this DoubleCollection collection)
{
int count = collection.Count;
double[] result = new double[count];
int i = 0;
foreach (double element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static byte[] ToArray(this ByteCollection collection, Type enumType = null)
{
int count = collection.Count;
byte[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (byte[])Array.CreateInstance(enumType, count);
}
else
{
result = new byte[count];
}
int i = 0;
foreach (byte element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static sbyte[] ToArray(this SByteCollection collection, Type enumType = null)
{
int count = collection.Count;
sbyte[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (sbyte[])Array.CreateInstance(enumType, count);
}
else
{
result = new sbyte[count];
}
int i = 0;
foreach (sbyte element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static ushort[] ToArray(this UInt16Collection collection, Type enumType = null)
{
int count = collection.Count;
ushort[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (ushort[])Array.CreateInstance(enumType, count);
}
else
{
result = new ushort[count];
}
int i = 0;
foreach (ushort element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static short[] ToArray(this Int16Collection collection, Type enumType = null)
{
int count = collection.Count;
short[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (short[])Array.CreateInstance(enumType, count);
}
else
{
result = new short[count];
}
int i = 0;
foreach (short element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static uint[] ToArray(this UInt32Collection collection, Type enumType = null)
{
int count = collection.Count;
uint[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (uint[])Array.CreateInstance(enumType, count);
}
else
{
result = new uint[count];
}
int i = 0;
foreach (uint element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static int[] ToArray(this Int32Collection collection, Type enumType = null)
{
int count = collection.Count;
int[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (int[])Array.CreateInstance(enumType, count);
}
else
{
result = new int[count];
}
int i = 0;
foreach (int element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static ulong[] ToArray(this UInt64Collection collection, Type enumType = null)
{
int count = collection.Count;
ulong[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (ulong[])Array.CreateInstance(enumType, count);
}
else
{
result = new ulong[count];
}
int i = 0;
foreach (ulong element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
public static long[] ToArray(this Int64Collection collection, Type enumType = null)
{
int count = collection.Count;
long[] result;
if (enumType != null)
{
Debug.Assert(enumType.IsEnum);
result = (long[])Array.CreateInstance(enumType, count);
}
else
{
result = new long[count];
}
int i = 0;
foreach (long element in collection)
{
result[i++] = element;
}
Debug.Assert(i == count);
return result;
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kodestruct.Common.CalculationLogger.Interfaces;
using Kodestruct.Common.Entities;
using Kodestruct.Common.Mathematics;
using Kodestruct.Common.Section.Interfaces;
namespace Kodestruct.Common.Section
{
public abstract class SectionBase: AnalyticalElement, ISection
{
public SectionBase():this(null)
{
}
public SectionBase(string Name): this(Name,null)
{
}
public SectionBase(string Name, ICalcLog Log)
{
this.name = Name;
plasticCentroidCoordinate = new Point2D(0,0);
elasticCentroidCoordinate = new Point2D(0,0);
}
private string name;
public virtual string Name
{
get { return name; }
}
protected double _B;
public double B
{
get { return _B; }
set { _B = value; }
}
protected double _H;
public double H
{
get { return _H; }
set { _H = value; }
}
protected double _A;
public virtual double A
{
get { return _A; }
set { _A = value; }
}
protected double _I_x;
public virtual double I_x
{
get { return _I_x; }
}
protected double _I_y;
public virtual double I_y
{
get { return _I_y; }
}
protected double _S_x_Top;
public virtual double S_xTop
{
get
{
if (_S_x_Top==0)
{
_S_x_Top = _I_x / (_H - _y_Bar);
}
return _S_x_Top;
}
}
protected double _S_xBot;
public virtual double S_xBot
{
get
{
if (_S_xBot == 0)
{
_S_xBot = _I_x / _y_Bar;
}
return _S_xBot;
}
}
protected double _S_yLeft;
public virtual double S_yLeft
{
get
{
if (_S_yLeft == 0)
{
_S_yLeft = _I_y / _x_Bar;
}
return _S_yLeft;
}
}
protected double _S_yRight;
public virtual double S_yRight
{
get
{
if (_S_yRight == 0)
{
_S_yRight = _I_y / (_B - _x_Bar);
}
return _S_yRight;
}
}
protected double _Z_x;
public virtual double Z_x
{
get { return _Z_x; }
}
protected double _Z_y;
public virtual double Z_y
{
get { return _Z_y; }
}
protected double _r_x;
public virtual double r_x
{
get {
_r_x = Math.Sqrt(_I_x / _A);
return _r_x; }
}
protected double _r_y;
public virtual double r_y
{
get {
_r_y = Math.Sqrt(_I_y / _A);
return _r_y; }
}
protected double _x_Bar;
public virtual double x_Bar
{
get { return _x_Bar; }
}
protected double _y_Bar;
public virtual double y_Bar
{
get {
return _y_Bar; }
}
protected double _x_pBar;
public virtual double x_pBar
{
get { return _x_pBar; }
}
protected double _y_pBar;
public virtual double y_pBar
{
get { return _y_pBar; }
}
protected double _C_w;
public virtual double C_w
{
get { return _C_w; }
}
protected double _J;
public virtual double J
{
get { return _J; }
}
protected Point2D elasticCentroidCoordinate;
public Point2D ElasticCentroidCoordinate
{
get
{
return elasticCentroidCoordinate;
}
set
{
elasticCentroidCoordinate = value;
}
}
protected Point2D plasticCentroidCoordinate;
public Point2D PlasticCentroidCoordinate
{
get
{
return plasticCentroidCoordinate;
}
set
{
plasticCentroidCoordinate = value;
}
}
//public abstract ISection Clone();
}
}
| |
namespace android.graphics.drawable
{
[global::MonoJavaBridge.JavaClass()]
public partial class LayerDrawable : android.graphics.drawable.Drawable, android.graphics.drawable.Drawable.Callback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected LayerDrawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual int getId(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getId", "(I)I", ref global::android.graphics.drawable.LayerDrawable._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V", ref global::android.graphics.drawable.LayerDrawable._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual global::android.graphics.drawable.Drawable getDrawable(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getDrawable", "(I)Landroid/graphics/drawable/Drawable;", ref global::android.graphics.drawable.LayerDrawable._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable;
}
private static global::MonoJavaBridge.MethodId _m3;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V", ref global::android.graphics.drawable.LayerDrawable._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int ChangingConfigurations
{
get
{
return getChangingConfigurations();
}
}
private static global::MonoJavaBridge.MethodId _m4;
public override int getChangingConfigurations()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getChangingConfigurations", "()I", ref global::android.graphics.drawable.LayerDrawable._m4);
}
public new bool Dither
{
set
{
setDither(value);
}
}
private static global::MonoJavaBridge.MethodId _m5;
public override void setDither(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "setDither", "(Z)V", ref global::android.graphics.drawable.LayerDrawable._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int Alpha
{
set
{
setAlpha(value);
}
}
private static global::MonoJavaBridge.MethodId _m6;
public override void setAlpha(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "setAlpha", "(I)V", ref global::android.graphics.drawable.LayerDrawable._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new global::android.graphics.ColorFilter ColorFilter
{
set
{
setColorFilter(value);
}
}
private static global::MonoJavaBridge.MethodId _m7;
public override void setColorFilter(android.graphics.ColorFilter arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V", ref global::android.graphics.drawable.LayerDrawable._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
public override bool isStateful()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "isStateful", "()Z", ref global::android.graphics.drawable.LayerDrawable._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public override bool setVisible(bool arg0, bool arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "setVisible", "(ZZ)Z", ref global::android.graphics.drawable.LayerDrawable._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new int Opacity
{
get
{
return getOpacity();
}
}
private static global::MonoJavaBridge.MethodId _m10;
public override int getOpacity()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getOpacity", "()I", ref global::android.graphics.drawable.LayerDrawable._m10);
}
private static global::MonoJavaBridge.MethodId _m11;
protected override bool onStateChange(int[] arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "onStateChange", "([I)Z", ref global::android.graphics.drawable.LayerDrawable._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
protected override bool onLevelChange(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "onLevelChange", "(I)Z", ref global::android.graphics.drawable.LayerDrawable._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
protected override void onBoundsChange(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V", ref global::android.graphics.drawable.LayerDrawable._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int IntrinsicWidth
{
get
{
return getIntrinsicWidth();
}
}
private static global::MonoJavaBridge.MethodId _m14;
public override int getIntrinsicWidth()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getIntrinsicWidth", "()I", ref global::android.graphics.drawable.LayerDrawable._m14);
}
public new int IntrinsicHeight
{
get
{
return getIntrinsicHeight();
}
}
private static global::MonoJavaBridge.MethodId _m15;
public override int getIntrinsicHeight()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getIntrinsicHeight", "()I", ref global::android.graphics.drawable.LayerDrawable._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public override bool getPadding(android.graphics.Rect arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z", ref global::android.graphics.drawable.LayerDrawable._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public override global::android.graphics.drawable.Drawable mutate()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "mutate", "()Landroid/graphics/drawable/Drawable;", ref global::android.graphics.drawable.LayerDrawable._m17) as android.graphics.drawable.Drawable;
}
public new global::android.graphics.drawable.Drawable.ConstantState ConstantState
{
get
{
return getConstantState();
}
}
private static global::MonoJavaBridge.MethodId _m18;
public override global::android.graphics.drawable.Drawable.ConstantState getConstantState()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;", ref global::android.graphics.drawable.LayerDrawable._m18) as android.graphics.drawable.Drawable.ConstantState;
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual void invalidateDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "invalidateDrawable", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.graphics.drawable.LayerDrawable._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void scheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1, long arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "scheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V", ref global::android.graphics.drawable.LayerDrawable._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
public void scheduleDrawable(android.graphics.drawable.Drawable arg0, global::java.lang.RunnableDelegate arg1, long arg2)
{
scheduleDrawable(arg0, (global::java.lang.RunnableDelegateWrapper)arg1, arg2);
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual void unscheduleDrawable(android.graphics.drawable.Drawable arg0, java.lang.Runnable arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "unscheduleDrawable", "(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;)V", ref global::android.graphics.drawable.LayerDrawable._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void unscheduleDrawable(android.graphics.drawable.Drawable arg0, global::java.lang.RunnableDelegate arg1)
{
unscheduleDrawable(arg0, (global::java.lang.RunnableDelegateWrapper)arg1);
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual void setId(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "setId", "(II)V", ref global::android.graphics.drawable.LayerDrawable._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual global::android.graphics.drawable.Drawable findDrawableByLayerId(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "findDrawableByLayerId", "(I)Landroid/graphics/drawable/Drawable;", ref global::android.graphics.drawable.LayerDrawable._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable;
}
public new int NumberOfLayers
{
get
{
return getNumberOfLayers();
}
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual int getNumberOfLayers()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "getNumberOfLayers", "()I", ref global::android.graphics.drawable.LayerDrawable._m24);
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual bool setDrawableByLayerId(int arg0, android.graphics.drawable.Drawable arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "setDrawableByLayerId", "(ILandroid/graphics/drawable/Drawable;)Z", ref global::android.graphics.drawable.LayerDrawable._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual void setLayerInset(int arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.drawable.LayerDrawable.staticClass, "setLayerInset", "(IIIII)V", ref global::android.graphics.drawable.LayerDrawable._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
private static global::MonoJavaBridge.MethodId _m27;
public LayerDrawable(android.graphics.drawable.Drawable[] arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.graphics.drawable.LayerDrawable._m27.native == global::System.IntPtr.Zero)
global::android.graphics.drawable.LayerDrawable._m27 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.LayerDrawable.staticClass, "<init>", "([Landroid/graphics/drawable/Drawable;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.LayerDrawable.staticClass, global::android.graphics.drawable.LayerDrawable._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
static LayerDrawable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.LayerDrawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/LayerDrawable"));
}
}
}
| |
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using Nuke.Common;
using Nuke.Common.CI;
using Nuke.Common.Execution;
using Nuke.Common.Git;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
[CheckBuildProjectConfigurations]
[ShutdownDotNetAfterServerBuild]
partial class Build : NukeBuild
{
/// Support plugins are available for:
/// - JetBrains ReSharper https://nuke.build/resharper
/// - JetBrains Rider https://nuke.build/rider
/// - Microsoft VisualStudio https://nuke.build/visualstudio
/// - Microsoft VSCode https://nuke.build/vscode
public static int Main () => Execute<Build>(x => x.Compile);
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Solution] readonly Solution Solution;
[GitRepository] readonly GitRepository GitRepository;
AbsolutePath SourceDirectory => RootDirectory / "src";
AbsolutePath ArtifactsDirectory => RootDirectory / "artifacts";
string TagVersion => GitRepository.Tags.SingleOrDefault(x => x.StartsWith("v"))?[1..];
string VersionSuffix =>
string.IsNullOrWhiteSpace(TagVersion)
? "preview-" + DateTime.UtcNow.ToString("yyyyMMdd-HHmm")
: "";
static bool IsRunningOnWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory);
EnsureCleanDirectory(ArtifactsDirectory);
});
Target Restore => _ => _
.Executes(() =>
{
DotNetRestore(s => s
.SetProjectFile(Solution));
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
const string assemblyInfoContents = @"
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyMetadataAttribute(""githash"",""GIT_HASH"")]
namespace System {
internal static class AssemblyVersionInformation {
internal const System.String AssemblyMetadata_githash = ""GIT_HASH"";
}
}
";
var final = assemblyInfoContents.Replace("GIT_HASH", GitRepository?.Commit ?? "");
File.WriteAllText(SourceDirectory / "AssemblyInfo.cs", final.TrimStart());
DotNetBuild(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.EnableNoRestore());
});
Target Test => _ => _
.After(Compile)
.Executes(() =>
{
var framework = "";
if (!IsRunningOnWindows)
{
framework = "net6.0";
}
DotNetTest(s => s
.EnableNoRestore()
.EnableNoBuild()
.SetProjectFile(Solution.GetProject("Quartz.Tests.Unit"))
.SetConfiguration(Configuration)
.SetFramework(framework)
);
});
Target Pack => _ => _
.After(Compile, Test)
.Produces(ArtifactsDirectory / "*.*")
.Executes(() =>
{
EnsureCleanDirectory(ArtifactsDirectory);
DotNetPack(s => s
.SetAssemblyVersion(TagVersion)
.SetFileVersion(TagVersion)
.SetInformationalVersion(TagVersion)
.SetVersionSuffix(VersionSuffix)
.SetConfiguration(Configuration)
.SetOutputDirectory(ArtifactsDirectory)
);
var zipContents = Array.Empty<AbsolutePath>()
.Concat(SourceDirectory.GlobFiles("**/*.*"))
.Concat(RootDirectory.GlobFiles("database/**/*"))
.Concat(RootDirectory.GlobFiles("changelog.md"))
.Concat(RootDirectory.GlobFiles("license.txt"))
.Concat(RootDirectory.GlobFiles("README.md"))
.Concat(RootDirectory.GlobFiles("*.sln"))
.Concat(RootDirectory.GlobFiles("build.*"))
.Concat(RootDirectory.GlobFiles("quartz.net.snk"))
.Concat(RootDirectory.GlobFiles("build.*"))
.Where(x => !x.Contains(""))
.Where(x => !x.Contains("Quartz.Web"))
.Where(x => !x.Contains("Quartz.Benchmark"))
.Where(x => !x.Contains("Quartz.Test"))
.Where(x => !x.Contains("/obj/"))
.Where(x => !x.ToString().EndsWith(".suo"))
.Where(x => !x.ToString().EndsWith(".user"))
;
var zipTempDirectory = RootDirectory / "temp" / "package";
EnsureCleanDirectory(zipTempDirectory);
CopyDirectoryRecursively(
source: SourceDirectory,
target: zipTempDirectory / "src",
excludeDirectory: dir => dir.Name is "Quartz.Web" or "obj" or "bin",
excludeFile: file => file.Name.EndsWith(".suo") || file.Name.EndsWith(".user"));
CopyDirectoryRecursively(
source: RootDirectory / "build",
target: zipTempDirectory / "build",
excludeDirectory: dir => dir.Name is "obj" or "bin");
CopyDirectoryRecursively(source: RootDirectory / "database", target: zipTempDirectory / "database");
var binaries = Solution.GetProjects("*")
.Where(x => x.GetProperty("IsPackable") != "false" || x.Name.Contains("Example") || x.Name == "Quartz.Server");
foreach (var project in binaries)
{
CopyDirectoryRecursively(source: SourceDirectory / project.Name / "bin" / Configuration, target: zipTempDirectory / "bin" / Configuration / project.Name);
}
CopyFileToDirectory("README.md", zipTempDirectory);
CopyFileToDirectory("Quartz.sln", zipTempDirectory);
CopyFileToDirectory("quartz.net.snk", zipTempDirectory);
CopyFileToDirectory("license.txt", zipTempDirectory);
CopyFileToDirectory("changelog.md", zipTempDirectory);
CopyFileToDirectory("build.cmd", zipTempDirectory);
CopyFileToDirectory("build.sh", zipTempDirectory);
CopyFileToDirectory("build.ps1", zipTempDirectory);
var props = File.ReadAllText(SourceDirectory / "Directory.Build.props");
var baseVersion = Regex.Match(props, "<VersionPrefix>(.+)</VersionPrefix>").Groups[1].Captures[0].Value;
if (!string.IsNullOrWhiteSpace(VersionSuffix))
{
baseVersion += "-";
}
ZipFile.CreateFromDirectory(zipTempDirectory, ArtifactsDirectory / $"Quartz.NET-{baseVersion}{VersionSuffix}.zip");
});
Target ApiDoc => _ => _
.Executes(() =>
{
var headerContent = File.ReadAllText("doc/header.template");
var footerContent = File.ReadAllText("doc/footer.template");
var docsDirectory = RootDirectory / "build" / "apidoc";
foreach (var file in docsDirectory.GlobFiles("**/*.htm", "**/*.html"))
{
var contents = File.ReadAllText(file);
contents = contents.Replace("@HEADER@", headerContent);
contents = contents.Replace("@FOOTER@", footerContent);
File.WriteAllText(file, contents);
}
});
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace PopcornNetFrameworkExample.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
Copyright 2016 Utrecht University http://www.uu.nl/
This software has been created in the context of the EU-funded RAGE project.
Realising and Applied Gaming Eco-System (RAGE), Grant agreement No 644187,
http://rageproject.eu/
The Behavior Markup Language (BML) is a language whose specifications were developed
in the SAIBA framework. More information here : http://www.mindmakers.org/projects/bml-1-0/wiki
Created by: Christyowidiasmoro, Utrecht University <c.christyowidiasmoro@uu.nl>
For more information, contact Dr. Zerrin YUMAK, Email: z.yumak@uu.nl Web: http://www.zerrinyumak.com/
https://www.staff.science.uu.nl/~yumak001/UUVHC/index.html
*/
// <copyright file="RageBMLNet.cs" company="RAGE">
// Copyright (c) 2016 RAGE All rights reserved.
// </copyright>
// <author>Chris021</author>
// <date>12/5/2016 11:53:54 AM</date>
// <summary>Implements the RageBMLNet class</summary>
namespace AssetPackage
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using AssetManagerPackage;
using BMLNet;
/// <summary>
/// An BMLNet Rage asset
/// </summary>
public class RageBMLNet : BaseAsset
{
#region Fields
/// <summary>
/// callback function. it will be called when the specific sync point is completed
/// </summary>
/// <param name="id"></param> the ID of block
/// <param name="eventName"></param>the event name of sync point (start, ready, strokeStart, attackPeak, stroke, strokeEnd, relax, end)
public delegate void SyncPointCompleted(string id, string eventName);
public SyncPointCompleted OnSyncPointCompleted;
/// <summary>
/// Options for controlling the operation.
/// </summary>
private RageBMLNetSettings settings = null;
/// <summary>
/// dictionary that will hold the value of all block / behavior
/// </summary>
private Dictionary<string, Type> blocks = new Dictionary<string, Type>();
/// <summary>
/// the dictionary that save all the blocks / behavior that need to be run
/// </summary>
private Dictionary<string, BMLBlock> scheduledBlocks = new Dictionary<string, BMLBlock>();
/// <summary>
/// global timer
/// </summary>
private float timer;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the RageBMLNet.Asset class.
/// </summary>
public RageBMLNet()
: base()
{
//! Create Settings and let it's BaseSettings class assign Defaultvalues where it can.
//
settings = new RageBMLNetSettings();
blocks.Add("bml", typeof(BMLBml));
blocks.Add("wait", typeof(BMLWait));
// TODO <synchronize>, <before>
blocks.Add("face", typeof(BMLFace));
blocks.Add("faceFacs", typeof(BMLFaceFacs));
blocks.Add("faceLexeme", typeof(BMLFaceLexeme));
blocks.Add("faceShift", typeof(BMLFaceShift));
blocks.Add("gaze", typeof(BMLGaze));
blocks.Add("gazeShift", typeof(BMLGazeShift));
blocks.Add("gesture", typeof(BMLGesture));
blocks.Add("pointing", typeof(BMLPointing));
blocks.Add("head", typeof(BMLHead));
blocks.Add("headDirectionShift", typeof(BMLHeadDirectionShift));
blocks.Add("locomotion", typeof(BMLLocomotion));
blocks.Add("posture", typeof(BMLPosture));
blocks.Add("postureShift", typeof(BMLPostureShift));
blocks.Add("stance", typeof(BMLStance));
blocks.Add("pose", typeof(BMLPose));
blocks.Add("speech", typeof(BMLSpeech));
// TODO <feedback> <blockProgress>
timer = 0.0f;
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets options for controlling the operation.
/// </summary>
///
/// <remarks> Besides the toXml() and fromXml() methods, we never use this property but use
/// it's correctly typed backing field 'settings' instead. </remarks>
/// <remarks> This property should go into each asset having Settings of its own. </remarks>
/// <remarks> The actual class used should be derived from BaseAsset (and not directly from
/// ISetting). </remarks>
///
/// <value>
/// The settings.
/// </value>
public override ISettings Settings
{
get
{
return settings;
}
set
{
settings = (value as RageBMLNetSettings);
}
}
/// <summary>
/// the dictionary that hold the blocks / behavior that need to be run
/// </summary>
public Dictionary<string, BMLBlock> ScheduledBlocks
{
get
{
return scheduledBlocks;
}
}
/// <summary>
/// global timer
/// </summary>
public float Timer
{
get
{
return timer;
}
}
#endregion Properties
#region Methods
public void ParseFromFile(string filename)
{
AssetManager.Instance.Log(Severity.Warning, "not supported yet in portable version");
//XmlTextReader reader = new XmlTextReader(filename);
//if (reader != null)
// Parse(reader);
//else
// AssetManager.Instance.Log(Severity.Warning, "file error");
}
public void ParseFromString(string xml)
{
XmlReader reader = XmlReader.Create(new StringReader(xml));
Parse(reader);
}
/// <summary>
/// update function will be called everytime when the program is run. it can be called inside Unity Update function
/// </summary>
/// <param name="deltaTime"></param> the time from last called
public void Update(float deltaTime)
{
timer += deltaTime;
foreach (KeyValuePair<string, BMLBlock> block in scheduledBlocks)
{
foreach (KeyValuePair<string, BMLSyncPoint> syncPoint in block.Value.syncPoints)
{
syncPoint.Value.Update(this);
}
}
}
/// <summary>
/// this function can be called from outside library to trigger sync point.
/// </summary>
/// <param name="id"></param> the ID of the block where the sync point is resided
/// <param name="eventName"></param> the event name of sync point (start, ready, strokeStart, attackPeak, stroke, strokeEnd, relax, end)
public void TriggerSyncPoint(string id, string eventName)
{
if (scheduledBlocks.ContainsKey(id))
{
if (scheduledBlocks[id].syncPoints.ContainsKey(eventName) == false)
{
// create a new sync point
scheduledBlocks[id].syncPoints.Add(eventName, new BMLSyncPoint(scheduledBlocks[id], eventName, ""));
}
// trigger sync point
scheduledBlocks[id].syncPoints[eventName].TriggerSyncPoint();
}
}
/// <summary>
/// function to get behavior from ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public BMLBlock GetBehaviorFromId(string id)
{
if (scheduledBlocks.ContainsKey(id))
{
return scheduledBlocks[id];
}
else
{
return null;
}
}
/// <summary>
/// parsing the XML
/// TODO: need to check whether we have bml tag or not
/// </summary>
/// <param name="reader"></param> the XMLReader
private void Parse(XmlReader reader)
{
BMLBml currentBml = null;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (blocks.ContainsKey(reader.Name))
{
Type t = blocks[reader.Name];
BMLBlock instance = (BMLBlock)Activator.CreateInstance(t);
instance.Parse(reader);
// TODO: need to accomodate different tag such as constraint, ...
if (instance is BMLBml)
{
BMLBml bml = (BMLBml)instance;
if (bml.composition == BMLBml.Composition.REPLACE)
{
// The new block will completely replace all prior <bml> blocks.
// All behavior specified in earlier blocks will be ended and
ClearBlocks();
// TODO: the ECA will revert to a neutral state before the new block starts.
}
else if (bml.composition == BMLBml.Composition.APPEND)
{
// The start time of the new block will be as soon as possible after the end time of all prior blocks.
if (currentBml != null)
bml.SetGlobalStartTrigger(currentBml.id + ":globalEnd");
}
else if (bml.composition == BMLBml.Composition.MERGE)
{
// The behaviors specified in the new <bml> block will be realized together with the behaviors specified in prior <bml> blocks.
// TODO: In case of conflict, behaviors in the newly merged <bml> block cannot modify behaviors defined by prior <bml> blocks.
}
// save this bml for upcomming tag
currentBml = bml;
// add to scheduled block
scheduledBlocks.Add((bml).id, bml);
}
else
{
// create a new bml if this xml is started without <bml> tag
if (currentBml == null)
{
currentBml = new BMLBml();
}
// track this tag belong to a bml tag
instance.parentBml = currentBml;
// keep tracking the number of tag inside <bml> tag. in order to check whether all bml inside this <bml> tag are already finish or not
instance.parentBml.IncreaseChild();
if (instance is BMLBehavior)
{
// add to scheduled block
scheduledBlocks.Add(((BMLBehavior)instance).id, (BMLBehavior)instance);
}
}
}
break;
}
}
}
private void ClearBlocks()
{
IEnumerator enumerator = scheduledBlocks.GetEnumerator();
while (enumerator.MoveNext())
{
//get the pair of Dictionary
KeyValuePair<string, BMLBlock> pair = ((KeyValuePair<string, BMLBlock>)(enumerator.Current));
//dispose it
pair.Value.Dispose();
}
// clear the dictionary
scheduledBlocks.Clear();
}
#endregion Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const bool CheckOperationsRequiresSetHandle = true;
internal ThreadPoolBoundHandle _threadPoolBinding;
internal static string GetPipePath(string serverName, string pipeName)
{
string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (String.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
return normalizedPipePath;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
// Check that this handle is infact a handle to a pipe.
if (Interop.Kernel32.GetFileType(safePipeHandle) != Interop.Kernel32.FileTypes.FILE_TYPE_PIPE)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// If the handle is of async type, bind the handle to the ThreadPool so that we can use
// the async operations (it's needed so that our native callbacks get called).
_threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle);
}
private void DisposeCore(bool disposing)
{
if (disposing)
{
_threadPoolBinding?.Dispose();
}
}
[SecurityCritical]
private unsafe int ReadCore(Span<byte> buffer)
{
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, null, out errorCode);
if (r == -1)
{
// If the other side has broken the connection, set state to Broken and return 0
if (errorCode == Interop.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
r = 0;
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty);
}
}
_isMessageComplete = (errorCode != Interop.Errors.ERROR_MORE_DATA);
Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");
return r;
}
[SecuritySafeCritical]
private Task<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, isWrite: false);
// Queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
int r;
unsafe
{
r = ReadFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
}
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
// returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer read back from this call
// when using overlapped structures! You must not pass in a non-null lpNumBytesRead to
// ReadFile when using overlapped structures! This is by design NT behavior.
if (r == -1)
{
switch (errorCode)
{
// One side has closed its handle or server disconnected.
// Set the state to Broken and do some cleanup work
case Interop.Errors.ERROR_BROKEN_PIPE:
case Interop.Errors.ERROR_PIPE_NOT_CONNECTED:
State = PipeState.Broken;
unsafe
{
// Clear the overlapped status bit for this special case. Failure to do so looks
// like we are freeing a pending overlapped.
completionSource.Overlapped->InternalLow = IntPtr.Zero;
}
completionSource.ReleaseResources();
UpdateMessageCompletion(true);
return s_zeroTask;
case Interop.Errors.ERROR_IO_PENDING:
break;
default:
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
completionSource.RegisterForCancellation(cancellationToken);
return completionSource.Task;
}
[SecurityCritical]
private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
{
int errorCode = 0;
int r = WriteFileNative(_handle, buffer, null, out errorCode);
if (r == -1)
{
throw WinIOError(errorCode);
}
Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
}
[SecuritySafeCritical]
private Task WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, isWrite: true);
int errorCode = 0;
// Queue an async WriteFile operation and pass in a packed overlapped
int r;
unsafe
{
r = WriteFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
}
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
// wrapper returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer written back from this
// call when using overlapped structures! You must not pass in a non-null
// lpNumBytesWritten to WriteFile when using overlapped structures! This is by design
// NT behavior.
if (r == -1 && errorCode != Interop.Errors.ERROR_IO_PENDING)
{
completionSource.ReleaseResources();
throw WinIOError(errorCode);
}
completionSource.RegisterForCancellation(cancellationToken);
return completionSource.Task;
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
// Block until other end of the pipe has read everything.
if (!Interop.Kernel32.FlushFileBuffers(_handle))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (_isFromExistingHandle)
{
int pipeFlags;
if (!Interop.Kernel32.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
if ((pipeFlags & Interop.Kernel32.PipeOptions.PIPE_TYPE_MESSAGE) != 0)
{
return PipeTransmissionMode.Message;
}
else
{
return PipeTransmissionMode.Byte;
}
}
else
{
return _transmissionMode;
}
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
int inBufferSize;
if (!Interop.Kernel32.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
return inBufferSize;
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
int outBufferSize;
// Use cached value if direction is out; otherwise get fresh version
if (_pipeDirection == PipeDirection.Out)
{
outBufferSize = _outBufferSize;
}
else if (!Interop.Kernel32.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize,
IntPtr.Zero, IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
return outBufferSize;
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
// get fresh value if it could be stale
if (_isFromExistingHandle || IsHandleExposed)
{
UpdateReadMode();
}
return _readMode;
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
// Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream
// and the AnonymousPipeStreams override this.
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
unsafe
{
int pipeReadType = (int)value << 1;
if (!Interop.Kernel32.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
else
{
_readMode = value;
}
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
[SecurityCritical]
private unsafe int ReadFileNative(SafePipeHandle handle, Span<byte> buffer, NativeOverlapped* overlapped, out int errorCode)
{
DebugAssertHandleValid(handle);
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesRead = 0;
fixed (byte* p = &buffer.DangerousGetPinnableReference())
{
r = _isAsync ?
Interop.Kernel32.ReadFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) :
Interop.Kernel32.ReadFile(handle, p, buffer.Length, out numBytesRead, IntPtr.Zero);
}
if (r == 0)
{
// In message mode, the ReadFile can inform us that there is more data to come.
errorCode = Marshal.GetLastWin32Error();
return errorCode == Interop.Errors.ERROR_MORE_DATA ?
numBytesRead :
-1;
}
else
{
errorCode = 0;
return numBytesRead;
}
}
[SecurityCritical]
private unsafe int WriteFileNative(SafePipeHandle handle, ReadOnlySpan<byte> buffer, NativeOverlapped* overlapped, out int errorCode)
{
DebugAssertHandleValid(handle);
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesWritten = 0;
fixed (byte* p = &buffer.DangerousGetPinnableReference())
{
r = _isAsync ?
Interop.Kernel32.WriteFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) :
Interop.Kernel32.WriteFile(handle, p, buffer.Length, out numBytesWritten, IntPtr.Zero);
}
if (r == 0)
{
errorCode = Marshal.GetLastWin32Error();
return -1;
}
else
{
errorCode = 0;
return numBytesWritten;
}
}
[SecurityCritical]
internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES);
secAttrs.bInheritHandle = Interop.BOOL.TRUE;
}
return secAttrs;
}
/// <summary>
/// Determine pipe read mode from Win32
/// </summary>
[SecurityCritical]
private void UpdateReadMode()
{
int flags;
if (!Interop.Kernel32.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero, 0))
{
throw WinIOError(Marshal.GetLastWin32Error());
}
if ((flags & Interop.Kernel32.PipeOptions.PIPE_READMODE_MESSAGE) != 0)
{
_readMode = PipeTransmissionMode.Message;
}
else
{
_readMode = PipeTransmissionMode.Byte;
}
}
/// <summary>
/// Filter out all pipe related errors and do some cleanup before calling Error.WinIOError.
/// </summary>
/// <param name="errorCode"></param>
[SecurityCritical]
internal Exception WinIOError(int errorCode)
{
switch (errorCode)
{
case Interop.Errors.ERROR_BROKEN_PIPE:
case Interop.Errors.ERROR_PIPE_NOT_CONNECTED:
case Interop.Errors.ERROR_NO_DATA:
// Other side has broken the connection
_state = PipeState.Broken;
return new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));
case Interop.Errors.ERROR_HANDLE_EOF:
return Error.GetEndOfFile();
case Interop.Errors.ERROR_INVALID_HANDLE:
// For invalid handles, detect the error and mark our handle
// as invalid to give slightly better error messages. Also
// help ensure we avoid handle recycling bugs.
_handle.SetHandleAsInvalid();
_state = PipeState.Broken;
break;
}
return Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Common;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !WINDOWS_UWP
namespace NLog.Targets
{
using System;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using Config;
/// <summary>
/// Writes log messages to the console with customizable coloring.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/ColoredConsole-target">Documentation on NLog Wiki</seealso>
[Target("ColoredConsole")]
public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter
{
/// <summary>
/// Should logging being paused/stopped because of the race condition bug in Console.Writeline?
/// </summary>
/// <remarks>
/// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug.
/// See http://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written
/// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service
///
/// Full error:
/// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory.
/// The I/ O package is not thread safe by default.In multithreaded applications,
/// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or
/// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader.
///
/// </remarks>
private bool _pauseLogging;
private static readonly IList<ConsoleRowHighlightingRule> DefaultConsoleRowHighlightingRules = new List<ConsoleRowHighlightingRule>()
{
new ConsoleRowHighlightingRule("level == LogLevel.Fatal", ConsoleOutputColor.Red, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Error", ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Warn", ConsoleOutputColor.Magenta, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Info", ConsoleOutputColor.White, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Debug", ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Trace", ConsoleOutputColor.DarkGray, ConsoleOutputColor.NoChange),
};
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public ColoredConsoleTarget()
{
WordHighlightingRules = new List<ConsoleWordHighlightingRule>();
RowHighlightingRules = new List<ConsoleRowHighlightingRule>();
UseDefaultRowHighlightingRules = true;
_pauseLogging = false;
DetectConsoleAvailable = false;
OptimizeBufferReuse = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ColoredConsoleTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
/// <param name="name">Name of the target.</param>
public ColoredConsoleTarget(string name) : this()
{
Name = name;
}
/// <summary>
/// Gets or sets a value indicating whether the error stream (stderr) should be used instead of the output stream (stdout).
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool ErrorStream { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use default row highlighting rules.
/// </summary>
/// <remarks>
/// The default rules are:
/// <table>
/// <tr>
/// <th>Condition</th>
/// <th>Foreground Color</th>
/// <th>Background Color</th>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Fatal</td>
/// <td>Red</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Error</td>
/// <td>Yellow</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Warn</td>
/// <td>Magenta</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Info</td>
/// <td>White</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Debug</td>
/// <td>Gray</td>
/// <td>NoChange</td>
/// </tr>
/// <tr>
/// <td>level == LogLevel.Trace</td>
/// <td>DarkGray</td>
/// <td>NoChange</td>
/// </tr>
/// </table>
/// </remarks>
/// <docgen category='Highlighting Rules' order='9' />
[DefaultValue(true)]
public bool UseDefaultRowHighlightingRules { get; set; }
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
/// <summary>
/// The encoding for writing messages to the <see cref="Console"/>.
/// </summary>
/// <remarks>Has side effect</remarks>
public Encoding Encoding
{
get => ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, IsInitialized, _pauseLogging);
set
{
if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, IsInitialized, _pauseLogging))
_encoding = value;
}
}
private Encoding _encoding;
#endif
/// <summary>
/// Gets or sets a value indicating whether to auto-check if the console is available.
/// - Disables console writing if Environment.UserInteractive = False (Windows Service)
/// - Disables console writing if Console Standard Input is not available (Non-Console-App)
/// </summary>
[DefaultValue(false)]
public bool DetectConsoleAvailable { get; set; }
/// <summary>
/// Gets the row highlighting rules.
/// </summary>
/// <docgen category='Highlighting Rules' order='10' />
[ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")]
public IList<ConsoleRowHighlightingRule> RowHighlightingRules { get; private set; }
/// <summary>
/// Gets the word highlighting rules.
/// </summary>
/// <docgen category='Highlighting Rules' order='11' />
[ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")]
public IList<ConsoleWordHighlightingRule> WordHighlightingRules { get; private set; }
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
_pauseLogging = false;
if (DetectConsoleAvailable)
{
string reason;
_pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason);
if (_pauseLogging)
{
InternalLogger.Info("Console has been detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {0}", reason);
}
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
if (_encoding != null && !_pauseLogging)
Console.OutputEncoding = _encoding;
#endif
base.InitializeTarget();
if (Header != null)
{
LogEventInfo lei = LogEventInfo.CreateNullEvent();
WriteToOutput(lei, RenderLogEvent(Header, lei));
}
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected override void CloseTarget()
{
if (Footer != null)
{
LogEventInfo lei = LogEventInfo.CreateNullEvent();
WriteToOutput(lei, RenderLogEvent(Footer, lei));
}
base.CloseTarget();
}
/// <summary>
/// Writes the specified log event to the console highlighting entries
/// and words based on a set of defined rules.
/// </summary>
/// <param name="logEvent">Log event.</param>
protected override void Write(LogEventInfo logEvent)
{
if (_pauseLogging)
{
//check early for performance
return;
}
WriteToOutput(logEvent, RenderLogEvent(Layout, logEvent));
}
private void WriteToOutput(LogEventInfo logEvent, string message)
{
ConsoleColor oldForegroundColor = Console.ForegroundColor;
ConsoleColor oldBackgroundColor = Console.BackgroundColor;
bool didChangeForegroundColor = false, didChangeBackgroundColor = false;
try
{
var matchingRule = GetMatchingRowHighlightingRule(logEvent);
didChangeForegroundColor = IsColorChange(matchingRule.ForegroundColor, oldForegroundColor);
if (didChangeForegroundColor)
Console.ForegroundColor = (ConsoleColor)matchingRule.ForegroundColor;
didChangeBackgroundColor = IsColorChange(matchingRule.BackgroundColor, oldBackgroundColor);
if (didChangeBackgroundColor)
Console.BackgroundColor = (ConsoleColor)matchingRule.BackgroundColor;
try
{
var consoleStream = ErrorStream ? Console.Error : Console.Out;
if (WordHighlightingRules.Count == 0)
{
consoleStream.WriteLine(message);
}
else
{
message = message.Replace("\a", "\a\a");
foreach (ConsoleWordHighlightingRule hl in WordHighlightingRules)
{
message = hl.ReplaceWithEscapeSequences(message);
}
ColorizeEscapeSequences(consoleStream, message, new ColorPair(Console.ForegroundColor, Console.BackgroundColor), new ColorPair(oldForegroundColor, oldBackgroundColor));
consoleStream.WriteLine();
didChangeForegroundColor = didChangeBackgroundColor = true;
}
}
catch (IndexOutOfRangeException ex)
{
//this is a bug and therefor stopping logging. For docs, see PauseLogging property
_pauseLogging = true;
InternalLogger.Warn(ex, "An IndexOutOfRangeException has been thrown and this is probably due to a race condition." +
"Logging to the console will be paused. Enable by reloading the config or re-initialize the targets");
}
catch (ArgumentOutOfRangeException ex)
{
//this is a bug and therefor stopping logging. For docs, see PauseLogging property
_pauseLogging = true;
InternalLogger.Warn(ex, "An ArgumentOutOfRangeException has been thrown and this is probably due to a race condition." +
"Logging to the console will be paused. Enable by reloading the config or re-initialize the targets");
}
}
finally
{
if (didChangeForegroundColor)
Console.ForegroundColor = oldForegroundColor;
if (didChangeBackgroundColor)
Console.BackgroundColor = oldBackgroundColor;
}
}
private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(LogEventInfo logEvent)
{
foreach (ConsoleRowHighlightingRule rule in RowHighlightingRules)
{
if (rule.CheckCondition(logEvent))
return rule;
}
if (UseDefaultRowHighlightingRules)
{
foreach (ConsoleRowHighlightingRule rule in DefaultConsoleRowHighlightingRules)
{
if (rule.CheckCondition(logEvent))
return rule;
}
}
return ConsoleRowHighlightingRule.Default;
}
private static bool IsColorChange(ConsoleOutputColor targetColor, ConsoleColor oldColor)
{
return (targetColor != ConsoleOutputColor.NoChange) && ((ConsoleColor)targetColor != oldColor);
}
private static void ColorizeEscapeSequences(
TextWriter output,
string message,
ColorPair startingColor,
ColorPair defaultColor)
{
var colorStack = new Stack<ColorPair>();
colorStack.Push(startingColor);
int p0 = 0;
while (p0 < message.Length)
{
int p1 = p0;
while (p1 < message.Length && message[p1] >= 32)
{
p1++;
}
// text
if (p1 != p0)
{
output.Write(message.Substring(p0, p1 - p0));
}
if (p1 >= message.Length)
{
p0 = p1;
break;
}
// control characters
char c1 = message[p1];
char c2 = (char)0;
if (p1 + 1 < message.Length)
{
c2 = message[p1 + 1];
}
if (c1 == '\a' && c2 == '\a')
{
output.Write('\a');
p0 = p1 + 2;
continue;
}
if (c1 == '\r' || c1 == '\n')
{
Console.ForegroundColor = defaultColor.ForegroundColor;
Console.BackgroundColor = defaultColor.BackgroundColor;
output.Write(c1);
Console.ForegroundColor = colorStack.Peek().ForegroundColor;
Console.BackgroundColor = colorStack.Peek().BackgroundColor;
p0 = p1 + 1;
continue;
}
if (c1 == '\a')
{
if (c2 == 'X')
{
colorStack.Pop();
Console.ForegroundColor = colorStack.Peek().ForegroundColor;
Console.BackgroundColor = colorStack.Peek().BackgroundColor;
p0 = p1 + 2;
continue;
}
var foreground = (ConsoleOutputColor)(c2 - 'A');
var background = (ConsoleOutputColor)(message[p1 + 2] - 'A');
if (foreground != ConsoleOutputColor.NoChange)
{
Console.ForegroundColor = (ConsoleColor)foreground;
}
if (background != ConsoleOutputColor.NoChange)
{
Console.BackgroundColor = (ConsoleColor)background;
}
colorStack.Push(new ColorPair(Console.ForegroundColor, Console.BackgroundColor));
p0 = p1 + 3;
continue;
}
output.Write(c1);
p0 = p1 + 1;
}
if (p0 < message.Length)
{
output.Write(message.Substring(p0));
}
}
/// <summary>
/// Color pair (foreground and background).
/// </summary>
internal struct ColorPair
{
private readonly ConsoleColor _foregroundColor;
private readonly ConsoleColor _backgroundColor;
internal ColorPair(ConsoleColor foregroundColor, ConsoleColor backgroundColor)
{
_foregroundColor = foregroundColor;
_backgroundColor = backgroundColor;
}
internal ConsoleColor BackgroundColor => _backgroundColor;
internal ConsoleColor ForegroundColor => _foregroundColor;
}
}
}
#endif
| |
using System;
using System.Collections;
using Server;
using Server.Gumps;
using Server.Items;
using Server.Mobiles;
using Server.Regions;
using System.Collections.Generic;
namespace Server.Engines.CannedEvil
{
public class ChampionSpawn : Item
{
[CommandProperty(AccessLevel.GameMaster)]
public int SpawnSzMod
{
get
{
return (m_SPawnSzMod < 1 || m_SPawnSzMod > 12) ? 12 : m_SPawnSzMod;
}
set
{
m_SPawnSzMod = (value < 1 || value > 12) ? 12 : value;
}
}
private int m_SPawnSzMod;
private bool m_Active;
private bool m_RandomizeType;
private ChampionSpawnType m_Type;
private List<Mobile> m_Creatures;
private List<Item> m_RedSkulls;
private List<Item> m_WhiteSkulls;
private ChampionPlatform m_Platform;
private ChampionAltar m_Altar;
private int m_Kills;
private Mobile m_Champion;
//private int m_SpawnRange;
private Rectangle2D m_SpawnArea;
private ChampionSpawnRegion m_Region;
private TimeSpan m_ExpireDelay;
private DateTime m_ExpireTime;
private TimeSpan m_RestartDelay;
private DateTime m_RestartTime;
private Timer m_Timer, m_RestartTimer;
private IdolOfTheChampion m_Idol;
private bool m_HasBeenAdvanced;
private bool m_ConfinedRoaming;
private Dictionary<Mobile, int> m_DamageEntries;
[CommandProperty(AccessLevel.GameMaster)]
public bool ConfinedRoaming
{
get { return m_ConfinedRoaming; }
set { m_ConfinedRoaming = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool HasBeenAdvanced
{
get { return m_HasBeenAdvanced; }
set { m_HasBeenAdvanced = value; }
}
[Constructable]
public ChampionSpawn()
: base(0xBD2)
{
Movable = false;
Visible = false;
m_Creatures = new List<Mobile>();
m_RedSkulls = new List<Item>();
m_WhiteSkulls = new List<Item>();
m_Platform = new ChampionPlatform(this);
m_Altar = new ChampionAltar(this);
m_Idol = new IdolOfTheChampion(this);
m_ExpireDelay = TimeSpan.FromMinutes(10.0);
m_RestartDelay = TimeSpan.FromMinutes(10.0);
m_DamageEntries = new Dictionary<Mobile, int>();
Timer.DelayCall(TimeSpan.Zero, new TimerCallback(SetInitialSpawnArea));
}
public void SetInitialSpawnArea()
{
//Previous default used to be 24;
SpawnArea = new Rectangle2D(new Point2D(X - 24, Y - 24), new Point2D(X + 24, Y + 24));
}
public void UpdateRegion()
{
if (m_Region != null)
m_Region.Unregister();
if (!Deleted && this.Map != Map.Internal)
{
m_Region = new ChampionSpawnRegion(this);
m_Region.Register();
}
/*
if( m_Region == null )
{
m_Region = new ChampionSpawnRegion( this );
}
else
{
m_Region.Unregister();
//Why doesn't Region allow me to set it's map/Area meself? ><
m_Region = new ChampionSpawnRegion( this );
}
*/
}
[CommandProperty(AccessLevel.GameMaster)]
public bool RandomizeType
{
get { return m_RandomizeType; }
set { m_RandomizeType = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public int Kills
{
get
{
return m_Kills;
}
set
{
m_Kills = value;
InvalidateProperties();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public Rectangle2D SpawnArea
{
get
{
return m_SpawnArea;
}
set
{
m_SpawnArea = value;
InvalidateProperties();
UpdateRegion();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public TimeSpan RestartDelay
{
get
{
return m_RestartDelay;
}
set
{
m_RestartDelay = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public DateTime RestartTime
{
get
{
return m_RestartTime;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public TimeSpan ExpireDelay
{
get
{
return m_ExpireDelay;
}
set
{
m_ExpireDelay = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public DateTime ExpireTime
{
get
{
return m_ExpireTime;
}
set
{
m_ExpireTime = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public ChampionSpawnType Type
{
get
{
return m_Type;
}
set
{
m_Type = value;
InvalidateProperties();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Active
{
get
{
return m_Active;
}
set
{
if (value)
Start();
else
Stop();
InvalidateProperties();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public Mobile Champion
{
get
{
return m_Champion;
}
set
{
m_Champion = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public int Level
{
get
{
return m_RedSkulls.Count;
}
set
{
for (int i = m_RedSkulls.Count - 1; i >= value; --i)
{
m_RedSkulls[i].Delete();
m_RedSkulls.RemoveAt(i);
}
for (int i = m_RedSkulls.Count; i < value; ++i)
{
Item skull = new Item(0x1854);
skull.Hue = 0x26;
skull.Movable = false;
skull.Light = LightType.Circle150;
skull.MoveToWorld(GetRedSkullLocation(i), Map);
m_RedSkulls.Add(skull);
}
InvalidateProperties();
}
}
public int MaxKills
{
get
{
return (m_SPawnSzMod * (250 / 12)) - (Level * m_SPawnSzMod);
}
}
public bool IsChampionSpawn(Mobile m)
{
return m_Creatures.Contains(m);
}
public void SetWhiteSkullCount(int val)
{
for (int i = m_WhiteSkulls.Count - 1; i >= val; --i)
{
m_WhiteSkulls[i].Delete();
m_WhiteSkulls.RemoveAt(i);
}
for (int i = m_WhiteSkulls.Count; i < val; ++i)
{
Item skull = new Item(0x1854);
skull.Movable = false;
skull.Light = LightType.Circle150;
skull.MoveToWorld(GetWhiteSkullLocation(i), Map);
m_WhiteSkulls.Add(skull);
Effects.PlaySound(skull.Location, skull.Map, 0x29);
Effects.SendLocationEffect(new Point3D(skull.X + 1, skull.Y + 1, skull.Z), skull.Map, 0x3728, 10);
}
}
public void Start()
{
if (m_Active || Deleted)
return;
m_Active = true;
m_HasBeenAdvanced = false;
if (m_Timer != null)
m_Timer.Stop();
m_Timer = new SliceTimer(this);
m_Timer.Start();
if (m_RestartTimer != null)
m_RestartTimer.Stop();
m_RestartTimer = null;
if (m_Altar != null)
{
if (m_Champion != null)
m_Altar.Hue = 0x26;
else
m_Altar.Hue = 0;
}
if (m_Platform != null)
m_Platform.Hue = 0x452;
}
public void Stop()
{
if (!m_Active || Deleted)
return;
m_Active = false;
m_HasBeenAdvanced = false;
if (m_Timer != null)
m_Timer.Stop();
m_Timer = null;
if (m_RestartTimer != null)
m_RestartTimer.Stop();
m_RestartTimer = null;
if (m_Altar != null)
m_Altar.Hue = 0;
if (m_Platform != null)
m_Platform.Hue = 0x497;
}
public void BeginRestart(TimeSpan ts)
{
if (m_RestartTimer != null)
m_RestartTimer.Stop();
m_RestartTime = DateTime.Now + ts;
m_RestartTimer = new RestartTimer(this, ts);
m_RestartTimer.Start();
}
public void EndRestart()
{
if (RandomizeType)
{
switch (Utility.Random(5))
{
case 0: Type = ChampionSpawnType.VerminHorde; break;
case 1: Type = ChampionSpawnType.UnholyTerror; break;
case 2: Type = ChampionSpawnType.ColdBlood; break;
case 3: Type = ChampionSpawnType.Abyss; break;
case 4: Type = ChampionSpawnType.Arachnid; break;
}
}
m_HasBeenAdvanced = false;
Start();
}
#region Scroll of Transcendence
private ScrollofTranscendence CreateRandomSoT(bool felucca)
{
int level = Utility.RandomMinMax(1, 5);
if (felucca)
level += 5;
return ScrollofTranscendence.CreateRandom(level, level);
}
#endregion
public static void GiveScrollTo(Mobile killer, SpecialScroll scroll)
{
if (scroll == null || killer == null) //sanity
return;
if (scroll is ScrollofTranscendence)
killer.SendLocalizedMessage(1094936); // You have received a Scroll of Transcendence!
else
killer.SendLocalizedMessage(1049524); // You have received a scroll of power!
if (killer.Alive)
killer.AddToBackpack(scroll);
else
{
if (killer.Corpse != null && !killer.Corpse.Deleted)
killer.Corpse.DropItem(scroll);
else
killer.AddToBackpack(scroll);
}
// Justice reward
PlayerMobile pm = (PlayerMobile)killer;
for (int j = 0; j < pm.JusticeProtectors.Count; ++j)
{
Mobile prot = (Mobile)pm.JusticeProtectors[j];
if (prot.Map != killer.Map || prot.Kills >= 5 || prot.Criminal || !JusticeVirtue.CheckMapRegion(killer, prot))
continue;
int chance = 0;
switch (VirtueHelper.GetLevel(prot, VirtueName.Justice))
{
case VirtueLevel.Seeker: chance = 60; break;
case VirtueLevel.Follower: chance = 80; break;
case VirtueLevel.Knight: chance = 100; break;
}
if (chance > Utility.Random(100))
{
try
{
prot.SendLocalizedMessage(1049368); // You have been rewarded for your dedication to Justice!
SpecialScroll scrollDupe = Activator.CreateInstance(scroll.GetType()) as SpecialScroll;
if (scrollDupe != null)
{
scrollDupe.Skill = scroll.Skill;
scrollDupe.Value = scroll.Value;
prot.AddToBackpack(scrollDupe);
}
}
catch { }
}
}
}
public void OnSlice()
{
if (!m_Active || Deleted)
return;
if (m_Champion != null)
{
if (m_Champion.Deleted)
{
RegisterDamageTo(m_Champion);
if (m_Champion is BaseChampion)
AwardArtifact(((BaseChampion)m_Champion).GetArtifact());
m_DamageEntries.Clear();
if (m_Platform != null)
m_Platform.Hue = 0x497;
if (m_Altar != null)
{
m_Altar.Hue = 0;
if (!Core.ML || Map == Map.Felucca)
{
new StarRoomGate(true, m_Altar.Location, m_Altar.Map);
}
}
m_Champion = null;
Stop();
BeginRestart(m_RestartDelay);
}
}
else
{
int kills = m_Kills;
for (int i = 0; i < m_Creatures.Count; ++i)
{
Mobile m = m_Creatures[i];
if (m.Deleted)
{
if (m.Corpse != null && !m.Corpse.Deleted)
{
((Corpse)m.Corpse).BeginDecay(TimeSpan.FromMinutes(1));
}
m_Creatures.RemoveAt(i);
--i;
++m_Kills;
Mobile killer = m.FindMostRecentDamager(false);
RegisterDamageTo(m);
if (killer is BaseCreature)
killer = ((BaseCreature)killer).GetMaster();
if (killer is PlayerMobile)
{
#region Scroll of Transcendence
if (Core.ML)
{
if (Map == Map.Felucca)
{
if (Utility.RandomDouble() < 0.001)
{
PlayerMobile pm = (PlayerMobile)killer;
double random = Utility.Random(49);
if (random <= 24)
{
ScrollofTranscendence SoTF = CreateRandomSoT(true);
GiveScrollTo(pm, (SpecialScroll)SoTF);
}
else
{
PowerScroll PS = PowerScroll.CreateRandomNoCraft(5, 5);
GiveScrollTo(pm, (SpecialScroll)PS);
}
}
}
if (Map == Map.Ilshenar || Map == Map.Tokuno || Map == Map.Malas)
{
if (Utility.RandomDouble() < 0.0015)
{
killer.SendLocalizedMessage(1094936); // You have received a Scroll of Transcendence!
ScrollofTranscendence SoTT = CreateRandomSoT(false);
killer.AddToBackpack(SoTT);
}
}
}
#endregion
int mobSubLevel = GetSubLevelFor(m) + 1;
if (mobSubLevel >= 0)
{
bool gainedPath = false;
int pointsToGain = mobSubLevel * 40;
if (VirtueHelper.Award(killer, VirtueName.Valor, pointsToGain, ref gainedPath))
{
if (gainedPath)
m.SendLocalizedMessage(1054032); // You have gained a path in Valor!
else
m.SendLocalizedMessage(1054030); // You have gained in Valor!
//No delay on Valor gains
}
PlayerMobile.ChampionTitleInfo info = ((PlayerMobile)killer).ChampionTitles;
info.Award(m_Type, mobSubLevel);
}
}
}
}
// Only really needed once.
if (m_Kills > kills)
InvalidateProperties();
double n = m_Kills / (double)MaxKills;
int p = (int)(n * 100);
if (p >= 90)
AdvanceLevel();
else if (p > 0)
SetWhiteSkullCount(p / 20);
if (DateTime.Now >= m_ExpireTime)
Expire();
Respawn();
}
}
public void AdvanceLevel()
{
m_ExpireTime = DateTime.Now + m_ExpireDelay;
if (Level < 16)
{
m_Kills = 0;
++Level;
InvalidateProperties();
SetWhiteSkullCount(0);
if (m_Altar != null)
{
Effects.PlaySound(m_Altar.Location, m_Altar.Map, 0x29);
Effects.SendLocationEffect(new Point3D(m_Altar.X + 1, m_Altar.Y + 1, m_Altar.Z), m_Altar.Map, 0x3728, 10);
}
}
else
{
SpawnChampion();
}
}
public void SpawnChampion()
{
if (m_Altar != null)
m_Altar.Hue = 0x26;
if (m_Platform != null)
m_Platform.Hue = 0x452;
m_Kills = 0;
Level = 0;
InvalidateProperties();
SetWhiteSkullCount(0);
try
{
m_Champion = Activator.CreateInstance(ChampionSpawnInfo.GetInfo(m_Type).Champion) as Mobile;
}
catch { }
if (m_Champion != null)
m_Champion.MoveToWorld(new Point3D(X, Y, Z - 15), Map);
}
public void Respawn()
{
if (!m_Active || Deleted || m_Champion != null)
return;
while (m_Creatures.Count < ((m_SPawnSzMod * (200 / 12))) - (GetSubLevel() * (m_SPawnSzMod * (40 / 12))))
{
Mobile m = Spawn();
if (m == null)
return;
Point3D loc = GetSpawnLocation();
// Allow creatures to turn into Paragons at Ilshenar champions.
m.OnBeforeSpawn(loc, Map);
m_Creatures.Add(m);
m.MoveToWorld(loc, Map);
if (m is BaseCreature)
{
BaseCreature bc = m as BaseCreature;
bc.Tamable = false;
if (!m_ConfinedRoaming)
{
bc.Home = this.Location;
bc.RangeHome = (int)(Math.Sqrt(m_SpawnArea.Width * m_SpawnArea.Width + m_SpawnArea.Height * m_SpawnArea.Height) / 2);
}
else
{
bc.Home = bc.Location;
Point2D xWall1 = new Point2D(m_SpawnArea.X, bc.Y);
Point2D xWall2 = new Point2D(m_SpawnArea.X + m_SpawnArea.Width, bc.Y);
Point2D yWall1 = new Point2D(bc.X, m_SpawnArea.Y);
Point2D yWall2 = new Point2D(bc.X, m_SpawnArea.Y + m_SpawnArea.Height);
double minXDist = Math.Min(bc.GetDistanceToSqrt(xWall1), bc.GetDistanceToSqrt(xWall2));
double minYDist = Math.Min(bc.GetDistanceToSqrt(yWall1), bc.GetDistanceToSqrt(yWall2));
bc.RangeHome = (int)Math.Min(minXDist, minYDist);
}
}
}
}
public Point3D GetSpawnLocation()
{
Map map = Map;
if (map == null)
return Location;
// Try 20 times to find a spawnable location.
for (int i = 0; i < 20; i++)
{
/*
int x = Location.X + (Utility.Random( (m_SpawnRange * 2) + 1 ) - m_SpawnRange);
int y = Location.Y + (Utility.Random( (m_SpawnRange * 2) + 1 ) - m_SpawnRange);
*/
int x = Utility.Random(m_SpawnArea.X, m_SpawnArea.Width);
int y = Utility.Random(m_SpawnArea.Y, m_SpawnArea.Height);
int z = Map.GetAverageZ(x, y);
if (Map.CanSpawnMobile(new Point2D(x, y), z))
return new Point3D(x, y, z);
/* try @ platform Z if map z fails */
else if (Map.CanSpawnMobile(new Point2D(x, y), m_Platform.Location.Z))
return new Point3D(x, y, m_Platform.Location.Z);
}
return Location;
}
private const int Level1 = 4; // First spawn level from 0-4 red skulls
private const int Level2 = 8; // Second spawn level from 5-8 red skulls
private const int Level3 = 12; // Third spawn level from 9-12 red skulls
public int GetSubLevel()
{
int level = this.Level;
if (level <= Level1)
return 0;
else if (level <= Level2)
return 1;
else if (level <= Level3)
return 2;
return 3;
}
public int GetSubLevelFor(Mobile m)
{
Type[][] types = ChampionSpawnInfo.GetInfo(m_Type).SpawnTypes;
Type t = m.GetType();
for (int i = 0; i < types.GetLength(0); i++)
{
Type[] individualTypes = types[i];
for (int j = 0; j < individualTypes.Length; j++)
{
if (t == individualTypes[j])
return i;
}
}
return -1;
}
public Mobile Spawn()
{
Type[][] types = ChampionSpawnInfo.GetInfo(m_Type).SpawnTypes;
int v = GetSubLevel();
if (v >= 0 && v < types.Length)
return Spawn(types[v]);
return null;
}
public Mobile Spawn(params Type[] types)
{
try
{
return Activator.CreateInstance(types[Utility.Random(types.Length)]) as Mobile;
}
catch
{
return null;
}
}
public void Expire()
{
m_Kills = 0;
if (m_WhiteSkulls.Count == 0)
{
// They didn't even get 20%, go back a level
if (Level > 0)
--Level;
InvalidateProperties();
}
else
{
SetWhiteSkullCount(0);
}
m_ExpireTime = DateTime.Now + m_ExpireDelay;
}
public Point3D GetRedSkullLocation(int index)
{
int x, y;
if (index < 5)
{
x = index - 2;
y = -2;
}
else if (index < 9)
{
x = 2;
y = index - 6;
}
else if (index < 13)
{
x = 10 - index;
y = 2;
}
else
{
x = -2;
y = 14 - index;
}
return new Point3D(X + x, Y + y, Z - 15);
}
public Point3D GetWhiteSkullLocation(int index)
{
int x, y;
switch (index)
{
default:
case 0: x = -1; y = -1; break;
case 1: x = 1; y = -1; break;
case 2: x = 1; y = 1; break;
case 3: x = -1; y = 1; break;
}
return new Point3D(X + x, Y + y, Z - 15);
}
public override void AddNameProperty(ObjectPropertyList list)
{
list.Add("champion spawn");
}
public override void GetProperties(ObjectPropertyList list)
{
base.GetProperties(list);
if (m_Active)
{
list.Add(1060742); // active
list.Add(1060658, "Type\t{0}", m_Type); // ~1_val~: ~2_val~
list.Add(1060659, "Level\t{0}", Level); // ~1_val~: ~2_val~
list.Add(1060660, "Kills\t{0} of {1} ({2:F1}%)", m_Kills, MaxKills, 100.0 * ((double)m_Kills / MaxKills)); // ~1_val~: ~2_val~
//list.Add( 1060661, "Spawn Range\t{0}", m_SpawnRange ); // ~1_val~: ~2_val~
}
else
{
list.Add(1060743); // inactive
}
}
public override void OnSingleClick(Mobile from)
{
if (m_Active)
LabelTo(from, "{0} (Active; Level: {1}; Kills: {2}/{3})", m_Type, Level, m_Kills, MaxKills);
else
LabelTo(from, "{0} (Inactive)", m_Type);
}
public override void OnDoubleClick(Mobile from)
{
from.SendGump(new PropertiesGump(from, this));
}
public override void OnLocationChange(Point3D oldLoc)
{
if (Deleted)
return;
if (m_Platform != null)
m_Platform.Location = new Point3D(X, Y, Z - 20);
if (m_Altar != null)
m_Altar.Location = new Point3D(X, Y, Z - 15);
if (m_Idol != null)
m_Idol.Location = new Point3D(X, Y, Z - 15);
if (m_RedSkulls != null)
{
for (int i = 0; i < m_RedSkulls.Count; ++i)
m_RedSkulls[i].Location = GetRedSkullLocation(i);
}
if (m_WhiteSkulls != null)
{
for (int i = 0; i < m_WhiteSkulls.Count; ++i)
m_WhiteSkulls[i].Location = GetWhiteSkullLocation(i);
}
m_SpawnArea.X += Location.X - oldLoc.X;
m_SpawnArea.Y += Location.Y - oldLoc.Y;
UpdateRegion();
}
public override void OnMapChange()
{
if (Deleted)
return;
if (m_Platform != null)
m_Platform.Map = Map;
if (m_Altar != null)
m_Altar.Map = Map;
if (m_Idol != null)
m_Idol.Map = Map;
if (m_RedSkulls != null)
{
for (int i = 0; i < m_RedSkulls.Count; ++i)
m_RedSkulls[i].Map = Map;
}
if (m_WhiteSkulls != null)
{
for (int i = 0; i < m_WhiteSkulls.Count; ++i)
m_WhiteSkulls[i].Map = Map;
}
UpdateRegion();
}
public override void OnAfterDelete()
{
base.OnAfterDelete();
if (m_Platform != null)
m_Platform.Delete();
if (m_Altar != null)
m_Altar.Delete();
if (m_Idol != null)
m_Idol.Delete();
if (m_RedSkulls != null)
{
for (int i = 0; i < m_RedSkulls.Count; ++i)
m_RedSkulls[i].Delete();
m_RedSkulls.Clear();
}
if (m_WhiteSkulls != null)
{
for (int i = 0; i < m_WhiteSkulls.Count; ++i)
m_WhiteSkulls[i].Delete();
m_WhiteSkulls.Clear();
}
if (m_Creatures != null)
{
for (int i = 0; i < m_Creatures.Count; ++i)
{
Mobile mob = m_Creatures[i];
if (!mob.Player)
mob.Delete();
}
m_Creatures.Clear();
}
if (m_Champion != null && !m_Champion.Player)
m_Champion.Delete();
Stop();
UpdateRegion();
}
public ChampionSpawn(Serial serial)
: base(serial)
{
}
public virtual void RegisterDamageTo(Mobile m)
{
if (m == null)
return;
foreach (DamageEntry de in m.DamageEntries)
{
if (de.HasExpired)
continue;
Mobile damager = de.Damager;
Mobile master = damager.GetDamageMaster(m);
if (master != null)
damager = master;
RegisterDamage(damager, de.DamageGiven);
}
}
public void RegisterDamage(Mobile from, int amount)
{
if (from == null || !from.Player)
return;
if (m_DamageEntries.ContainsKey(from))
m_DamageEntries[from] += amount;
else
m_DamageEntries.Add(from, amount);
}
public void AwardArtifact(Item artifact)
{
if (artifact == null)
return;
int totalDamage = 0;
Dictionary<Mobile, int> validEntries = new Dictionary<Mobile, int>();
foreach (KeyValuePair<Mobile, int> kvp in m_DamageEntries)
{
if (IsEligible(kvp.Key, artifact))
{
validEntries.Add(kvp.Key, kvp.Value);
totalDamage += kvp.Value;
}
}
int randomDamage = Utility.RandomMinMax(1, totalDamage);
totalDamage = 0;
foreach (KeyValuePair<Mobile, int> kvp in validEntries)
{
totalDamage += kvp.Value;
if (totalDamage >= randomDamage)
{
GiveArtifact(kvp.Key, artifact);
return;
}
}
artifact.Delete();
}
public void GiveArtifact(Mobile to, Item artifact)
{
if (to == null || artifact == null)
return;
Container pack = to.Backpack;
if (pack == null || !pack.TryDropItem(to, artifact, false))
artifact.Delete();
else
to.SendLocalizedMessage(1062317); // For your valor in combating the fallen beast, a special artifact has been bestowed on you.
}
public bool IsEligible(Mobile m, Item Artifact)
{
return m.Player && m.Alive && m.Region != null && m.Region == m_Region && m.Backpack != null && m.Backpack.CheckHold(m, Artifact, false);
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)6); // version
writer.Write((int)m_SPawnSzMod);
writer.Write(m_DamageEntries.Count);
foreach (KeyValuePair<Mobile, int> kvp in m_DamageEntries)
{
writer.Write(kvp.Key);
writer.Write(kvp.Value);
}
writer.Write(m_ConfinedRoaming);
writer.WriteItem<IdolOfTheChampion>(m_Idol);
writer.Write(m_HasBeenAdvanced);
writer.Write(m_SpawnArea);
writer.Write(m_RandomizeType);
// writer.Write( m_SpawnRange );
writer.Write(m_Kills);
writer.Write((bool)m_Active);
writer.Write((int)m_Type);
writer.Write(m_Creatures, true);
writer.Write(m_RedSkulls, true);
writer.Write(m_WhiteSkulls, true);
writer.WriteItem<ChampionPlatform>(m_Platform);
writer.WriteItem<ChampionAltar>(m_Altar);
writer.Write(m_ExpireDelay);
writer.WriteDeltaTime(m_ExpireTime);
writer.Write(m_Champion);
writer.Write(m_RestartDelay);
writer.Write(m_RestartTimer != null);
if (m_RestartTimer != null)
writer.WriteDeltaTime(m_RestartTime);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
m_DamageEntries = new Dictionary<Mobile, int>();
int version = reader.ReadInt();
switch (version)
{
case 6:
{
m_SPawnSzMod = reader.ReadInt();
goto case 5;
}
case 5:
{
int entries = reader.ReadInt();
Mobile m;
int damage;
for (int i = 0; i < entries; ++i)
{
m = reader.ReadMobile();
damage = reader.ReadInt();
if (m == null)
continue;
m_DamageEntries.Add(m, damage);
}
goto case 4;
}
case 4:
{
m_ConfinedRoaming = reader.ReadBool();
m_Idol = reader.ReadItem<IdolOfTheChampion>();
m_HasBeenAdvanced = reader.ReadBool();
goto case 3;
}
case 3:
{
m_SpawnArea = reader.ReadRect2D();
goto case 2;
}
case 2:
{
m_RandomizeType = reader.ReadBool();
goto case 1;
}
case 1:
{
if (version < 3)
{
int oldRange = reader.ReadInt();
m_SpawnArea = new Rectangle2D(new Point2D(X - oldRange, Y - oldRange), new Point2D(X + oldRange, Y + oldRange));
}
m_Kills = reader.ReadInt();
goto case 0;
}
case 0:
{
if (version < 1)
m_SpawnArea = new Rectangle2D(new Point2D(X - 24, Y - 24), new Point2D(X + 24, Y + 24)); //Default was 24
bool active = reader.ReadBool();
m_Type = (ChampionSpawnType)reader.ReadInt();
m_Creatures = reader.ReadStrongMobileList();
m_RedSkulls = reader.ReadStrongItemList();
m_WhiteSkulls = reader.ReadStrongItemList();
m_Platform = reader.ReadItem<ChampionPlatform>();
m_Altar = reader.ReadItem<ChampionAltar>();
m_ExpireDelay = reader.ReadTimeSpan();
m_ExpireTime = reader.ReadDeltaTime();
m_Champion = reader.ReadMobile();
m_RestartDelay = reader.ReadTimeSpan();
if (reader.ReadBool())
{
m_RestartTime = reader.ReadDeltaTime();
BeginRestart(m_RestartTime - DateTime.Now);
}
if (version < 4)
{
m_Idol = new IdolOfTheChampion(this);
m_Idol.MoveToWorld(new Point3D(X, Y, Z - 15), Map);
}
if (m_Platform == null || m_Altar == null || m_Idol == null)
Delete();
else if (active)
Start();
break;
}
}
Timer.DelayCall(TimeSpan.Zero, new TimerCallback(UpdateRegion));
}
}
public class ChampionSpawnRegion : BaseRegion
{
public override bool YoungProtected { get { return false; } }
private ChampionSpawn m_Spawn;
public ChampionSpawn ChampionSpawn
{
get { return m_Spawn; }
}
public ChampionSpawnRegion(ChampionSpawn spawn)
: base(null, spawn.Map, Region.Find(spawn.Location, spawn.Map), spawn.SpawnArea)
{
m_Spawn = spawn;
}
public override bool AllowHousing(Mobile from, Point3D p)
{
return false;
}
public override void AlterLightLevel(Mobile m, ref int global, ref int personal)
{
base.AlterLightLevel(m, ref global, ref personal);
global = Math.Max(global, 1 + m_Spawn.Level); //This is a guesstimate. TODO: Verify & get exact values // OSI testing: at 2 red skulls, light = 0x3 ; 1 red = 0x3.; 3 = 8; 9 = 0xD 8 = 0xD 12 = 0x12 10 = 0xD
}
}
public class IdolOfTheChampion : Item
{
private ChampionSpawn m_Spawn;
public ChampionSpawn Spawn { get { return m_Spawn; } }
public override string DefaultName
{
get { return "Idol of the Champion"; }
}
public IdolOfTheChampion(ChampionSpawn spawn)
: base(0x1F18)
{
m_Spawn = spawn;
Movable = false;
}
public override void OnAfterDelete()
{
base.OnAfterDelete();
if (m_Spawn != null)
m_Spawn.Delete();
}
public IdolOfTheChampion(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
writer.Write(m_Spawn);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 0:
{
m_Spawn = reader.ReadItem() as ChampionSpawn;
if (m_Spawn == null)
Delete();
break;
}
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
/// <summary>
/// This example analysis shows how to use the value abstraction provided by the CodeAnalysis infrastructure to
/// perform an analysis without having to concern yourself with the intricacies of the MSIL memory model.
/// At this level, almost all instructions are turned into assumptions that are there for informational purposes.
/// Branches are not visible, instead Assume statements are visited that constrain the branch condition.
///
/// At edges leading to join points, actual assignments are present as parallel assignments. These are the only state changing
/// operations from the value analysis point of view.
///
/// This example analysis computes symbolic upper bounds for values to try to discharge the upper bound limit proof obligation
/// in array accesses. As our abstract domain, we use an EnvironmentDomain mapping Symbolic variables to a set of Symbolic variables representing
/// upper bounds. The meaning is that if sv -> SV, then sv is less than all sv' in SV.
///
/// This outermost class should be non-generic and implement the interface IValueAnalysis<AState> to obtain an instance of the analysis.
/// </summary>
public class SimpleBoundsAnalysis
{
public static void Analyze<Label, Local, Parameter, Method, Field, Type, Expression, Variable>(
IMethodDriver<Label, Local, Parameter, Method, Field, Type, Expression, Variable> driver,
bool doDebug
)
where Variable : IEquatable<Variable>
{
TypeBindings<Label, Local, Parameter, Method, Field, Type, Expression, Variable>.Analysis analysis =
new TypeBindings<Label, Local, Parameter, Method, Field, Type, Expression, Variable>.Analysis(driver.MetaDataDecoder);
analysis.Debug = doDebug;
driver.CreateForward(analysis, doDebug)(analysis.InitialValue(driver.KeyNumber));
}
/// <summary>
/// We should write our analyses to be generic over the underlying representation of code. This nested static class
/// simply binds the type parameters common to all interior classes.
/// </summary>
static class TypeBindings<Label, Local, Parameter, Method, Field, Type, Expression, Variable>
where Variable : IEquatable<Variable>
{
/// <summary>
/// Defines the type of abstract state we work over. We use a struct wrapper here to abbreviate the underlying type instance
///
/// [sv -> SV] means sv is strictly less numerically than sv' for all sv' in SV
/// </summary>
public struct Domain
{
public readonly EnvironmentDomain<Variable, SetDomain<Variable>> Value;
public Domain(EnvironmentDomain<Variable, SetDomain<Variable>> value)
{
this.Value = value;
}
}
/// <summary>
/// To be a client of a value analysis, implement the IValueAnalysis interface.
/// We do this here in a nested class instead of the top-level class to take advantage of name abbreviations and to not
/// expose things at the higher level.
///
/// We inherit the MSILVisitor class to get a default visitor for MSIL where we can just override the few instructions
/// that we find interesting.
/// </summary>
public class Analysis : MSILVisitor<Label, Local, Parameter, Method, Field, Type, Variable, Variable, Domain, Domain>,
IValueAnalysis<Label, Domain, IVisitMSIL<Label, Local, Parameter, Method, Field, Type, Variable, Variable, Domain, Domain>,
Variable,
IExpressionContext<Label, Local, Parameter, Method, Type, Expression, Variable>>
{
#region Privates
/// <summary>
/// Here we hold the state lookup functions for future reference.
/// </summary>
StateLookup<Label, Domain> preStateLookup;
StateLookup<Label, Domain> postStateLookup;
/// <summary>
/// Context we got from the upcall to Visitor. This lets us find out things about Variables and Expressions
/// </summary>
IExpressionContext<Label, Local, Parameter, Method, Type, Expression, Variable> context;
/// <summary>
/// An analysis likely needs access to a meta data decoder to make sense of types etc.
/// </summary>
IDecodeMetaData<Local, Parameter, Method, Field, Type> mdDecoder;
#endregion
public bool Debug = false;
public Analysis(IDecodeMetaData<Local, Parameter, Method, Field, Type> mdDecoder)
{
this.mdDecoder = mdDecoder;
}
public Domain InitialValue(Converter<Variable, int> keyNumber)
{
return new Domain(EnvironmentDomain<Variable, SetDomain<Variable>>.TopValue(keyNumber));
}
#region IValueAnalysis<Label,Domain,IVisitMSIL<Label,Local,Parameter,Method,Field,Type,Expression,Variable,Domain,Domain>,Variable,Expression,IExpressionContext<Label,Method,Type,Expression,Variable>> Members
/// <summary>
/// Here, we return the transfer function. Since we implement this via MSILVisitor, we just return this.
///
/// </summary>
/// <param name="context">The expression context is an interface we can use to find out more about expressions, such as their type etc.</param>
/// <returns>The transfer function.</returns>
public IVisitMSIL<Label, Local, Parameter, Method, Field, Type, Variable, Variable, Domain, Domain> Visitor(IExpressionContext<Label, Local, Parameter, Method, Type, Expression, Variable> context)
{
// store away the context for future reference
this.context = context;
return this;
}
/// <summary>
/// Must implement the join/widen operation
/// </summary>
/// <param name="edge"></param>
/// <param name="newState"></param>
/// <param name="prevState"></param>
/// <param name="weaker">should return false if result is less than or equal prevState.</param>
/// <param name="widen">true if this is a widen operation. For our domain, this makes no difference</param>
public Domain Join(DataStructures.Pair<Label, Label> edge, Domain newState, Domain prevState, out bool weaker, bool widen)
{
return new Domain(prevState.Value.Join(newState.Value, out weaker, widen));
}
public bool IsBottom(Domain state)
{
return state.Value.IsBottom;
}
public Domain ImmutableVersion(Domain state)
{
// our domain is pure
return state;
}
public Domain MutableVersion(Domain state)
{
// our domain is pure
return state;
}
public void Dump(Pair<Domain, System.IO.TextWriter> stateAndWriter)
{
stateAndWriter.One.Value.Dump(stateAndWriter.Two);
}
/// <summary>
/// Here's where the actual work is. We get passed a list of pairs (source,targets) representing
/// the assignments t = source for each t in targets.
///
/// For our domain, we thus add new mappings for all targets by looking up the bounds of the source and map the source bounds to new target bounds.
/// </summary>
public Domain ParallelAssign(Pair<Label, Label> edge, IFunctionalMap<Variable, FList<Variable>> sourceTargetMap, Domain state)
{
EnvironmentDomain<Variable, SetDomain<Variable>> originalState = state.Value;
EnvironmentDomain<Variable, SetDomain<Variable>> newState = originalState;
foreach (Variable source in sourceTargetMap.Keys) {
FList<Variable> targets = sourceTargetMap[source];
// 1) for each target in this assignment, assign it the same bounds as source.
// 2) since we also have to map the source bounds, we assign it actually the union of all targets of all bounds of the source.
SetDomain<Variable> targetBounds = SetDomain<Variable>.TopValue;
if (originalState.Contains(source)) {
SetDomain<Variable> originalBounds = originalState[source];
foreach (Variable origBound in originalBounds.Elements) {
FList<Variable> targetBoundNames = sourceTargetMap[origBound];
while (targetBoundNames != null) {
targetBounds = targetBounds.Add(targetBoundNames.Head);
targetBoundNames = targetBoundNames.Tail;
}
}
}
if (targetBounds.IsTop) {
// have no bounds, so havoc all targets
while (targets != null) {
newState = newState.Remove(targets.Head);
targets = targets.Tail;
}
}
else {
while (targets != null) {
newState = newState.Add(targets.Head, targetBounds);
targets = targets.Tail;
}
}
}
return new Domain(newState);
}
/// <summary>
/// This method is called by the underlying driver of the fixpoint computation. It provides delegates for future lookup
/// of the abstract state at given pcs.
/// </summary>
/// <returns>Return true only if you want the fixpoint computation to eagerly cache each pc state.</returns>
public bool CacheStates(StateLookup<Label, Domain> preState, StateLookup<Label, Domain> postState)
{
this.preStateLookup = preState;
this.postStateLookup = postState;
return false;
}
#endregion
/// <summary>
/// Our default transfer function is do nothing.
/// </summary>
protected override Domain Default(Label pc, Domain data)
{
return data;
}
/// <summary>
/// The only other interesting case is when we have a constraining assumption.
/// </summary>
public override Domain Assume(Label pc, string tag, Variable source, Domain data)
{
// refine source boolean to an expression
Expression exp = this.context.Refine(pc, source);
switch (tag) {
case "true":
return this.context.Decode<Pair<bool, Domain>, Domain, ExpressionAssumeDecoder>(exp, new ExpressionAssumeDecoder(this.context), new Pair<bool, Domain>(true, data));
case "false":
return this.context.Decode<Pair<bool, Domain>, Domain, ExpressionAssumeDecoder>(exp, new ExpressionAssumeDecoder(this.context), new Pair<bool, Domain>(false, data));
default:
// no refinement
return data;
}
}
/// <summary>
/// Here's one place where we want to check the bound. In principle, we want to only record the position and relevant
/// parameters for a proof obligation and check it only after the fixpoint is computed.
/// I'm lazy and checking it right away.
/// </summary>
public override Domain Ldelem(Label pc, Type type, Variable dest, Variable array, Variable index, Domain data)
{
if (data.Value.Contains(index)) {
SetDomain<Variable> bounds = data.Value[index];
// lookup upper bound of index and array bound
Variable bound;
if (this.context.TryGetArrayLength(pc, array, out bound)) {
if (Debug) {
Console.WriteLine("bound for array {0} is {1}", array.ToString(), bound.ToString());
}
// check that bound is in bounds of index
if (!bounds.Contains(bound)) {
Console.WriteLine("{0}: WARNING: Can't prove that array index is okay", this.context.SourceContext(pc));
}
else {
Console.WriteLine("{0}: INFO: Array index looks good.", this.context.SourceContext(pc));
}
}
else {
Console.WriteLine("{0}: WARNING: Can't prove that array index is okay", this.context.SourceContext(pc));
}
}
else {
Console.WriteLine("{0}: WARNING: Can't prove that array index is okay", this.context.SourceContext(pc));
}
// TODO: might want to constrain index by bound of array to eliminate subsequent errors
return data;
}
/// <summary>
/// Given an expression in an assume, this decoder tries to find if it is a less-than constraint and transforms the
/// state accordingly.
/// </summary>
struct ExpressionAssumeDecoder : IVisitValueExprIL<Expression, Type, Expression, Variable, Pair<bool, Domain>, Domain>
{
IExpressionContext<Label, Local, Parameter, Method, Type, Expression, Variable> context;
public ExpressionAssumeDecoder(IExpressionContext<Label, Local, Parameter, Method, Type, Expression, Variable> context)
{
this.context = context;
}
/// <summary>
/// Here we actually add constraints to our state.
/// </summary>
private Domain ConstrainLessThan(Expression var, Expression bound, Domain domain)
{
// First, skip unary coercions on var and bound
SkipConversionDecoder skipper = new SkipConversionDecoder();
var = this.context.Decode<Unit,Expression,SkipConversionDecoder>(var, skipper, Unit.Value);
bound = this.context.Decode<Unit,Expression,SkipConversionDecoder>(bound, skipper, Unit.Value);
Variable left = this.context.Unrefine(var);
Variable right = this.context.Unrefine(bound);
// add the bound to the set of bounds known
SetDomain<Variable> currentBounds =
(domain.Value.Contains(left)) ? domain.Value[left] : SetDomain<Variable>.TopValue;
return new Domain(domain.Value.Add(left, currentBounds.Add(right)));
}
#region IVisitValueExprIL<Label,Type,Expression,Variable,CheckPointClosure<bool,Domain>,Domain> Members
public Domain Binary(Expression orig, BinaryOperator op, Variable dest, Expression s1, Expression s2, Pair<bool, Domain> data)
{
switch (op) {
case BinaryOperator.Cgt:
case BinaryOperator.Cgt_Un:
// s1 is a bound on s2 provided data.One is true, otherwise we don't have a strict inclusion.
if (data.One) {
return ConstrainLessThan(s2, s1, data.Two);
}
return data.Two; // no constraint
case BinaryOperator.Clt:
case BinaryOperator.Clt_Un:
// s2 is a bound on s1, provided that data.One is true, otherwise no strict inclusion
if (data.One) {
return ConstrainLessThan(s1, s2, data.Two);
}
return data.Two; // no constraint
default:
// no info
return data.Two;
}
}
public Domain Isinst(Expression orig, Type type, Variable dest, Expression obj, Pair<bool, Domain> data)
{
// no info
return data.Two;
}
public Domain Ldconst(Expression orig, object constant, Type type, Variable dest, Pair<bool, Domain> data)
{
// no info
return data.Two;
}
public Domain Ldnull(Expression orig, Variable dest, Pair<bool, Domain> data)
{
// no info
return data.Two;
}
public Domain Sizeof(Expression orig, Type type, Variable dest, Pair<bool, Domain> data)
{
// no info
return data.Two;
}
public Domain Unary(Expression orig, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, Pair<bool, Domain> data)
{
switch (op) {
// ignore all coercions
case UnaryOperator.Conv_i:
case UnaryOperator.Conv_i1:
case UnaryOperator.Conv_i2:
case UnaryOperator.Conv_i4:
case UnaryOperator.Conv_i8:
case UnaryOperator.Conv_u:
case UnaryOperator.Conv_u1:
case UnaryOperator.Conv_u2:
case UnaryOperator.Conv_u4:
case UnaryOperator.Conv_u8:
// recurse
return this.context.Decode<Pair<bool, Domain>, Domain, ExpressionAssumeDecoder>(source, this, data);
case UnaryOperator.Neg:
case UnaryOperator.Not:
// recurse but flip context truthiness
return this.context.Decode<Pair<bool, Domain>, Domain, ExpressionAssumeDecoder>(source, this, new Pair<bool, Domain>(!data.One, data.Two));
default:
// extracting no info
return data.Two;
}
}
public Domain SymbolicConstant(Expression orig, Variable symbol, Pair<bool, Domain> data)
{
// no more refined info
return data.Two;
}
#endregion
}
/// <summary>
/// Skips any Unary conversion operators and returns the underlying value, e.g. [conv_u4 exp], returns [exp]
/// </summary>
struct SkipConversionDecoder : IVisitValueExprIL<Expression, Type, Expression, Variable, Unit, Expression>
{
#region IVisitValueExprIL<Expression,Type,Expression,Variable,Unit,Expression> Members
public Expression SymbolicConstant(Expression orig, Variable symbol, Unit data)
{
// nothing to skip
return orig;
}
public Expression Binary(Expression orig, BinaryOperator op, Variable dest, Expression s1, Expression s2, Unit data)
{
// nothing to skip
return orig;
}
public Expression Isinst(Expression orig, Type type, Variable dest, Expression obj, Unit data)
{
// nothing to skip
return orig;
}
public Expression Ldconst(Expression orig, object constant, Type type, Variable dest, Unit data)
{
// nothing to skip
return orig;
}
public Expression Ldnull(Expression orig, Variable dest, Unit data)
{
// nothing to skip
return orig;
}
public Expression Sizeof(Expression orig, Type type, Variable dest, Unit data)
{
// nothing to skip
return orig;
}
public Expression Unary(Expression orig, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Expression source, Unit data)
{
switch (op) {
// ignore all coercions
case UnaryOperator.Conv_i:
case UnaryOperator.Conv_i1:
case UnaryOperator.Conv_i2:
case UnaryOperator.Conv_i4:
case UnaryOperator.Conv_i8:
case UnaryOperator.Conv_u:
case UnaryOperator.Conv_u1:
case UnaryOperator.Conv_u2:
case UnaryOperator.Conv_u4:
case UnaryOperator.Conv_u8:
return source; // should we recurse here?
default:
return orig;
}
}
#endregion
}
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using log4net.Core;
using log4net.Util;
namespace Umbraco.Core.Logging
{
/// <summary>
/// An asynchronous appender based on <see cref="BlockingCollection{T}"/>
/// </summary>
/// <remarks>
/// Based on https://github.com/cjbhaines/Log4Net.Async
/// </remarks>
public class ParallelForwardingAppender : AsyncForwardingAppenderBase, IDisposable
{
#region Private Members
private const int DefaultBufferSize = 1000;
private BlockingCollection<LoggingEventContext> _loggingEvents;
private CancellationTokenSource _loggingCancelationTokenSource;
private CancellationToken _loggingCancelationToken;
private Task _loggingTask;
private Double _shutdownFlushTimeout = 5;
private TimeSpan _shutdownFlushTimespan = TimeSpan.FromSeconds(5);
private static readonly Type ThisType = typeof(ParallelForwardingAppender);
private volatile bool _shutDownRequested;
private int? _bufferSize = DefaultBufferSize;
#endregion Private Members
#region Properties
/// <summary>
/// Gets or sets the number of LoggingEvents that will be buffered. Set to null for unlimited.
/// </summary>
public override int? BufferSize
{
get { return _bufferSize; }
set { _bufferSize = value; }
}
public int BufferEntryCount
{
get
{
if (_loggingEvents == null) return 0;
return _loggingEvents.Count;
}
}
/// <summary>
/// Gets or sets the time period in which the system will wait for appenders to flush before canceling the background task.
/// </summary>
public Double ShutdownFlushTimeout
{
get
{
return _shutdownFlushTimeout;
}
set
{
_shutdownFlushTimeout = value;
}
}
protected override string InternalLoggerName
{
get { return "ParallelForwardingAppender"; }
}
#endregion Properties
#region Startup
public override void ActivateOptions()
{
base.ActivateOptions();
_shutdownFlushTimespan = TimeSpan.FromSeconds(_shutdownFlushTimeout);
StartForwarding();
}
private void StartForwarding()
{
if (_shutDownRequested)
{
return;
}
//Create a collection which will block the thread and wait for new entries
//if the collection is empty
if (BufferSize.HasValue && BufferSize > 0)
{
_loggingEvents = new BlockingCollection<LoggingEventContext>(BufferSize.Value);
}
else
{
//No limit on the number of events.
_loggingEvents = new BlockingCollection<LoggingEventContext>();
}
//The cancellation token is used to cancel a running task gracefully.
_loggingCancelationTokenSource = new CancellationTokenSource();
_loggingCancelationToken = _loggingCancelationTokenSource.Token;
_loggingTask = new Task(SubscriberLoop, _loggingCancelationToken);
_loggingTask.Start();
}
#endregion Startup
#region Shutdown
private void CompleteSubscriberTask()
{
_shutDownRequested = true;
if (_loggingEvents == null || _loggingEvents.IsAddingCompleted)
{
return;
}
//Don't allow more entries to be added.
_loggingEvents.CompleteAdding();
//Allow some time to flush
Thread.Sleep(_shutdownFlushTimespan);
if (!_loggingTask.IsCompleted && !_loggingCancelationToken.IsCancellationRequested)
{
_loggingCancelationTokenSource.Cancel();
//Wait here so that the error logging messages do not get into a random order.
//Don't pass the cancellation token because we are not interested
//in catching the OperationCanceledException that results.
_loggingTask.Wait();
}
if (!_loggingEvents.IsCompleted)
{
ForwardInternalError("The buffer was not able to be flushed before timeout occurred.", null, ThisType);
}
}
protected override void OnClose()
{
CompleteSubscriberTask();
base.OnClose();
}
#endregion Shutdown
#region Appending
protected override void Append(LoggingEvent loggingEvent)
{
if (_loggingEvents == null || _loggingEvents.IsAddingCompleted || loggingEvent == null)
{
return;
}
loggingEvent.Fix = Fix;
//In the case where blocking on a full collection, and the task is subsequently completed, the cancellation token
//will prevent the entry from attempting to add to the completed collection which would result in an exception.
_loggingEvents.Add(new LoggingEventContext(loggingEvent), _loggingCancelationToken);
}
protected override void Append(LoggingEvent[] loggingEvents)
{
if (_loggingEvents == null || _loggingEvents.IsAddingCompleted || loggingEvents == null)
{
return;
}
foreach (var loggingEvent in loggingEvents)
{
Append(loggingEvent);
}
}
#endregion Appending
#region Forwarding
/// <summary>
/// Iterates over a BlockingCollection containing LoggingEvents.
/// </summary>
private void SubscriberLoop()
{
Thread.CurrentThread.Name = String.Format("{0} ParallelForwardingAppender Subscriber Task", Name);
//The task will continue in a blocking loop until
//the queue is marked as adding completed, or the task is canceled.
try
{
//This call blocks until an item is available or until adding is completed
foreach (var entry in _loggingEvents.GetConsumingEnumerable(_loggingCancelationToken))
{
ForwardLoggingEvent(entry.LoggingEvent, ThisType);
}
}
catch (OperationCanceledException ex)
{
//The thread was canceled before all entries could be forwarded and the collection completed.
ForwardInternalError("Subscriber task was canceled before completion.", ex, ThisType);
//Cancellation is called in the CompleteSubscriberTask so don't call that again.
}
catch (ThreadAbortException ex)
{
//Thread abort may occur on domain unload.
ForwardInternalError("Subscriber task was aborted.", ex, ThisType);
//Cannot recover from a thread abort so complete the task.
CompleteSubscriberTask();
//The exception is swallowed because we don't want the client application
//to halt due to a logging issue.
}
catch (Exception ex)
{
//On exception, try to log the exception
ForwardInternalError("Subscriber task error in forwarding loop.", ex, ThisType);
//Any error in the loop is going to be some sort of extenuating circumstance from which we
//probably cannot recover anyway. Complete subscribing.
CompleteSubscriberTask();
}
}
#endregion Forwarding
#region IDisposable Implementation
private bool _disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_loggingTask != null)
{
if (!(_loggingTask.IsCanceled || _loggingTask.IsCompleted || _loggingTask.IsFaulted))
{
try
{
CompleteSubscriberTask();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Completing Subscriber Task in Dispose Method", ex);
}
}
try
{
_loggingTask.Dispose();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Disposing Logging Task", ex);
}
finally
{
_loggingTask = null;
}
}
if (_loggingEvents != null)
{
try
{
_loggingEvents.Dispose();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Disposing BlockingCollection", ex);
}
finally
{
_loggingEvents = null;
}
}
if (_loggingCancelationTokenSource != null)
{
try
{
_loggingCancelationTokenSource.Dispose();
}
catch (Exception ex)
{
LogLog.Error(ThisType, "Exception Disposing CancellationTokenSource", ex);
}
finally
{
_loggingCancelationTokenSource = null;
}
}
}
_disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~ParallelForwardingAppender()
{
// Simply call Dispose(false).
Dispose(false);
}
#endregion IDisposable Implementation
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using DotSpatial.Data;
using DotSpatial.Projections;
using DotSpatial.Serialization;
using NetTopologySuite.Geometries;
namespace DotSpatial.Symbology
{
/// <summary>
/// Base class for different layers.
/// </summary>
[ToolboxItem(false)]
public class Layer : RenderableLegendItem, ILayer
{
#region Fields
private IDataSet _dataSet;
private int _disposeLockCount;
private Extent _invalidatedRegion; // When a region is invalidated instead of the whole layer.
private IProgressHandler _progressHandler;
private ProgressMeter _progressMeter;
private ProjectionInfo _projection;
private string _projectionString;
private IPropertyDialogProvider _propertyDialogProvider;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Layer"/> class.
/// </summary>
protected Layer()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="Layer"/> class.
/// </summary>
/// <param name="container">The container this layer should be a member of.</param>
protected Layer(ICollection<ILayer> container)
{
container?.Add(this);
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="Layer"/> class.
/// </summary>
/// <param name="progressHandler">The progress handler.</param>
protected Layer(IProgressHandler progressHandler)
{
_progressHandler = progressHandler;
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="Layer"/> class.
/// </summary>
/// <param name="container">The container this layer should be a member of.</param>
/// <param name="progressHandler">A progress handler for handling progress messages.</param>
protected Layer(ICollection<ILayer> container, IProgressHandler progressHandler)
{
_progressHandler = progressHandler;
container?.Add(this);
Configure();
}
/// <summary>
/// Finalizes an instance of the <see cref="Layer"/> class.
/// </summary>
~Layer()
{
Dispose(false);
}
#endregion
#region Events
/// <summary>
/// Occurs when layer disposed.
/// </summary>
public event EventHandler Disposed;
/// <summary>
/// Occurs when all aspects of the layer finish loading.
/// </summary>
public event EventHandler FinishedLoading;
/// <summary>
/// Occurs if this layer was selected
/// </summary>
public event EventHandler<LayerSelectedEventArgs> LayerSelected;
/// <summary>
/// Occurs after the selection is changed
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Occurs before the properties are actually shown, also allowing the event to be handled.
/// </summary>
public event HandledEventHandler ShowProperties;
/// <summary>
/// Occurs if the maps should zoom to this layer.
/// </summary>
public event EventHandler<EnvelopeArgs> ZoomToLayer;
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether this layer can be reprojected.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool CanReproject => DataSet != null && DataSet.CanReproject;
/// <summary>
/// Gets or sets the internal data set. This can be null, as in the cases of groups or map-frames.
/// Copying a layer should not create a duplicate of the dataset, but rather it should point to the
/// original dataset. The ShallowCopy attribute is used so even though the DataSet itself may be cloneable,
/// cloning a layer will treat the dataset like a shallow copy.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[ShallowCopy]
public IDataSet DataSet
{
get
{
return _dataSet;
}
set
{
if (_dataSet == value) return;
if (_dataSet != null)
{
_dataSet.UnlockDispose();
if (!_dataSet.IsDisposeLocked)
{
_dataSet.Dispose();
}
}
_dataSet = value;
_dataSet?.LockDispose();
}
}
/// <summary>
/// Gets or sets whether the layer is visible when zoomed in closer than the dynamic
/// visibility width or only when further away from the dynamic visibility width.
/// </summary>
[Serialize("DynamicVisibilityMode")]
[Category("Behavior")]
[Description("This controls whether the layer is visible when zoomed in closer than the dynamic visiblity width or only when further away from the dynamic visibility width")]
public DynamicVisibilityMode DynamicVisibilityMode { get; set; }
/// <summary>
/// Gets or sets the geographic width in which dynamic visibility is active.
/// </summary>
[Serialize("DynamicVisibilityWidth")]
[Category("Behavior")]
[Description("Dynamic visibility represents layers that only appear when the zoom scale is closer (or further) from a set scale. This value represents the geographic width where the change takes place.")]
public double DynamicVisibilityWidth { get; set; }
/// <summary>
/// Gets or sets the currently invalidated region.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Extent InvalidRegion
{
get
{
return _invalidatedRegion;
}
protected set
{
_invalidatedRegion = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the memory objects have already been disposed of.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDisposed { get; set; }
/// <summary>
/// Gets a value indicating whether an existing reference is requesting that the object is not disposed of.
/// Automatic disposal, as is the case when a layer is removed from the map, will not take place until
/// all the locks on dispose have been removed.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDisposeLocked => _disposeLockCount > 0;
/// <inheritdoc />
[Category("Behavior")]
[Description("Gets or sets a boolean indicating whether this layer is selected in the legend.")]
public override bool IsSelected
{
get
{
return base.IsSelected;
}
set
{
if (base.IsSelected != value)
{
base.IsSelected = value;
OnLayerSelected(this, value);
}
}
}
/// <inheritdoc />
[Serialize("IsVisible")]
[Category("Behavior")]
[Description("Gets or sets a boolean indicating whether this layer is visible in the map.")]
public override bool IsVisible
{
get
{
return base.IsVisible;
}
set
{
base.IsVisible = value;
}
}
/// <summary>
/// Gets or sets custom actions for Layer.
/// </summary>
[Browsable(false)]
public ILayerActions LayerActions { get; set; }
/// <summary>
/// Gets or sets the map frame of the parent LayerCollection.
/// </summary>
[Browsable(false)]
[ShallowCopy]
public virtual IFrame MapFrame { get; set; }
/// <summary>
/// Gets or sets the ProgressHandler for this layer. Setting this overrides the default
/// behavior which is to use the ProgressHandler of the DefaultDataManager.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IProgressHandler ProgressHandler
{
get
{
if (_progressHandler != null) return _progressHandler;
return DataManager.DefaultDataManager.ProgressHandler;
}
set
{
_progressHandler = value;
if (_progressMeter == null) _progressMeter = new ProgressMeter(_progressHandler);
_progressMeter.ProgressHandler = value;
}
}
/// <summary>
/// Gets or sets the projection information for the dataset of this layer.
/// This only defines the projection information and does not reproject the dataset or the layer.
/// </summary>
[Category("DataSet Properties")]
[Description("The geographic projection that this raster is using.")]
public ProjectionInfo Projection
{
get
{
if (DataSet != null) return DataSet.Projection;
return _projection;
}
set
{
var current = Projection;
if (current == value) return;
if (DataSet != null)
{
DataSet.Projection = value;
}
_projection = value;
}
}
/// <summary>
/// Gets or sets the unmodified projection string that can be used regardless of whether the
/// DotSpatial.Projection module is available. This string can be in the Proj4string or in the
/// EsriString format. Setting the Projection string only defines projection information.
/// Call the Reproject() method to actually reproject the dataset and layer.
/// </summary>
[Category("DataSet Properties")]
[Description("The geographic projection that this raster is using.")]
public string ProjectionString
{
get
{
if (DataSet != null) return DataSet.ProjectionString;
return _projectionString;
}
set
{
var current = ProjectionString;
if (current == value) return;
if (DataSet != null)
{
DataSet.ProjectionString = value;
}
_projectionString = value;
var test = ProjectionInfo.FromProj4String(value);
if (!test.IsValid)
{
test.TryParseEsriString(value);
}
if (test.IsValid) Projection = test;
}
}
/// <summary>
/// Gets or sets the PropertyDialogProvider. Layers launch a "Property Grid" by default. However, this can be overridden with a different UIEditor by this.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IPropertyDialogProvider PropertyDialogProvider
{
get
{
return _propertyDialogProvider;
}
protected set
{
if (_propertyDialogProvider != null)
{
_propertyDialogProvider.ChangesApplied -= PropertyDialogProviderChangesApplied;
}
_propertyDialogProvider = value;
if (_propertyDialogProvider != null)
{
ContextMenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.Layer_Properties, ShowPropertiesClick));
_propertyDialogProvider.ChangesApplied += PropertyDialogProviderChangesApplied;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether or not items from the layer can be selected.
/// </summary>
[Serialize("SelectionEnabled")]
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool SelectionEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to allow the dynamic visibility envelope to control visibility.
/// </summary>
[Serialize("UseDynamicVisibility")]
[Category("Behavior")]
[Description("Gets or sets a boolean indicating whether to allow the dynamic visibility envelope to control visibility.")]
public bool UseDynamicVisibility { get; set; }
/// <summary>
/// Gets or sets the progress meter being used internally by layer classes.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
protected ProgressMeter ProgressMeter
{
get
{
return _progressMeter ?? (_progressMeter = new ProgressMeter(ProgressHandler));
}
set
{
_progressMeter = value;
}
}
#endregion
#region Methods
/// <summary>
/// Opens a fileName using the default layer provider and returns a new layer. The layer will not automatically have a container or be added to a map.
/// </summary>
/// <param name="fileName">The string fileName of the layer to open.</param>
/// <returns>An ILayer interface.</returns>
public static ILayer OpenFile(string fileName)
{
if (File.Exists(fileName) == false) return null;
return LayerManager.DefaultLayerManager.OpenLayer(fileName);
}
/// <summary>
/// Opens a fileName using the default layer provider and returns a new layer. The layer will not automatically have a container or be added to a map.
/// </summary>
/// <param name="fileName">The string fileName of the layer to open.</param>
/// <param name="progressHandler">An IProgresshandler that overrides the Default Layer Manager's progress handler.</param>
/// <returns>An ILayer interface with the new layer.</returns>
public static ILayer OpenFile(string fileName, IProgressHandler progressHandler)
{
return File.Exists(fileName) == false ? null : LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler);
}
/// <summary>
/// Opens a new layer and automatically adds it to the specified container.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="container">The container (usually a LayerCollection) to add to.</param>
/// <returns>The layer after it has been created and added to the container.</returns>
public static ILayer OpenFile(string fileName, ICollection<ILayer> container)
{
if (!File.Exists(fileName)) return null;
var dm = LayerManager.DefaultLayerManager;
return dm.OpenLayer(fileName, container);
}
/// <summary>
/// Tests the specified legend item. If the item is another layer or a group or a map-frame, then this
/// will return false. Furthermore, if the parent of the item is not also this object, then it will
/// also return false. The idea is that layers can have sub-nodes move around, but not transport from
/// place to place.
/// </summary>
/// <param name="item">the legend item to test.</param>
/// <returns>Boolean that if true means that it is ok to insert the specified item into this layer.</returns>
public override bool CanReceiveItem(ILegendItem item)
{
if (item.GetParentItem() != this) return false;
var lyr = item as ILayer;
return lyr == null;
}
/// <summary>
/// This is overriden in sub-classes.
/// </summary>
/// <param name="affectedArea">The area affecting by the clearing.</param>
/// <param name="force">Indicates whether the selection should be cleared although SelectionEnabled is false.</param>
/// <returns>False.</returns>
public virtual bool ClearSelection(out Envelope affectedArea, bool force = false)
{
affectedArea = null;
return false;
}
/// <summary>
/// Disposes the memory objects in this layer.
/// </summary>
public void Dispose()
{
// This is a new feature, so may be buggy if someone is calling dispose without checking the lock.
// This will help find those spots in debug mode but will cross fingers and hope for the best
// in release mode rather than throwing an exception.
Debug.Assert(IsDisposeLocked == false, "IsDisposeLocked == false");
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Notifies the layer that the next time an area that intersects with this region
/// is specified, it must first re-draw content to the image buffer.
/// </summary>
/// <param name="region">The envelope where content has become invalidated.</param>
public virtual void Invalidate(Extent region)
{
if (_invalidatedRegion != null)
{
// This is set to null when we do the redrawing, so we would rather expand
// the redraw region than forget to update a modified area.
_invalidatedRegion.ExpandToInclude(region);
}
else
{
_invalidatedRegion = region;
}
}
/// <summary>
/// Notifies parent layer that this item is invalid and should be redrawn.
/// </summary>
public override void Invalidate()
{
OnItemChanged(this);
}
/// <summary>
/// This is overriden in sub-classes.
/// </summary>
/// <param name="tolerant">The geographic envelope in cases like cliking near points where tolerance is allowed.</param>
/// <param name="strict">The geographic region when working with absolutes, without a tolerance.</param>
/// <param name="mode">The selection mode.</param>
/// <param name="affectedArea">The affected area.</param>
/// <returns>False.</returns>
public virtual bool InvertSelection(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = null;
return false;
}
/// <summary>
/// Locks dispose. This typically adds one instance of an internal reference counter.
/// </summary>
public void LockDispose()
{
_disposeLockCount++;
}
/// <summary>
/// Attempts to call the open fileName method for any ILayerProvider plugin
/// that matches the extension on the string.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this LayerManager.</param>
/// <param name="container">A container to open this layer in.</param>
/// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this LayerManager.</param>
/// <returns>An ILayer.</returns>
public virtual ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler)
{
if (File.Exists(fileName) == false) return null;
var dm = LayerManager.DefaultLayerManager;
return dm.OpenLayer(fileName, inRam, container, progressHandler);
}
/// <summary>
/// Reprojects the dataset for this layer.
/// </summary>
/// <param name="targetProjection">The target projection to use.</param>
public virtual void Reproject(ProjectionInfo targetProjection)
{
if (DataSet != null)
{
ProgressHandler?.Progress(0, "Reprojecting Layer " + LegendText);
DataSet.Reproject(targetProjection);
ProgressHandler?.Reset();
}
}
/// <summary>
/// This is overriden in sub-classes.
/// </summary>
/// <param name="tolerant">The geographic envelope in cases like cliking near points where tolerance is allowed.</param>
/// <param name="strict">The geographic region when working with absolutes, without a tolerance.</param>
/// <param name="mode">The selection mode.</param>
/// <param name="affectedArea">The affected area.</param>
/// <param name="clear">Indicates whether prior selected features should be cleared.</param>
/// <returns>False.</returns>
public virtual bool Select(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea, ClearStates clear)
{
affectedArea = null;
return false;
}
/// <summary>
/// Unlocks dispose. This typically removes one instance of an internal reference counter.
/// </summary>
public void UnlockDispose()
{
_disposeLockCount--;
}
/// <summary>
/// This is overriden in sub-classes.
/// </summary>
/// <param name="tolerant">The geographic envelope in cases like cliking near points where tolerance is allowed.</param>
/// <param name="strict">The geographic region when working with absolutes, without a tolerance.</param>
/// <param name="mode">The selection mode.</param>
/// <param name="affectedArea">The affected area.</param>
/// <returns>False.</returns>
public virtual bool UnSelect(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = null;
return false;
}
/// <summary>
/// Given a geographic extent, this tests the "IsVisible", "UseDynamicVisibility",
/// "DynamicVisibilityMode" and "DynamicVisibilityWidth"
/// In order to determine if this layer is visible for the specified scale.
/// </summary>
/// <param name="geographicExtent">The geographic extent, where the width will be tested.</param>
/// <returns>Boolean, true if this layer should be visible for this extent.</returns>
public bool VisibleAtExtent(Extent geographicExtent)
{
if (!IsVisible) return false;
if (UseDynamicVisibility)
{
if (DynamicVisibilityMode == DynamicVisibilityMode.ZoomedIn)
{
if (geographicExtent.Width > DynamicVisibilityWidth)
{
return false; // skip the geoLayer if we are zoomed out too far.
}
}
else
{
if (geographicExtent.Width < DynamicVisibilityWidth)
{
return false; // skip the geoLayer if we are zoomed in too far.
}
}
}
return true;
}
/// <summary>
/// This allows overriding layers to handle any memory cleanup.
/// </summary>
/// <param name="disposeManagedResources">True if managed resources should be set to null.</param>
protected virtual void Dispose(bool disposeManagedResources)
{
if (IsDisposed) return;
if (disposeManagedResources)
{
DataSet = null;
Disposed?.Invoke(this, EventArgs.Empty);
}
IsDisposed = true;
}
/// <summary>
/// special treatment for event handlers during a copy event.
/// </summary>
/// <param name="copy">The copy.</param>
protected override void OnCopy(Descriptor copy)
{
// Remove event handlers from the copy. (They will be set again when adding to a new map.)
Layer copyLayer = copy as Layer;
if (copyLayer == null) return;
if (copyLayer.LayerSelected != null)
{
foreach (var handler in copyLayer.LayerSelected.GetInvocationList())
{
copyLayer.LayerSelected -= (EventHandler<LayerSelectedEventArgs>)handler;
}
}
if (copyLayer.ZoomToLayer != null)
{
foreach (var handler in copyLayer.ZoomToLayer.GetInvocationList())
{
copyLayer.ZoomToLayer -= (EventHandler<EnvelopeArgs>)handler;
}
}
if (copyLayer.ShowProperties != null)
{
foreach (var handler in copyLayer.ShowProperties.GetInvocationList())
{
copyLayer.ShowProperties -= (HandledEventHandler)handler;
}
}
if (copyLayer.FinishedLoading != null)
{
foreach (var handler in copyLayer.FinishedLoading.GetInvocationList())
{
copyLayer.FinishedLoading -= (EventHandler)handler;
}
}
if (copyLayer.SelectionChanged != null)
{
foreach (var handler in copyLayer.SelectionChanged.GetInvocationList())
{
copyLayer.SelectionChanged -= (EventHandler)handler;
}
}
base.OnCopy(copy);
}
/// <summary>
/// This should be overridden to copy the symbolizer properties from editCopy.
/// </summary>
/// <param name="editCopy">The version that went into the property dialog.</param>
protected override void OnCopyProperties(object editCopy)
{
ILayer layer = editCopy as ILayer;
if (layer != null)
{
SuspendChangeEvent();
base.OnCopyProperties(editCopy);
ResumeChangeEvent();
}
}
/// <summary>
/// Occurs when instructions are being sent for this layer to export data.
/// </summary>
protected virtual void OnExportData()
{
}
/// <summary>
/// Fires the OnFinishedLoading event.
/// </summary>
protected void OnFinishedLoading()
{
FinishedLoading?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Fires the LayerSelected event.
/// </summary>
/// <param name="sender">Sender that raised the event.</param>
/// <param name="selected">Indicates whether the layer is selected.</param>
protected virtual void OnLayerSelected(ILayer sender, bool selected)
{
LayerSelected?.Invoke(this, new LayerSelectedEventArgs(sender, selected));
}
/// <summary>
/// Fires the SelectionChanged event.
/// </summary>
protected virtual void OnSelectionChanged()
{
SelectionChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Occurs before showing the properties dialog. If the handled member
/// was set to true, then this class will not show the event args.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnShowProperties(HandledEventArgs e)
{
ShowProperties?.Invoke(this, e);
}
/// <summary>
/// Fires the zoom to layer event.
/// </summary>
protected virtual void OnZoomToLayer()
{
if (!Extent.IsEmpty())
{
// changed by jany_ (2015-07-17) zooming to an empty layer makes no sense
ZoomToLayer?.Invoke(this, new EnvelopeArgs(Extent.ToEnvelope()));
}
}
/// <summary>
/// Fires the zoom to layer event, but specifies the extent.
/// </summary>
/// <param name="env">Envelope env.</param>
protected virtual void OnZoomToLayer(Envelope env)
{
ZoomToLayer?.Invoke(this, new EnvelopeArgs(env));
}
private void Configure()
{
SelectionEnabled = true;
ContextMenuItems = new List<SymbologyMenuItem>
{
new SymbologyMenuItem(SymbologyMessageStrings.RemoveLayer, SymbologyImages.mnuLayerClear, RemoveLayerClick),
new SymbologyMenuItem(SymbologyMessageStrings.ZoomToLayer, SymbologyImages.ZoomInMap, ZoomToLayerClick),
new SymbologyMenuItem(SymbologyMessageStrings.SetDynamicVisibilityScale, SymbologyImages.ZoomScale, SetDynamicVisibility)
};
SymbologyMenuItem mnuData = new SymbologyMenuItem(SymbologyMessageStrings.Data);
mnuData.MenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.ExportData, SymbologyImages.save, ExportDataClick));
ContextMenuItems.Add(mnuData);
ContextMenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.Properties, SymbologyImages.color_scheme, ShowPropertiesClick));
LegendSymbolMode = SymbolMode.Checkbox;
LegendType = LegendType.Layer;
IsExpanded = true;
}
private void ExportDataClick(object sender, EventArgs e)
{
OnExportData();
}
private void PropertyDialogProviderChangesApplied(object sender, ChangedObjectEventArgs e)
{
CopyProperties(e.Item as ILegendItem);
}
/// <summary>
/// Removes this layer from its parent list.
/// </summary>
/// <param name="sender">Sender that raised the event.</param>
/// <param name="e">The event args.</param>
private void RemoveLayerClick(object sender, EventArgs e)
{
OnRemoveItem();
}
private void SetDynamicVisibility(object sender, EventArgs e)
{
LayerActions?.DynamicVisibility(this, MapFrame);
}
private void ShowPropertiesClick(object sender, EventArgs e)
{
// Allow subclasses to prevent this class from showing the default dialog
HandledEventArgs result = new HandledEventArgs(false);
OnShowProperties(result);
if (result.Handled) return;
if (_propertyDialogProvider == null) return;
var editCopy = CloneableEm.Copy(this);
CopyProperties(editCopy); // for some reason we are getting blank layers during edits, this tries to fix that
_propertyDialogProvider.ShowDialog(editCopy);
editCopy.Dispose();
LayerManager.DefaultLayerManager.ActiveProjectLayers = new List<ILayer>();
}
/// <summary>
/// Zooms to the specific layer.
/// </summary>
/// <param name="sender">Sender that raised the event.</param>
/// <param name="e">The event args.</param>
private void ZoomToLayerClick(object sender, EventArgs e)
{
OnZoomToLayer();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using SIL.Code;
using SIL.Extensions;
using SIL.Keyboarding;
using SIL.ObjectModel;
namespace SIL.WritingSystems
{
/// <summary>
/// IPA status choices
/// </summary>
public enum IpaStatusChoices
{
/// <summary>
/// Not IPA
/// </summary>
NotIpa,
/// <summary>
/// Generic IPA
/// </summary>
Ipa,
/// <summary>
/// Phonetic IPA
/// </summary>
IpaPhonetic,
/// <summary>
/// Phonemic IPA
/// </summary>
IpaPhonemic
}
public enum QuotationParagraphContinueType
{
None,
All,
Outermost,
Innermost
}
/// <summary>
/// This class stores the information used to define various writing system properties. The Language, Script, Region, and Variants
/// properties conform to the subtags of the same name defined in BCP 47 (RFC 5646). It is worth noting that any of these properties
/// can contain private use subtags. Regardless, a valid IETF language tag is generated.
/// Furthermore the WritingSystemDefinition.WellknownSubtags class provides certain well defined Subtags that carry special meaning
/// apart from the IANA subtag registry. In particular this class defines "qaa" as the default "unlisted language" language subtag.
/// It should be used when there is no match for a language in the IANA subtag registry. Private use properties are "emic" and "etic"
/// which mark phonemic and phonetic writing systems respectively. These must always be used in conjunction with the "fonipa" variant.
/// Likewise "audio" marks a writing system as audio and must always be used in conjunction with script "Zxxx". Convenience methods
/// are provided for Ipa and Audio properties as IpaStatus and IsVoice respectively.
/// </summary>
public class WritingSystemDefinition : DefinitionBase<WritingSystemDefinition>
{
private const int MinimumFontSize = 7;
private const int DefaultSizeIfWeDontKnow = 10;
private LanguageSubtag _language;
private ScriptSubtag _script;
private RegionSubtag _region;
private readonly BulkObservableList<VariantSubtag> _variants;
private string _abbreviation;
private string _versionNumber;
private string _versionDescription;
private DateTime _dateModified;
private float _defaultFontSize;
private FontDefinition _defaultFont;
private string _keyboard;
private bool _rightToLeftScript;
private IKeyboardDefinition _localKeyboard;
private string _languageTag;
private string _defaultRegion;
private string _windowsLcid;
private string _spellCheckingId;
private string _defaultCollationType;
private CollationDefinition _defaultCollation;
private QuotationParagraphContinueType _quotationParagraphContinueType;
private readonly KeyedBulkObservableList<string, FontDefinition> _fonts;
private readonly KeyedBulkObservableList<string, IKeyboardDefinition> _knownKeyboards;
private readonly KeyedBulkObservableList<SpellCheckDictionaryFormat, SpellCheckDictionaryDefinition> _spellCheckDictionaries;
private readonly KeyedBulkObservableList<string, CollationDefinition> _collations;
private readonly ObservableHashSet<MatchedPair> _matchedPairs;
private readonly ObservableHashSet<PunctuationPattern> _punctuationPatterns;
private readonly BulkObservableList<QuotationMark> _quotationMarks;
private readonly KeyedBulkObservableList<string, CharacterSetDefinition> _characterSets;
private readonly SimpleMonitor _ignoreVariantChanges = new SimpleMonitor();
private string _legacyMapping;
private bool _isGraphiteEnabled = true;
/// <summary>
/// Creates a new WritingSystemDefinition with language tag set to "qaa".
/// </summary>
public WritingSystemDefinition()
: this(WellKnownSubtags.UnlistedLanguage)
{
}
public WritingSystemDefinition(string language, string script, string region, string variant)
: this(IetfLanguageTag.Create(language, script, region, variant))
{
}
public WritingSystemDefinition(string language, string script, string region, string variant, string abbreviation, bool rightToLeftScript)
: this(IetfLanguageTag.Create(language, script, region, variant))
{
_abbreviation = abbreviation;
_rightToLeftScript = rightToLeftScript;
}
/// <summary>
/// Creates a new WritingSystemDefinition by parsing a valid IETF language tag.
/// </summary>
public WritingSystemDefinition(string languageTag)
{
if (!IetfLanguageTag.IsValid(languageTag))
throw new ArgumentException("The language tag is invalid.", languageTag);
_languageTag = IetfLanguageTag.Canonicalize(languageTag);
IEnumerable<VariantSubtag> variantSubtags;
IetfLanguageTag.TryGetSubtags(_languageTag, out _language, out _script, out _region, out variantSubtags);
_variants = new BulkObservableList<VariantSubtag>(variantSubtags);
string message;
if (!ValidateLanguageTag(out message))
throw new ArgumentException(message, "languageTag");
_fonts = new KeyedBulkObservableList<string, FontDefinition>(fd => fd.Name, StringComparer.InvariantCultureIgnoreCase);
_knownKeyboards = new KeyedBulkObservableList<string, IKeyboardDefinition>(kd => kd.Id);
_spellCheckDictionaries = new KeyedBulkObservableList<SpellCheckDictionaryFormat, SpellCheckDictionaryDefinition>(scdd => scdd.Format);
_collations = new KeyedBulkObservableList<string, CollationDefinition>(cd => cd.Type);
_matchedPairs = new ObservableHashSet<MatchedPair>();
_punctuationPatterns = new ObservableHashSet<PunctuationPattern>();
_quotationMarks = new BulkObservableList<QuotationMark>();
_characterSets = new KeyedBulkObservableList<string, CharacterSetDefinition>(csd => csd.Type);
SetupCollectionChangeListeners();
}
/// <summary>
/// Copy constructor.
/// </summary>
public WritingSystemDefinition(WritingSystemDefinition ws)
{
_language = ws._language;
_script = ws._script;
_region = ws._region;
_variants = new BulkObservableList<VariantSubtag>(ws._variants);
_abbreviation = ws._abbreviation;
_rightToLeftScript = ws._rightToLeftScript;
_fonts = new KeyedBulkObservableList<string, FontDefinition>(ws._fonts.CloneItems(), fd => fd.Name, StringComparer.InvariantCultureIgnoreCase);
if (ws._defaultFont != null)
_defaultFont = _fonts[ws._fonts.IndexOf(ws._defaultFont)];
_keyboard = ws._keyboard;
_versionNumber = ws._versionNumber;
_versionDescription = ws._versionDescription;
_spellCheckingId = ws._spellCheckingId;
_spellCheckDictionaries = new KeyedBulkObservableList<SpellCheckDictionaryFormat, SpellCheckDictionaryDefinition>(ws._spellCheckDictionaries.CloneItems(), scdd => scdd.Format);
_dateModified = ws._dateModified;
_localKeyboard = ws._localKeyboard;
_windowsLcid = ws._windowsLcid;
_defaultRegion = ws._defaultRegion;
_defaultFontSize = ws._defaultFontSize;
_knownKeyboards = new KeyedBulkObservableList<string, IKeyboardDefinition>(ws._knownKeyboards, kd => kd.Id);
_matchedPairs = new ObservableHashSet<MatchedPair>(ws._matchedPairs);
_punctuationPatterns = new ObservableHashSet<PunctuationPattern>(ws._punctuationPatterns);
_quotationMarks = new BulkObservableList<QuotationMark>(ws._quotationMarks);
_quotationParagraphContinueType = ws._quotationParagraphContinueType;
_languageTag = ws._languageTag;
_defaultCollationType = ws._defaultCollationType;
_collations = new KeyedBulkObservableList<string, CollationDefinition>(ws._collations.CloneItems(), cd => cd.Type);
if (ws._defaultCollation != null)
_defaultCollation = _collations[ws._collations.IndexOf(ws._defaultCollation)];
_characterSets = new KeyedBulkObservableList<string, CharacterSetDefinition>(ws._characterSets.CloneItems(), csd => csd.Type);
_isGraphiteEnabled = ws._isGraphiteEnabled;
_legacyMapping = ws._legacyMapping;
SetupCollectionChangeListeners();
}
private void SetupCollectionChangeListeners()
{
_fonts.CollectionChanged += _fonts_CollectionChanged;
_knownKeyboards.CollectionChanged += _knownKeyboards_CollectionChanged;
_spellCheckDictionaries.CollectionChanged += _spellCheckDictionaries_CollectionChanged;
_matchedPairs.CollectionChanged += _matchedPairs_CollectionChanged;
_punctuationPatterns.CollectionChanged += _punctuationPatterns_CollectionChanged;
_quotationMarks.CollectionChanged += _quotationMarks_CollectionChanged;
_collations.CollectionChanged += _collations_CollectionChanged;
_variants.CollectionChanged += _variants_CollectionChanged;
_characterSets.CollectionChanged += _characterSets_CollectionChanged;
}
private void _characterSets_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IsChanged = true;
}
private void _variants_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_ignoreVariantChanges.Busy)
return;
// if the variant codes haven't changed, then no need to update language tag
if (e.Action != NotifyCollectionChangedAction.Replace
|| !e.OldItems.Cast<VariantSubtag>().Select(v => v.Code).SequenceEqual(e.NewItems.Cast<VariantSubtag>().Select(v => v.Code)))
{
UpdateLanguageTag();
}
IsChanged = true;
}
private void _quotationMarks_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IsChanged = true;
}
private void _punctuationPatterns_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IsChanged = true;
}
private void _matchedPairs_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IsChanged = true;
}
private void _spellCheckDictionaries_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IsChanged = true;
}
private void _fonts_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_defaultFont != null && !_fonts.Contains(_defaultFont))
_defaultFont = null;
IsChanged = true;
}
private void _knownKeyboards_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_localKeyboard != null && !_knownKeyboards.Contains(_localKeyboard))
_localKeyboard = null;
IsChanged = true;
}
private void _collations_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (_defaultCollation != null && !_collations.Contains(_defaultCollation))
_defaultCollation = null;
IsChanged = true;
}
///<summary>
///This is the version of the locale data contained in this writing system.
///This should not be confused with the version of our writingsystemDefinition implementation which is mostly used for migration purposes.
///That information is stored in the "LatestWritingSystemDefinitionVersion" property.
///</summary>
public string VersionNumber
{
get { return _versionNumber ?? string.Empty; }
set { Set(() => VersionNumber, ref _versionNumber, value); }
}
/// <summary>
/// Gets or sets the version description.
/// </summary>
public string VersionDescription
{
get { return _versionDescription ?? string.Empty; }
set { Set(() => VersionDescription, ref _versionDescription, value); }
}
/// <summary>
/// Gets or sets the date modified.
/// </summary>
public DateTime DateModified
{
get { return _dateModified; }
set { _dateModified = value; }
}
private static int GetIndexOfFirstPrivateUseVariant(IEnumerable<VariantSubtag> variantSubtags)
{
int i = 0;
foreach (VariantSubtag variantSubtag in variantSubtags)
{
if (variantSubtag.IsPrivateUse)
break;
i++;
}
return i;
}
/// <summary>
/// Adjusts the IETF language tag to indicate the desired form of Ipa by inserting fonipa in the variant and emic or etic in private use where necessary.
/// </summary>
public IpaStatusChoices IpaStatus
{
get
{
if (_variants.Contains(WellKnownSubtags.IpaVariant))
{
if (_variants.Contains(WellKnownSubtags.IpaPhonemicPrivateUse))
return IpaStatusChoices.IpaPhonemic;
if (_variants.Contains(WellKnownSubtags.IpaPhoneticPrivateUse))
return IpaStatusChoices.IpaPhonetic;
return IpaStatusChoices.Ipa;
}
return IpaStatusChoices.NotIpa;
}
set
{
if (IpaStatus != value)
{
using (_variants.BulkUpdate())
{
RemoveVariants(WellKnownSubtags.IpaVariant, WellKnownSubtags.IpaPhonemicPrivateUse, WellKnownSubtags.IpaPhoneticPrivateUse, WellKnownSubtags.AudioPrivateUse);
int index = GetIndexOfFirstPrivateUseVariant(_variants);
switch (value)
{
case IpaStatusChoices.Ipa:
_variants.Insert(index, WellKnownSubtags.IpaVariant);
break;
case IpaStatusChoices.IpaPhonemic:
_variants.Insert(index, WellKnownSubtags.IpaVariant);
_variants.Insert(index + 1, WellKnownSubtags.IpaPhonemicPrivateUse);
break;
case IpaStatusChoices.IpaPhonetic:
_variants.Insert(index, WellKnownSubtags.IpaVariant);
_variants.Insert(index + 1, WellKnownSubtags.IpaPhoneticPrivateUse);
break;
}
}
}
}
}
private void RemoveVariants(params VariantSubtag[] variantSubtags)
{
var variantSubtagsSet = new HashSet<VariantSubtag>(variantSubtags);
for (int i = _variants.Count - 1; i >= 0; i--)
{
if (variantSubtagsSet.Contains(_variants[i]))
{
variantSubtagsSet.Remove(_variants[i]);
_variants.RemoveAt(i);
if (variantSubtagsSet.Count == 0)
break;
}
}
}
/// <summary>
/// Adjusts the IETF language tag to indicate that this is an "audio writing system" by inserting "audio" in the private use and "Zxxx" in the script
/// </summary>
public bool IsVoice
{
get
{
return ScriptSubTagIsAudio && _variants.Contains(WellKnownSubtags.AudioPrivateUse);
}
set
{
if (IsVoice == value)
return;
if (value)
{
IpaStatus = IpaStatusChoices.NotIpa;
Keyboard = string.Empty;
Set(() => Script, ref _script, WellKnownSubtags.AudioScript);
_variants.Add(WellKnownSubtags.AudioPrivateUse);
}
else
{
Set(() => Script, ref _script, null);
RemoveVariants(WellKnownSubtags.AudioPrivateUse);
}
}
}
private bool ScriptSubTagIsAudio
{
get { return _script != null && _script.Code.Equals(WellKnownSubtags.AudioScript, StringComparison.OrdinalIgnoreCase); }
}
public bool ValidateLanguageTag(out string message)
{
if (!IetfLanguageTag.Validate(_language, _script, _region, _variants, out message))
return false;
if (_variants.Contains(WellKnownSubtags.AudioPrivateUse) && !ScriptSubTagIsAudio)
{
message = "The script subtag must be set to Zxxx when the variant tag indicates an audio writing system.";
return false;
}
bool rfcTagHasAnyIpa = _variants.Contains(WellKnownSubtags.IpaVariant)
|| _variants.Contains(WellKnownSubtags.IpaPhonemicPrivateUse) || _variants.Contains(WellKnownSubtags.IpaPhoneticPrivateUse);
if (_variants.Contains(WellKnownSubtags.AudioPrivateUse) && rfcTagHasAnyIpa)
{
message = "A writing system may not be marked as audio and ipa at the same time.";
return false;
}
if ((_variants.Contains(WellKnownSubtags.IpaPhonemicPrivateUse) || _variants.Contains(WellKnownSubtags.IpaPhoneticPrivateUse))
&& !_variants.Contains(WellKnownSubtags.IpaVariant))
{
message = "A writing system may not be marked as phonetic (x-etic) or phonemic (x-emic) and lack the variant marker fonipa.";
return false;
}
message = null;
return true;
}
/// <summary>
/// Gets or sets the language.
/// </summary>
public LanguageSubtag Language
{
get { return _language; }
set
{
string oldCode = _language == null ? string.Empty : _language.Code;
Set(() => Language, ref _language, value);
if (oldCode != (_language == null ? string.Empty : _language.Code))
UpdateLanguageTag();
}
}
/// <summary>
/// Gets or sets the script. If the language tag for the writing system has an implicit script,
/// this property will return the implicit script.
/// </summary>
public ScriptSubtag Script
{
get { return _script; }
set
{
string oldCode = _script == null ? string.Empty : _script.Code;
Set(() => Script, ref _script, value);
if (oldCode != (_script == null ? string.Empty : _script.Code))
UpdateLanguageTag();
}
}
/// <summary>
/// Gets or sets the region.
/// </summary>
public RegionSubtag Region
{
get { return _region; }
set
{
string oldCode = _region == null ? string.Empty : _region.Code;
Set(() => Region, ref _region, value);
if (oldCode != (_region == null ? string.Empty : _region.Code))
UpdateLanguageTag();
}
}
/// <summary>
/// The variant and private use subtags.
/// </summary>
public BulkObservableList<VariantSubtag> Variants
{
get { return _variants; }
}
/// <summary>
/// The desired abbreviation for the writing system
/// </summary>
public virtual string Abbreviation
{
get
{
if (String.IsNullOrEmpty(_abbreviation))
{
// Use the language subtag unless it's an unlisted language.
// If it's an unlisted language, use the private use area language subtag.
if (_language == null || _language == WellKnownSubtags.UnlistedLanguage)
{
int idx = LanguageTag.IndexOf("x-", StringComparison.Ordinal);
if (idx > 0 && LanguageTag.Length > idx + 2)
{
var abbr = LanguageTag.Substring(idx + 2);
idx = abbr.IndexOf('-');
if (idx > 0)
abbr = abbr.Substring(0, idx);
return abbr;
}
}
return _language;
}
return _abbreviation;
}
set { Set(() => Abbreviation, ref _abbreviation, value); }
}
/// <summary>
/// Used by IWritingSystemRepository to identify writing systems. This is an IETF language tag, but does not necessarily
/// correspond to the writing system's current language tag. Id and LanguageTag can be different if the language
/// tag has changed, but IWritingSystemRepository.Set() hasn't been called on it yet. Only change this if you would like
/// to replace a writing system with the same Id already contained in the repo. This is useful creating a temporary copy
/// of a writing system that you may or may not care to persist to the IWritingSystemRepository.
/// Typical use would therefore be:
/// ws.Clone(wsorig);
/// ws.Id = wsOrig.Id;
/// **make changes to ws**
/// repo.Set(ws);
/// </summary>
public string Id { get; set; }
/// <summary>
/// A automatically generated descriptive label for the writing system definition.
/// </summary>
public virtual string DisplayLabel
{
get
{
//jh (Oct 2010) made it start with RFC5646 because all ws's in a lang start with the
//same abbreviation, making imppossible to see (in SOLID for example) which you chose.
bool languageIsUnknown = _languageTag.Equals(WellKnownSubtags.UnlistedLanguage, StringComparison.OrdinalIgnoreCase);
if (!string.IsNullOrEmpty(_languageTag) && !languageIsUnknown)
{
return _languageTag;
}
if (languageIsUnknown)
{
if (!string.IsNullOrEmpty(_abbreviation))
{
return _abbreviation;
}
if (_language != null && _language != WellKnownSubtags.UnlistedLanguage && !string.IsNullOrEmpty(_language.Name))
{
string n = _language.Name;
return n.Substring(0, n.Length > 4 ? 4 : n.Length);
}
}
return "???";
}
}
/// <summary>
/// Gets the list label.
/// </summary>
public virtual string ListLabel
{
get
{
//the idea here is to give writing systems a nice legible label for. For this reason subtags are replaced with nice labels
var details = new StringBuilder();
if (IpaStatus != IpaStatusChoices.NotIpa)
{
switch (IpaStatus)
{
case IpaStatusChoices.Ipa:
details.Append("IPA-");
break;
case IpaStatusChoices.IpaPhonetic:
details.Append("IPA-etic-");
break;
case IpaStatusChoices.IpaPhonemic:
details.Append("IPA-emic-");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
if (IsVoice)
details.Append("Voice-");
if (IsDuplicate)
{
foreach (string number in DuplicateNumbers)
{
details.Append("Copy");
if (number != "0")
details.Append(number);
details.Append("-");
}
}
if (_script != null && !IsVoice && !IetfLanguageTag.IsScriptImplied(_languageTag))
details.AppendFormat("{0}-", _script.Code);
if (_region != null)
details.AppendFormat("{0}-", _region.Code);
foreach (VariantSubtag variantSubtag in _variants.Where(v => !v.IsPrivateUse))
{
// skip variant tags that have already been added to the details
if (variantSubtag == WellKnownSubtags.IpaVariant)
continue;
details.AppendFormat("{0}-", variantSubtag.Code);
}
bool first = true;
foreach (VariantSubtag variantSubtag in _variants.Where(v => v.IsPrivateUse))
{
// skip variant tags that have already been added to the details
if (variantSubtag == WellKnownSubtags.AudioPrivateUse
|| variantSubtag == WellKnownSubtags.IpaPhonemicPrivateUse
|| variantSubtag == WellKnownSubtags.IpaPhoneticPrivateUse
|| variantSubtag.Code.StartsWith("dupl"))
{
continue;
}
if (first)
{
details.Append("x-");
first = false;
}
details.AppendFormat("{0}-", variantSubtag.Code);
}
string name = _language != null && !string.IsNullOrEmpty(_language.Name) ? _language.Name : DisplayLabel;
if (details.Length > 0)
{
// remove trailing dash
details.Remove(details.Length - 1, 1);
return string.Format("{0} ({1})", name, details);
}
return name;
}
}
/// <summary>
/// Gets a value indicating whether this instance is a duplicate.
/// </summary>
private bool IsDuplicate
{
get { return _variants.Any(v => v.Code.StartsWith("dupl")); }
}
/// <summary>
/// Gets the duplicate numbers.
/// </summary>
private IEnumerable<string> DuplicateNumbers
{
get
{
return _variants.Where(v => v.Code.StartsWith("dupl")).Select(v => Regex.Match(v.Code, @"\d*$").Value);
}
}
/// <summary>
/// The IETF language tag for this writing system.
/// </summary>
public string LanguageTag
{
get { return _languageTag; }
set
{
if (value == null)
throw new ArgumentNullException("value");
if (!IetfLanguageTag.IsValid(value))
throw new ArgumentException("The language tag is invalid.", "value");
string newLangTag = IetfLanguageTag.Canonicalize(value);
if (!newLangTag.Equals(_languageTag, StringComparison.InvariantCultureIgnoreCase))
{
LanguageSubtag language;
ScriptSubtag script;
RegionSubtag region;
IEnumerable<VariantSubtag> variantSubtags;
IetfLanguageTag.TryGetSubtags(newLangTag, out language, out script, out region, out variantSubtags);
Set(() => Language, ref _language, language);
Set(() => Script, ref _script, script);
Set(() => Region, ref _region, region);
using (_ignoreVariantChanges.Enter())
_variants.ReplaceAll(variantSubtags);
string message;
if (!ValidateLanguageTag(out message))
throw new ArgumentException(message, "value");
Set(() => LanguageTag, ref _languageTag, newLangTag);
}
}
}
/// <summary>
/// Indicates whether the writing system definition has been modified.
/// Note that this flag is automatically set by all methods that cause a modification and is reset by the IWritingSystemRepository.Save() method
/// </summary>
public override bool IsChanged
{
get
{
return base.IsChanged || ChildrenIsChanged(_fonts) || ChildrenIsChanged(_spellCheckDictionaries)
|| ChildrenIsChanged(_collations) || ChildrenIsChanged(_characterSets);
}
}
public override void AcceptChanges()
{
base.AcceptChanges();
ChildrenAcceptChanges(_fonts);
ChildrenAcceptChanges(_spellCheckDictionaries);
ChildrenAcceptChanges(_collations);
ChildrenAcceptChanges(_characterSets);
}
public void ForceChanged()
{
IsChanged = true;
}
/// <summary>
/// Gets or sets a value indicating whether the writing system will be deleted.
/// </summary>
public bool MarkedForDeletion { get; set; }
/// <summary>
/// The preferred keyboard to use to generate data encoded in this writing system.
/// </summary>
public virtual string Keyboard
{
get { return _keyboard ?? string.Empty; }
set { Set(() => Keyboard, ref _keyboard, value); }
}
/// <summary>
/// This field retrieves the value obtained from the FieldWorks LDML extension fw:windowsLCID.
/// This is used only when current information in LocalKeyboard or KnownKeyboards is not useable.
/// It is not useful to modify this or set it in new LDML files; however, we need a public setter
/// because FieldWorks overrides the code that normally reads this from the LDML file.
/// </summary>
public virtual string WindowsLcid
{
get { return _windowsLcid ?? string.Empty; }
set { Set(() => WindowsLcid, ref _windowsLcid, value); }
}
/// <summary>
/// Indicates whether this writing system is read and written from left to right or right to left
/// </summary>
public virtual bool RightToLeftScript
{
get { return _rightToLeftScript; }
set { Set(() => RightToLeftScript, ref _rightToLeftScript, value); }
}
public virtual string DefaultCollationType
{
get { return _defaultCollationType ?? "standard"; }
set { Set(() => DefaultCollationType, ref _defaultCollationType, value); }
}
public virtual CollationDefinition DefaultCollation
{
get
{
if (_defaultCollation != null)
return _defaultCollation;
CollationDefinition cd;
if (_collations.TryGet(DefaultCollationType, out cd))
return cd;
return _collations.FirstOrDefault();
}
set
{
if (Set(() => DefaultCollation, ref _defaultCollation, value) && value != null)
{
CollationDefinition cd;
if (_collations.TryGet(value.Type, out cd))
{
if (cd == value)
return;
// if a collation with the same type already exists, replace it
int index = _collations.IndexOf(cd);
_collations[index] = value;
}
else
{
_collations.Add(value);
}
}
}
}
public KeyedBulkObservableList<string, CollationDefinition> Collations
{
get { return _collations; }
}
public KeyedBulkObservableList<string, CharacterSetDefinition> CharacterSets
{
get { return _characterSets; }
}
protected virtual void UpdateLanguageTag()
{
if (_language == null && (_script != null || _region != null || _variants.Any(v => !v.IsPrivateUse)))
Set(() => Language, ref _language, WellKnownSubtags.UnlistedLanguage);
Set(() => LanguageTag, ref _languageTag, IetfLanguageTag.Create(_language, _script, _region, _variants, false));
if (_script == null && IetfLanguageTag.IsValid(_languageTag) && IetfLanguageTag.IsScriptImplied(_languageTag))
Set(() => Script, ref _script, IetfLanguageTag.GetScriptSubtag(_languageTag));
}
/// <summary>
/// This tracks the keyboard that should be used for this writing system on this computer.
/// It is not shared with other users of the project.
/// </summary>
public virtual IKeyboardDefinition LocalKeyboard
{
get
{
IKeyboardDefinition keyboard = _localKeyboard;
if (keyboard == null)
keyboard = _knownKeyboards.FirstOrDefault(k => k.IsAvailable);
if (keyboard == null)
keyboard = LegacyKeyboard ?? Keyboarding.Keyboard.Controller.DefaultKeyboard;
return keyboard;
}
set
{
if (Set(() => LocalKeyboard, ref _localKeyboard, value) && value != null && !_knownKeyboards.Contains(value.Id))
_knownKeyboards.Add(value);
}
}
/// <summary>
/// Finds a keyboard specified using one of the legacy fields. If such a keyboard is found, it is appropriate to
/// automatically add it to KnownKeyboards. If one is not, a general DefaultKeyboard should NOT be added.
/// </summary>
public IKeyboardDefinition LegacyKeyboard
{
get
{
if (!string.IsNullOrEmpty(WindowsLcid))
{
IKeyboardDefinition keyboard = GetFWLegacyKeyboard();
if (keyboard != null)
return keyboard;
}
if (!string.IsNullOrEmpty(Keyboard))
{
IKeyboardDefinition keyboard = GetPalasoLegacyKeyboard();
if (keyboard != null)
return keyboard;
}
return null;
}
}
private IKeyboardDefinition GetFWLegacyKeyboard()
{
int lcid;
if (int.TryParse(WindowsLcid, out lcid))
{
if (string.IsNullOrEmpty(Keyboard))
{
// FW system keyboard
IKeyboardDefinition keyboard;
if (Keyboarding.Keyboard.Controller.TryGetKeyboard(lcid, out keyboard))
return keyboard;
}
else
{
try
{
// FW keyman keyboard
var culture = new CultureInfo(lcid);
IKeyboardDefinition keyboard;
if (Keyboarding.Keyboard.Controller.TryGetKeyboard(Keyboard, culture.Name, out keyboard))
return keyboard;
}
catch (CultureNotFoundException)
{
// Culture specified by LCID is not supported on current system. Just ignore.
}
}
}
return null;
}
private IKeyboardDefinition GetPalasoLegacyKeyboard()
{
IKeyboardDefinition keyboard;
if (Keyboarding.Keyboard.Controller.TryGetKeyboard(Keyboard, out keyboard))
return keyboard;
// Palaso WinIME keyboard
string locale = GetLocaleName(Keyboard);
string layout = GetLayoutName(Keyboard);
if (Keyboarding.Keyboard.Controller.TryGetKeyboard(layout, locale, out keyboard))
return keyboard;
// Palaso Keyman or Ibus keyboard
if (Keyboarding.Keyboard.Controller.TryGetKeyboard(layout, out keyboard))
return keyboard;
return null;
}
private static string GetLocaleName(string name)
{
var split = name.Split(new[] { '-' });
string localeName;
if (split.Length <= 1)
{
localeName = string.Empty;
}
else if (split.Length > 1 && split.Length <= 3)
{
localeName = string.Join("-", split.Skip(1).ToArray());
}
else
{
localeName = string.Join("-", split.Skip(split.Length - 2).ToArray());
}
return localeName;
}
private static string GetLayoutName(string name)
{
//Just cut off the length of the locale + 1 for the dash
var locale = GetLocaleName(name);
if (string.IsNullOrEmpty(locale))
{
return name;
}
var layoutName = name.Substring(0, name.Length - (locale.Length + 1));
return layoutName;
}
public IKeyboardDefinition RawLocalKeyboard
{
get { return _localKeyboard; }
}
/// <summary>
/// Keyboards known to have been used with this writing system. Not all may be available on this system.
/// Enhance: document (or add to this class?) a way of getting available keyboards.
/// </summary>
public KeyedBulkObservableList<string, IKeyboardDefinition> KnownKeyboards
{
get { return _knownKeyboards; }
}
/// <summary>
/// Returns the available keyboards (known to Keyboard.Controller) that are not KnownKeyboards for this writing system.
/// </summary>
public IEnumerable<IKeyboardDefinition> OtherAvailableKeyboards
{
get
{
return Keyboarding.Keyboard.Controller.AvailableKeyboards.Except(KnownKeyboards);
}
}
/// <summary>
/// the preferred font size to use for data encoded in this writing system.
/// </summary>
public virtual float DefaultFontSize
{
get { return _defaultFontSize; }
set
{
if (value < 0 || float.IsNaN(value) || float.IsInfinity(value))
throw new ArgumentOutOfRangeException("value");
Set(() => DefaultFontSize, ref _defaultFontSize, value);
}
}
/// <summary>
/// enforcing a minimum on _defaultFontSize, while reasonable, just messed up too many IO unit tests
/// </summary>
/// <returns></returns>
public virtual float GetDefaultFontSizeOrMinimum()
{
if (_defaultFontSize < MinimumFontSize)
return DefaultSizeIfWeDontKnow;
return _defaultFontSize;
}
/// <summary>
/// The font used to display data encoded in this writing system
/// </summary>
public virtual FontDefinition DefaultFont
{
get
{
FontDefinition font = _defaultFont;
if (font == null)
font = _fonts.FirstOrDefault(fd => fd.Roles.HasFlag(FontRoles.Default));
if (font == null)
font = _fonts.FirstOrDefault();
return font;
}
set
{
if (Set(() => DefaultFont, ref _defaultFont, value) && value != null)
{
FontDefinition fd;
if (_fonts.TryGet(value.Name, out fd))
{
if (fd == value)
return;
// if a font with the same name already exists, replace it
int index = _fonts.IndexOf(fd);
_fonts[index] = value;
}
else
{
_fonts.Add(value);
}
}
}
}
public KeyedBulkObservableList<string, FontDefinition> Fonts
{
get { return _fonts; }
}
/// <summary>
/// The Id used to select the spell checker.
/// </summary>
public virtual string SpellCheckingId
{
get { return _spellCheckingId ?? string.Empty; }
set { Set(() => SpellCheckingId, ref _spellCheckingId, value); }
}
public KeyedBulkObservableList<SpellCheckDictionaryFormat, SpellCheckDictionaryDefinition> SpellCheckDictionaries
{
get { return _spellCheckDictionaries; }
}
public virtual string DefaultRegion
{
get { return _defaultRegion ?? string.Empty; }
set { Set(() => DefaultRegion, ref _defaultRegion, value); }
}
public IObservableSet<MatchedPair> MatchedPairs
{
get { return _matchedPairs; }
}
public IObservableSet<PunctuationPattern> PunctuationPatterns
{
get { return _punctuationPatterns; }
}
public BulkObservableList<QuotationMark> QuotationMarks
{
get { return _quotationMarks; }
}
public QuotationParagraphContinueType QuotationParagraphContinueType
{
get { return _quotationParagraphContinueType; }
set { Set(() => QuotationParagraphContinueType, ref _quotationParagraphContinueType, value); }
}
/// <summary>
/// Gets or sets the legacy mapping.
/// </summary>
/// <value>The legacy mapping.</value>
public string LegacyMapping
{
get { return _legacyMapping ?? string.Empty; }
set { Set(() => LegacyMapping, ref _legacyMapping, value); }
}
/// <summary>
/// Gets or sets a value indicating whether Graphite is enabled for this writing system.
/// </summary>
/// <value><c>true</c> if Graphite is enabled, otherwise <c>false</c>.</value>
public bool IsGraphiteEnabled
{
get { return _isGraphiteEnabled; }
set { Set(() => IsGraphiteEnabled, ref _isGraphiteEnabled, value); }
}
/// <summary>
/// Gets or sets the template that was used to create this writing system.
/// This is not persisted and only used by repositories.
/// </summary>
public string Template { get; set; }
public override string ToString()
{
return _languageTag;
}
/// <summary>
/// Creates a clone of the current writing system.
/// Note that this excludes the properties: Modified, MarkedForDeletion and Id
/// </summary>
/// <returns></returns>
public override WritingSystemDefinition Clone()
{
return new WritingSystemDefinition(this);
}
/// <summary>
/// Checks for value equality with the specified writing system.
/// </summary>
public override bool ValueEquals(WritingSystemDefinition other)
{
if (other == null)
return false;
if (_language != other._language)
return false;
if (_script != other._script)
return false;
if (_region != other._region)
return false;
if (!_variants.SequenceEqual(other._variants))
return false;
if (Abbreviation != other.Abbreviation)
return false;
if (VersionNumber != other.VersionNumber)
return false;
if (VersionDescription != other.VersionDescription)
return false;
if (Keyboard != other.Keyboard)
return false;
if (_languageTag != other._languageTag)
return false;
if (_dateModified != other._dateModified)
return false;
if (_rightToLeftScript != other._rightToLeftScript)
return false;
if (WindowsLcid != other.WindowsLcid)
return false;
if (DefaultRegion != other.DefaultRegion)
return false;
if (!_matchedPairs.SetEquals(other._matchedPairs))
return false;
if (!_punctuationPatterns.SetEquals(other._punctuationPatterns))
return false;
if (!_quotationMarks.SequenceEqual(other._quotationMarks))
return false;
if (_quotationParagraphContinueType != other._quotationParagraphContinueType)
return false;
if (_isGraphiteEnabled != other._isGraphiteEnabled)
return false;
if (LegacyMapping != other.LegacyMapping)
return false;
if (SpellCheckingId != other.SpellCheckingId)
return false;
if (_defaultFontSize != other._defaultFontSize)
return false;
if (DefaultCollationType != other.DefaultCollationType)
return false;
// fonts
if (_fonts.Count != other._fonts.Count)
return false;
for (int i = 0; i < _fonts.Count; i++)
{
if (!_fonts[i].ValueEquals(other._fonts[i]))
return false;
}
if (DefaultFont == null)
{
if (other.DefaultFont != null)
return false;
}
else if (!DefaultFont.ValueEquals(other.DefaultFont))
{
return false;
}
// spell checking dictionaries
if (_spellCheckDictionaries.Count != other._spellCheckDictionaries.Count)
return false;
for (int i = 0; i < _spellCheckDictionaries.Count; i++)
{
if (!_spellCheckDictionaries[i].ValueEquals(other._spellCheckDictionaries[i]))
return false;
}
// keyboards
if (!_knownKeyboards.SequenceEqual(other._knownKeyboards))
return false;
if (LocalKeyboard != other.LocalKeyboard)
return false;
// collations
if (_collations.Count != other._collations.Count)
return false;
for (int i = 0; i < _collations.Count; i++)
{
if (!_collations[i].ValueEquals(other._collations[i]))
return false;
}
if (DefaultCollation == null)
{
if (other.DefaultCollation != null)
return false;
}
else if (!DefaultCollation.ValueEquals(other.DefaultCollation))
{
return false;
}
// character sets
if (_characterSets.Count != other._characterSets.Count)
return false;
foreach (CharacterSetDefinition csd in _characterSets)
{
CharacterSetDefinition otherCsd;
if (!other._characterSets.TryGet(csd.Type, out otherCsd) || !csd.ValueEquals(otherCsd))
return false;
}
return true;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.Drawing;
namespace fyiReporting.RDL
{
///<summary>
/// Bar chart definition and processing.
///</summary>
internal class ChartBar: ChartBase
{
int _GapSize = 6; // TODO: hard code for now
internal ChartBar(Report r, Row row, Chart c, MatrixCellEntry[,] m, Expression showTooltips, Expression showTooltipsX,Expression _ToolTipYFormat, Expression _ToolTipXFormat)
: base(r, row, c, m,showTooltips,showTooltipsX,_ToolTipYFormat,_ToolTipXFormat)
{
}
override internal void Draw(Report rpt)
{
CreateSizedBitmap();
//AJM GJL 14082008 Using Vector Graphics
using (Graphics g1 = Graphics.FromImage(_bm))
{
_aStream = new System.IO.MemoryStream();
IntPtr HDC = g1.GetHdc();
_mf = new System.Drawing.Imaging.Metafile(_aStream, HDC, new RectangleF(0, 0, _bm.Width, _bm.Height), System.Drawing.Imaging.MetafileFrameUnit.Pixel);
g1.ReleaseHdc(HDC);
}
using (Graphics g = Graphics.FromImage(_mf))
{
// 06122007AJM Used to Force Higher Quality
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
// Adjust the top margin to depend on the title height
Size titleSize = DrawTitleMeasure(rpt, g, ChartDefn.Title);
Layout.TopMargin = titleSize.Height;
double max=0,min=0; // Get the max and min values
// 20022008 AJM GJL - Now requires Y axis identifier
GetValueMaxMin(rpt, ref max, ref min, 0,1);
DrawChartStyle(rpt, g);
// Draw title; routine determines if necessary
DrawTitle(rpt, g, ChartDefn.Title, new System.Drawing.Rectangle(0, 0, _bm.Width, Layout.TopMargin));
// Adjust the left margin to depend on the Category Axis
Size caSize = CategoryAxisSize(rpt, g);
Layout.LeftMargin = caSize.Width;
// Adjust the bottom margin to depend on the Value Axis
Size vaSize = ValueAxisSize(rpt, g, min, max);
Layout.BottomMargin = vaSize.Height;
// Draw legend
System.Drawing.Rectangle lRect = DrawLegend(rpt, g, false, true);
// 20022008 AJM GJL - Requires Rpt and Graphics
AdjustMargins(lRect,rpt,g ); // Adjust margins based on legend.
// Draw Plot area
DrawPlotAreaStyle(rpt, g, lRect);
// Draw Value Axis
if (vaSize.Width > 0) // If we made room for the axis - we need to draw it
DrawValueAxis(rpt, g, min, max,
new System.Drawing.Rectangle(Layout.LeftMargin, _bm.Height-Layout.BottomMargin, _bm.Width - Layout.LeftMargin - Layout.RightMargin, vaSize.Height), Layout.TopMargin, _bm.Height - Layout.BottomMargin);
// Draw Category Axis
if (caSize.Height > 0)
DrawCategoryAxis(rpt, g,
new System.Drawing.Rectangle(Layout.LeftMargin - caSize.Width, Layout.TopMargin, caSize.Width, _bm.Height - Layout.TopMargin - Layout.BottomMargin));
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked)
DrawPlotAreaStacked(rpt, g, min, max);
else if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked)
DrawPlotAreaPercentStacked(rpt, g);
else
DrawPlotAreaPlain(rpt, g, min, max);
DrawLegend(rpt, g, false, false); // after the plot is drawn
}
}
void DrawPlotAreaPercentStacked(Report rpt, Graphics g)
{
int barsNeeded = CategoryCount;
int gapsNeeded = CategoryCount * 2;
// Draw Plot area data
double max = 1;
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
// Loop thru calculating all the data points
for (int iRow = 1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
double sum=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
sum += GetDataValue(rpt, iRow, iCol);
}
double v=0;
int saveX=0;
double t=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
t = GetDataValue(rpt, iRow, iCol);
v += t;
int x = (int) ((Math.Min(v/sum,max) / max) * maxBarWidth);
System.Drawing.Rectangle rect;
rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar);
DrawColumnBar(rpt, g,
GetSeriesBrush(rpt, iRow, iCol),
rect, iRow, iCol);
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips)
{
String val = "ToolTip:" + t.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
saveX = x;
}
}
return;
}
void DrawPlotAreaPlain(Report rpt, Graphics g, double min, double max)
{
int barsNeeded = SeriesCount * CategoryCount;
int gapsNeeded = CategoryCount * 2;
// Draw Plot area data
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
//int barLoc=Layout.LeftMargin;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
for (int iCol=1; iCol <= SeriesCount; iCol++)
{
double v = this.GetDataValue(rpt, iRow, iCol);
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth);
DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol),
new System.Drawing.Rectangle(Layout.PlotArea.Left, barLoc, x, heightBar), iRow, iCol);
//Add a metafilecomment to use as a tooltip GJL 26092008
if (_showToolTips)
{
String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)Layout.PlotArea.Left + "|Y:" + (int)(barLoc) + "|W:" + x + "|H:" + heightBar;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
barLoc += heightBar;
}
}
return;
}
void DrawPlotAreaStacked(Report rpt, Graphics g, double min, double max)
{
int barsNeeded = CategoryCount;
int gapsNeeded = CategoryCount * 2;
int heightBar = (int) ((Layout.PlotArea.Height - gapsNeeded*_GapSize) / barsNeeded);
int maxBarWidth = (int) (Layout.PlotArea.Width);
// Loop thru calculating all the data points
for (int iRow = 1; iRow <= CategoryCount; iRow++)
{
int barLoc=(int) (Layout.PlotArea.Top + (iRow-1) * ((double) (Layout.PlotArea.Height) / CategoryCount));
barLoc += _GapSize; // space before series
double v=0;
double t = 0;
int saveX=0;
for (int iCol = 1; iCol <= SeriesCount; iCol++)
{
t = GetDataValue(rpt, iRow, iCol);
v += t;
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * maxBarWidth);
System.Drawing.Rectangle rect;
rect = new System.Drawing.Rectangle(Layout.PlotArea.Left + saveX, barLoc, x - saveX, heightBar);
DrawColumnBar(rpt, g, GetSeriesBrush(rpt, iRow, iCol), rect, iRow, iCol);
if (_showToolTips)
{
String val = "ToolTip:" + v.ToString(_tooltipYFormat) + "|X:" + (int)rect.X + "|Y:" + (int)rect.Y + "|W:" + rect.Width + "|H:" + rect.Height;
g.AddMetafileComment(new System.Text.ASCIIEncoding().GetBytes(val));
}
saveX = x;
}
}
return;
}
// Calculate the size of the category axis
Size CategoryAxisSize(Report rpt, Graphics g)
{
_LastCategoryWidth = 0;
Size size=Size.Empty;
if (this.ChartDefn.CategoryAxis == null)
return size;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return size;
Style s = a.Style;
// Measure the title
size = DrawTitleMeasure(rpt, g, a.Title);
if (!a.Visible) // don't need to calculate the height
return size;
// Calculate the tallest category name
TypeCode tc;
int maxWidth=0;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
Size tSize;
if (s == null)
tSize = Style.MeasureStringDefaults(rpt, g, v, tc, null, int.MaxValue);
else
tSize =s.MeasureString(rpt, g, v, tc, null, int.MaxValue);
if (tSize.Width > maxWidth)
maxWidth = tSize.Width;
if (iRow == CategoryCount)
_LastCategoryWidth = tSize.Width;
}
// Add on the widest category name
size.Width += maxWidth;
return size;
}
// DrawCategoryAxis
void DrawCategoryAxis(Report rpt, Graphics g, System.Drawing.Rectangle rect)
{
if (this.ChartDefn.CategoryAxis == null)
return;
Axis a = this.ChartDefn.CategoryAxis.Axis;
if (a == null)
return;
Style s = a.Style;
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title,
new System.Drawing.Rectangle(rect.Left, rect.Top, tSize.Width, rect.Height));
int drawHeight = rect.Height / CategoryCount;
TypeCode tc;
for (int iRow=1; iRow <= CategoryCount; iRow++)
{
object v = this.GetCategoryValue(rpt, iRow, out tc);
int drawLoc=(int) (rect.Top + (iRow-1) * ((double) rect.Height / CategoryCount));
// Draw the category text
if (a.Visible)
{
System.Drawing.Rectangle drawRect = new System.Drawing.Rectangle(rect.Left + tSize.Width, drawLoc, rect.Width-tSize.Width, drawHeight);
if (s == null)
Style.DrawStringDefaults(g, v, drawRect);
else
s.DrawString(rpt, g, v, tc, null, drawRect);
}
// Draw the Major Tick Marks (if necessary)
DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, drawLoc));
}
// Draw the end on (if necessary)
DrawCategoryAxisTick(g, true, a.MajorTickMarks, new Point(rect.Right, rect.Bottom));
return;
}
protected void DrawCategoryAxisTick(Graphics g, bool bMajor, AxisTickMarksEnum tickType, Point p)
{
int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen;
switch (tickType)
{
case AxisTickMarksEnum.Outside:
g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X-len, p.Y));
break;
case AxisTickMarksEnum.Inside:
g.DrawLine(Pens.Black, new Point(p.X, p.Y), new Point(p.X+len, p.Y));
break;
case AxisTickMarksEnum.Cross:
g.DrawLine(Pens.Black, new Point(p.X-len, p.Y), new Point(p.X+len, p.Y));
break;
case AxisTickMarksEnum.None:
default:
break;
}
return;
}
void DrawColumnBar(Report rpt, Graphics g, Brush brush, System.Drawing.Rectangle rect, int iRow, int iCol)
{
g.FillRectangle(brush, rect);
g.DrawRectangle(Pens.Black, rect);
if ((ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.Stacked ||
(ChartSubTypeEnum)Enum.Parse(typeof(ChartSubTypeEnum), _ChartDefn.Subtype.EvaluateString(rpt, _row)) == ChartSubTypeEnum.PercentStacked)
{
DrawDataPoint(rpt, g, rect, iRow, iCol);
}
else
{
Point p;
p = new Point(rect.Right, rect.Top);
DrawDataPoint(rpt, g, p, iRow, iCol);
}
return;
}
protected void DrawValueAxis(Report rpt, Graphics g, double min, double max, System.Drawing.Rectangle rect, int plotTop, int plotBottom)
{
if (this.ChartDefn.ValueAxis == null)
return;
Axis a = this.ChartDefn.ValueAxis.Axis;
if (a == null)
return;
Style s = a.Style;
// Account for tick marks
int tickSize=0;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
tickSize = this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
tickSize += this.AxisTickMarkMinorLen;
int intervalCount;
double incr;
SetIncrementAndInterval(rpt, a, min, max, out incr, out intervalCount); // Calculate the interval count
int maxValueHeight = 0;
double v = min;
Size size= Size.Empty;
for (int i = 0; i < intervalCount+1; i++)
{
int x = (int) (((Math.Min(v,max)-min) / (max-min)) * rect.Width);
if (!a.Visible)
{
// nothing to do
}
else if (s != null)
{
size = s.MeasureString(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height);
s.DrawString(rpt, g, v, TypeCode.Double, null, vRect);
}
else
{
size = Style.MeasureStringDefaults(rpt, g, v, TypeCode.Double, null, int.MaxValue);
System.Drawing.Rectangle vRect =
new System.Drawing.Rectangle(rect.Left + x - size.Width/2, rect.Top+tickSize, size.Width, size.Height);
Style.DrawStringDefaults(g, v, vRect);
}
if (size.Height > maxValueHeight) // Need to keep track of the maximum height
maxValueHeight = size.Height; // this is probably overkill since it should always be the same??
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left + x, plotTop), new Point(rect.Left + x, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left + x, plotBottom ));
v += incr;
}
// Draw the end points of the major grid lines
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Left, plotTop), new Point(rect.Left, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Left, plotBottom));
DrawValueAxisGrid(rpt, g, a.MajorGridLines, new Point(rect.Right, plotTop), new Point(rect.Right, plotBottom));
DrawValueAxisTick(rpt, g, true, a.MajorTickMarks, a.MajorGridLines, new Point(rect.Right, plotBottom));
Size tSize = DrawTitleMeasure(rpt, g, a.Title);
DrawTitle(rpt, g, a.Title,
new System.Drawing.Rectangle(rect.Left, rect.Top+maxValueHeight+tickSize, rect.Width, tSize.Height));
return;
}
protected void DrawValueAxisGrid(Report rpt, Graphics g, ChartGridLines gl, Point s, Point e)
{
if (gl == null || !gl.ShowGridLines)
return;
if (gl.Style != null)
gl.Style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
protected void DrawValueAxisTick(Report rpt, Graphics g, bool bMajor, AxisTickMarksEnum tickType, ChartGridLines gl, Point p)
{
if (tickType == AxisTickMarksEnum.None)
return;
int len = bMajor? AxisTickMarkMajorLen: AxisTickMarkMinorLen;
Point s, e;
switch (tickType)
{
case AxisTickMarksEnum.Inside:
s = new Point(p.X, p.Y);
e = new Point(p.X, p.Y-len);
break;
case AxisTickMarksEnum.Cross:
s = new Point(p.X, p.Y-len);
e = new Point(p.X, p.Y+len);
break;
case AxisTickMarksEnum.Outside:
default:
s = new Point(p.X, p.Y+len);
e = new Point(p.X, p.Y);
break;
}
Style style = gl.Style;
if (style != null)
style.DrawStyleLine(rpt, g, null, s, e);
else
g.DrawLine(Pens.Black, s, e);
return;
}
// Calculate the size of the value axis; width is max value width + title width
// height is max value height
protected Size ValueAxisSize(Report rpt, Graphics g, double min, double max)
{
Size size=Size.Empty;
if (ChartDefn.ValueAxis == null)
return size;
Axis a = ChartDefn.ValueAxis.Axis;
if (a == null)
return size;
Size minSize;
Size maxSize;
if (!a.Visible)
{
minSize = maxSize = Size.Empty;
}
else if (a.Style != null)
{
minSize = a.Style.MeasureString(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = a.Style.MeasureString(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
else
{
minSize = Style.MeasureStringDefaults(rpt, g, min, TypeCode.Double, null, int.MaxValue);
maxSize = Style.MeasureStringDefaults(rpt, g, max, TypeCode.Double, null, int.MaxValue);
}
// Choose the largest
size.Width = Math.Max(minSize.Width, maxSize.Width);
size.Height = Math.Max(minSize.Height, maxSize.Height);
// Now we need to add in the height of the title (if any)
Size titleSize = DrawTitleMeasure(rpt, g, a.Title);
size.Height += titleSize.Height;
if (a.MajorTickMarks == AxisTickMarksEnum.Cross ||
a.MajorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMajorLen;
else if (a.MinorTickMarks == AxisTickMarksEnum.Cross ||
a.MinorTickMarks == AxisTickMarksEnum.Outside)
size.Height += this.AxisTickMarkMinorLen;
return size;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.Forms.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
//
// The Original Code is from http://gps3.codeplex.com/ version 3.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0
// | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
#if !PocketPC || DesignTime || Framework20
using System.ComponentModel;
#endif
#if PocketPC
using DotSpatial.Positioning.Licensing;
#endif
namespace DotSpatial.Positioning.Forms
{
#if !PocketPC || DesignTime
/// <summary>
/// Represents a user control used to measure speed graphically.
/// </summary>
[ToolboxBitmap(typeof(Speedometer), "Resources.Speedometer.bmp")]
[DefaultProperty("Value")]
#endif
#if Framework20
#if !PocketPC
[ToolboxItem(true)]
#endif
#endif
public sealed class Speedometer : PolarControl
{
#if !PocketPC
private readonly Thread _interpolationThread;
private bool _isInterpolationActive;
// private ManualResetEvent InterpolationThreadWaitHandle = new ManualResetEvent(false);
private readonly ManualResetEvent _animationWaitHandle = new ManualResetEvent(false);
private readonly Interpolator _valueInterpolator = new Interpolator(15, InterpolationMethod.CubicEaseInOut);
private int _interpolationIndex;
private Size _pNeedleShadowSize = new Size(5, 5);
#endif
private Color _minorTickPenColor = Color.Black;
private Color _majorTickPenColor = Color.Black;
private Color _speedLabelBrushColor = Color.Black;
private Color _needleShadowBrushColor = Color.FromArgb(128, 0, 0, 0);
private Speed _pMaximumSpeed = new Speed(120, SpeedUnit.KilometersPerHour);
private Speed _pSpeedLabelInterval = new Speed(10, SpeedUnit.KilometersPerHour);
private Speed _pMinorTickInterval = new Speed(5, SpeedUnit.KilometersPerHour);
private Speed _pMajorTickInterval = new Speed(10, SpeedUnit.KilometersPerHour);
private string _pSpeedLabelFormat = "v";
private Speed _pSpeed = new Speed(0, SpeedUnit.MetersPerSecond);
private Color _needleFillColor = Color.Red;
private Color _needleOutlineColor = Color.Black;
private Angle _pMinimumAngle = new Angle(40);
private Angle _pMaximumAngle = new Angle(320);
private static readonly PolarCoordinate[] _speedometerNeedle = new[]
{
new PolarCoordinate(70, new Angle(1), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(90), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(95), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(100), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(105), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(110), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(115), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(120), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(125), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(130), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(135), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(140), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(145), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(150), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(155), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(160), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(165), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(170), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(175), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(180), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(185), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(190), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(195), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(200), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(205), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(210), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(215), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(220), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(225), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(230), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(235), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(240), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(245), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(250), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(255), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(260), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(265), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(8, new Angle(270), Azimuth.South, PolarCoordinateOrientation.Clockwise),
new PolarCoordinate(70, new Angle(359), Azimuth.South, PolarCoordinateOrientation.Clockwise)
};
private bool _pIsUsingRealTimeData;
private bool _pIsUnitLabelVisible = true;
private double _conversionFactor;
#if (PocketPC && Framework20)
private const int MaximumGracefulShutdownTime = 2000;
#elif !PocketPC
private const int MAXIMUM_GRACEFUL_SHUTDOWN_TIME = 500;
#endif
///<summary>
/// Occurs when the value changed
///</summary>
public event EventHandler<SpeedEventArgs> ValueChanged;
/// <summary>
/// Speedometer
/// </summary>
public Speedometer()
: base("DotSpatial.Positioning Multithreaded Speedometer Control (http://dotspatial.codeplex.com)")
{
#if !PocketPC
// Start the interpolation thread
_interpolationThread = new Thread(InterpolationLoop)
{
IsBackground = true,
Name =
"DotSpatial.Positioning Speedometer Needle Animation Thread (http://dotspatial.codeplex.com)"
};
_isInterpolationActive = true;
_interpolationThread.Start();
#endif
// Set the control to display clockwise from north
Orientation = PolarCoordinateOrientation.Clockwise;
Origin = Azimuth.South;
// The center is zero and edge is 100
CenterR = 0;
MaximumR = 100;
// Use the speed depending on the local culture
if (RegionInfo.CurrentRegion.IsMetric)
{
_pMaximumSpeed = new Speed(120, SpeedUnit.KilometersPerHour);
_pSpeedLabelInterval = new Speed(10, SpeedUnit.KilometersPerHour);
#if PocketPC
Font = new Font("Tahoma", 7.0f, FontStyle.Regular);
_pMinorTickInterval = new Speed(5, SpeedUnit.KilometersPerHour);
#else
_pMinorTickInterval = new Speed(1, SpeedUnit.KilometersPerHour);
Font = new Font("Tahoma", 11.0f, FontStyle.Regular);
#endif
_pMajorTickInterval = new Speed(10, SpeedUnit.KilometersPerHour);
}
else
{
_pMaximumSpeed = new Speed(120, SpeedUnit.StatuteMilesPerHour);
_pSpeedLabelInterval = new Speed(10, SpeedUnit.StatuteMilesPerHour);
#if PocketPC
_pMinorTickInterval = new Speed(5, SpeedUnit.StatuteMilesPerHour);
#else
_pMinorTickInterval = new Speed(1, SpeedUnit.StatuteMilesPerHour);
#endif
_pMajorTickInterval = new Speed(10, SpeedUnit.StatuteMilesPerHour);
}
// Calculate the factor for converting speed into an angle
_conversionFactor = (_pMaximumAngle.DecimalDegrees - _pMinimumAngle.DecimalDegrees) / _pMaximumSpeed.Value;
}
/// <inheritdocs/>
protected override void Dispose(bool disposing)
{
// Only hook into events if we're at run-time. Hooking events
// at design-time can actually cause errors in the WF Designer.
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime
&& _pIsUsingRealTimeData)
{
Devices.SpeedChanged -= Devices_CurrentSpeedChanged;
}
#if !PocketPC
// Get the interpolation thread out of a loop
_isInterpolationActive = false;
if (_interpolationThread != null)
{
if (_animationWaitHandle != null) _animationWaitHandle.Set();
if (!_interpolationThread.Join(MAXIMUM_GRACEFUL_SHUTDOWN_TIME)) _interpolationThread.Abort();
}
if (_animationWaitHandle != null) _animationWaitHandle.Close();
#endif
base.Dispose(disposing);
}
#if Framework20 && !PocketPC
/// <summary>
/// The azimuth angle of hte origin
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Azimuth Origin
{
get
{
return base.Origin;
}
set
{
base.Origin = value;
}
}
/// <summary>
/// The rotation angle
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Angle Rotation
{
get
{
return base.Rotation;
}
set
{
base.Rotation = value;
}
}
#endif
/// <inheritdocs/>
protected override void OnPaintOffScreen(PaintEventArgs e)
{
PolarGraphics f = CreatePolarGraphics(e.Graphics);
// What altitude are we drawing?
#if PocketPC
Speed SpeedToRender = pSpeed;
#else
Speed speedToRender = new Speed(_valueInterpolator[_interpolationIndex], _pSpeed.Units);
#endif
// Cache drawing intervals and such to prevent a race condition
double minorInterval = _pMinorTickInterval.Value;
double majorInterval = _pMajorTickInterval.Value;
double cachedSpeedLabelInterval = _pSpeedLabelInterval.ToUnitType(_pMaximumSpeed.Units).Value;
Speed maxSpeed = _pMaximumSpeed.Clone();
double minorStep = _pMinorTickInterval.ToUnitType(_pMaximumSpeed.Units).Value;
double majorStep = _pMajorTickInterval.ToUnitType(_pMaximumSpeed.Units).Value;
// Draw tick marks
double angle;
PolarCoordinate start;
PolarCoordinate end;
#region Draw minor tick marks
if (minorInterval > 0)
{
for (double speed = 0; speed < maxSpeed.Value; speed += minorStep)
{
// Convert the speed to an angle
angle = speed * _conversionFactor + _pMinimumAngle.DecimalDegrees;
// Get the coordinate of the line's start
start = new PolarCoordinate(95, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise);
end = new PolarCoordinate(100, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise);
// And draw a line
Pen p = new Pen(_minorTickPenColor);
f.DrawLine(p, start, end);
p.Dispose();
}
}
#endregion
#region Draw major tick marks
if (majorInterval > 0)
{
using (Pen majorPen = new Pen(_majorTickPenColor))
{
for (double speed = 0; speed < maxSpeed.Value; speed += majorStep)
{
// Convert the speed to an angle
angle = speed * _conversionFactor + _pMinimumAngle.DecimalDegrees;
// Get the coordinate of the line's start
start = new PolarCoordinate(90, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise);
end = new PolarCoordinate(100, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise);
// And draw a line
f.DrawLine(majorPen, start, end);
}
#region Draw a major tick mark at the maximum speed
// Convert the speed to an angle
angle = maxSpeed.Value * _conversionFactor + _pMinimumAngle.DecimalDegrees;
// Get the coordinate of the line's start
start = new PolarCoordinate(90, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise);
end = new PolarCoordinate(100, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise);
// And draw a line
f.DrawLine(majorPen, start, end);
#endregion
}
}
#endregion
using (SolidBrush fontBrush = new SolidBrush(_speedLabelBrushColor))
{
if (cachedSpeedLabelInterval > 0)
{
for (double speed = 0; speed < maxSpeed.Value; speed += cachedSpeedLabelInterval)
{
// Convert the speed to an angle
angle = speed * _conversionFactor + _pMinimumAngle.DecimalDegrees;
// And draw a line
f.DrawCenteredString(new Speed(speed, maxSpeed.Units).ToString(_pSpeedLabelFormat, CultureInfo.CurrentCulture), Font, fontBrush,
new PolarCoordinate(75, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise));
}
// Convert the speed to an angle
angle = maxSpeed.Value * _conversionFactor + _pMinimumAngle.DecimalDegrees;
// And draw the speed label
f.DrawCenteredString(maxSpeed.ToString(_pSpeedLabelFormat, CultureInfo.CurrentCulture), Font, fontBrush,
new PolarCoordinate(75, angle, Azimuth.South, PolarCoordinateOrientation.Clockwise));
}
// Draw the units for the speedometer
if (_pIsUnitLabelVisible)
{
f.DrawCenteredString(_pMaximumSpeed.ToString("u", CultureInfo.CurrentCulture), Font, fontBrush,
new PolarCoordinate(90, Angle.Empty, Azimuth.South, PolarCoordinateOrientation.Clockwise));
}
}
PolarCoordinate[] needle = new PolarCoordinate[_speedometerNeedle.Length];
for (int index = 0; index < needle.Length; index++)
{
needle[index] = _speedometerNeedle[index].Rotate((speedToRender.ToUnitType(_pMaximumSpeed.Units).Value * _conversionFactor) + _pMinimumAngle.DecimalDegrees);
}
// Draw an ellipse at the center
f.DrawEllipse(Pens.Gray, PolarCoordinate.Empty, 10);
#if !PocketPC
// Now draw a shadow
f.Graphics.TranslateTransform(_pNeedleShadowSize.Width, _pNeedleShadowSize.Height, MatrixOrder.Append);
using (Brush b = new SolidBrush(_needleShadowBrushColor)) f.FillPolygon(b, needle);
f.Graphics.ResetTransform();
#endif
// Then draw the actual needle
using (SolidBrush needleFill = new SolidBrush(_needleFillColor)) f.FillPolygon(needleFill, needle);
using (Pen needlePen = new Pen(_needleOutlineColor)) f.DrawPolygon(needlePen, needle);
}
#if !PocketPC || DesignTime
/// <summary>
/// Gets or sets the spedometer needle color of the edge
/// </summary>
[Category("Speedometer Needle")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color of the edge of the needle.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color NeedleOutlineColor
{
get { return _needleOutlineColor; }
set
{
_needleOutlineColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Gets or sets the needle fill color.
/// </summary>
[Category("Speedometer Needle")]
[DefaultValue(typeof(Color), "Red")]
[Description("Controls the color of the interior of the needle.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color NeedleFillColor
{
get
{
return _needleFillColor;
}
set
{
_needleFillColor = value;
InvokeRepaint();
}
}
#if !PocketPC
/// <summary>
/// The Needle Shadow Brush color intially semitransparent black.
/// </summary>
[Category("Appearance")]
[DefaultValue(typeof(Color), "128, 0, 0, 0")]
[Description("Controls the color of the shadow cast by the needle.")]
public Color NeedleShadowColor
{
get { return _needleShadowBrushColor; }
set
{
_needleShadowBrushColor = value;
InvokeRepaint();
}
}
#endif
#if !PocketPC
/// <summary>
///
/// </summary>
[Category("Appearance")]
[DefaultValue(typeof(Size), "5, 5")]
[Description("Controls the size of the shadow cast by the needle.")]
public Size NeedleShadowSize
{
get
{
return _pNeedleShadowSize;
}
set
{
_pNeedleShadowSize = value;
InvokeRepaint();
}
}
#endif
#if !PocketPC || DesignTime
/// <summary>
/// Controls the amount of speed being displayed in the control
/// </summary>
[Category("Behavior")]
[Description("Controls the amount of speed being displayed in the control.")]
[DefaultValue(typeof(Speed), "0 m/s")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
////[CLSCompliant(false)]
public Speed Value
{
get
{
return _pSpeed;
}
set
{
if (_pSpeed.Equals(value)) return;
_pSpeed = value.ToUnitType(_pMaximumSpeed.Units);
#if PocketPC
InvokeRepaint();
#else
if (IsDisposed)
return;
lock (_valueInterpolator)
{
// Are we changing direction?
if (_pSpeed.Value >= _valueInterpolator.Minimum
&& _pSpeed.Value > _valueInterpolator[_interpolationIndex])
{
// No. Just set the new maximum
_valueInterpolator.Maximum = _pSpeed.Value;
}
else if (_pSpeed.Value < _valueInterpolator.Minimum)
{
// We're changing directions, so stop then accellerate again
_valueInterpolator.Minimum = _valueInterpolator[_interpolationIndex];
_valueInterpolator.Maximum = _pSpeed.Value;
_interpolationIndex = 0;
}
else if (_pSpeed.Value > _valueInterpolator.Minimum
&& _pSpeed.Value < _valueInterpolator[_interpolationIndex])
{
// We're changing directions, so stop then accellerate again
_valueInterpolator.Minimum = _valueInterpolator[_interpolationIndex];
_valueInterpolator.Maximum = _pSpeed.Value;
_interpolationIndex = 0;
}
else if (_pSpeed.Value > _valueInterpolator.Maximum)
{
// No. Just set the new maximum
_valueInterpolator.Maximum = _pSpeed.Value;
}
}
// And activate the interpolation thread
_animationWaitHandle.Set();
#endif
OnValueChanged(new SpeedEventArgs(_pSpeed));
}
}
private void OnValueChanged(SpeedEventArgs e)
{
if (ValueChanged != null)
ValueChanged(this, e);
}
#if !PocketPC
/// <summary>
/// Controls how the control smoothly transitions from one value to another.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(InterpolationMethod), "CubicEaseInOut")]
[Description("Controls how the control smoothly transitions from one value to another.")]
public InterpolationMethod ValueInterpolationMethod
{
get
{
return _valueInterpolator.InterpolationMethod;
}
set
{
_valueInterpolator.InterpolationMethod = value;
}
}
#endif
#if !PocketPC || DesignTime
/// <summary>
/// Controls the fastest speed allowed by the control.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(Speed), "120 km/h")]
[Description("Controls the fastest speed allowed by the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
////[CLSCompliant(false)]
public Speed MaximumSpeed
{
get
{
return _pMaximumSpeed;
}
set
{
if (_pMaximumSpeed.Equals(value)) return;
_pMaximumSpeed = value;
// Calculate the factor for converting speed into an angle
_conversionFactor = (_pMaximumAngle.DecimalDegrees - _pMinimumAngle.DecimalDegrees) / _pMaximumSpeed.Value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the amount of speed in between each label around the control.
/// </summary>
[Category("Speed Label")]
[DefaultValue(typeof(Speed), "10 km/h")]
[Description("Controls the amount of speed in between each label around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Speed SpeedLabelInterval
{
get
{
return _pSpeedLabelInterval;
}
set
{
if (_pSpeedLabelInterval.Equals(value)) return;
_pSpeedLabelInterval = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the number of degrees in between each smaller tick mark around the control.
/// </summary>
[Category("Tick Marks")]
[DefaultValue(typeof(Speed), "5 km/h")]
[Description("Controls the number of degrees in between each smaller tick mark around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Speed MinorTickInterval
{
get
{
return _pMinorTickInterval;
}
set
{
if (_pMinorTickInterval.Equals(value)) return;
_pMinorTickInterval = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the number of degrees in between each larger tick mark around the control.
/// </summary>
[Category("Tick Marks")]
[DefaultValue(typeof(Speed), "10 km/h")]
[Description("Controls the number of degrees in between each larger tick mark around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Speed MajorTickInterval
{
get
{
return _pMajorTickInterval;
}
set
{
if (_pMajorTickInterval.Equals(value)) return;
_pMajorTickInterval = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// the color of the minor ticks.
/// </summary>
[Category("Tick Marks")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color of smaller tick marks drawn around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color MinorTickColor
{
get { return _minorTickPenColor; }
set
{
_minorTickPenColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls whether the speed label is drawn in the center of the control.
/// </summary>
[Category("Appearance")]
[DefaultValue(typeof(bool), "True")]
[Description("Controls whether the speed label is drawn in the center of the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public bool IsUnitLabelVisible
{
get
{
return _pIsUnitLabelVisible;
}
set
{
if (_pIsUnitLabelVisible.Equals(value))
return;
_pIsUnitLabelVisible = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls whether the Value property is set manually, or automatically read from any available GPS device.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(bool), "False")]
[Description("Controls whether the Value property is set manually, or automatically read from any available GPS device.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public bool IsUsingRealTimeData
{
get
{
return _pIsUsingRealTimeData;
}
set
{
// Has nothing changed?
if (_pIsUsingRealTimeData == value)
return;
// Store the new value
_pIsUsingRealTimeData = value;
if (_pIsUsingRealTimeData)
{
// Only hook into events if we're at run-time. Hooking events
// at design-time can actually cause errors in the WF Designer.
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
Devices.SpeedChanged += Devices_CurrentSpeedChanged;
}
// Set the current real-time speed
Value = Devices.Speed;
}
else
{
// Only hook into events if we're at run-time. Hooking events
// at design-time can actually cause errors in the WF Designer.
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
Devices.SpeedChanged -= Devices_CurrentSpeedChanged;
}
// Reset the value to zero
Value = Speed.AtRest;
}
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Gets or sets the Major Tick Color
/// </summary>
[Category("Tick Marks")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color of larger tick marks drawn around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color MajorTickColor
{
get
{
return _majorTickPenColor;
}
set
{
_majorTickPenColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the display format used for speed labels drawn around the control.
/// </summary>
[Category("Speed Label")]
[DefaultValue(typeof(string), "v")]
[Description("Controls the display format used for speed labels drawn around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public string SpeedLabelFormat
{
get
{
return _pSpeedLabelFormat;
}
set
{
if (_pSpeedLabelFormat.Equals(value)) return;
_pSpeedLabelFormat = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <inheritdocs/>
[Category("Speed Label")]
#if PocketPC
[DefaultValue(typeof(Font), "Tahoma, 7pt")]
#else
[DefaultValue(typeof(Font), "Tahoma, 11pt")]
#endif
[Description("Controls the font used for speed labels drawn around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Gets or sets the Speed Label font color
/// </summary>
[Category("Speed Label")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color of speed labels drawn around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color SpeedLabelColor
{
get
{
return _speedLabelBrushColor;
}
set
{
_speedLabelBrushColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the angle associated with the smallest possible speed.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(Angle), "40")]
[Description("Controls the angle associated with the smallest possible speed.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Angle MinimumAngle
{
get
{
return _pMinimumAngle;
}
set
{
if (_pMinimumAngle.Equals(value)) return;
_pMinimumAngle = value;
// Calculate the factor for converting speed into an angle
_conversionFactor = (_pMaximumAngle.DecimalDegrees - _pMinimumAngle.DecimalDegrees) / _pMaximumSpeed.Value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the angle associated with the largest possible speed.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(Angle), "320")]
[Description("Controls the angle associated with the largest possible speed.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Angle MaximumAngle
{
get
{
return _pMaximumAngle;
}
set
{
if (_pMaximumAngle.Equals(value)) return;
_pMaximumAngle = value;
// Calculate the factor for converting speed into an angle
_conversionFactor = (_pMaximumAngle.DecimalDegrees - _pMinimumAngle.DecimalDegrees) / _pMaximumSpeed.Value;
InvokeRepaint();
}
}
private void Devices_CurrentSpeedChanged(object sender, SpeedEventArgs e)
{
if (_pIsUsingRealTimeData)
Value = e.Speed;
}
#if !PocketPC
/// <inheritdocs/>
protected override void OnTargetFrameRateChanged(int framesPerSecond)
{
base.OnTargetFrameRateChanged(framesPerSecond);
// Recalculate our things
_valueInterpolator.Count = framesPerSecond;
// Adjust the index if it's outside of bounds
if (_interpolationIndex > _valueInterpolator.Count - 1)
_interpolationIndex = _valueInterpolator.Count - 1;
}
private void InterpolationLoop()
{
// Flag that we're alive
// InterpolationThreadWaitHandle.Set();
// Are we at the end?
while (_isInterpolationActive)
{
try
{
// Wait for interpolation to actually be needed
// InterpolationThread.Suspend();
_animationWaitHandle.WaitOne();
// If we're shutting down, just exit
if (!_isInterpolationActive)
break;
// Keep updating interpolation until we're done
while (_isInterpolationActive && _interpolationIndex < _valueInterpolator.Count)
{
// Render the next value
InvokeRepaint();
_interpolationIndex++;
// Wait for the next frame
Thread.Sleep(1000 / _valueInterpolator.Count);
}
// Reset interpolation
_valueInterpolator.Minimum = _valueInterpolator.Maximum;
_interpolationIndex = 0;
_animationWaitHandle.Reset();
}
catch (ThreadAbortException)
{
// Just exit!
break;
}
}
// Flag that we're alive
// InterpolationThreadWaitHandle.Set();
}
#endif
}
}
| |
using System;
namespace ClosedXML.Excel
{
public enum XLShiftDeletedCells { ShiftCellsUp, ShiftCellsLeft }
public enum XLTransposeOptions { MoveCells, ReplaceCells }
public enum XLSearchContents { Values, Formulas, ValuesAndFormulas }
public interface IXLRange: IXLRangeBase
{
/// <summary>
/// Gets the cell at the specified row and column.
/// <para>The cell address is relative to the parent range.</para>
/// </summary>
/// <param name="row">The cell's row.</param>
/// <param name="column">The cell's column.</param>
IXLCell Cell(int row, int column);
/// <summary>Gets the cell at the specified address.</summary>
/// <para>The cell address is relative to the parent range.</para>
/// <param name="cellAddressInRange">The cell address in the parent range.</param>
IXLCell Cell(string cellAddressInRange);
/// <summary>
/// Gets the cell at the specified row and column.
/// <para>The cell address is relative to the parent range.</para>
/// </summary>
/// <param name="row">The cell's row.</param>
/// <param name="column">The cell's column.</param>
IXLCell Cell(int row, string column);
/// <summary>Gets the cell at the specified address.</summary>
/// <para>The cell address is relative to the parent range.</para>
/// <param name="cellAddressInRange">The cell address in the parent range.</param>
IXLCell Cell(IXLAddress cellAddressInRange);
/// <summary>
/// Gets the specified column of the range.
/// </summary>
/// <param name="column">The range column.</param>
IXLRangeColumn Column(int column);
/// <summary>
/// Gets the specified column of the range.
/// </summary>
/// <param name="column">The range column.</param>
IXLRangeColumn Column(string column);
/// <summary>
/// Gets the first column of the range.
/// </summary>
IXLRangeColumn FirstColumn(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets the first column of the range that contains a cell with a value.
/// </summary>
IXLRangeColumn FirstColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null);
IXLRangeColumn FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets the last column of the range.
/// </summary>
IXLRangeColumn LastColumn(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets the last column of the range that contains a cell with a value.
/// </summary>
IXLRangeColumn LastColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null);
IXLRangeColumn LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets a collection of all columns in this range.
/// </summary>
IXLRangeColumns Columns(Func<IXLRangeColumn, Boolean> predicate = null);
/// <summary>
/// Gets a collection of the specified columns in this range.
/// </summary>
/// <param name="firstColumn">The first column to return.</param>
/// <param name="lastColumn">The last column to return.</param>
IXLRangeColumns Columns(int firstColumn, int lastColumn);
/// <summary>
/// Gets a collection of the specified columns in this range.
/// </summary>
/// <param name="firstColumn">The first column to return.</param>
/// <param name="lastColumn">The last column to return.</param>
IXLRangeColumns Columns(string firstColumn, string lastColumn);
/// <summary>
/// Gets a collection of the specified columns in this range, separated by commas.
/// <para>e.g. Columns("G:H"), Columns("10:11,13:14"), Columns("P:Q,S:T"), Columns("V")</para>
/// </summary>
/// <param name="columns">The columns to return.</param>
IXLRangeColumns Columns(string columns);
/// <summary>
/// Returns the first row that matches the given predicate
/// </summary>
IXLRangeColumn FindColumn(Func<IXLRangeColumn, Boolean> predicate);
/// <summary>
/// Returns the first row that matches the given predicate
/// </summary>
IXLRangeRow FindRow(Func<IXLRangeRow, Boolean> predicate);
/// <summary>
/// Gets the first row of the range.
/// </summary>
IXLRangeRow FirstRow(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the first row of the range that contains a cell with a value.
/// </summary>
IXLRangeRow FirstRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeRow FirstRowUsed(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the last row of the range.
/// </summary>
IXLRangeRow LastRow(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the last row of the range that contains a cell with a value.
/// </summary>
IXLRangeRow LastRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeRow LastRowUsed(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets the specified row of the range.
/// </summary>
/// <param name="row">The range row.</param>
IXLRangeRow Row(int row);
IXLRangeRows Rows(Func<IXLRangeRow, Boolean> predicate = null);
/// <summary>
/// Gets a collection of the specified rows in this range.
/// </summary>
/// <param name="firstRow">The first row to return.</param>
/// <param name="lastRow">The last row to return.</param>
/// <returns></returns>
IXLRangeRows Rows(int firstRow, int lastRow);
/// <summary>
/// Gets a collection of the specified rows in this range, separated by commas.
/// <para>e.g. Rows("4:5"), Rows("7:8,10:11"), Rows("13")</para>
/// </summary>
/// <param name="rows">The rows to return.</param>
IXLRangeRows Rows(string rows);
/// <summary>
/// Returns the specified range.
/// </summary>
/// <param name="rangeAddress">The range boundaries.</param>
IXLRange Range(IXLRangeAddress rangeAddress);
/// <summary>Returns the specified range.</summary>
/// <para>e.g. Range("A1"), Range("A1:C2")</para>
/// <param name="rangeAddress">The range boundaries.</param>
IXLRange Range(string rangeAddress);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCell">The first cell in the range.</param>
/// <param name="lastCell"> The last cell in the range.</param>
IXLRange Range(IXLCell firstCell, IXLCell lastCell);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellAddress">The first cell address in the range.</param>
/// <param name="lastCellAddress"> The last cell address in the range.</param>
IXLRange Range(string firstCellAddress, string lastCellAddress);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellAddress">The first cell address in the range.</param>
/// <param name="lastCellAddress"> The last cell address in the range.</param>
IXLRange Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress);
/// <summary>Returns a collection of ranges, separated by commas.</summary>
/// <para>e.g. Ranges("A1"), Ranges("A1:C2"), Ranges("A1:B2,D1:D4")</para>
/// <param name="ranges">The ranges to return.</param>
IXLRanges Ranges(string ranges);
/// <summary>Returns the specified range.</summary>
/// <param name="firstCellRow"> The first cell's row of the range to return.</param>
/// <param name="firstCellColumn">The first cell's column of the range to return.</param>
/// <param name="lastCellRow"> The last cell's row of the range to return.</param>
/// <param name="lastCellColumn"> The last cell's column of the range to return.</param>
/// <returns>.</returns>
IXLRange Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn);
/// <summary>Gets the number of rows in this range.</summary>
int RowCount();
/// <summary>Gets the number of columns in this range.</summary>
int ColumnCount();
/// <summary>
/// Inserts X number of columns to the right of this range.
/// <para>All cells to the right of this range will be shifted X number of columns.</para>
/// </summary>
/// <param name="numberOfColumns">Number of columns to insert.</param>
IXLRangeColumns InsertColumnsAfter(int numberOfColumns);
IXLRangeColumns InsertColumnsAfter(int numberOfColumns, Boolean expandRange);
/// <summary>
/// Inserts X number of columns to the left of this range.
/// <para>This range and all cells to the right of this range will be shifted X number of columns.</para>
/// </summary>
/// <param name="numberOfColumns">Number of columns to insert.</param>
IXLRangeColumns InsertColumnsBefore(int numberOfColumns);
IXLRangeColumns InsertColumnsBefore(int numberOfColumns, Boolean expandRange);
/// <summary>
/// Inserts X number of rows on top of this range.
/// <para>This range and all cells below this range will be shifted X number of rows.</para>
/// </summary>
/// <param name="numberOfRows">Number of rows to insert.</param>
IXLRangeRows InsertRowsAbove(int numberOfRows);
IXLRangeRows InsertRowsAbove(int numberOfRows, Boolean expandRange);
/// <summary>
/// Inserts X number of rows below this range.
/// <para>All cells below this range will be shifted X number of rows.</para>
/// </summary>
/// <param name="numberOfRows">Number of rows to insert.</param>
IXLRangeRows InsertRowsBelow(int numberOfRows);
IXLRangeRows InsertRowsBelow(int numberOfRows, Boolean expandRange);
/// <summary>
/// Deletes this range and shifts the surrounding cells accordingly.
/// </summary>
/// <param name="shiftDeleteCells">How to shift the surrounding cells.</param>
void Delete(XLShiftDeletedCells shiftDeleteCells);
/// <summary>
/// Transposes the contents and styles of all cells in this range.
/// </summary>
/// <param name="transposeOption">How to handle the surrounding cells when transposing the range.</param>
void Transpose(XLTransposeOptions transposeOption);
IXLTable AsTable();
IXLTable AsTable(String name);
IXLTable CreateTable();
IXLTable CreateTable(String name);
IXLRange RangeUsed();
IXLRange CopyTo(IXLCell target);
IXLRange CopyTo(IXLRangeBase target);
IXLSortElements SortRows { get; }
IXLSortElements SortColumns { get; }
IXLRange Sort();
IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true);
IXLRange SetDataType(XLCellValues dataType);
/// <summary>
/// Clears the contents of this range.
/// </summary>
/// <param name="clearOptions">Specify what you want to clear.</param>
new IXLRange Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats);
IXLRangeRows RowsUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeRows RowsUsed(Func<IXLRangeRow, Boolean> predicate = null);
IXLRangeColumns ColumnsUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate = null);
IXLRangeColumns ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate = null);
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// YearlyResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Api.V2010.Account.Usage.Record
{
public class YearlyResource : Resource
{
public sealed class CategoryEnum : StringEnum
{
private CategoryEnum(string value) : base(value) {}
public CategoryEnum() {}
public static implicit operator CategoryEnum(string value)
{
return new CategoryEnum(value);
}
public static readonly CategoryEnum AgentConference = new CategoryEnum("agent-conference");
public static readonly CategoryEnum AnsweringMachineDetection = new CategoryEnum("answering-machine-detection");
public static readonly CategoryEnum AuthyAuthentications = new CategoryEnum("authy-authentications");
public static readonly CategoryEnum AuthyCallsOutbound = new CategoryEnum("authy-calls-outbound");
public static readonly CategoryEnum AuthyMonthlyFees = new CategoryEnum("authy-monthly-fees");
public static readonly CategoryEnum AuthyPhoneIntelligence = new CategoryEnum("authy-phone-intelligence");
public static readonly CategoryEnum AuthyPhoneVerifications = new CategoryEnum("authy-phone-verifications");
public static readonly CategoryEnum AuthySmsOutbound = new CategoryEnum("authy-sms-outbound");
public static readonly CategoryEnum CallProgessEvents = new CategoryEnum("call-progess-events");
public static readonly CategoryEnum Calleridlookups = new CategoryEnum("calleridlookups");
public static readonly CategoryEnum Calls = new CategoryEnum("calls");
public static readonly CategoryEnum CallsClient = new CategoryEnum("calls-client");
public static readonly CategoryEnum CallsGlobalconference = new CategoryEnum("calls-globalconference");
public static readonly CategoryEnum CallsInbound = new CategoryEnum("calls-inbound");
public static readonly CategoryEnum CallsInboundLocal = new CategoryEnum("calls-inbound-local");
public static readonly CategoryEnum CallsInboundMobile = new CategoryEnum("calls-inbound-mobile");
public static readonly CategoryEnum CallsInboundTollfree = new CategoryEnum("calls-inbound-tollfree");
public static readonly CategoryEnum CallsOutbound = new CategoryEnum("calls-outbound");
public static readonly CategoryEnum CallsPayVerbTransactions = new CategoryEnum("calls-pay-verb-transactions");
public static readonly CategoryEnum CallsRecordings = new CategoryEnum("calls-recordings");
public static readonly CategoryEnum CallsSip = new CategoryEnum("calls-sip");
public static readonly CategoryEnum CallsSipInbound = new CategoryEnum("calls-sip-inbound");
public static readonly CategoryEnum CallsSipOutbound = new CategoryEnum("calls-sip-outbound");
public static readonly CategoryEnum CallsTransfers = new CategoryEnum("calls-transfers");
public static readonly CategoryEnum CarrierLookups = new CategoryEnum("carrier-lookups");
public static readonly CategoryEnum Conversations = new CategoryEnum("conversations");
public static readonly CategoryEnum ConversationsApiRequests = new CategoryEnum("conversations-api-requests");
public static readonly CategoryEnum ConversationsConversationEvents = new CategoryEnum("conversations-conversation-events");
public static readonly CategoryEnum ConversationsEndpointConnectivity = new CategoryEnum("conversations-endpoint-connectivity");
public static readonly CategoryEnum ConversationsEvents = new CategoryEnum("conversations-events");
public static readonly CategoryEnum ConversationsParticipantEvents = new CategoryEnum("conversations-participant-events");
public static readonly CategoryEnum ConversationsParticipants = new CategoryEnum("conversations-participants");
public static readonly CategoryEnum Cps = new CategoryEnum("cps");
public static readonly CategoryEnum FlexUsage = new CategoryEnum("flex-usage");
public static readonly CategoryEnum FraudLookups = new CategoryEnum("fraud-lookups");
public static readonly CategoryEnum GroupRooms = new CategoryEnum("group-rooms");
public static readonly CategoryEnum GroupRoomsDataTrack = new CategoryEnum("group-rooms-data-track");
public static readonly CategoryEnum GroupRoomsEncryptedMediaRecorded = new CategoryEnum("group-rooms-encrypted-media-recorded");
public static readonly CategoryEnum GroupRoomsMediaDownloaded = new CategoryEnum("group-rooms-media-downloaded");
public static readonly CategoryEnum GroupRoomsMediaRecorded = new CategoryEnum("group-rooms-media-recorded");
public static readonly CategoryEnum GroupRoomsMediaRouted = new CategoryEnum("group-rooms-media-routed");
public static readonly CategoryEnum GroupRoomsMediaStored = new CategoryEnum("group-rooms-media-stored");
public static readonly CategoryEnum GroupRoomsParticipantMinutes = new CategoryEnum("group-rooms-participant-minutes");
public static readonly CategoryEnum GroupRoomsRecordedMinutes = new CategoryEnum("group-rooms-recorded-minutes");
public static readonly CategoryEnum ImpV1Usage = new CategoryEnum("imp-v1-usage");
public static readonly CategoryEnum Lookups = new CategoryEnum("lookups");
public static readonly CategoryEnum Marketplace = new CategoryEnum("marketplace");
public static readonly CategoryEnum MarketplaceAlgorithmiaNamedEntityRecognition = new CategoryEnum("marketplace-algorithmia-named-entity-recognition");
public static readonly CategoryEnum MarketplaceCadenceTranscription = new CategoryEnum("marketplace-cadence-transcription");
public static readonly CategoryEnum MarketplaceCadenceTranslation = new CategoryEnum("marketplace-cadence-translation");
public static readonly CategoryEnum MarketplaceCapioSpeechToText = new CategoryEnum("marketplace-capio-speech-to-text");
public static readonly CategoryEnum MarketplaceConvrizaAbaba = new CategoryEnum("marketplace-convriza-ababa");
public static readonly CategoryEnum MarketplaceDeepgramPhraseDetector = new CategoryEnum("marketplace-deepgram-phrase-detector");
public static readonly CategoryEnum MarketplaceDigitalSegmentBusinessInfo = new CategoryEnum("marketplace-digital-segment-business-info");
public static readonly CategoryEnum MarketplaceFacebookOfflineConversions = new CategoryEnum("marketplace-facebook-offline-conversions");
public static readonly CategoryEnum MarketplaceGoogleSpeechToText = new CategoryEnum("marketplace-google-speech-to-text");
public static readonly CategoryEnum MarketplaceIbmWatsonMessageInsights = new CategoryEnum("marketplace-ibm-watson-message-insights");
public static readonly CategoryEnum MarketplaceIbmWatsonMessageSentiment = new CategoryEnum("marketplace-ibm-watson-message-sentiment");
public static readonly CategoryEnum MarketplaceIbmWatsonRecordingAnalysis = new CategoryEnum("marketplace-ibm-watson-recording-analysis");
public static readonly CategoryEnum MarketplaceIbmWatsonToneAnalyzer = new CategoryEnum("marketplace-ibm-watson-tone-analyzer");
public static readonly CategoryEnum MarketplaceIcehookSystemsScout = new CategoryEnum("marketplace-icehook-systems-scout");
public static readonly CategoryEnum MarketplaceInfogroupDataaxleBizinfo = new CategoryEnum("marketplace-infogroup-dataaxle-bizinfo");
public static readonly CategoryEnum MarketplaceKeenIoContactCenterAnalytics = new CategoryEnum("marketplace-keen-io-contact-center-analytics");
public static readonly CategoryEnum MarketplaceMarchexCleancall = new CategoryEnum("marketplace-marchex-cleancall");
public static readonly CategoryEnum MarketplaceMarchexSentimentAnalysisForSms = new CategoryEnum("marketplace-marchex-sentiment-analysis-for-sms");
public static readonly CategoryEnum MarketplaceMarketplaceNextcallerSocialId = new CategoryEnum("marketplace-marketplace-nextcaller-social-id");
public static readonly CategoryEnum MarketplaceMobileCommonsOptOutClassifier = new CategoryEnum("marketplace-mobile-commons-opt-out-classifier");
public static readonly CategoryEnum MarketplaceNexiwaveVoicemailToText = new CategoryEnum("marketplace-nexiwave-voicemail-to-text");
public static readonly CategoryEnum MarketplaceNextcallerAdvancedCallerIdentification = new CategoryEnum("marketplace-nextcaller-advanced-caller-identification");
public static readonly CategoryEnum MarketplaceNomoroboSpamScore = new CategoryEnum("marketplace-nomorobo-spam-score");
public static readonly CategoryEnum MarketplacePayfoneTcpaCompliance = new CategoryEnum("marketplace-payfone-tcpa-compliance");
public static readonly CategoryEnum MarketplaceRemeetingAutomaticSpeechRecognition = new CategoryEnum("marketplace-remeeting-automatic-speech-recognition");
public static readonly CategoryEnum MarketplaceTcpaDefenseSolutionsBlacklistFeed = new CategoryEnum("marketplace-tcpa-defense-solutions-blacklist-feed");
public static readonly CategoryEnum MarketplaceTeloOpencnam = new CategoryEnum("marketplace-telo-opencnam");
public static readonly CategoryEnum MarketplaceTruecnamTrueSpam = new CategoryEnum("marketplace-truecnam-true-spam");
public static readonly CategoryEnum MarketplaceTwilioCallerNameLookupUs = new CategoryEnum("marketplace-twilio-caller-name-lookup-us");
public static readonly CategoryEnum MarketplaceTwilioCarrierInformationLookup = new CategoryEnum("marketplace-twilio-carrier-information-lookup");
public static readonly CategoryEnum MarketplaceVoicebasePci = new CategoryEnum("marketplace-voicebase-pci");
public static readonly CategoryEnum MarketplaceVoicebaseTranscription = new CategoryEnum("marketplace-voicebase-transcription");
public static readonly CategoryEnum MarketplaceVoicebaseTranscriptionCustomVocabulary = new CategoryEnum("marketplace-voicebase-transcription-custom-vocabulary");
public static readonly CategoryEnum MarketplaceWhitepagesProCallerIdentification = new CategoryEnum("marketplace-whitepages-pro-caller-identification");
public static readonly CategoryEnum MarketplaceWhitepagesProPhoneIntelligence = new CategoryEnum("marketplace-whitepages-pro-phone-intelligence");
public static readonly CategoryEnum MarketplaceWhitepagesProPhoneReputation = new CategoryEnum("marketplace-whitepages-pro-phone-reputation");
public static readonly CategoryEnum MarketplaceWolfarmSpokenResults = new CategoryEnum("marketplace-wolfarm-spoken-results");
public static readonly CategoryEnum MarketplaceWolframShortAnswer = new CategoryEnum("marketplace-wolfram-short-answer");
public static readonly CategoryEnum MarketplaceYticaContactCenterReportingAnalytics = new CategoryEnum("marketplace-ytica-contact-center-reporting-analytics");
public static readonly CategoryEnum Mediastorage = new CategoryEnum("mediastorage");
public static readonly CategoryEnum Mms = new CategoryEnum("mms");
public static readonly CategoryEnum MmsInbound = new CategoryEnum("mms-inbound");
public static readonly CategoryEnum MmsInboundLongcode = new CategoryEnum("mms-inbound-longcode");
public static readonly CategoryEnum MmsInboundShortcode = new CategoryEnum("mms-inbound-shortcode");
public static readonly CategoryEnum MmsMessagesCarrierfees = new CategoryEnum("mms-messages-carrierfees");
public static readonly CategoryEnum MmsOutbound = new CategoryEnum("mms-outbound");
public static readonly CategoryEnum MmsOutboundLongcode = new CategoryEnum("mms-outbound-longcode");
public static readonly CategoryEnum MmsOutboundShortcode = new CategoryEnum("mms-outbound-shortcode");
public static readonly CategoryEnum MonitorReads = new CategoryEnum("monitor-reads");
public static readonly CategoryEnum MonitorStorage = new CategoryEnum("monitor-storage");
public static readonly CategoryEnum MonitorWrites = new CategoryEnum("monitor-writes");
public static readonly CategoryEnum Notify = new CategoryEnum("notify");
public static readonly CategoryEnum NotifyActionsAttempts = new CategoryEnum("notify-actions-attempts");
public static readonly CategoryEnum NotifyChannels = new CategoryEnum("notify-channels");
public static readonly CategoryEnum NumberFormatLookups = new CategoryEnum("number-format-lookups");
public static readonly CategoryEnum Pchat = new CategoryEnum("pchat");
public static readonly CategoryEnum PchatUsers = new CategoryEnum("pchat-users");
public static readonly CategoryEnum PeerToPeerRoomsParticipantMinutes = new CategoryEnum("peer-to-peer-rooms-participant-minutes");
public static readonly CategoryEnum Pfax = new CategoryEnum("pfax");
public static readonly CategoryEnum PfaxMinutes = new CategoryEnum("pfax-minutes");
public static readonly CategoryEnum PfaxMinutesInbound = new CategoryEnum("pfax-minutes-inbound");
public static readonly CategoryEnum PfaxMinutesOutbound = new CategoryEnum("pfax-minutes-outbound");
public static readonly CategoryEnum PfaxPages = new CategoryEnum("pfax-pages");
public static readonly CategoryEnum Phonenumbers = new CategoryEnum("phonenumbers");
public static readonly CategoryEnum PhonenumbersCps = new CategoryEnum("phonenumbers-cps");
public static readonly CategoryEnum PhonenumbersEmergency = new CategoryEnum("phonenumbers-emergency");
public static readonly CategoryEnum PhonenumbersLocal = new CategoryEnum("phonenumbers-local");
public static readonly CategoryEnum PhonenumbersMobile = new CategoryEnum("phonenumbers-mobile");
public static readonly CategoryEnum PhonenumbersSetups = new CategoryEnum("phonenumbers-setups");
public static readonly CategoryEnum PhonenumbersTollfree = new CategoryEnum("phonenumbers-tollfree");
public static readonly CategoryEnum Premiumsupport = new CategoryEnum("premiumsupport");
public static readonly CategoryEnum Proxy = new CategoryEnum("proxy");
public static readonly CategoryEnum ProxyActiveSessions = new CategoryEnum("proxy-active-sessions");
public static readonly CategoryEnum Pstnconnectivity = new CategoryEnum("pstnconnectivity");
public static readonly CategoryEnum Pv = new CategoryEnum("pv");
public static readonly CategoryEnum PvCompositionMediaDownloaded = new CategoryEnum("pv-composition-media-downloaded");
public static readonly CategoryEnum PvCompositionMediaEncrypted = new CategoryEnum("pv-composition-media-encrypted");
public static readonly CategoryEnum PvCompositionMediaStored = new CategoryEnum("pv-composition-media-stored");
public static readonly CategoryEnum PvCompositionMinutes = new CategoryEnum("pv-composition-minutes");
public static readonly CategoryEnum PvRecordingCompositions = new CategoryEnum("pv-recording-compositions");
public static readonly CategoryEnum PvRoomParticipants = new CategoryEnum("pv-room-participants");
public static readonly CategoryEnum PvRoomParticipantsAu1 = new CategoryEnum("pv-room-participants-au1");
public static readonly CategoryEnum PvRoomParticipantsBr1 = new CategoryEnum("pv-room-participants-br1");
public static readonly CategoryEnum PvRoomParticipantsIe1 = new CategoryEnum("pv-room-participants-ie1");
public static readonly CategoryEnum PvRoomParticipantsJp1 = new CategoryEnum("pv-room-participants-jp1");
public static readonly CategoryEnum PvRoomParticipantsSg1 = new CategoryEnum("pv-room-participants-sg1");
public static readonly CategoryEnum PvRoomParticipantsUs1 = new CategoryEnum("pv-room-participants-us1");
public static readonly CategoryEnum PvRoomParticipantsUs2 = new CategoryEnum("pv-room-participants-us2");
public static readonly CategoryEnum PvRooms = new CategoryEnum("pv-rooms");
public static readonly CategoryEnum PvSipEndpointRegistrations = new CategoryEnum("pv-sip-endpoint-registrations");
public static readonly CategoryEnum Recordings = new CategoryEnum("recordings");
public static readonly CategoryEnum Recordingstorage = new CategoryEnum("recordingstorage");
public static readonly CategoryEnum RoomsGroupBandwidth = new CategoryEnum("rooms-group-bandwidth");
public static readonly CategoryEnum RoomsGroupMinutes = new CategoryEnum("rooms-group-minutes");
public static readonly CategoryEnum RoomsPeerToPeerMinutes = new CategoryEnum("rooms-peer-to-peer-minutes");
public static readonly CategoryEnum Shortcodes = new CategoryEnum("shortcodes");
public static readonly CategoryEnum ShortcodesCustomerowned = new CategoryEnum("shortcodes-customerowned");
public static readonly CategoryEnum ShortcodesMmsEnablement = new CategoryEnum("shortcodes-mms-enablement");
public static readonly CategoryEnum ShortcodesMps = new CategoryEnum("shortcodes-mps");
public static readonly CategoryEnum ShortcodesRandom = new CategoryEnum("shortcodes-random");
public static readonly CategoryEnum ShortcodesUk = new CategoryEnum("shortcodes-uk");
public static readonly CategoryEnum ShortcodesVanity = new CategoryEnum("shortcodes-vanity");
public static readonly CategoryEnum SmallGroupRooms = new CategoryEnum("small-group-rooms");
public static readonly CategoryEnum SmallGroupRoomsDataTrack = new CategoryEnum("small-group-rooms-data-track");
public static readonly CategoryEnum SmallGroupRoomsParticipantMinutes = new CategoryEnum("small-group-rooms-participant-minutes");
public static readonly CategoryEnum Sms = new CategoryEnum("sms");
public static readonly CategoryEnum SmsInbound = new CategoryEnum("sms-inbound");
public static readonly CategoryEnum SmsInboundLongcode = new CategoryEnum("sms-inbound-longcode");
public static readonly CategoryEnum SmsInboundShortcode = new CategoryEnum("sms-inbound-shortcode");
public static readonly CategoryEnum SmsMessagesCarrierfees = new CategoryEnum("sms-messages-carrierfees");
public static readonly CategoryEnum SmsMessagesFeatures = new CategoryEnum("sms-messages-features");
public static readonly CategoryEnum SmsMessagesFeaturesSenderid = new CategoryEnum("sms-messages-features-senderid");
public static readonly CategoryEnum SmsOutbound = new CategoryEnum("sms-outbound");
public static readonly CategoryEnum SmsOutboundContentInspection = new CategoryEnum("sms-outbound-content-inspection");
public static readonly CategoryEnum SmsOutboundLongcode = new CategoryEnum("sms-outbound-longcode");
public static readonly CategoryEnum SmsOutboundShortcode = new CategoryEnum("sms-outbound-shortcode");
public static readonly CategoryEnum SpeechRecognition = new CategoryEnum("speech-recognition");
public static readonly CategoryEnum StudioEngagements = new CategoryEnum("studio-engagements");
public static readonly CategoryEnum Sync = new CategoryEnum("sync");
public static readonly CategoryEnum SyncActions = new CategoryEnum("sync-actions");
public static readonly CategoryEnum SyncEndpointHours = new CategoryEnum("sync-endpoint-hours");
public static readonly CategoryEnum SyncEndpointHoursAboveDailyCap = new CategoryEnum("sync-endpoint-hours-above-daily-cap");
public static readonly CategoryEnum TaskrouterTasks = new CategoryEnum("taskrouter-tasks");
public static readonly CategoryEnum Totalprice = new CategoryEnum("totalprice");
public static readonly CategoryEnum Transcriptions = new CategoryEnum("transcriptions");
public static readonly CategoryEnum TrunkingCps = new CategoryEnum("trunking-cps");
public static readonly CategoryEnum TrunkingEmergencyCalls = new CategoryEnum("trunking-emergency-calls");
public static readonly CategoryEnum TrunkingOrigination = new CategoryEnum("trunking-origination");
public static readonly CategoryEnum TrunkingOriginationLocal = new CategoryEnum("trunking-origination-local");
public static readonly CategoryEnum TrunkingOriginationMobile = new CategoryEnum("trunking-origination-mobile");
public static readonly CategoryEnum TrunkingOriginationTollfree = new CategoryEnum("trunking-origination-tollfree");
public static readonly CategoryEnum TrunkingRecordings = new CategoryEnum("trunking-recordings");
public static readonly CategoryEnum TrunkingSecure = new CategoryEnum("trunking-secure");
public static readonly CategoryEnum TrunkingTermination = new CategoryEnum("trunking-termination");
public static readonly CategoryEnum Turnmegabytes = new CategoryEnum("turnmegabytes");
public static readonly CategoryEnum TurnmegabytesAustralia = new CategoryEnum("turnmegabytes-australia");
public static readonly CategoryEnum TurnmegabytesBrasil = new CategoryEnum("turnmegabytes-brasil");
public static readonly CategoryEnum TurnmegabytesGermany = new CategoryEnum("turnmegabytes-germany");
public static readonly CategoryEnum TurnmegabytesIndia = new CategoryEnum("turnmegabytes-india");
public static readonly CategoryEnum TurnmegabytesIreland = new CategoryEnum("turnmegabytes-ireland");
public static readonly CategoryEnum TurnmegabytesJapan = new CategoryEnum("turnmegabytes-japan");
public static readonly CategoryEnum TurnmegabytesSingapore = new CategoryEnum("turnmegabytes-singapore");
public static readonly CategoryEnum TurnmegabytesUseast = new CategoryEnum("turnmegabytes-useast");
public static readonly CategoryEnum TurnmegabytesUswest = new CategoryEnum("turnmegabytes-uswest");
public static readonly CategoryEnum TwilioInterconnect = new CategoryEnum("twilio-interconnect");
public static readonly CategoryEnum VerifyPush = new CategoryEnum("verify-push");
public static readonly CategoryEnum VideoRecordings = new CategoryEnum("video-recordings");
public static readonly CategoryEnum VoiceInsights = new CategoryEnum("voice-insights");
public static readonly CategoryEnum VoiceInsightsClientInsightsOnDemandMinute = new CategoryEnum("voice-insights-client-insights-on-demand-minute");
public static readonly CategoryEnum VoiceInsightsPtsnInsightsOnDemandMinute = new CategoryEnum("voice-insights-ptsn-insights-on-demand-minute");
public static readonly CategoryEnum VoiceInsightsSipInterfaceInsightsOnDemandMinute = new CategoryEnum("voice-insights-sip-interface-insights-on-demand-minute");
public static readonly CategoryEnum VoiceInsightsSipTrunkingInsightsOnDemandMinute = new CategoryEnum("voice-insights-sip-trunking-insights-on-demand-minute");
public static readonly CategoryEnum Wireless = new CategoryEnum("wireless");
public static readonly CategoryEnum WirelessOrders = new CategoryEnum("wireless-orders");
public static readonly CategoryEnum WirelessOrdersArtwork = new CategoryEnum("wireless-orders-artwork");
public static readonly CategoryEnum WirelessOrdersBulk = new CategoryEnum("wireless-orders-bulk");
public static readonly CategoryEnum WirelessOrdersEsim = new CategoryEnum("wireless-orders-esim");
public static readonly CategoryEnum WirelessOrdersStarter = new CategoryEnum("wireless-orders-starter");
public static readonly CategoryEnum WirelessUsage = new CategoryEnum("wireless-usage");
public static readonly CategoryEnum WirelessUsageCommands = new CategoryEnum("wireless-usage-commands");
public static readonly CategoryEnum WirelessUsageCommandsAfrica = new CategoryEnum("wireless-usage-commands-africa");
public static readonly CategoryEnum WirelessUsageCommandsAsia = new CategoryEnum("wireless-usage-commands-asia");
public static readonly CategoryEnum WirelessUsageCommandsCentralandsouthamerica = new CategoryEnum("wireless-usage-commands-centralandsouthamerica");
public static readonly CategoryEnum WirelessUsageCommandsEurope = new CategoryEnum("wireless-usage-commands-europe");
public static readonly CategoryEnum WirelessUsageCommandsHome = new CategoryEnum("wireless-usage-commands-home");
public static readonly CategoryEnum WirelessUsageCommandsNorthamerica = new CategoryEnum("wireless-usage-commands-northamerica");
public static readonly CategoryEnum WirelessUsageCommandsOceania = new CategoryEnum("wireless-usage-commands-oceania");
public static readonly CategoryEnum WirelessUsageCommandsRoaming = new CategoryEnum("wireless-usage-commands-roaming");
public static readonly CategoryEnum WirelessUsageData = new CategoryEnum("wireless-usage-data");
public static readonly CategoryEnum WirelessUsageDataAfrica = new CategoryEnum("wireless-usage-data-africa");
public static readonly CategoryEnum WirelessUsageDataAsia = new CategoryEnum("wireless-usage-data-asia");
public static readonly CategoryEnum WirelessUsageDataCentralandsouthamerica = new CategoryEnum("wireless-usage-data-centralandsouthamerica");
public static readonly CategoryEnum WirelessUsageDataCustomAdditionalmb = new CategoryEnum("wireless-usage-data-custom-additionalmb");
public static readonly CategoryEnum WirelessUsageDataCustomFirst5Mb = new CategoryEnum("wireless-usage-data-custom-first5mb");
public static readonly CategoryEnum WirelessUsageDataDomesticRoaming = new CategoryEnum("wireless-usage-data-domestic-roaming");
public static readonly CategoryEnum WirelessUsageDataEurope = new CategoryEnum("wireless-usage-data-europe");
public static readonly CategoryEnum WirelessUsageDataIndividualAdditionalgb = new CategoryEnum("wireless-usage-data-individual-additionalgb");
public static readonly CategoryEnum WirelessUsageDataIndividualFirstgb = new CategoryEnum("wireless-usage-data-individual-firstgb");
public static readonly CategoryEnum WirelessUsageDataInternationalRoamingCanada = new CategoryEnum("wireless-usage-data-international-roaming-canada");
public static readonly CategoryEnum WirelessUsageDataInternationalRoamingIndia = new CategoryEnum("wireless-usage-data-international-roaming-india");
public static readonly CategoryEnum WirelessUsageDataInternationalRoamingMexico = new CategoryEnum("wireless-usage-data-international-roaming-mexico");
public static readonly CategoryEnum WirelessUsageDataNorthamerica = new CategoryEnum("wireless-usage-data-northamerica");
public static readonly CategoryEnum WirelessUsageDataOceania = new CategoryEnum("wireless-usage-data-oceania");
public static readonly CategoryEnum WirelessUsageDataPooled = new CategoryEnum("wireless-usage-data-pooled");
public static readonly CategoryEnum WirelessUsageDataPooledDownlink = new CategoryEnum("wireless-usage-data-pooled-downlink");
public static readonly CategoryEnum WirelessUsageDataPooledUplink = new CategoryEnum("wireless-usage-data-pooled-uplink");
public static readonly CategoryEnum WirelessUsageMrc = new CategoryEnum("wireless-usage-mrc");
public static readonly CategoryEnum WirelessUsageMrcCustom = new CategoryEnum("wireless-usage-mrc-custom");
public static readonly CategoryEnum WirelessUsageMrcIndividual = new CategoryEnum("wireless-usage-mrc-individual");
public static readonly CategoryEnum WirelessUsageMrcPooled = new CategoryEnum("wireless-usage-mrc-pooled");
public static readonly CategoryEnum WirelessUsageMrcSuspended = new CategoryEnum("wireless-usage-mrc-suspended");
public static readonly CategoryEnum WirelessUsageSms = new CategoryEnum("wireless-usage-sms");
public static readonly CategoryEnum WirelessUsageVoice = new CategoryEnum("wireless-usage-voice");
}
private static Request BuildReadRequest(ReadYearlyOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
"/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Usage/Records/Yearly.json",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Yearly parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Yearly </returns>
public static ResourceSet<YearlyResource> Read(ReadYearlyOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<YearlyResource>.FromJson("usage_records", response.Content);
return new ResourceSet<YearlyResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read Yearly parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Yearly </returns>
public static async System.Threading.Tasks.Task<ResourceSet<YearlyResource>> ReadAsync(ReadYearlyOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<YearlyResource>.FromJson("usage_records", response.Content);
return new ResourceSet<YearlyResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="category"> The usage category of the UsageRecord resources to read </param>
/// <param name="startDate"> Only include usage that has occurred on or after this date </param>
/// <param name="endDate"> Only include usage that occurred on or before this date </param>
/// <param name="includeSubaccounts"> Whether to include usage from the master account and all its subaccounts </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Yearly </returns>
public static ResourceSet<YearlyResource> Read(string pathAccountSid = null,
YearlyResource.CategoryEnum category = null,
DateTime? startDate = null,
DateTime? endDate = null,
bool? includeSubaccounts = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadYearlyOptions(){PathAccountSid = pathAccountSid, Category = category, StartDate = startDate, EndDate = endDate, IncludeSubaccounts = includeSubaccounts, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param>
/// <param name="category"> The usage category of the UsageRecord resources to read </param>
/// <param name="startDate"> Only include usage that has occurred on or after this date </param>
/// <param name="endDate"> Only include usage that occurred on or before this date </param>
/// <param name="includeSubaccounts"> Whether to include usage from the master account and all its subaccounts </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Yearly </returns>
public static async System.Threading.Tasks.Task<ResourceSet<YearlyResource>> ReadAsync(string pathAccountSid = null,
YearlyResource.CategoryEnum category = null,
DateTime? startDate = null,
DateTime? endDate = null,
bool? includeSubaccounts = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadYearlyOptions(){PathAccountSid = pathAccountSid, Category = category, StartDate = startDate, EndDate = endDate, IncludeSubaccounts = includeSubaccounts, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<YearlyResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<YearlyResource>.FromJson("usage_records", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<YearlyResource> NextPage(Page<YearlyResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<YearlyResource>.FromJson("usage_records", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<YearlyResource> PreviousPage(Page<YearlyResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<YearlyResource>.FromJson("usage_records", response.Content);
}
/// <summary>
/// Converts a JSON string into a YearlyResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> YearlyResource object represented by the provided JSON </returns>
public static YearlyResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<YearlyResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account accrued the usage
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The API version used to create the resource
/// </summary>
[JsonProperty("api_version")]
public string ApiVersion { get; private set; }
/// <summary>
/// Usage records up to date as of this timestamp
/// </summary>
[JsonProperty("as_of")]
public string AsOf { get; private set; }
/// <summary>
/// The category of usage
/// </summary>
[JsonProperty("category")]
[JsonConverter(typeof(StringEnumConverter))]
public YearlyResource.CategoryEnum Category { get; private set; }
/// <summary>
/// The number of usage events
/// </summary>
[JsonProperty("count")]
public string Count { get; private set; }
/// <summary>
/// The units in which count is measured
/// </summary>
[JsonProperty("count_unit")]
public string CountUnit { get; private set; }
/// <summary>
/// A plain-language description of the usage category
/// </summary>
[JsonProperty("description")]
public string Description { get; private set; }
/// <summary>
/// The last date for which usage is included in the UsageRecord
/// </summary>
[JsonProperty("end_date")]
public DateTime? EndDate { get; private set; }
/// <summary>
/// The total price of the usage
/// </summary>
[JsonProperty("price")]
public decimal? Price { get; private set; }
/// <summary>
/// The currency in which `price` is measured
/// </summary>
[JsonProperty("price_unit")]
public string PriceUnit { get; private set; }
/// <summary>
/// The first date for which usage is included in this UsageRecord
/// </summary>
[JsonProperty("start_date")]
public DateTime? StartDate { get; private set; }
/// <summary>
/// A list of related resources identified by their relative URIs
/// </summary>
[JsonProperty("subresource_uris")]
public Dictionary<string, string> SubresourceUris { get; private set; }
/// <summary>
/// The URI of the resource, relative to `https://api.twilio.com`
/// </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
/// <summary>
/// The amount of usage
/// </summary>
[JsonProperty("usage")]
public string Usage { get; private set; }
/// <summary>
/// The units in which usage is measured
/// </summary>
[JsonProperty("usage_unit")]
public string UsageUnit { get; private set; }
private YearlyResource()
{
}
}
}
| |
using UnityEngine;
using System;
using System.IO;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
namespace CUDLR
{
public class RequestContext
{
public HttpListenerContext context;
public Match match;
public bool pass;
public string path;
public int currentRoute;
public HttpListenerRequest Request { get { return context.Request; } }
public HttpListenerResponse Response { get { return context.Response; } }
public RequestContext (HttpListenerContext ctx)
{
context = ctx;
match = null;
pass = false;
path = WWW.UnEscapeURL (context.Request.Url.AbsolutePath);
if (path == "/")
path = "/index.html";
currentRoute = 0;
}
}
public class Server : MonoBehaviour
{
[SerializeField]
public int Port = 55055;
[SerializeField]
public bool RegisterLogCallback = false;
private static Thread mainThread;
private static string fileRoot;
private static HttpListener listener;
private static List<RouteAttribute> registeredRoutes;
private static Queue<RequestContext> mainRequests = new Queue<RequestContext> ();
// List of supported files
// FIXME add an api to register new types
private static Dictionary<string, string> fileTypes = new Dictionary<string, string> {
{ "js", "application/javascript" },
{ "json", "application/json" },
{ "jpg", "image/jpeg" },
{ "jpeg", "image/jpeg" },
{ "gif", "image/gif" },
{ "png", "image/png" },
{ "css", "text/css" },
{ "htm", "text/html" },
{ "html", "text/html" },
{ "ico", "image/x-icon" },
};
public virtual void Awake ()
{
mainThread = Thread.CurrentThread;
fileRoot = Path.Combine (Application.streamingAssetsPath, "CUDLR");
StartServer (Port);
StartCoroutine (HandleRequests ());
DontDestroyOnLoad (this.gameObject);
}
void StartServer (int port)
{
try {
// Start server
Debug.Log ("Starting CUDLR Server on port : " + port);
if (listener == null) {
listener = new HttpListener ();
listener.Prefixes.Add ("http://*:" + port + "/");
}
if (!listener.IsListening) {
listener.Start ();
listener.BeginGetContext (ListenerCallback, null);
}
} catch (SocketException e) {
Debug.Log (e.Message);
port++;
StartServer (port);
}
}
public void OnApplicationPause (bool paused)
{
if (paused) {
listener.Stop ();
} else {
listener.Start ();
listener.BeginGetContext (ListenerCallback, null);
}
}
public virtual void OnDestroy ()
{
listener.Close ();
listener = null;
}
private void RegisterRoutes ()
{
if (registeredRoutes == null) {
registeredRoutes = new List<RouteAttribute> ();
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (Type type in assembly.GetTypes()) {
// FIXME add support for non-static methods (FindObjectByType?)
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
RouteAttribute[] attrs = method.GetCustomAttributes (typeof(RouteAttribute), true) as RouteAttribute[];
if (attrs.Length == 0)
continue;
RouteAttribute.Callback cbm = Delegate.CreateDelegate (typeof(RouteAttribute.Callback), method, false) as RouteAttribute.Callback;
if (cbm == null) {
Debug.LogError (string.Format ("Method {0}.{1} takes the wrong arguments for a console route.", type, method.Name));
continue;
}
// try with a bare action
foreach (RouteAttribute route in attrs) {
if (route.m_route == null) {
Debug.LogError (string.Format ("Method {0}.{1} needs a valid route regexp.", type, method.Name));
continue;
}
route.m_callback = cbm;
registeredRoutes.Add (route);
}
}
}
}
RegisterFileHandlers ();
}
}
static void FindFileType (RequestContext context, bool download, out string path, out string type)
{
path = Path.Combine (fileRoot, context.match.Groups [1].Value);
string ext = Path.GetExtension (path).ToLower ().TrimStart (new char[] { '.' });
if (download || !fileTypes.TryGetValue (ext, out type))
type = "application/octet-stream";
}
public delegate void FileHandlerDelegate (RequestContext context, bool download);
static void WWWFileHandler (RequestContext context, bool download)
{
string path, type;
FindFileType (context, download, out path, out type);
WWW req = new WWW (path);
while (!req.isDone) {
Thread.Sleep (0);
}
if (string.IsNullOrEmpty (req.error)) {
context.Response.ContentType = type;
if (download)
context.Response.AddHeader ("Content-disposition", string.Format ("attachment; filename={0}", Path.GetFileName (path)));
context.Response.WriteBytes (req.bytes);
return;
}
if (req.error.StartsWith ("Couldn't open file")) {
context.pass = true;
} else {
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.StatusDescription = string.Format ("Fatal error:\n{0}", req.error);
}
}
static void FileHandler (RequestContext context, bool download)
{
string path, type;
FindFileType (context, download, out path, out type);
if (File.Exists (path)) {
context.Response.WriteFile (path, type, download);
} else {
context.pass = true;
}
}
static void RegisterFileHandlers ()
{
string pattern = string.Format ("({0})", string.Join ("|", fileTypes.Select (x => x.Key).ToArray ()));
RouteAttribute downloadRoute = new RouteAttribute (string.Format (@"^/download/(.*\.{0})$", pattern));
RouteAttribute fileRoute = new RouteAttribute (string.Format (@"^/(.*\.{0})$", pattern));
bool needs_www = fileRoot.Contains ("://");
downloadRoute.m_runOnMainThread = needs_www;
fileRoute.m_runOnMainThread = needs_www;
FileHandlerDelegate callback = FileHandler;
if (needs_www)
callback = WWWFileHandler;
downloadRoute.m_callback = delegate (RequestContext context) {
callback (context, true);
};
fileRoute.m_callback = delegate (RequestContext context) {
callback (context, false);
};
registeredRoutes.Add (downloadRoute);
registeredRoutes.Add (fileRoute);
}
void OnEnable ()
{
if (RegisterLogCallback) {
// Capture Console Logs
Application.RegisterLogCallback (Console.LogCallback);
}
}
void OnDisable ()
{
if (RegisterLogCallback) {
Application.RegisterLogCallback (null);
}
}
void Update ()
{
Console.Update ();
}
void ListenerCallback (IAsyncResult result)
{
RequestContext context = new RequestContext (listener.EndGetContext (result));
HandleRequest (context);
if (listener.IsListening) {
listener.BeginGetContext (ListenerCallback, null);
}
}
void HandleRequest (RequestContext context)
{
RegisterRoutes ();
try {
bool handled = false;
for (; context.currentRoute < registeredRoutes.Count; ++context.currentRoute) {
RouteAttribute route = registeredRoutes [context.currentRoute];
Match match = route.m_route.Match (context.path);
if (!match.Success)
continue;
if (!route.m_methods.IsMatch (context.Request.HttpMethod))
continue;
// Upgrade to main thread if necessary
if (route.m_runOnMainThread && Thread.CurrentThread != mainThread) {
lock (mainRequests) {
mainRequests.Enqueue (context);
}
return;
}
context.match = match;
route.m_callback (context);
handled = !context.pass;
if (handled)
break;
}
if (!handled) {
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
context.Response.StatusDescription = "Not Found";
}
} catch (Exception exception) {
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.StatusDescription = string.Format ("Fatal error:\n{0}", exception);
Debug.LogException (exception);
}
context.Response.OutputStream.Close ();
}
IEnumerator HandleRequests ()
{
while (true) {
while (mainRequests.Count == 0) {
yield return new WaitForEndOfFrame ();
}
RequestContext context = null;
lock (mainRequests) {
context = mainRequests.Dequeue ();
}
HandleRequest (context);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using TwainDotNet.TwainNative;
using log4net;
namespace TwainDotNet
{
public class DataSource : IDisposable
{
private static ILog log = LogManager.GetLogger(typeof(DataSource));
Identity _applicationId;
IWindowsMessageHook _messageHook;
public DataSource(Identity applicationId, Identity sourceId, IWindowsMessageHook messageHook)
{
_applicationId = applicationId;
SourceId = sourceId.Clone();
_messageHook = messageHook;
}
~DataSource()
{
Dispose(false);
}
public Identity SourceId { get; private set; }
public void NegotiateTransferCount(ScanSettings scanSettings)
{
try
{
scanSettings.TransferCount = Capability.SetCapability(
Capabilities.XferCount,
scanSettings.TransferCount,
_applicationId,
SourceId);
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
public void NegotiateFeeder(ScanSettings scanSettings)
{
try
{
if (scanSettings.UseDocumentFeeder.HasValue)
{
Capability.SetCapability(Capabilities.FeederEnabled, scanSettings.UseDocumentFeeder.Value, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
try
{
if (scanSettings.UseAutoFeeder.HasValue)
{
Capability.SetCapability(Capabilities.AutoFeed, scanSettings.UseAutoFeeder == true && scanSettings.UseDocumentFeeder == true, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
try
{
if (scanSettings.UseAutoScanCache.HasValue)
{
Capability.SetCapability(Capabilities.AutoScan, scanSettings.UseAutoScanCache.Value, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
public PixelType GetPixelType(ScanSettings scanSettings)
{
switch (scanSettings.Resolution.ColourSetting)
{
case ColourSetting.BlackAndWhite:
return PixelType.BlackAndWhite;
case ColourSetting.GreyScale:
return PixelType.Grey;
case ColourSetting.Colour:
return PixelType.Rgb;
}
throw new NotImplementedException();
}
public short GetBitDepth(ScanSettings scanSettings)
{
switch (scanSettings.Resolution.ColourSetting)
{
case ColourSetting.BlackAndWhite:
return 1;
case ColourSetting.GreyScale:
return 8;
case ColourSetting.Colour:
return 16;
}
throw new NotImplementedException();
}
public bool PaperDetectable
{
get
{
try
{
return Capability.GetBoolCapability(Capabilities.FeederLoaded, _applicationId, SourceId);
}
catch
{
return false;
}
}
}
public bool SupportsDuplex
{
get
{
try
{
var cap = new Capability(Capabilities.Duplex, TwainType.Int16, _applicationId, SourceId);
return ((Duplex)cap.GetBasicValue().Int16Value) != Duplex.None;
}
catch
{
return false;
}
}
}
public void NegotiateColour(ScanSettings scanSettings)
{
try
{
Capability.SetBasicCapability(Capabilities.IPixelType, (ushort)GetPixelType(scanSettings), TwainType.UInt16, _applicationId, SourceId);
}
catch
{
// Do nothing if the data source does not support the requested capability
}
// TODO: Also set this for colour scanning
try
{
if (scanSettings.Resolution.ColourSetting != ColourSetting.Colour)
{
Capability.SetCapability(Capabilities.BitDepth, GetBitDepth(scanSettings), _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
public void NegotiateResolution(ScanSettings scanSettings)
{
try
{
if (scanSettings.Resolution.Dpi.HasValue)
{
int dpi = scanSettings.Resolution.Dpi.Value;
Capability.SetBasicCapability(Capabilities.XResolution, dpi, TwainType.Fix32, _applicationId, SourceId);
Capability.SetBasicCapability(Capabilities.YResolution, dpi, TwainType.Fix32, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
public void NegotiateDuplex(ScanSettings scanSettings)
{
try
{
if (scanSettings.UseDuplex.HasValue && SupportsDuplex)
{
Capability.SetCapability(Capabilities.DuplexEnabled, scanSettings.UseDuplex.Value, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
public void NegotiateOrientation(ScanSettings scanSettings)
{
// Set orientation (default is portrait)
try
{
var cap = new Capability(Capabilities.Orientation, TwainType.Int16, _applicationId, SourceId);
if ((Orientation)cap.GetBasicValue().Int16Value != Orientation.Default)
{
Capability.SetBasicCapability(Capabilities.Orientation, (ushort)scanSettings.Page.Orientation, TwainType.UInt16, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
/// <summary>
/// Negotiates the size of the page.
/// </summary>
/// <param name="scanSettings">The scan settings.</param>
public void NegotiatePageSize(ScanSettings scanSettings)
{
try
{
var cap = new Capability(Capabilities.Supportedsizes, TwainType.Int16, _applicationId, SourceId);
if ((PageType)cap.GetBasicValue().Int16Value != PageType.UsLetter)
{
Capability.SetBasicCapability(Capabilities.Supportedsizes, (ushort)scanSettings.Page.Size, TwainType.UInt16, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
/// <summary>
/// Negotiates the automatic rotation capability.
/// </summary>
/// <param name="scanSettings">The scan settings.</param>
public void NegotiateAutomaticRotate(ScanSettings scanSettings)
{
try
{
if (scanSettings.Rotation.AutomaticRotate)
{
Capability.SetCapability(Capabilities.Automaticrotate, true, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
/// <summary>
/// Negotiates the automatic border detection capability.
/// </summary>
/// <param name="scanSettings">The scan settings.</param>
public void NegotiateAutomaticBorderDetection(ScanSettings scanSettings)
{
try
{
if (scanSettings.Rotation.AutomaticBorderDetection)
{
Capability.SetCapability(Capabilities.Automaticborderdetection, true, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
/// <summary>
/// Negotiates the indicator.
/// </summary>
/// <param name="scanSettings">The scan settings.</param>
public void NegotiateProgressIndicator(ScanSettings scanSettings)
{
try
{
if (scanSettings.ShowProgressIndicatorUI.HasValue)
{
Capability.SetCapability(Capabilities.Indicators, scanSettings.ShowProgressIndicatorUI.Value, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
}
public bool Open(ScanSettings settings)
{
OpenSource();
if (settings.AbortWhenNoPaperDetectable && !PaperDetectable)
throw new FeederEmptyException();
// Set whether or not to show progress window
NegotiateProgressIndicator(settings);
NegotiateTransferCount(settings);
NegotiateFeeder(settings);
NegotiateDuplex(settings);
if (settings.UseDocumentFeeder == true &&
settings.Page != null)
{
NegotiatePageSize(settings);
NegotiateOrientation(settings);
}
if (settings.Area != null)
{
NegotiateArea(settings);
}
if (settings.Resolution != null)
{
NegotiateColour(settings);
NegotiateResolution(settings);
}
// Configure automatic rotation and image border detection
if (settings.Rotation != null)
{
NegotiateAutomaticRotate(settings);
NegotiateAutomaticBorderDetection(settings);
}
return Enable(settings);
}
private bool NegotiateArea(ScanSettings scanSettings)
{
var area = scanSettings.Area;
if (area == null)
{
return false;
}
try
{
var cap = new Capability(Capabilities.IUnits, TwainType.Int16, _applicationId, SourceId);
if ((Units)cap.GetBasicValue().Int16Value != area.Units)
{
Capability.SetCapability(Capabilities.IUnits, (short)area.Units, _applicationId, SourceId);
}
}
catch
{
// Do nothing if the data source does not support the requested capability
}
var imageLayout = new ImageLayout
{
Frame = new Frame
{
Left = new Fix32(area.Left),
Top = new Fix32(area.Top),
Right = new Fix32(area.Right),
Bottom = new Fix32(area.Bottom)
}
};
var result = Twain32Native.DsImageLayout(
_applicationId,
SourceId,
DataGroup.Image,
DataArgumentType.ImageLayout,
Message.Set,
imageLayout);
if (result != TwainResult.Success)
{
throw new TwainException("DsImageLayout.GetDefault error", result);
}
return true;
}
public void OpenSource()
{
var result = Twain32Native.DsmIdentity(
_applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.OpenDS,
SourceId);
if (result != TwainResult.Success)
{
throw new TwainException("Error opening data source", result);
}
}
public bool Enable(ScanSettings settings)
{
UserInterface ui = new UserInterface();
ui.ShowUI = (short)(settings.ShowTwainUI ? 1 : 0);
ui.ModalUI = 1;
ui.ParentHand = _messageHook.WindowHandle;
var result = Twain32Native.DsUserInterface(
_applicationId,
SourceId,
DataGroup.Control,
DataArgumentType.UserInterface,
Message.EnableDS,
ui);
if (result != TwainResult.Success)
{
Dispose();
return false;
}
return true;
}
public static DataSource GetDefault(Identity applicationId, IWindowsMessageHook messageHook)
{
log.Debug("create new identity");
var defaultSourceId = new Identity();
// Attempt to get information about the system default source
log.Debug("call DsmIdentity");
var result = Twain32Native.DsmIdentity(
applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.GetDefault,
defaultSourceId);
if (result != TwainResult.Success)
{
log.Debug("result != success");
var status = DataSourceManager.GetConditionCode(applicationId, null);
throw new TwainException("Error getting information about the default source: " + result, result, status);
}
log.Debug("return new data source");
return new DataSource(applicationId, defaultSourceId, messageHook);
}
public static DataSource UserSelected(Identity applicationId, IWindowsMessageHook messageHook)
{
var defaultSourceId = new Identity();
// Show the TWAIN interface to allow the user to select a source
Twain32Native.DsmIdentity(
applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.UserSelect,
defaultSourceId);
return new DataSource(applicationId, defaultSourceId, messageHook);
}
public static List<DataSource> GetAllSources(Identity applicationId, IWindowsMessageHook messageHook)
{
var sources = new List<DataSource>();
Identity id = new Identity();
// Get the first source
var result = Twain32Native.DsmIdentity(
applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.GetFirst,
id);
if (result == TwainResult.EndOfList)
{
return sources;
}
else if (result != TwainResult.Success)
{
throw new TwainException("Error getting first source.", result);
}
else
{
sources.Add(new DataSource(applicationId, id, messageHook));
}
while (true)
{
// Get the next source
result = Twain32Native.DsmIdentity(
applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.GetNext,
id);
if (result == TwainResult.EndOfList)
{
break;
}
else if (result != TwainResult.Success)
{
throw new TwainException("Error enumerating sources.", result);
}
sources.Add(new DataSource(applicationId, id, messageHook));
}
return sources;
}
public static DataSource GetSource(string sourceProductName, Identity applicationId, IWindowsMessageHook messageHook)
{
// A little slower than it could be, if enumerating unnecessary sources is slow. But less code duplication.
foreach (var source in GetAllSources(applicationId, messageHook))
{
if (sourceProductName.Equals(source.SourceId.ProductName, StringComparison.InvariantCultureIgnoreCase))
{
return source;
}
}
return null;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
public void Close()
{
if (SourceId.Id != 0)
{
UserInterface userInterface = new UserInterface();
TwainResult result = Twain32Native.DsUserInterface(
_applicationId,
SourceId,
DataGroup.Control,
DataArgumentType.UserInterface,
Message.DisableDS,
userInterface);
if (result != TwainResult.Failure)
{
result = Twain32Native.DsmIdentity(
_applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.CloseDS,
SourceId);
}
}
}
}
}
| |
namespace OpenRiaServices.DomainServices.Tools.TextTemplate
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security.Principal;
using OpenRiaServices.DomainServices;
using OpenRiaServices.DomainServices.Server;
using OpenRiaServices.DomainServices.Server.ApplicationServices;
/// <summary>
/// Proxy generator for an entity.
/// </summary>
public abstract partial class EntityGenerator
{
private DomainServiceDescriptionAggregate _domainServiceDescriptionAggregate;
Type _visibleBaseType;
private List<PropertyDescriptor> _associationProperties;
/// <summary>
/// Gets the list of all the DomainServiceDescription objects.
/// </summary>
protected IEnumerable<DomainServiceDescription> DomainServiceDescriptions { get; private set; }
/// <summary>
/// Generates the entity class on the client.
/// </summary>
/// <param name="entityType">The type of the entity to be generated</param>
/// <param name="domainServiceDescriptions">The list of all the DomainServiceDescription objects.</param>
/// <param name="clientCodeGenerator">The ClientCodeGenerator object for this instance.</param>
/// <returns>Generated entity class code.</returns>
public string Generate(Type entityType, IEnumerable<DomainServiceDescription> domainServiceDescriptions, ClientCodeGenerator clientCodeGenerator)
{
this.Type = entityType;
this.ClientCodeGenerator = clientCodeGenerator;
this.DomainServiceDescriptions = domainServiceDescriptions;
return this.GenerateDataContractProxy();
}
internal override void Initialize()
{
this._domainServiceDescriptionAggregate = new DomainServiceDescriptionAggregate(this.DomainServiceDescriptions.Where(dsd => dsd.EntityTypes.Contains(this.Type)));
this._visibleBaseType = this._domainServiceDescriptionAggregate.GetEntityBaseType(this.Type);
this.GenerateGetIdentity = !this.IsDerivedType;
this._associationProperties = new List<PropertyDescriptor>();
base.Initialize();
}
internal bool GenerateGetIdentity { get; private set; }
internal override bool IsDerivedType
{
get
{
return this._visibleBaseType != null;
}
}
internal override IEnumerable<Type> ComplexTypes
{
get
{
return this._domainServiceDescriptionAggregate.ComplexTypes;
}
}
internal IEnumerable<PropertyDescriptor> AssociationProperties
{
get
{
if (this._associationProperties == null)
{
this._associationProperties = new List<PropertyDescriptor>();
}
return this._associationProperties;
}
}
internal override bool CanGenerateProperty(PropertyDescriptor propertyDescriptor)
{
// Check if it is an excluded property
if (propertyDescriptor.Attributes[typeof(ExcludeAttribute)] != null)
{
return false;
}
// Check if it is an external reference.
if (propertyDescriptor.Attributes[typeof(ExternalReferenceAttribute)] != null)
{
return true;
}
// The base can't generate the property, it could be an association which we know how to generate.
if (!base.CanGenerateProperty(propertyDescriptor))
{
AttributeCollection propertyAttributes = propertyDescriptor.ExplicitAttributes();
bool hasKeyAttr = (propertyAttributes[typeof(KeyAttribute)] != null);
// If we can't generate Key property, log a VS error (this will cancel CodeGen effectively)
if (hasKeyAttr)
{
// Property must not be serializable based on attributes (e.g. no DataMember), because
// we already checked its type which was fine.
this.ClientCodeGenerator.CodeGenerationHost.LogError(string.Format(
CultureInfo.CurrentCulture,
Resource.EntityCodeGen_EntityKey_PropertyNotSerializable,
this.Type, propertyDescriptor.Name));
return false;
}
// Get the implied element type (e.g. int32[], Nullable<int32>, IEnumerable<int32>)
// If the ultimate element type is not allowed, it's not acceptable, no matter whether
// this is an array, Nullable<T> or whatever
Type elementType = TypeUtility.GetElementType(propertyDescriptor.PropertyType);
if (!this._domainServiceDescriptionAggregate.EntityTypes.Contains(elementType) || (propertyDescriptor.Attributes[typeof(AssociationAttribute)] == null))
{
// If the base class says we can't generate the property, it is because the property is not serializable.
// The only other type entity would serialize is associations. Since it is not, return now.
return false;
}
}
// Ensure the property is not virtual, abstract or new
// If there is a violation, we log the error and keep
// running to accumulate all such errors. This function
// may return an "okay" for non-error case polymorphics.
if (!this.CanGeneratePropertyIfPolymorphic(propertyDescriptor))
{
return false;
}
return true;
}
/// <summary>
/// Determines whether the specified property belonging to the
/// current entity is polymorphic, and if so whether it is legal to generate it.
/// </summary>
/// <param name="pd">The property to validate</param>
/// <returns><c>true</c> if it is not polymorphic or it is legal to generate it, else <c>false</c></returns>
internal override bool CanGeneratePropertyIfPolymorphic(PropertyDescriptor pd)
{
PropertyInfo propertyInfo = this.Type.GetProperty(pd.Name);
if (propertyInfo != null)
{
if (this.IsMethodPolymorphic(propertyInfo.GetGetMethod()) ||
this.IsMethodPolymorphic(propertyInfo.GetSetMethod()))
{
// This property is polymorphic. To determine whether it is
// legal to generate, we determine whether any of our visible
// base types also expose this property. If so, we cannot generate it.
foreach (Type baseType in this.GetVisibleBaseTypes(this.Type))
{
if (baseType.GetProperty(pd.Name) != null)
{
return false;
}
}
// If get here, we have not generated an entity in the hierarchy between the
// current entity type and the entity that declared this. This means it is
// save to generate
return true;
}
}
return true;
}
private IEnumerable<Type> GetVisibleBaseTypes(Type entityType)
{
List<Type> types = new List<Type>();
for (Type baseType = this._domainServiceDescriptionAggregate.GetEntityBaseType(entityType);
baseType != null;
baseType = this._domainServiceDescriptionAggregate.GetEntityBaseType(baseType))
{
types.Add(baseType);
}
return types;
}
private bool IsMethodPolymorphic(MethodInfo methodInfo)
{
// Null allowed for convenience.
// If method is declared on a different entity type, then one of 2
// things will be true:
// 1. The declaring type is invisible, in which case it is not a problem
// 2. The declaring type is visible, in which case the error is reported there.
if (methodInfo == null || methodInfo.DeclaringType != this.Type)
{
return false;
}
// Virtual methods are disallowed.
// But the CLR marks interface methods IsVirtual=true, so the
// recommended test is this one.
if (methodInfo.IsVirtual && !methodInfo.IsFinal)
{
return true;
}
// Detecting the "new" keyword requires a check whether this method is
// hiding a method with the same signature in a derived type. IsHideBySig does not do this.
if (this.Type.BaseType != null)
{
Type[] parameterTypes = methodInfo.GetParameters().Select<ParameterInfo, Type>(p => p.ParameterType).ToArray();
MethodInfo baseMethod = this.Type.BaseType.GetMethod(methodInfo.Name, parameterTypes);
if (baseMethod != null)
{
return true;
}
}
return false;
}
internal override bool ShouldDeclareProperty(PropertyDescriptor pd)
{
if (!base.ShouldDeclareProperty(pd))
{
return false;
}
// Inheritance: when dealing with derived entities, we need to
// avoid generating a property already on the base. But we also
// need to account for flattening (holes in the exposed hiearchy.
// This helper method encapsulates that logic.
if (!this.ShouldFlattenProperty(pd))
{
return false;
}
AttributeCollection propertyAttributes = pd.ExplicitAttributes();
Type propertyType = pd.PropertyType;
// The [Key] attribute means this property is part of entity key
bool hasKeyAttr = (propertyAttributes[typeof(KeyAttribute)] != null);
if (hasKeyAttr)
{
if (!TypeUtility.IsPredefinedSimpleType(propertyType))
{
this.ClientCodeGenerator.CodeGenerationHost.LogError(string.Format(
CultureInfo.CurrentCulture,
Resource.EntityCodeGen_EntityKey_KeyTypeNotSupported,
this.Type, pd.Name, propertyType));
return false;
}
}
return true;
}
internal override bool HandleNonSerializableProperty(PropertyDescriptor propertyDescriptor)
{
AttributeCollection propertyAttributes = propertyDescriptor.ExplicitAttributes();
AssociationAttribute associationAttr = (AssociationAttribute)propertyAttributes[typeof(AssociationAttribute)];
bool externalReference = propertyAttributes[typeof(ExternalReferenceAttribute)] != null;
if (associationAttr != null)
{
this.AddAssociationToGenerate(propertyDescriptor);
return true;
}
return false;
}
private void AddAssociationToGenerate(PropertyDescriptor pd)
{
Type associationType =
IsCollectionType(pd.PropertyType) ?
TypeUtility.GetElementType(pd.PropertyType) :
pd.PropertyType;
if (!CodeGenUtilities.RegisterTypeName(associationType, this.Type.Namespace))
{
IEnumerable<Type> potentialConflicts =
this.ClientCodeGenerator.DomainServiceDescriptions
.SelectMany<DomainServiceDescription, Type>(dsd => dsd.EntityTypes)
.Where(entity => entity.Namespace == associationType.Namespace).Distinct();
foreach (Type potentialConflict in potentialConflicts)
{
CodeGenUtilities.RegisterTypeName(potentialConflict, this.Type.Namespace);
}
}
this._associationProperties.Add(pd);
}
internal void GetKeysInfo(out string[] keyNames, out string[] nullableKeyNames)
{
var keys = new List<string>();
var nullableKeys = new List<string>();
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this.Type);
foreach (PropertyDescriptor prop in properties)
{
if (prop.Attributes[typeof(KeyAttribute)] as KeyAttribute != null)
{
string propName = CodeGenUtilities.MakeCompliantFieldName(prop.Name);
keys.Add(propName);
if (TypeUtility.IsNullableType(prop.PropertyType) || !prop.PropertyType.IsValueType)
{
nullableKeys.Add(propName);
}
}
}
keyNames = keys.ToArray();
nullableKeyNames = nullableKeys.ToArray();
}
private bool ShouldFlattenProperty(PropertyDescriptor propertyDescriptor)
{
Type declaringType = propertyDescriptor.ComponentType;
// If this property is declared by the current entity type,
// the answer is always 'yes'
if (declaringType == this.Type)
{
return true;
}
// If this is a projection property (meaning it is declared outside this hierarchy),
// then the answer is "yes, declare it"
if (!declaringType.IsAssignableFrom(this.Type))
{
return true;
}
// If it is declared in any visible entity type, the answer is 'no'
// because it will be generated with that entity
if (this._domainServiceDescriptionAggregate.EntityTypes.Contains(declaringType))
{
return false;
}
// This property is defined in an entity that is not among the known types.
// We may need to lift it during code generation. But beware -- if there
// are multiple gaps in the hierarchy, we want to lift it only if some other
// visible base type of ours has not already done so.
Type baseType = this.Type.BaseType;
while (baseType != null)
{
// If we find the declaring type, we know from the test above it is
// not a known entity type. The first such non-known type is grounds
// for us lifting its properties.
if (baseType == declaringType)
{
return true;
}
// The first known type we encounter walking toward the base type
// will generate it, so we must not.
if (this._domainServiceDescriptionAggregate.EntityTypes.Contains(baseType))
{
break;
}
// Note: we explicitly allow this walkback to cross past
// the visible root, examining types lower than our root.
baseType = baseType.BaseType;
}
return false;
}
internal override bool IsPropertyShared(PropertyDescriptor pd)
{
if (base.IsPropertyShared(pd))
{
if (pd.ExplicitAttributes()[typeof(KeyAttribute)] != null)
{
// If there are any shared key members, don't generate GetIdentity method.
// Default implementation of GetIdentity on the Entity class will be used.
this.GenerateGetIdentity = false;
}
return true;
}
return false;
}
internal override void OnPropertySkipped(PropertyDescriptor pd)
{
AttributeCollection propertyAttributes = pd.ExplicitAttributes();
bool hasKeyAttr = (propertyAttributes[typeof(KeyAttribute)] != null);
// If we can't generate Key property, log a VS error (this will cancel CodeGen effectively)
if (hasKeyAttr)
{
// Property must not be serializable based on attributes (e.g. no DataMember), because
// we already checked its type which was fine.
this.ClientCodeGenerator.CodeGenerationHost.LogError(string.Format(
CultureInfo.CurrentCulture,
Resource.EntityCodeGen_EntityKey_PropertyNotSerializable,
this.Type, pd.Name));
}
}
internal override IEnumerable<Type> GetDerivedTypes()
{
return this._domainServiceDescriptionAggregate.EntityTypes.Where(t => t != this.Type && this.Type.IsAssignableFrom(t));
}
internal override string GetBaseTypeName()
{
string baseTypeName = string.Empty;
if (this._visibleBaseType != null)
{
baseTypeName = CodeGenUtilities.GetTypeName(this._visibleBaseType);
}
else
{
baseTypeName = "OpenRiaServices.DomainServices.Client.Entity";
}
// We special case User type to be able to handle the User entity that we define.
if (this.IsUserType)
{
return this.GetBaseTypeNameForUserType(baseTypeName);
}
return baseTypeName;
}
private string GetBaseTypeNameForUserType(string baseTypeName)
{
// Add the IIdentity and the IPrincipal interfaces to the User type.
baseTypeName = baseTypeName + ", " + CodeGenUtilities.GetTypeNameInGlobalNamespace(typeof(IIdentity));
baseTypeName = baseTypeName + ", " + CodeGenUtilities.GetTypeNameInGlobalNamespace(typeof(IPrincipal));
return baseTypeName;
}
internal bool IsUserType
{
get
{
return typeof(IUser).IsAssignableFrom(this.Type);
}
}
private class DomainServiceDescriptionAggregate
{
private HashSet<Type> _complexTypes;
private HashSet<Type> _entityTypes;
/// <summary>
/// Initializes a new instance of the <see cref="DomainServiceDescriptionAggregate"/> class.
/// </summary>
/// <param name="domainServiceDescriptions">The descriptions that exposes the entity type.</param>
internal DomainServiceDescriptionAggregate(IEnumerable<DomainServiceDescription> domainServiceDescriptions)
{
this.DomainServiceDescriptions = domainServiceDescriptions;
this._complexTypes = new HashSet<Type>();
this._entityTypes = new HashSet<Type>();
foreach (var dsd in domainServiceDescriptions)
{
foreach (var complexType in dsd.ComplexTypes)
{
this._complexTypes.Add(complexType);
}
foreach (var entityType in dsd.EntityTypes)
{
this._entityTypes.Add(entityType);
}
}
}
/// <summary>
/// Gets all the <see cref="DomainServiceDescription"/> that expose this entity.
/// </summary>
internal IEnumerable<DomainServiceDescription> DomainServiceDescriptions
{
get;
private set;
}
/// <summary>
/// Gets an enumerable representing the union of all complex types exposed
/// by each <see cref="DomainServiceDescription"/>.
/// </summary>
internal IEnumerable<Type> ComplexTypes
{
get
{
foreach (Type complexType in this._complexTypes)
{
yield return complexType;
}
}
}
/// <summary>
/// Gets an enumerable representing the union of all entity types exposed
/// by each <see cref="DomainServiceDescription"/>.
/// </summary>
internal IEnumerable<Type> EntityTypes
{
get
{
foreach (Type entityType in this._entityTypes)
{
yield return entityType;
}
}
}
/// <summary>
/// Returns true if the entity is shared.
/// </summary>
internal bool IsShared
{
get
{
return this.DomainServiceDescriptions.Count() > 1;
}
}
/// <summary>
/// Gets the base type of the given entity type.
/// </summary>
/// <param name="entityType">The entity type whose base type is required.</param>
/// <returns>The base type or <c>null</c> if the given
/// <paramref name="entityType"/> had no visible base types.</returns>
internal Type GetEntityBaseType(Type entityType)
{
Type baseType = entityType.BaseType;
while (baseType != null)
{
if (this.EntityTypes.Contains(baseType))
{
break;
}
baseType = baseType.BaseType;
}
return baseType;
}
/// <summary>
/// Returns the root type for the given entity type.
/// </summary>
/// <remarks>
/// The root type is the least derived entity type in the entity type
/// hierarchy that is exposed through a <see cref="DomainService"/>.
/// </remarks>
/// <param name="entityType">The entity type whose root is required.</param>
/// <returns>The type of the root or <c>null</c> if the given <paramref name="entityType"/>
/// has no base types.</returns>
internal Type GetRootEntityType(Type entityType)
{
Type rootType = null;
while (entityType != null)
{
if (this.EntityTypes.Contains(entityType))
{
rootType = entityType;
}
entityType = entityType.BaseType;
}
return rootType;
}
}
internal static bool IsCollectionType(Type t)
{
return typeof(IEnumerable).IsAssignableFrom(t);
}
internal static PropertyDescriptor GetReverseAssociation(PropertyDescriptor propertyDescriptor, AssociationAttribute assocAttrib)
{
Type otherType = TypeUtility.GetElementType(propertyDescriptor.PropertyType);
foreach (PropertyDescriptor entityMember in TypeDescriptor.GetProperties(otherType))
{
if (entityMember.Name == propertyDescriptor.Name)
{
// for self associations, both ends of the association are in
// the same class and have the same name. Therefore, we need to
// skip the member itself.
continue;
}
AssociationAttribute otherAssocAttrib = entityMember.Attributes[typeof(AssociationAttribute)] as AssociationAttribute;
if (otherAssocAttrib != null && otherAssocAttrib.Name == assocAttrib.Name)
{
return entityMember;
}
}
return null;
}
internal IEnumerable<DomainOperationEntry> GetEntityCustomMethods()
{
Dictionary<string, DomainOperationEntry> entityCustomMethods = new Dictionary<string, DomainOperationEntry>();
Dictionary<string, DomainServiceDescription> customMethodToDescriptionMap = new Dictionary<string, DomainServiceDescription>();
string methodName;
foreach (DomainServiceDescription description in this.DomainServiceDescriptions)
{
foreach (DomainOperationEntry customMethod in description.GetCustomMethods(this.Type))
{
methodName = customMethod.Name;
if (entityCustomMethods.ContainsKey(methodName))
{
this.ClientCodeGenerator.CodeGenerationHost.LogError(string.Format(CultureInfo.CurrentCulture, Resource.EntityCodeGen_DuplicateCustomMethodName, methodName, this.Type, customMethodToDescriptionMap[methodName].DomainServiceType, description.DomainServiceType));
}
else
{
entityCustomMethods.Add(methodName, customMethod);
customMethodToDescriptionMap.Add(methodName, description);
}
}
}
return entityCustomMethods.Values.AsEnumerable();
}
}
}
| |
// Copyright (c) 2002-2003, Sony Computer Entertainment America
// Copyright (c) 2002-2003, Craig Reynolds <craig_reynolds@playstation.sony.com>
// Copyright (C) 2007 Bjoern Graf <bjoern.graf@gmx.net>
// Copyright (C) 2007 Michael Coles <michael@digini.com>
// All rights reserved.
//
// This software is licensed as described in the file license.txt, which
// you should have received as part of this distribution. The terms
// are also available at http://www.codeplex.com/SharpSteer/Project/License.aspx.
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using SharpSteer2;
using SharpSteer2.Database;
using SharpSteer2.Helpers;
using Vector3 = System.Numerics.Vector3;
namespace Demo.PlugIns.Pedestrian
{
public class Pedestrian : SimpleVehicle
{
Trail _trail;
public override float MaxForce { get { return 16; } }
public override float MaxSpeed { get { return 2; } }
// called when steerToFollowPath decides steering is required
public void AnnotatePathFollowing(Vector3 future, Vector3 onPath, Vector3 target, float outside)
{
Color yellow = Color.Yellow;
Color lightOrange = new Color((byte)(255.0f * 1.0f), (byte)(255.0f * 0.5f), 0);
Color darkOrange = new Color((byte)(255.0f * 0.6f), (byte)(255.0f * 0.3f), 0);
// draw line from our position to our predicted future position
annotation.Line(Position, future, yellow.ToVector3().FromXna());
// draw line from our position to our steering target on the path
annotation.Line(Position, target, Color.Orange.ToVector3().FromXna());
// draw a two-toned line between the future test point and its
// projection onto the path, the change from dark to light color
// indicates the boundary of the tube.
Vector3 boundaryOffset = Vector3.Normalize(onPath - future);
boundaryOffset *= outside;
Vector3 onPathBoundary = future + boundaryOffset;
annotation.Line(onPath, onPathBoundary, darkOrange.ToVector3().FromXna());
annotation.Line(onPathBoundary, future, lightOrange.ToVector3().FromXna());
}
// called when steerToAvoidCloseNeighbors decides steering is required
public void AnnotateAvoidCloseNeighbor(IVehicle other)
{
// draw the word "Ouch!" above colliding vehicles
bool headOn = Vector3.Dot(Forward, other.Forward) < 0;
Color green = new Color((byte)(255.0f * 0.4f), (byte)(255.0f * 0.8f), (byte)(255.0f * 0.1f));
Color red = new Color((byte)(255.0f * 1), (byte)(255.0f * 0.1f), 0);
Color color = headOn ? red : green;
String text = headOn ? "OUCH!" : "pardon me";
Vector3 location = Position + new Vector3(0, 0.5f, 0);
if (annotation.IsEnabled)
Drawing.Draw2dTextAt3dLocation(text, location, color);
}
public void AnnotateAvoidNeighbor(IVehicle threat, Vector3 ourFuture, Vector3 threatFuture)
{
Color green = new Color((byte)(255.0f * 0.15f), (byte)(255.0f * 0.6f), 0);
annotation.Line(Position, ourFuture, green.ToVector3().FromXna());
annotation.Line(threat.Position, threatFuture, green.ToVector3().FromXna());
annotation.Line(ourFuture, threatFuture, Color.Red.ToVector3().FromXna());
annotation.CircleXZ(Radius, ourFuture, green.ToVector3().FromXna(), 12);
annotation.CircleXZ(Radius, threatFuture, green.ToVector3().FromXna(), 12);
}
// xxx perhaps this should be a call to a general purpose annotation for
// xxx "local xxx axis aligned box in XZ plane" -- same code in in
// xxx CaptureTheFlag.cpp
public void AnnotateAvoidObstacle(float minDistanceToCollision)
{
Vector3 boxSide = Side * Radius;
Vector3 boxFront = Forward * minDistanceToCollision;
Vector3 fr = Position + boxFront - boxSide;
Vector3 fl = Position + boxFront + boxSide;
Vector3 br = Position - boxSide;
Vector3 bl = Position + boxSide;
annotation.Line(fr, fl, Color.White.ToVector3().FromXna());
annotation.Line(fl, bl, Color.White.ToVector3().FromXna());
annotation.Line(bl, br, Color.White.ToVector3().FromXna());
annotation.Line(br, fr, Color.White.ToVector3().FromXna());
}
// constructor
public Pedestrian(IProximityDatabase<IVehicle> pd, IAnnotationService annotations = null)
:base(annotations)
{
// allocate a token for this boid in the proximity database
_proximityToken = null;
NewPD(pd);
// reset Pedestrian state
Reset();
}
// reset all instance state
public override void Reset()
{
// reset the vehicle
base.Reset();
// initially stopped
Speed = 0;
// size of bounding sphere, for obstacle avoidance, etc.
Radius = 0.5f; // width = 0.7, add 0.3 margin, take half
// set the path for this Pedestrian to follow
_path = Globals.GetTestPath();
// set initial position
// (random point on path + random horizontal offset)
float d = _path.TotalPathLength * RandomHelpers.Random();
float r = _path.Radius;
Vector3 randomOffset = Vector3Helpers.RandomVectorOnUnitRadiusXZDisk() * r;
Position = (_path.MapPathDistanceToPoint(d) + randomOffset);
// randomize 2D heading
RandomizeHeadingOnXZPlane();
// pick a random direction for path following (upstream or downstream)
_pathDirection = RandomHelpers.Random() <= 0.5;
// trail parameters: 3 seconds with 60 points along the trail
_trail = new Trail(3, 60);
// notify proximity database that our position has changed
if (_proximityToken != null) _proximityToken.UpdateForNewPosition(Position);
}
// per frame simulation update
public void Update(float currentTime, float elapsedTime)
{
// apply steering force to our momentum
ApplySteeringForce(DetermineCombinedSteering(elapsedTime), elapsedTime);
// reverse direction when we reach an endpoint
if (Globals.UseDirectedPathFollowing)
{
if (Vector3.Distance(Position, Globals.Endpoint0) < _path.Radius)
{
_pathDirection = true;
annotation.CircleXZ(_path.Radius, Globals.Endpoint0, Color.DarkRed.ToVector3().FromXna(), 20);
}
if (Vector3.Distance(Position, Globals.Endpoint1) < _path.Radius)
{
_pathDirection = false;
annotation.CircleXZ(_path.Radius, Globals.Endpoint1, Color.DarkRed.ToVector3().FromXna(), 20);
}
}
// annotation
annotation.VelocityAcceleration(this, 5, 0);
_trail.Record(currentTime, Position);
// notify proximity database that our position has changed
_proximityToken.UpdateForNewPosition(Position);
}
// compute combined steering force: move forward, avoid obstacles
// or neighbors if needed, otherwise follow the path and wander
private Vector3 DetermineCombinedSteering(float elapsedTime)
{
// move forward
Vector3 steeringForce = Forward;
// probability that a lower priority behavior will be given a
// chance to "drive" even if a higher priority behavior might
// otherwise be triggered.
const float LEAK_THROUGH = 0.1f;
// determine if obstacle avoidance is required
Vector3 obstacleAvoidance = Vector3.Zero;
if (LEAK_THROUGH < RandomHelpers.Random())
{
const float O_TIME = 6; // minTimeToCollision = 6 seconds
obstacleAvoidance = SteerToAvoidObstacles(O_TIME, Globals.Obstacles);
}
// if obstacle avoidance is needed, do it
if (obstacleAvoidance != Vector3.Zero)
{
steeringForce += obstacleAvoidance;
}
else
{
// otherwise consider avoiding collisions with others
Vector3 collisionAvoidance = Vector3.Zero;
const float CA_LEAD_TIME = 3;
// find all neighbors within maxRadius using proximity database
// (radius is largest distance between vehicles traveling head-on
// where a collision is possible within caLeadTime seconds.)
float maxRadius = CA_LEAD_TIME * MaxSpeed * 2;
_neighbors.Clear();
_proximityToken.FindNeighbors(Position, maxRadius, _neighbors);
if (_neighbors.Count > 0 && LEAK_THROUGH < RandomHelpers.Random())
collisionAvoidance = SteerToAvoidNeighbors(CA_LEAD_TIME, _neighbors) * 10;
// if collision avoidance is needed, do it
if (collisionAvoidance != Vector3.Zero)
{
steeringForce += collisionAvoidance;
}
else
{
// add in wander component (according to user switch)
if (Globals.WanderSwitch)
steeringForce += SteerForWander(elapsedTime);
// do (interactively) selected type of path following
const float PF_LEAD_TIME = 3;
Vector3 pathFollow =
(Globals.UseDirectedPathFollowing ?
SteerToFollowPath(_pathDirection, PF_LEAD_TIME, _path) :
SteerToStayOnPath(PF_LEAD_TIME, _path));
// add in to steeringForce
steeringForce += pathFollow * 0.5f;
}
}
// return steering constrained to global XZ "ground" plane
steeringForce.Y = 0;
return steeringForce;
}
// draw this pedestrian into scene
public void Draw()
{
Drawing.DrawBasic2dCircularVehicle(this, Color.Gray);
_trail.Draw(annotation);
}
// switch to new proximity database -- just for demo purposes
public void NewPD(IProximityDatabase<IVehicle> pd)
{
// delete this boid's token in the old proximity database
if (_proximityToken != null)
{
_proximityToken.Dispose();
_proximityToken = null;
}
// allocate a token for this boid in the proximity database
_proximityToken = pd.AllocateToken(this);
}
// a pointer to this boid's interface object for the proximity database
ITokenForProximityDatabase<IVehicle> _proximityToken;
// allocate one and share amoung instances just to save memory usage
// (change to per-instance allocation to be more MP-safe)
static readonly List<IVehicle> _neighbors = new List<IVehicle>();
// path to be followed by this pedestrian
// XXX Ideally this should be a generic Pathway, but we use the
// XXX getTotalPathLength and radius methods (currently defined only
// XXX on PolylinePathway) to set random initial positions. Could
// XXX there be a "random position inside path" method on Pathway?
PolylinePathway _path;
// direction for path following (upstream or downstream)
bool _pathDirection;
}
}
| |
// 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 Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace Internal.IL.Stubs
{
/// <summary>
/// Base class for all delegate invocation thunks.
/// </summary>
public abstract class DelegateThunk : ILStubMethod
{
private DelegateInfo _delegateInfo;
public DelegateThunk(DelegateInfo delegateInfo)
{
_delegateInfo = delegateInfo;
}
public sealed override TypeSystemContext Context
{
get
{
return _delegateInfo.Type.Context;
}
}
public sealed override TypeDesc OwningType
{
get
{
return _delegateInfo.Type;
}
}
public sealed override MethodSignature Signature
{
get
{
return _delegateInfo.Signature;
}
}
public sealed override Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
protected TypeDesc SystemDelegateType
{
get
{
return Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType;
}
}
protected FieldDesc ExtraFunctionPointerOrDataField
{
get
{
return SystemDelegateType.GetKnownField("m_extraFunctionPointerOrData");
}
}
protected FieldDesc HelperObjectField
{
get
{
return SystemDelegateType.GetKnownField("m_helperObject");
}
}
protected FieldDesc FirstParameterField
{
get
{
return SystemDelegateType.GetKnownField("m_firstParameter");
}
}
protected FieldDesc FunctionPointerField
{
get
{
return SystemDelegateType.GetKnownField("m_functionPointer");
}
}
}
/// <summary>
/// Invoke thunk for open delegates to static methods. Loads all arguments except
/// the 'this' pointer and performs an indirect call to the delegate target.
/// This method is injected into delegate types.
/// </summary>
public sealed class DelegateInvokeOpenStaticThunk : DelegateThunk
{
internal DelegateInvokeOpenStaticThunk(DelegateInfo delegateInfo)
: base(delegateInfo)
{
}
public override MethodIL EmitIL()
{
// Target has the same signature as the Invoke method, except it's static.
MethodSignatureBuilder builder = new MethodSignatureBuilder(Signature);
builder.Flags = Signature.Flags | MethodSignatureFlags.Static;
var emitter = new ILEmitter();
ILCodeStream codeStream = emitter.NewCodeStream();
// Load all arguments except 'this'
for (int i = 0; i < Signature.Length; i++)
{
codeStream.EmitLdArg(i + 1);
}
// Indirectly call the delegate target static method.
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
codeStream.Emit(ILOpcode.calli, emitter.NewToken(builder.ToSignature()));
codeStream.Emit(ILOpcode.ret);
return emitter.Link();
}
public override string Name
{
get
{
return "InvokeOpenStaticThunk";
}
}
}
/// <summary>
/// Invoke thunk for closed delegates to static methods. The target
/// is a static method, but the first argument is captured by the delegate.
/// The signature of the target has an extra object-typed argument, followed
/// by the arguments that are delegate-compatible with the thunk signature.
/// This method is injected into delegate types.
/// </summary>
public sealed class DelegateInvokeClosedStaticThunk : DelegateThunk
{
internal DelegateInvokeClosedStaticThunk(DelegateInfo delegateInfo)
: base(delegateInfo)
{
}
public override MethodIL EmitIL()
{
TypeDesc[] targetMethodParameters = new TypeDesc[Signature.Length + 1];
targetMethodParameters[0] = Context.GetWellKnownType(WellKnownType.Object);
for (int i = 0; i < Signature.Length; i++)
{
targetMethodParameters[i + 1] = Signature[i];
}
var targetMethodSignature = new MethodSignature(
Signature.Flags | MethodSignatureFlags.Static, 0, Signature.ReturnType, targetMethodParameters);
var emitter = new ILEmitter();
ILCodeStream codeStream = emitter.NewCodeStream();
// Load the stored 'this'
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));
// Load all arguments except 'this'
for (int i = 0; i < Signature.Length; i++)
{
codeStream.EmitLdArg(i + 1);
}
// Indirectly call the delegate target static method.
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSignature));
codeStream.Emit(ILOpcode.ret);
return emitter.Link();
}
public override string Name
{
get
{
return "InvokeClosedStaticThunk";
}
}
}
/// <summary>
/// Multicast invoke thunk for delegates that are a result of Delegate.Combine.
/// Passes it's arguments to each of the delegates that got combined and calls them
/// one by one. Returns the value of the last delegate executed.
/// This method is injected into delegate types.
/// </summary>
public sealed class DelegateInvokeMulticastThunk : DelegateThunk
{
internal DelegateInvokeMulticastThunk(DelegateInfo delegateInfo)
: base(delegateInfo)
{
}
public override MethodIL EmitIL()
{
ILEmitter emitter = new ILEmitter();
ILCodeStream codeStream = emitter.NewCodeStream();
ArrayType invocationListArrayType = SystemDelegateType.MakeArrayType();
ILLocalVariable delegateArrayLocal = emitter.NewLocal(invocationListArrayType);
ILLocalVariable invocationCountLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
ILLocalVariable iteratorLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32));
ILLocalVariable delegateToCallLocal = emitter.NewLocal(SystemDelegateType);
ILLocalVariable returnValueLocal = 0;
if (Signature.ReturnType is SignatureVariable || !Signature.ReturnType.IsVoid)
{
returnValueLocal = emitter.NewLocal(Signature.ReturnType);
}
// Fill in delegateArrayLocal
// Delegate[] delegateArrayLocal = (Delegate[])this.m_helperObject
// ldarg.0 (this pointer)
// ldfld Delegate.HelperObjectField
// castclass Delegate[]
// stloc delegateArrayLocal
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField));
codeStream.Emit(ILOpcode.castclass, emitter.NewToken(invocationListArrayType));
codeStream.EmitStLoc(delegateArrayLocal);
// Fill in invocationCountLocal
// int invocationCountLocal = this.m_extraFunctionPointerOrData
// ldarg.0 (this pointer)
// ldfld Delegate.m_extraFunctionPointerOrData
// stloc invocationCountLocal
codeStream.EmitLdArg(0);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField));
codeStream.EmitStLoc(invocationCountLocal);
// Fill in iteratorLocal
// int iteratorLocal = 0;
// ldc.0
// stloc iteratorLocal
codeStream.EmitLdc(0);
codeStream.EmitStLoc(iteratorLocal);
// Loop across every element of the array.
ILCodeLabel startOfLoopLabel = emitter.NewCodeLabel();
codeStream.EmitLabel(startOfLoopLabel);
// Implement as do/while loop. We only have this stub in play if we're in the multicast situation
// Find the delegate to call
// Delegate = delegateToCallLocal = delegateArrayLocal[iteratorLocal];
// ldloc delegateArrayLocal
// ldloc iteratorLocal
// ldelem System.Delegate
// stloc delegateToCallLocal
codeStream.EmitLdLoc(delegateArrayLocal);
codeStream.EmitLdLoc(iteratorLocal);
codeStream.Emit(ILOpcode.ldelem, emitter.NewToken(SystemDelegateType));
codeStream.EmitStLoc(delegateToCallLocal);
// Call the delegate
// returnValueLocal = delegateToCallLocal(...);
// ldloc delegateToCallLocal
// ldfld System.Delegate.m_firstParameter
// ldarg 1, n
// ldloc delegateToCallLocal
// ldfld System.Delegate.m_functionPointer
// calli returnValueType thiscall (all the params)
// IF there is a return value
// stloc returnValueLocal
codeStream.EmitLdLoc(delegateToCallLocal);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FirstParameterField));
for (int i = 0; i < Signature.Length; i++)
{
codeStream.EmitLdArg(i + 1);
}
codeStream.EmitLdLoc(delegateToCallLocal);
codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FunctionPointerField));
codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature));
if (returnValueLocal != 0)
codeStream.EmitStLoc(returnValueLocal);
// Increment iteratorLocal
// ++iteratorLocal;
// ldloc iteratorLocal
// ldc.i4.1
// add
// stloc iteratorLocal
codeStream.EmitLdLoc(iteratorLocal);
codeStream.EmitLdc(1);
codeStream.Emit(ILOpcode.add);
codeStream.EmitStLoc(iteratorLocal);
// Check to see if the loop is done
codeStream.EmitLdLoc(invocationCountLocal);
codeStream.EmitLdLoc(iteratorLocal);
codeStream.Emit(ILOpcode.bne_un, startOfLoopLabel);
// Return to caller. If the delegate has a return value, be certain to return that.
// return returnValueLocal;
// ldloc returnValueLocal
// ret
if (returnValueLocal != 0)
codeStream.EmitLdLoc(returnValueLocal);
codeStream.Emit(ILOpcode.ret);
return emitter.Link();
}
public override string Name
{
get
{
return "InvokeMulticastThunk";
}
}
}
/// <summary>
/// Synthetic method override of "IntPtr Delegate.GetThunk(Int32)". This method is injected
/// into all delegate types and provides means for System.Delegate to access the various thunks
/// generated by the compiler.
/// </summary>
public sealed class DelegateGetThunkMethodOverride : ILStubMethod
{
private DelegateInfo _delegateInfo;
private MethodSignature _signature;
internal DelegateGetThunkMethodOverride(DelegateInfo delegateInfo)
{
_delegateInfo = delegateInfo;
}
public override TypeSystemContext Context
{
get
{
return _delegateInfo.Type.Context;
}
}
public override TypeDesc OwningType
{
get
{
return _delegateInfo.Type;
}
}
public override MethodSignature Signature
{
get
{
if (_signature == null)
{
TypeSystemContext context = _delegateInfo.Type.Context;
TypeDesc intPtrType = context.GetWellKnownType(WellKnownType.IntPtr);
TypeDesc int32Type = context.GetWellKnownType(WellKnownType.Int32);
_signature = new MethodSignature(0, 0, intPtrType, new[] { int32Type });
}
return _signature;
}
}
public override MethodIL EmitIL()
{
const DelegateThunkKind maxThunkKind = DelegateThunkKind.ObjectArrayThunk;
ILEmitter emitter = new ILEmitter();
var codeStream = emitter.NewCodeStream();
ILCodeLabel returnNullLabel = emitter.NewCodeLabel();
ILCodeLabel[] labels = new ILCodeLabel[(int)maxThunkKind];
for (DelegateThunkKind i = 0; i < maxThunkKind; i++)
{
MethodDesc thunk = _delegateInfo.Thunks[i];
if (thunk != null)
labels[(int)i] = emitter.NewCodeLabel();
else
labels[(int)i] = returnNullLabel;
}
codeStream.EmitLdArg(1);
codeStream.EmitSwitch(labels);
codeStream.Emit(ILOpcode.br, returnNullLabel);
for (DelegateThunkKind i = 0; i < maxThunkKind; i++)
{
MethodDesc thunk = _delegateInfo.Thunks[i];
if (thunk != null)
{
codeStream.EmitLabel(labels[(int)i]);
codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(thunk.InstantiateAsOpen()));
codeStream.Emit(ILOpcode.ret);
}
}
codeStream.EmitLabel(returnNullLabel);
codeStream.EmitLdc(0);
codeStream.Emit(ILOpcode.conv_i);
codeStream.Emit(ILOpcode.ret);
return emitter.Link();
}
public override Instantiation Instantiation
{
get
{
return Instantiation.Empty;
}
}
public override bool IsVirtual
{
get
{
return true;
}
}
public override string Name
{
get
{
return "GetThunk";
}
}
}
}
| |
/*============================================================================
* Copyright (C) Microsoft Corporation, All rights reserved.
*============================================================================
*/
#region Using directives
using System;
using System.Management.Automation;
using System.Globalization;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
#region AsyncResultType
/// <summary>
/// <para>
/// Async result type
/// </para>
/// </summary>
public enum AsyncResultType
{
Result,
Exception,
Completion
}
#endregion
#region CimResultContext
/// <summary>
/// Cim Result Context
/// </summary>
internal class CimResultContext
{
/// <summary>
/// constructor
/// </summary>
/// <param name="ErrorSource"></param>
internal CimResultContext(object ErrorSource)
{
this.errorSource = ErrorSource;
}
/// <summary>
/// ErrorSource property
/// </summary>
internal object ErrorSource
{
get
{
return this.errorSource;
}
}
private object errorSource;
}
#endregion
#region AsyncResultEventArgsBase
/// <summary>
/// <para>
/// Base class of async result event argument
/// </para>
/// </summary>
internal abstract class AsyncResultEventArgsBase : EventArgs
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="resultType"></param>
public AsyncResultEventArgsBase(
CimSession session,
IObservable<object> observable,
AsyncResultType resultType)
{
this.session = session;
this.observable = observable;
this.resultType = resultType;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="resultType"></param>
/// <param name="context"></param>
public AsyncResultEventArgsBase(
CimSession session,
IObservable<object> observable,
AsyncResultType resultType,
CimResultContext cimResultContext)
{
this.session = session;
this.observable = observable;
this.resultType = resultType;
this.context = cimResultContext;
}
public readonly CimSession session;
public readonly IObservable<object> observable;
public readonly AsyncResultType resultType;
// property ErrorSource
public readonly CimResultContext context;
}
#endregion
#region AsyncResult*Args
/// <summary>
/// <para>
/// operation successfully completed event argument
/// </para>
/// </summary>
internal class AsyncResultCompleteEventArgs : AsyncResultEventArgsBase
{
/// <summary>
/// <para>
/// Constructor
/// </para>
/// </summary>
/// <param name="session"><see cref="CimSession"/> object</param>
/// <param name="cancellationDisposable"></param>
public AsyncResultCompleteEventArgs(
CimSession session,
IObservable<object> observable) :
base(session, observable, AsyncResultType.Completion)
{
}
}
/// <summary>
/// <para>
/// async result argument with object
/// </para>
/// </summary>
internal class AsyncResultObjectEventArgs : AsyncResultEventArgsBase
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="resultObject"></param>
public AsyncResultObjectEventArgs(
CimSession session,
IObservable<object> observable,
object resultObject) :
base(session, observable, AsyncResultType.Result)
{
this.resultObject = resultObject;
}
public readonly object resultObject;
}
/// <summary>
/// <para>
/// operation completed with exception event argument
/// </para>
/// </summary>
internal class AsyncResultErrorEventArgs : AsyncResultEventArgsBase
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="error"></param>
public AsyncResultErrorEventArgs(
CimSession session,
IObservable<object> observable,
Exception error) :
base(session, observable, AsyncResultType.Exception)
{
this.error = error;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="error"></param>
/// <param name="context"></param>
public AsyncResultErrorEventArgs(
CimSession session,
IObservable<object> observable,
Exception error,
CimResultContext cimResultContext) :
base(session, observable, AsyncResultType.Exception, cimResultContext)
{
this.error = error;
}
public readonly Exception error;
}
#endregion
#region CimResultObserver
/// <summary>
/// <para>
/// Observer to consume results from asynchronous operations, such as,
/// EnumerateInstancesAsync operation of <see cref="CimSession"/> object.
/// </para>
/// <para>
/// (See http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Contract/)
/// for the IObserver/IObservable contact
/// - the only possible sequence is OnNext* (OnCompleted|OnError)?
/// - callbacks are serialized
/// - Subscribe never throws
/// </para>
/// </summary>
/// <typeparam name="T">object type</typeparam>
internal class CimResultObserver<T> : IObserver<T>
{
/// <summary>
/// Define delegate that handles new cmdlet action come from
/// the operations related to the current CimSession object.
/// </summary>
/// <param name="cimSession">cimSession object, which raised the event</param>
/// <param name="actionArgs">Event args</param>
public delegate void ResultEventHandler(
object observer,
AsyncResultEventArgsBase resultArgs);
/// <summary>
/// Define an Event based on the NewActionHandler
/// </summary>
public event ResultEventHandler OnNewResult;
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"><see cref="CimSession"/> object that issued the operation</param>
/// <param name="observable">Operation that can be observed</param>
public CimResultObserver(CimSession session, IObservable<object> observable)
{
this.session = session;
this.observable = observable;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="session"><see cref="CimSession"/> object that issued the operation</param>
/// <param name="observable">Operation that can be observed</param>
public CimResultObserver(CimSession session,
IObservable<object> observable,
CimResultContext cimResultContext)
{
this.session = session;
this.observable = observable;
this.context = cimResultContext;
}
/// <summary>
/// <para>
/// Operation completed successfully
/// </para>
/// </summary>
public virtual void OnCompleted()
{
// callbacks should never throw any exception to
// protocol layer, otherwise the client process will be
// terminated because of unhandled exception, same with
// OnNext, OnError
try
{
AsyncResultCompleteEventArgs completeArgs = new AsyncResultCompleteEventArgs(
this.session, this.observable);
this.OnNewResult(this, completeArgs);
}
catch (Exception ex)
{
this.OnError(ex);
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// <para>
/// Operation completed with an error
/// </para>
/// </summary>
/// <param name="error">error object</param>
public virtual void OnError(Exception error)
{
try
{
AsyncResultErrorEventArgs errorArgs = new AsyncResultErrorEventArgs(
this.session, this.observable, error, this.context);
this.OnNewResult(this, errorArgs);
}
catch (Exception ex)
{
// !!ignore the exception
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// Deliver the result value
/// </summary>
/// <param name="value"></param>
protected void OnNextCore(object value)
{
DebugHelper.WriteLogEx("value = {0}.", 1, value);
try
{
AsyncResultObjectEventArgs resultArgs = new AsyncResultObjectEventArgs(
this.session, this.observable, value);
this.OnNewResult(this, resultArgs);
}
catch (Exception ex)
{
this.OnError(ex);
DebugHelper.WriteLogEx("{0}", 0, ex);
}
}
/// <summary>
/// <para>
/// Operation got a new result object
/// </para>
/// </summary>
/// <param name="value">result object</param>
public virtual void OnNext(T value)
{
DebugHelper.WriteLogEx("value = {0}.", 1, value);
// do not allow null value
if (value == null)
{
return;
}
this.OnNextCore(value);
}
#region members
/// <summary>
/// Session object of the operation
/// </summary>
protected CimSession CurrentSession
{
get
{
return session;
}
}
private CimSession session;
/// <summary>
/// async operation that can be observed
/// </summary>
private IObservable<object> observable;
/// <summary>
/// <see cref="CimResultContext"/> object used during delivering result.
/// </summary>
private CimResultContext context;
#endregion
}
/// <summary>
/// CimSubscriptionResultObserver class definition
/// </summary>
internal class CimSubscriptionResultObserver : CimResultObserver<CimSubscriptionResult>
{
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public CimSubscriptionResultObserver(CimSession session, IObservable<object> observable)
: base(session, observable)
{
}
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public CimSubscriptionResultObserver(
CimSession session,
IObservable<object> observable,
CimResultContext context)
: base(session, observable, context)
{
}
/// <summary>
/// Override the OnNext method
/// </summary>
/// <param name="value"></param>
public override void OnNext(CimSubscriptionResult value)
{
DebugHelper.WriteLogEx();
base.OnNextCore(value);
}
}
/// <summary>
/// CimMethodResultObserver class definition
/// </summary>
internal class CimMethodResultObserver : CimResultObserver<CimMethodResultBase>
{
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public CimMethodResultObserver(CimSession session, IObservable<object> observable)
: base(session, observable)
{
}
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
/// <param name="context"></param>
public CimMethodResultObserver(
CimSession session,
IObservable<object> observable,
CimResultContext context)
: base(session, observable, context)
{
}
/// <summary>
/// Override the OnNext method
/// </summary>
/// <param name="value"></param>
public override void OnNext(CimMethodResultBase value)
{
DebugHelper.WriteLogEx();
const string PSTypeCimMethodResult = @"Microsoft.Management.Infrastructure.CimMethodResult";
const string PSTypeCimMethodStreamedResult = @"Microsoft.Management.Infrastructure.CimMethodStreamedResult";
const string PSTypeCimMethodResultTemplate = @"{0}#{1}#{2}";
string resultObjectPSType = null;
PSObject resultObject = null;
CimMethodResult methodResult = value as CimMethodResult;
if (methodResult != null)
{
resultObjectPSType = PSTypeCimMethodResult;
resultObject = new PSObject();
foreach (CimMethodParameter param in methodResult.OutParameters)
{
resultObject.Properties.Add(new PSNoteProperty(param.Name, param.Value));
}
}
else
{
CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult;
if (methodStreamedResult != null)
{
resultObjectPSType = PSTypeCimMethodStreamedResult;
resultObject = new PSObject();
resultObject.Properties.Add(new PSNoteProperty(@"ParameterName", methodStreamedResult.ParameterName));
resultObject.Properties.Add(new PSNoteProperty(@"ItemType", methodStreamedResult.ItemType));
resultObject.Properties.Add(new PSNoteProperty(@"ItemValue", methodStreamedResult.ItemValue));
}
}
if (resultObject != null)
{
resultObject.Properties.Add(new PSNoteProperty(@"PSComputerName", this.CurrentSession.ComputerName));
resultObject.TypeNames.Insert(0, resultObjectPSType);
resultObject.TypeNames.Insert(0, String.Format(CultureInfo.InvariantCulture, PSTypeCimMethodResultTemplate, resultObjectPSType, ClassName, MethodName));
base.OnNextCore(resultObject);
}
}
/// <summary>
/// methodname
/// </summary>
internal String MethodName
{
get;
set;
}
/// <summary>
/// classname
/// </summary>
internal String ClassName
{
get;
set;
}
}
/// <summary>
/// IgnoreResultObserver class definition
/// </summary>
internal class IgnoreResultObserver : CimResultObserver<CimInstance>
{
/// <summary>
/// constructor
/// </summary>
/// <param name="session"></param>
/// <param name="observable"></param>
public IgnoreResultObserver(CimSession session, IObservable<object> observable)
: base(session, observable)
{
}
/// <summary>
/// Override the OnNext method
/// </summary>
/// <param name="value"></param>
public override void OnNext(CimInstance value)
{
DebugHelper.WriteLogEx();
}
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using System.Text;
internal partial class Interop
{
internal partial class WinHttp
{
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandle WinHttpOpen(
IntPtr userAgent,
uint accessType,
string proxyName,
string proxyBypass, int flags);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpCloseHandle(
IntPtr handle);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandle WinHttpConnect(
SafeWinHttpHandle sessionHandle,
string serverName,
ushort serverPort,
uint reserved);
// NOTE: except for the return type, this refers to the same function as WinHttpConnect.
[DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpConnect", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandleWithCallback WinHttpConnectWithCallback(
SafeWinHttpHandle sessionHandle,
string serverName,
ushort serverPort,
uint reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandle WinHttpOpenRequest(
SafeWinHttpHandle connectHandle,
string verb,
string objectName,
string version,
string referrer,
string acceptTypes,
uint flags);
// NOTE: except for the return type, this refers to the same function as WinHttpOpenRequest.
[DllImport(Interop.Libraries.WinHttp, EntryPoint = "WinHttpOpenRequest", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandleWithCallback WinHttpOpenRequestWithCallback(
SafeWinHttpHandle connectHandle,
string verb,
string objectName,
string version,
string referrer,
string acceptTypes,
uint flags);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpAddRequestHeaders(
SafeWinHttpHandle requestHandle,
[In] StringBuilder headers,
uint headersLength,
uint modifiers);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpAddRequestHeaders(
SafeWinHttpHandle requestHandle,
string headers,
uint headersLength,
uint modifiers);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSendRequest(
SafeWinHttpHandle requestHandle,
[In] StringBuilder headers,
uint headersLength,
IntPtr optional,
uint optionalLength,
uint totalLength,
IntPtr context);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpReceiveResponse(
SafeWinHttpHandle requestHandle,
IntPtr reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryDataAvailable(
SafeWinHttpHandle requestHandle,
out uint bytesAvailable);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryDataAvailable(
SafeWinHttpHandle requestHandle,
IntPtr parameterIgnoredAndShouldBeNullForAsync);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpReadData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
out uint bytesRead);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpReadData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
IntPtr parameterIgnoredAndShouldBeNullForAsync);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
[Out] StringBuilder buffer,
ref uint bufferLength,
IntPtr index);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryHeaders(
SafeWinHttpHandle requestHandle,
uint infoLevel,
string name,
ref uint number,
ref uint bufferLength,
IntPtr index);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
[Out] StringBuilder buffer,
ref uint bufferSize);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
ref IntPtr buffer,
ref uint bufferSize);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryOption(
SafeWinHttpHandle handle,
uint option,
IntPtr buffer,
ref uint bufferSize);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpWriteData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
out uint bytesWritten);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpWriteData(
SafeWinHttpHandle requestHandle,
IntPtr buffer,
uint bufferSize,
IntPtr parameterIgnoredAndShouldBeNullForAsync);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
ref uint optionData,
uint optionLength = sizeof(uint));
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
string optionData,
uint optionLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetOption(
SafeWinHttpHandle handle,
uint option,
IntPtr optionData,
uint optionLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetCredentials(
SafeWinHttpHandle requestHandle,
uint authTargets,
uint authScheme,
string userName,
string password,
IntPtr reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpQueryAuthSchemes(
SafeWinHttpHandle requestHandle,
out uint supportedSchemes,
out uint firstScheme,
out uint authTarget);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpSetTimeouts(
SafeWinHttpHandle handle,
int resolveTimeout,
int connectTimeout,
int sendTimeout,
int receiveTimeout);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpGetIEProxyConfigForCurrentUser(
out WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool WinHttpGetProxyForUrl(
SafeWinHttpHandle sessionHandle, string url,
ref WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions,
out WINHTTP_PROXY_INFO proxyInfo);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr WinHttpSetStatusCallback(
SafeWinHttpHandle handle,
WINHTTP_STATUS_CALLBACK callback,
uint notificationFlags,
IntPtr reserved);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern SafeWinHttpHandleWithCallback WinHttpWebSocketCompleteUpgrade(
SafeWinHttpHandle requestHandle,
IntPtr context);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketSend(
SafeWinHttpHandle webSocketHandle,
WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType,
IntPtr buffer,
uint bufferLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketReceive(
SafeWinHttpHandle webSocketHandle,
IntPtr buffer,
uint bufferLength,
out uint bytesRead,
out WINHTTP_WEB_SOCKET_BUFFER_TYPE bufferType);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketShutdown(
SafeWinHttpHandle webSocketHandle,
ushort status,
byte[] reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketShutdown(
SafeWinHttpHandle webSocketHandle,
ushort status,
IntPtr reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketClose(
SafeWinHttpHandle webSocketHandle,
ushort status,
byte[] reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketClose(
SafeWinHttpHandle webSocketHandle,
ushort status,
IntPtr reason,
uint reasonLength);
[DllImport(Interop.Libraries.WinHttp, CharSet = CharSet.Unicode, SetLastError = false)]
public static extern uint WinHttpWebSocketQueryCloseStatus(
SafeWinHttpHandle webSocketHandle,
out ushort status,
byte[] reason,
uint reasonLength,
out uint reasonLengthConsumed);
}
}
| |
//
// InternetAddress.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
#if PORTABLE
using EncoderReplacementFallback = Portable.Text.EncoderReplacementFallback;
using DecoderReplacementFallback = Portable.Text.DecoderReplacementFallback;
using EncoderExceptionFallback = Portable.Text.EncoderExceptionFallback;
using DecoderExceptionFallback = Portable.Text.DecoderExceptionFallback;
using EncoderFallbackException = Portable.Text.EncoderFallbackException;
using DecoderFallbackException = Portable.Text.DecoderFallbackException;
using DecoderFallbackBuffer = Portable.Text.DecoderFallbackBuffer;
using DecoderFallback = Portable.Text.DecoderFallback;
using Encoding = Portable.Text.Encoding;
using Encoder = Portable.Text.Encoder;
using Decoder = Portable.Text.Decoder;
#endif
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// An internet address, as specified by rfc0822.
/// </summary>
/// <remarks>
/// <para>A <see cref="InternetAddress"/> can be any type of address defined by the
/// original Internet Message specification.</para>
/// <para>There are effectively two (2) types of addresses: mailboxes and groups.</para>
/// <para>Mailbox addresses are what are most commonly known as email addresses and are
/// represented by the <see cref="MailboxAddress"/> class.</para>
/// <para>Group addresses are themselves lists of addresses and are represented by the
/// <see cref="GroupAddress"/> class. While rare, it is still important to handle these
/// types of addresses. They typically only contain mailbox addresses, but may also
/// contain other group addresses.</para>
/// </remarks>
public abstract class InternetAddress : IComparable<InternetAddress>, IEquatable<InternetAddress>
{
const string AtomSpecials = "()<>@,;:\\\".[]";
Encoding encoding;
string name;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.InternetAddress"/> class.
/// </summary>
/// <remarks>
/// Initializes the <see cref="Encoding"/> and <see cref="Name"/> properties of the internet address.
/// </remarks>
/// <param name="encoding">The character encoding to be used for encoding the name.</param>
/// <param name="name">The name of the mailbox or group.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="encoding"/> is <c>null</c>.
/// </exception>
protected InternetAddress (Encoding encoding, string name)
{
if (encoding == null)
throw new ArgumentNullException ("encoding");
Encoding = encoding;
Name = name;
}
/// <summary>
/// Gets or sets the character encoding to use when encoding the name of the address.
/// </summary>
/// <remarks>
/// The character encoding is used to convert the <see cref="Name"/> property, if it is set,
/// to a stream of bytes when encoding the internet address for transport.
/// </remarks>
/// <value>The character encoding.</value>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="value"/> is <c>null</c>.
/// </exception>
public Encoding Encoding {
get { return encoding; }
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value == encoding)
return;
encoding = value;
OnChanged ();
}
}
/// <summary>
/// Gets or sets the display name of the address.
/// </summary>
/// <remarks>
/// A name is optional and is typically set to the name of the person
/// or group that own the internet address.
/// </remarks>
/// <value>The name of the address.</value>
public string Name {
get { return name; }
set {
if (value == name)
return;
name = value;
OnChanged ();
}
}
/// <summary>
/// Clone the address.
/// </summary>
/// <remarks>
/// Clones the address.
/// </remarks>
/// <returns>The cloned address.</returns>
public abstract InternetAddress Clone ();
#region IComparable implementation
/// <summary>
/// Compares two internet addresses.
/// </summary>
/// <remarks>
/// Compares two internet addresses for the purpose of sorting.
/// </remarks>
/// <returns>The sort order of the current internet address compared to the other internet address.</returns>
/// <param name="other">The internet address to compare to.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="other"/> is <c>null</c>.
/// </exception>
public int CompareTo (InternetAddress other)
{
int rv;
if (other == null)
throw new ArgumentNullException ("other");
if ((rv = string.Compare (Name, other.Name, StringComparison.OrdinalIgnoreCase)) != 0)
return rv;
var otherMailbox = other as MailboxAddress;
var mailbox = this as MailboxAddress;
if (mailbox != null && otherMailbox != null) {
string otherAddress = otherMailbox.Address;
int otherAt = otherAddress.IndexOf ('@');
string address = mailbox.Address;
int at = address.IndexOf ('@');
if (at != -1 && otherAt != -1) {
int length = Math.Min (address.Length - (at + 1), otherAddress.Length - (otherAt + 1));
rv = string.Compare (address, at + 1, otherAddress, otherAt + 1, length, StringComparison.OrdinalIgnoreCase);
}
if (rv == 0) {
string otherUser = otherAt != -1 ? otherAddress.Substring (0, otherAt) : otherAddress;
string user = at != -1 ? address.Substring (0, at) : address;
rv = string.Compare (user, otherUser, StringComparison.OrdinalIgnoreCase);
}
return rv;
}
// sort mailbox addresses before group addresses
if (mailbox != null && otherMailbox == null)
return -1;
if (mailbox == null && otherMailbox != null)
return 1;
return 0;
}
#endregion
#region IEquatable implementation
/// <summary>
/// Determines whether the specified <see cref="MimeKit.InternetAddress"/> is equal to the current <see cref="MimeKit.InternetAddress"/>.
/// </summary>
/// <remarks>
/// Compares two internet addresses to determine if they are identical or not.
/// </remarks>
/// <param name="other">The <see cref="MimeKit.InternetAddress"/> to compare with the current <see cref="MimeKit.InternetAddress"/>.</param>
/// <returns><c>true</c> if the specified <see cref="MimeKit.InternetAddress"/> is equal to the current
/// <see cref="MimeKit.InternetAddress"/>; otherwise, <c>false</c>.</returns>
public abstract bool Equals (InternetAddress other);
#endregion
internal static string EncodeInternationalizedPhrase (string phrase)
{
for (int i = 0; i < phrase.Length; i++) {
if (char.IsControl (phrase[i]) || AtomSpecials.IndexOf (phrase[i]) != -1)
return MimeUtils.Quote (phrase);
}
return phrase;
}
internal abstract void Encode (FormatOptions options, StringBuilder builder, ref int lineLength);
/// <summary>
/// Returns a string representation of the <see cref="InternetAddress"/>,
/// optionally encoding it for transport.
/// </summary>
/// <remarks>
/// <para>If the <paramref name="encode"/> parameter is <c>true</c>, then this method will return
/// an encoded version of the internet address according to the rules described in rfc2047.</para>
/// <para>However, if the <paramref name="encode"/> parameter is <c>false</c>, then this method will
/// return a string suitable only for display purposes.</para>
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddress"/>.</returns>
/// <param name="options">The formatting options.</param>
/// <param name="encode">If set to <c>true</c>, the <see cref="InternetAddress"/> will be encoded.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="options"/> is <c>null</c>.
/// </exception>
public abstract string ToString (FormatOptions options, bool encode);
/// <summary>
/// Returns a string representation of the <see cref="InternetAddress"/>,
/// optionally encoding it for transport.
/// </summary>
/// <remarks>
/// <para>If the <paramref name="encode"/> parameter is <c>true</c>, then this method will return
/// an encoded version of the internet address according to the rules described in rfc2047.</para>
/// <para>However, if the <paramref name="encode"/> parameter is <c>false</c>, then this method will
/// return a string suitable only for display purposes.</para>
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddress"/>.</returns>
/// <param name="encode">If set to <c>true</c>, the <see cref="InternetAddress"/> will be encoded.</param>
public string ToString (bool encode)
{
return ToString (FormatOptions.Default, encode);
}
/// <summary>
/// Returns a string representation of a <see cref="InternetAddress"/> suitable for display.
/// </summary>
/// <remarks>
/// The string returned by this method is suitable only for display purposes.
/// </remarks>
/// <returns>A string representing the <see cref="InternetAddress"/>.</returns>
public override string ToString ()
{
return ToString (FormatOptions.Default, false);
}
internal event EventHandler Changed;
/// <summary>
/// Raises the internal changed event used by <see cref="MimeKit.MimeMessage"/> to keep headers in sync.
/// </summary>
/// <remarks>
/// This method is called whenever a property of the internet address is changed.
/// </remarks>
protected virtual void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
internal static bool TryParseLocalPart (byte[] text, ref int index, int endIndex, bool throwOnError, out string localpart)
{
var token = new StringBuilder ();
int startIndex = index;
localpart = null;
do {
if (!text[index].IsAtom () && text[index] != '"') {
if (throwOnError)
throw new ParseException (string.Format ("Invalid local-part at offset {0}", startIndex), startIndex, index);
return false;
}
int start = index;
if (!ParseUtils.SkipWord (text, ref index, endIndex, throwOnError))
return false;
try {
token.Append (CharsetUtils.UTF8.GetString (text, start, index - start));
} catch (DecoderFallbackException ex) {
if (throwOnError)
throw new ParseException ("Internationalized local-part tokens may only contain UTF-8 characters.", start, start, ex);
return false;
}
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex || text[index] != (byte) '.')
break;
token.Append ('.');
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete local-part at offset {0}", startIndex), startIndex, index);
return false;
}
} while (true);
localpart = token.ToString ();
return true;
}
internal static bool TryParseAddrspec (byte[] text, ref int index, int endIndex, byte sentinel, bool throwOnError, out string addrspec)
{
int startIndex = index;
addrspec = null;
string localpart;
if (!TryParseLocalPart (text, ref index, endIndex, throwOnError, out localpart))
return false;
if (index >= endIndex || text[index] == sentinel) {
addrspec = localpart;
return true;
}
if (text[index] != (byte) '@') {
if (throwOnError)
throw new ParseException (string.Format ("Invalid addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
index++;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete addr-spec token at offset {0}", startIndex), startIndex, index);
return false;
}
string domain;
if (!ParseUtils.TryParseDomain (text, ref index, endIndex, new [] { sentinel }, throwOnError, out domain))
return false;
addrspec = localpart + "@" + domain;
return true;
}
internal static bool TryParseMailbox (ParserOptions options, byte[] text, int startIndex, ref int index, int endIndex, string name, int codepage, bool throwOnError, out InternetAddress address)
{
DomainList route = null;
Encoding encoding;
try {
encoding = Encoding.GetEncoding (codepage);
} catch {
encoding = Encoding.UTF8;
}
address = null;
// skip over the '<'
index++;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
if (text[index] == (byte) '@') {
// Note: we always pass 'false' as the throwOnError argument here so that we can throw a more informative exception on error
if (!DomainList.TryParse (text, ref index, endIndex, false, out route)) {
if (throwOnError)
throw new ParseException (string.Format ("Invalid route in mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
if (index + 1 >= endIndex || text[index] != (byte) ':') {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete route in mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
index++;
}
string addrspec;
if (!TryParseAddrspec (text, ref index, endIndex, (byte) '>', throwOnError, out addrspec))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex || text[index] != (byte) '>') {
if (options.AddressParserComplianceMode == RfcComplianceMode.Strict) {
if (throwOnError)
throw new ParseException (string.Format ("Unexpected end of mailbox at offset {0}", startIndex), startIndex, index);
return false;
}
} else {
index++;
}
if (route != null)
address = new MailboxAddress (encoding, name, route, addrspec);
else
address = new MailboxAddress (encoding, name, addrspec);
return true;
}
static bool TryParseGroup (ParserOptions options, byte[] text, int startIndex, ref int index, int endIndex, string name, int codepage, bool throwOnError, out InternetAddress address)
{
List<InternetAddress> members;
Encoding encoding;
try {
encoding = Encoding.GetEncoding (codepage);
} catch {
encoding = Encoding.UTF8;
}
address = null;
// skip over the ':'
index++;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete address group at offset {0}", startIndex), startIndex, index);
return false;
}
if (InternetAddressList.TryParse (options, text, ref index, endIndex, true, throwOnError, out members))
address = new GroupAddress (encoding, name, members);
else
address = new GroupAddress (encoding, name);
if (index >= endIndex || text[index] != (byte) ';') {
if (throwOnError)
throw new ParseException (string.Format ("Expected to find ';' at offset {0}", index), startIndex, index);
while (index < endIndex && text[index] != (byte) ';')
index++;
} else {
index++;
}
return true;
}
[Flags]
internal enum AddressParserFlags {
AllowMailboxAddress = 1 << 0,
AllowGroupAddress = 1 << 1,
ThrowOnError = 1 << 2,
TryParse = AllowMailboxAddress | AllowGroupAddress,
Parse = TryParse | ThrowOnError
}
internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, AddressParserFlags flags, out InternetAddress address)
{
bool throwOnError = (flags & AddressParserFlags.ThrowOnError) != 0;
address = null;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index == endIndex) {
if (throwOnError)
throw new ParseException ("No address found.", index, index);
return false;
}
// keep track of the start & length of the phrase
int startIndex = index;
int length = 0;
while (index < endIndex && ParseUtils.SkipWord (text, ref index, endIndex, throwOnError)) {
length = index - startIndex;
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
// Note: some clients don't quote dots in the name
if (index >= endIndex || text[index] != (byte) '.')
break;
index++;
} while (true);
}
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
// specials = "(" / ")" / "<" / ">" / "@" ; Must be in quoted-
// / "," / ";" / ":" / "\" / <"> ; string, to use
// / "." / "[" / "]" ; within a word.
if (index >= endIndex || text[index] == (byte) ',' || text[index] == ';') {
// we've completely gobbled up an addr-spec w/o a domain
byte sentinel = index < endIndex ? text[index] : (byte) ',';
string name, addrspec;
// rewind back to the beginning of the local-part
index = startIndex;
if (!TryParseAddrspec (text, ref index, endIndex, sentinel, throwOnError, out addrspec))
return false;
ParseUtils.SkipWhiteSpace (text, ref index, endIndex);
if (index < endIndex && text[index] == '(') {
int comment = index;
if (!ParseUtils.SkipComment (text, ref index, endIndex)) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete comment token at offset {0}", comment), comment, index);
return false;
}
comment++;
name = Rfc2047.DecodePhrase (options, text, comment, (index - 1) - comment).Trim ();
} else {
name = string.Empty;
}
address = new MailboxAddress (name, addrspec);
return true;
}
if (text[index] == (byte) ':') {
// rfc2822 group address
int codepage = -1;
string name;
if ((flags & AddressParserFlags.AllowGroupAddress) == 0) {
if (throwOnError)
throw new ParseException (string.Format ("group address token at offset {0}", startIndex), startIndex, index);
return false;
}
if (length > 0) {
name = Rfc2047.DecodePhrase (options, text, startIndex, length, out codepage);
} else {
name = string.Empty;
}
if (codepage == -1)
codepage = 65001;
return TryParseGroup (options, text, startIndex, ref index, endIndex, MimeUtils.Unquote (name), codepage, throwOnError, out address);
}
if ((flags & AddressParserFlags.AllowMailboxAddress) == 0) {
if (throwOnError)
throw new ParseException (string.Format ("mailbox address token at offset {0}", startIndex), startIndex, index);
return false;
}
if (text[index] == (byte) '<') {
// rfc2822 angle-addr token
int codepage = -1;
string name;
if (length > 0) {
name = Rfc2047.DecodePhrase (options, text, startIndex, length, out codepage);
} else {
name = string.Empty;
}
if (codepage == -1)
codepage = 65001;
return TryParseMailbox (options, text, startIndex, ref index, endIndex, MimeUtils.Unquote (name), codepage, throwOnError, out address);
}
if (text[index] == (byte) '@') {
// we're either in the middle of an addr-spec token or we completely gobbled up an addr-spec w/o a domain
string name, addrspec;
// rewind back to the beginning of the local-part
index = startIndex;
if (!TryParseAddrspec (text, ref index, endIndex, (byte) ',', throwOnError, out addrspec))
return false;
ParseUtils.SkipWhiteSpace (text, ref index, endIndex);
if (index < endIndex && text[index] == '(') {
int comment = index;
if (!ParseUtils.SkipComment (text, ref index, endIndex)) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete comment token at offset {0}", comment), comment, index);
return false;
}
comment++;
name = Rfc2047.DecodePhrase (options, text, comment, (index - 1) - comment).Trim ();
} else {
name = string.Empty;
}
address = new MailboxAddress (name, addrspec);
return true;
}
if (throwOnError)
throw new ParseException (string.Format ("Invalid address token at offset {0}", startIndex), startIndex, index);
return false;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, int length, out InternetAddress address)
{
ParseUtils.ValidateArguments (options, buffer, startIndex, length);
int endIndex = startIndex + length;
int index = startIndex;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.TryParse, out address))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false)) {
address = null;
return false;
}
if (index != endIndex) {
address = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, int length, out InternetAddress address)
{
return TryParse (ParserOptions.Default, buffer, startIndex, length, out address);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, int startIndex, out InternetAddress address)
{
ParseUtils.ValidateArguments (options, buffer, startIndex);
int endIndex = buffer.Length;
int index = startIndex;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.TryParse, out address))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
address = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
public static bool TryParse (byte[] buffer, int startIndex, out InternetAddress address)
{
return TryParse (ParserOptions.Default, buffer, startIndex, out address);
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
public static bool TryParse (ParserOptions options, byte[] buffer, out InternetAddress address)
{
ParseUtils.ValidateArguments (options, buffer);
int endIndex = buffer.Length;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.TryParse, out address))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
address = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
public static bool TryParse (byte[] buffer, out InternetAddress address)
{
return TryParse (ParserOptions.Default, buffer, out address);
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the text contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (ParserOptions options, string text, out InternetAddress address)
{
ParseUtils.ValidateArguments (options, text);
var buffer = Encoding.UTF8.GetBytes (text);
int endIndex = buffer.Length;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.TryParse, out address))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, false) || index != endIndex) {
address = null;
return false;
}
return true;
}
/// <summary>
/// Tries to parse the given text into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the text contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns><c>true</c>, if the address was successfully parsed, <c>false</c> otherwise.</returns>
/// <param name="text">The text.</param>
/// <param name="address">The parsed address.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
public static bool TryParse (string text, out InternetAddress address)
{
return TryParse (ParserOptions.Default, text, out address);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (ParserOptions options, byte[] buffer, int startIndex, int length)
{
ParseUtils.ValidateArguments (options, buffer, startIndex, length);
int endIndex = startIndex + length;
InternetAddress address;
int index = startIndex;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.Parse, out address))
throw new ParseException ("No address found.", startIndex, startIndex);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return address;
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <param name="length">The number of bytes in the input buffer to parse.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> and <paramref name="length"/> do not specify
/// a valid range in the byte array.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (byte[] buffer, int startIndex, int length)
{
return Parse (ParserOptions.Default, buffer, startIndex, length);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/>is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (ParserOptions options, byte[] buffer, int startIndex)
{
ParseUtils.ValidateArguments (options, buffer, startIndex);
int endIndex = buffer.Length;
InternetAddress address;
int index = startIndex;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.Parse, out address))
throw new ParseException ("No address found.", startIndex, startIndex);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return address;
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <param name="startIndex">The starting index of the input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="startIndex"/> is out of range.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (byte[] buffer, int startIndex)
{
return Parse (ParserOptions.Default, buffer, startIndex);
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="buffer"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (ParserOptions options, byte[] buffer)
{
ParseUtils.ValidateArguments (options, buffer);
int endIndex = buffer.Length;
InternetAddress address;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.Parse, out address))
throw new ParseException ("No address found.", 0, 0);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return address;
}
/// <summary>
/// Parses the given input buffer into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the buffer contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="buffer">The input buffer.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="buffer"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="buffer"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (byte[] buffer)
{
return Parse (ParserOptions.Default, buffer);
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the text contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="options">The parser options to use.</param>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="options"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (ParserOptions options, string text)
{
ParseUtils.ValidateArguments (options, text);
var buffer = Encoding.UTF8.GetBytes (text);
int endIndex = buffer.Length;
InternetAddress address;
int index = 0;
if (!TryParse (options, buffer, ref index, endIndex, AddressParserFlags.Parse, out address))
throw new ParseException ("No address found.", 0, 0);
ParseUtils.SkipCommentsAndWhiteSpace (buffer, ref index, endIndex, true);
if (index != endIndex)
throw new ParseException (string.Format ("Unexpected token at offset {0}", index), index, index);
return address;
}
/// <summary>
/// Parses the given text into a new <see cref="MimeKit.InternetAddress"/> instance.
/// </summary>
/// <remarks>
/// Parses a single <see cref="MailboxAddress"/> or <see cref="GroupAddress"/>. If the text contains
/// more data, then parsing will fail.
/// </remarks>
/// <returns>The parsed <see cref="MimeKit.InternetAddress"/>.</returns>
/// <param name="text">The text.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="text"/> is <c>null</c>.
/// </exception>
/// <exception cref="MimeKit.ParseException">
/// <paramref name="text"/> could not be parsed.
/// </exception>
public static InternetAddress Parse (string text)
{
return Parse (ParserOptions.Default, text);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using ID3.ID3v2Frames;
using System.Collections;
/*
* This file only contain 2 classes that use for storing each frame information
* ex. if you find TIT2 FrameID in tag with FrameList you can understand is it a
* TextFrame or not. or even is it a valid FrameID ? and something like this
*/
namespace ID3.ID3v2Frames
{
/// <summary>
/// Static class that represent informaion about ID3v2 frames
/// </summary>
public static class FramesInfo
{
private static Dictionary<string, FrameInfo> _FramesDictionary; // a dictionary contain all Frames information
/// <summary>
/// Gets Dictionary of frames information
/// </summary>
private static Dictionary<string, FrameInfo> FramesDictionary
{
get
{
if (_FramesDictionary == null)
{
_FramesDictionary = new Dictionary<string, FrameInfo>();
InitialValues();
}
return _FramesDictionary;
}
}
/// <summary>
/// Initialize All FrameID infos
/// </summary>
private static void InitialValues()
{
/*
* Also we can use an XML file to store this information
* and just load it here. but i think in that way using DLL
* will not as relax as it don't use XML. because you need always
* have that XML file beside DLL. if you don't the DLL won't work
* without XML or any type of other storing file just you need this DLL
* and it's enough. i think it's better
*/
_FramesDictionary.Add("", new FrameInfo("", "CRM", "Encrypted Meta File",
new bool[] { true, false, false }));
_FramesDictionary.Add("AENC", new FrameInfo("AENC", "CRA", "Audio Encryption",
new bool[] { true, true, true }));
_FramesDictionary.Add("APIC", new FrameInfo("APIC", "PIC", "Attached Picture",
new bool[] { true, true, true }));
_FramesDictionary.Add("ASPI", new FrameInfo("ASPI", null, "Audio Seek Point Index",
new bool[] { false, false, true }));
_FramesDictionary.Add("COMM", new FrameInfo("COMM", "COM", "Comment",
new bool[] { true, true, true }));
_FramesDictionary.Add("COMR", new FrameInfo("COMR", null, "Commercial Frame",
new bool[] { false, true, true }));
_FramesDictionary.Add("ENCR", new FrameInfo("ENCR", null, "Encryption Method Registration",
new bool[] { false, true, true }));
_FramesDictionary.Add("EQU2", new FrameInfo("EQU2", null, "Equalisation (2)",
new bool[] { false, false, true }));
_FramesDictionary.Add("EQUA", new FrameInfo("EQUA", "EQU", "Equalisation",
new bool[] { true, true, false }));
_FramesDictionary.Add("ETCO", new FrameInfo("ETCO", "ETC", "Event Timing Code",
new bool[] { true, true, true }));
_FramesDictionary.Add("GEOB", new FrameInfo("GEOB", "GEO", "General Encapsulated Object",
new bool[] { true, true, true }));
_FramesDictionary.Add("GRID", new FrameInfo("GRID", null, "Group Identification Registration",
new bool[] { false, true, true }));
_FramesDictionary.Add("IPLS", new FrameInfo("IPLS", "IPL", "Involved People List",
new bool[] { true, true, false }));
_FramesDictionary.Add("LINK", new FrameInfo("LINK", "LNK", "Linked Information",
new bool[] { true, true, true }));
_FramesDictionary.Add("MCDI", new FrameInfo("MCDI", "MCI", "Music CD Identifier",
new bool[] { true, true, true }));
_FramesDictionary.Add("MLLT", new FrameInfo("MLLT", "MLL", "Mepg Location Lookup Table",
new bool[] { true, true, true }));
_FramesDictionary.Add("OWNE", new FrameInfo("OWNE", null, "Ownership Information",
new bool[] { false, true, true }));
_FramesDictionary.Add("PCNT", new FrameInfo("PCNT", "CNT", "Play Counter",
new bool[] { true, true, true }));
_FramesDictionary.Add("POPM", new FrameInfo("POPM", "POP", "Popularimeter",
new bool[] { true, true, true }));
_FramesDictionary.Add("POSS", new FrameInfo("POSS", null, "Position Synchronisation Frame",
new bool[] { false, true, true }));
_FramesDictionary.Add("PRIV", new FrameInfo("PRIV", null, "Private Frame",
new bool[] { false, true, true }));
_FramesDictionary.Add("RBUF", new FrameInfo("RBUF", "BUF", "Recommended Buffer Size",
new bool[] { true, true, true }));
_FramesDictionary.Add("RVA2", new FrameInfo("RVA2", null, "Relative Volume Adjustment (2)",
new bool[] { false, false, true }));
_FramesDictionary.Add("RVAD", new FrameInfo("RVAD", "RVA", "Relative Volume Adjustment",
new bool[] { true, true, false }));
_FramesDictionary.Add("RVRB", new FrameInfo("RVRB", "REV", "Reverb",
new bool[] { true, true, true }));
_FramesDictionary.Add("SEEK", new FrameInfo("SEEK", null, "Seek Frame",
new bool[] { false, false, true }));
_FramesDictionary.Add("SIGN", new FrameInfo("SIGN", null, "Signature Frame",
new bool[] { false, false, true }));
_FramesDictionary.Add("SYLT", new FrameInfo("SYLT", "SLT", "Synchronized Lyric/Text",
new bool[] { true, true, true }));
_FramesDictionary.Add("SYTC", new FrameInfo("SYTC", "STC", "Synced Tempo Codes",
new bool[] { true, true, true }));
_FramesDictionary.Add("TALB", new FrameInfo("TALB", "TAL", "Album",
new bool[] { true, true, true }));
_FramesDictionary.Add("TBPM", new FrameInfo("TBPM", "TBP", "BPM ( Beats Per Minutes)",
new bool[] { true, true, true }));
_FramesDictionary.Add("TCOM", new FrameInfo("TCOM", "TCM", "Composer",
new bool[] { true, true, true }));
_FramesDictionary.Add("TCON", new FrameInfo("TCON", "TCO", "Content Type",
new bool[] { true, true, true }));
_FramesDictionary.Add("TCOP", new FrameInfo("TCOP", "TCR", "Copyright Message",
new bool[] { true, true, true }));
_FramesDictionary.Add("TDAT", new FrameInfo("TDAT", "TDA", "Date",
new bool[] { true, true, false }));
_FramesDictionary.Add("TDEN", new FrameInfo("TDEN", null, "Encoding Time",
new bool[] { false, false, true }));
_FramesDictionary.Add("TDLY", new FrameInfo("TDLY", "TDY", "Playlist Delay",
new bool[] { true, true, true }));
_FramesDictionary.Add("TDOR", new FrameInfo("TDOR", null, "Orginal Release Time",
new bool[] { false, false, true }));
_FramesDictionary.Add("TDRC", new FrameInfo("TDRC", null, "Recording Time",
new bool[] { false, false, true }));
_FramesDictionary.Add("TDRL", new FrameInfo("TDRL", null, "Release Time",
new bool[] { false, false, true }));
_FramesDictionary.Add("TDTG", new FrameInfo("TDTG", null, "Tagging Time",
new bool[] { false, false, true }));
_FramesDictionary.Add("TENC", new FrameInfo("TENC", "TEN", "Encoded By",
new bool[] { true, true, true }));
_FramesDictionary.Add("TEXT", new FrameInfo("TEXT", "TXT", "Lyric/Text Writer",
new bool[] { true, true, true }));
_FramesDictionary.Add("TFLT", new FrameInfo("TFLT", "TFT", "File Type",
new bool[] { true, true, true }));
_FramesDictionary.Add("TIME", new FrameInfo("TIME", "TIM", "Time",
new bool[] { true, true, false }));
_FramesDictionary.Add("TIPL", new FrameInfo("TIPL", null, "Involved People List",
new bool[] { false, false, true }));
_FramesDictionary.Add("TIT1", new FrameInfo("TIT1", "TT1", "Content Group Description",
new bool[] { true, true, true }));
_FramesDictionary.Add("TIT2", new FrameInfo("TIT2", "TT2", "Title",
new bool[] { true, true, true }));
_FramesDictionary.Add("TIT3", new FrameInfo("TIT3", "TT3", "Subtitle/Desripction",
new bool[] { true, true, true }));
_FramesDictionary.Add("TKEY", new FrameInfo("TKEY", "TKE", "Initial Key",
new bool[] { true, true, true }));
_FramesDictionary.Add("TLAN", new FrameInfo("TLAN", "TLA", "Language",
new bool[] { true, true, true }));
_FramesDictionary.Add("TLEN", new FrameInfo("TLEN", "TLE", "Length",
new bool[] { true, true, true }));
_FramesDictionary.Add("TMCL", new FrameInfo("TMCL", null, "Musician Credits List",
new bool[] { false, false, true }));
_FramesDictionary.Add("TMED", new FrameInfo("TMED", "TMT", "Media Type",
new bool[] { true, true, true }));
_FramesDictionary.Add("TMOO", new FrameInfo("TMOO", null, "Mood",
new bool[] { false, false, true }));
_FramesDictionary.Add("TOAL", new FrameInfo("TOAL", "TOT", "Orginal Title",
new bool[] { true, true, true }));
_FramesDictionary.Add("TOFN", new FrameInfo("TOFN", "TOF", "Orginal Filename",
new bool[] { true, true, true }));
_FramesDictionary.Add("TOLY", new FrameInfo("TOLY", "TOL", "Orginal Lyricist",
new bool[] { true, true, true }));
_FramesDictionary.Add("TOPE", new FrameInfo("TOPE", "TOA", "Orginal Artist",
new bool[] { true, true, true }));
_FramesDictionary.Add("TORY", new FrameInfo("TORY", "TOR", "Orginal Release Year",
new bool[] { true, true, false }));
_FramesDictionary.Add("TOWN", new FrameInfo("TOWN", null, "File Owner",
new bool[] { false, true, true }));
_FramesDictionary.Add("TPE1", new FrameInfo("TPE1", "TP1", "Lead Artist",
new bool[] { true, true, true }));
_FramesDictionary.Add("TPE2", new FrameInfo("TPE2", "TP2", "Band Artist",
new bool[] { true, true, true }));
_FramesDictionary.Add("TPE3", new FrameInfo("TPE3", "TP3", "Conductor",
new bool[] { true, true, true }));
_FramesDictionary.Add("TPE4", new FrameInfo("TPE4", "TP4", "Interpreted",
new bool[] { true, true, true }));
_FramesDictionary.Add("TPOS", new FrameInfo("TPOS", "TPA", "Part of set",
new bool[] { true, true, true }));
_FramesDictionary.Add("TPRO", new FrameInfo("TPRO", null, "Produced Notice",
new bool[] { false, false, true }));
_FramesDictionary.Add("TPUB", new FrameInfo("TPUB", "TPB", "Publisher",
new bool[] { true, true, true }));
_FramesDictionary.Add("TRCK", new FrameInfo("TRCK", "TRK", "Track Number",
new bool[] { true, true, true }));
_FramesDictionary.Add("TRDA", new FrameInfo("TRDA", "TRD", "Recording Date",
new bool[] { true, true, false }));
_FramesDictionary.Add("TRSN", new FrameInfo("TRSN", null, "Internet Radio Station Name",
new bool[] { false, true, true }));
_FramesDictionary.Add("TRSO", new FrameInfo("TRSO", null, "Internet Radio Station Owner",
new bool[] { false, true, true }));
_FramesDictionary.Add("TSIZ", new FrameInfo("TSIZ", "TSI", "Size",
new bool[] { true, true, false }));
_FramesDictionary.Add("TSOA", new FrameInfo("TSOA", null, "Album Sort Order",
new bool[] { false, false, true }));
_FramesDictionary.Add("TSOP", new FrameInfo("TSOP", null, "Preformer Sort Order",
new bool[] { false, false, true }));
_FramesDictionary.Add("TSOT", new FrameInfo("TSOT", null, "Title Sort Order",
new bool[] { false, false, true }));
_FramesDictionary.Add("TSRC", new FrameInfo("TSRC", "TRC", "ISRC",
new bool[] { true, true, true }));
_FramesDictionary.Add("TSSE", new FrameInfo("TSSE", "TSS", "Software/Hardware And Setting Used For Encoding",
new bool[] { true, true, true }));
_FramesDictionary.Add("TSST", new FrameInfo("TSST", null, "Set Subtitle",
new bool[] { false, false, true }));
_FramesDictionary.Add("TYER", new FrameInfo("TYER", "TYE", "Year",
new bool[] { true, true, false }));
_FramesDictionary.Add("UFID", new FrameInfo("UFID", "UFI", "Unique File Identifier",
new bool[] { true, true, true }));
_FramesDictionary.Add("USER", new FrameInfo("USER", null, "Term Of Use",
new bool[] { false, true, true }));
_FramesDictionary.Add("USLT", new FrameInfo("USLT", "ULT", "Unsynchronized Lyric",
new bool[] { true, true, true }));
_FramesDictionary.Add("WCOM", new FrameInfo("WCOM", "WCM", "Commercial Information",
new bool[] { true, true, true }));
_FramesDictionary.Add("WCOP", new FrameInfo("WCOP", "WCP", "Copyright Information",
new bool[] { true, true, true }));
_FramesDictionary.Add("WOAF", new FrameInfo("WOAF", "WAF", "Official Audio File web",
new bool[] { true, true, true }));
_FramesDictionary.Add("WOAR", new FrameInfo("WOAR", "WAR", "Official Artist web",
new bool[] { true, true, true }));
_FramesDictionary.Add("WOAS", new FrameInfo("WOAS", "WAS", "Official Audio Source web",
new bool[] { true, true, true }));
_FramesDictionary.Add("WORS", new FrameInfo("WORS", null, "Official Radio Station Web",
new bool[] { false, true, true }));
_FramesDictionary.Add("WPAY", new FrameInfo("WPAY", null, "Payment web",
new bool[] { false, true, true }));
_FramesDictionary.Add("WPUB", new FrameInfo("WPUB", "WPB", "Publisher web",
new bool[] { true, true, true }));
}
/// <summary>
/// Get FrameInfo from 4 chacarter FrameID
/// </summary>
/// <param name="FrameID">4 character FrameID to get FrameInfo</param>
/// <returns>FrameInfo contain Specific frame information</returns>
public static FrameInfo GetFrame(string FrameID)
{
return (FrameInfo)FramesDictionary[FrameID];
}
/// <summary>
/// Get 4 Character FrameID for specific 3 Character FrameID
/// </summary>
/// <param name="FrameID">3 character FrameID</param>
/// <returns>System.String contain 4 Character FrameID or null if not found</returns>
public static string Get4CharID(string FrameID3)
{
foreach (FrameInfo FI in FramesDictionary.Values)
if (FrameID3 == FI.FrameID3Char)
return FI.FrameID4Char;
return null;
}
/// <summary>
/// Get 3 character FrameID from specific 4 Character FrameID
/// </summary>
/// <param name="FrameID">4 character FrameID</param>
/// <returns>3 Chacater FrameID</returns>
public static string Get3CharID(string FrameID)
{
if (FramesDictionary.ContainsKey(FrameID))
return ((FrameInfo)FramesDictionary[FrameID]).FrameID3Char;
return null;
}
/// <summary>
/// Indicate if specific FrameID is TextFrame(1), UserTextFrame(2) or non of them(0)
/// </summary>
/// <param name="FrameID">FrameID to control</param>
/// <param name="Ver">minor version of ID3v2</param>
/// <returns>int that indicate FrameID type</returns>
public static int IsTextFrame(string FrameID, int Ver)
{
// 0: mean's it's not TextFrame and UserTextFrame either
// 1: it's TextFrame
// 2: it's UserTextFrame
if (FrameID == "IPLS")
{
if (Ver == 4) // in version 4 IPLS frame removed
return 0;
else
return 1;
}
if (FrameID[0] == 'T' || FrameID[0] == 'W')
{
if (FramesDictionary.ContainsKey(FrameID))
{
if (((FrameInfo)FramesDictionary[FrameID]).IsValid(Ver))
return 1;
return 2;
}
else
return 2;
}
return 0;
}
/// <summary>
/// Indicate if specific FrameID is compatible with specific minor version of ID3v2
/// </summary>
/// <param name="FrameID">FrameID to check</param>
/// <param name="Ver">minor version of ID3v2</param>
/// <returns>true if it's compatible otherwise false</returns>
public static bool IsCompatible(string FrameID, int Ver)
{
if (!FramesDictionary.ContainsKey(FrameID))
return false;
return ((FrameInfo)FramesDictionary[FrameID]).IsValid(Ver);
}
/// <summary>
/// Indicate if specific string is a valid FrameID
/// </summary>
/// <param name="FrameID">FrameID to check</param>
/// <returns>true if valid otherwise false</returns>
public static bool IsValidFrameID(string FrameID)
{
if (FrameID == null)
return false;
if (FrameID.Length != 4)
return false;
else
foreach (char ch in FrameID)
if (!Char.IsUpper(ch) && !char.IsDigit(ch))
return false;
return true;
}
}
/// <summary>
/// Provide information for one Frame
/// </summary>
public class FrameInfo
{
private string _Name;
private string _FrameID4Ch; // FrameID with 4 Characters
private string _FrameID3Ch; // FrameID with 3 Characters
private bool[] _Validation;
internal FrameInfo(string FrameID, string FrameID3,
string Name, bool[] Validation)
{
_Name = Name;
_FrameID4Ch = FrameID;
_FrameID3Ch = FrameID3;
_Validation = Validation;
}
/// <summary>
/// Get Name of current FrameIDInfo
/// </summary>
public string Name
{
get
{ return _Name; }
}
/// <summary>
/// Get FrameID of current FrameIDInfo for specific version of ID3v2
/// </summary>
/// <param name="Version">minor version of ID3v2 to compatible with FrameID</param>
/// <returns>System.String retrieve FrameID of current FrameIDInfo</returns>
public string FrameID(int Version)
{
if (Version < 2 || Version > 4)
throw (new ArgumentOutOfRangeException("Version must be between 2-4"));
else if (Version == 2)
return _FrameID3Ch;
else
return _FrameID4Ch;
}
/// <summary>
/// Indicate if current FrameID is valid for specific Version of ID3v2
/// </summary>
/// <param name="Version">Version of ID3v2</param>
/// <returns>true if it's valid otherwise false</returns>
public bool IsValid(int Version)
{
if (Version < 2 && Version > 4)
throw (new ArgumentOutOfRangeException("Version value must be between 2-4"));
return _Validation[Version - 2];
}
/// <summary>
/// Get 3 character FrameID
/// </summary>
public string FrameID3Char
{
get
{ return _FrameID3Ch; }
}
/// <summary>
/// Get 4 character FrameID
/// </summary>
public string FrameID4Char
{
get
{ return _FrameID4Ch; }
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.