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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class LiftedBitwiseAndNullableTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableByteTest(bool useInterpreter)
{
byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableIntTest(bool useInterpreter)
{
int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableLongTest(bool useInterpreter)
{
long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableLong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableSByteTest(bool useInterpreter)
{
sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableSByte(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableShortTest(bool useInterpreter)
{
short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableUIntTest(bool useInterpreter)
{
uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableUInt(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableULongTest(bool useInterpreter)
{
ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableULong(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableUShortTest(bool useInterpreter)
{
ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableUShort(values[i], values[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLiftedBitwiseAndNullableNumberTest(bool useInterpreter)
{
Number?[] values = new Number?[] { null, new Number(0), new Number(1), Number.MaxValue };
for (int i = 0; i < values.Length; i++)
{
for (int j = 0; j < values.Length; j++)
{
VerifyBitwiseAndNullableNumber(values[i], values[j], useInterpreter);
}
}
}
#endregion
#region Helpers
public static byte AndNullableByte(byte a, byte b)
{
return (byte)(a & b);
}
public static int AndNullableInt(int a, int b)
{
return (int)(a & b);
}
public static long AndNullableLong(long a, long b)
{
return (long)(a & b);
}
public static sbyte AndNullableSByte(sbyte a, sbyte b)
{
return (sbyte)(a & b);
}
public static short AndNullableShort(short a, short b)
{
return (short)(a & b);
}
public static uint AndNullableUInt(uint a, uint b)
{
return (uint)(a & b);
}
public static ulong AndNullableULong(ulong a, ulong b)
{
return (ulong)(a & b);
}
public static ushort AndNullableUShort(ushort a, ushort b)
{
return (ushort)(a & b);
}
#endregion
#region Test verifiers
private static void VerifyBitwiseAndNullableByte(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.And(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableByte")));
Func<byte?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableInt(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.And(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableInt")));
Func<int?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableLong(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.And(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableLong")));
Func<long?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableSByte(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.And(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableSByte")));
Func<sbyte?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableShort(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.And(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableShort")));
Func<short?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableUInt(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.And(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableUInt")));
Func<uint?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableULong(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.And(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableULong")));
Func<ulong?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableUShort(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.And(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
typeof(LiftedBitwiseAndNullableTests).GetTypeInfo().GetDeclaredMethod("AndNullableUShort")));
Func<ushort?> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBitwiseAndNullableNumber(Number? a, Number? b, bool useInterpreter)
{
Expression<Func<Number?>> e =
Expression.Lambda<Func<Number?>>(
Expression.And(
Expression.Constant(a, typeof(Number?)),
Expression.Constant(b, typeof(Number?))));
Assert.Equal(typeof(Number?), e.Body.Type);
Func<Number?> f = e.Compile(useInterpreter);
Number? expected = a & b;
Assert.Equal(expected, f());
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using Microsoft.Scripting;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime.Binding {
using Ast = Expression;
using AstUtils = Microsoft.Scripting.Ast.Utils;
class MetaOldClass : MetaPythonObject, IPythonInvokable, IPythonGetable, IPythonOperable, IPythonConvertible {
public MetaOldClass(Expression/*!*/ expression, BindingRestrictions/*!*/ restrictions, OldClass/*!*/ value)
: base(expression, BindingRestrictions.Empty, value) {
Assert.NotNull(value);
}
#region IPythonInvokable Members
public DynamicMetaObject/*!*/ Invoke(PythonInvokeBinder/*!*/ pythonInvoke, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ target, DynamicMetaObject/*!*/[]/*!*/ args) {
return MakeCallRule(pythonInvoke, codeContext, args);
}
#endregion
#region IPythonGetable Members
public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObject codeContext) {
// no codeContext filtering but avoid an extra site by handling this action directly
return MakeGetMember(member, codeContext);
}
#endregion
#region MetaObject Overrides
public override DynamicMetaObject/*!*/ BindInvokeMember(InvokeMemberBinder/*!*/ action, DynamicMetaObject/*!*/[]/*!*/ args) {
return BindingHelpers.GenericInvokeMember(action, null, this, args);
}
public override DynamicMetaObject/*!*/ BindInvoke(InvokeBinder/*!*/ call, params DynamicMetaObject/*!*/[]/*!*/ args) {
return MakeCallRule(call, AstUtils.Constant(PythonContext.GetPythonContext(call).SharedContext), args);
}
public override DynamicMetaObject/*!*/ BindCreateInstance(CreateInstanceBinder/*!*/ create, params DynamicMetaObject/*!*/[]/*!*/ args) {
return MakeCallRule(create, AstUtils.Constant(PythonContext.GetPythonContext(create).SharedContext), args);
}
public override DynamicMetaObject/*!*/ BindGetMember(GetMemberBinder/*!*/ member) {
return MakeGetMember(member, PythonContext.GetCodeContextMO(member));
}
public override DynamicMetaObject/*!*/ BindSetMember(SetMemberBinder/*!*/ member, DynamicMetaObject/*!*/ value) {
return MakeSetMember(member.Name, value);
}
public override DynamicMetaObject/*!*/ BindDeleteMember(DeleteMemberBinder/*!*/ member) {
return MakeDeleteMember(member);
}
public override DynamicMetaObject BindConvert(ConvertBinder/*!*/ conversion) {
return ConvertWorker(conversion, conversion.Type, conversion.Explicit ? ConversionResultKind.ExplicitCast : ConversionResultKind.ImplicitCast);
}
public DynamicMetaObject BindConvert(PythonConversionBinder binder) {
return ConvertWorker(binder, binder.Type, binder.ResultKind);
}
public DynamicMetaObject ConvertWorker(DynamicMetaObjectBinder binder, Type toType, ConversionResultKind kind) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass Convert");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass Convert");
if (toType.IsSubclassOf(typeof(Delegate))) {
return MakeDelegateTarget(binder, toType, Restrict(typeof(OldClass)));
}
return FallbackConvert(binder);
}
public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() {
foreach (object o in ((IPythonMembersList)Value).GetMemberNames(DefaultContext.Default)) {
if (o is string) {
yield return (string)o;
}
}
}
#endregion
#region Calls
private DynamicMetaObject/*!*/ MakeCallRule(DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, DynamicMetaObject[] args) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass Invoke w/ " + args.Length + " args");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass Invoke");
CallSignature signature = BindingHelpers.GetCallSignature(call);
// TODO: If we know __init__ wasn't present we could construct the OldInstance directly.
Expression[] exprArgs = new Expression[args.Length];
for (int i = 0; i < args.Length; i++) {
exprArgs[i] = args[i].Expression;
}
ParameterExpression init = Ast.Variable(typeof(object), "init");
ParameterExpression instTmp = Ast.Variable(typeof(object), "inst");
DynamicMetaObject self = Restrict(typeof(OldClass));
return new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { init, instTmp },
Ast.Assign(
instTmp,
Ast.New(
typeof(OldInstance).GetConstructor(new Type[] { typeof(CodeContext), typeof(OldClass) }),
codeContext,
self.Expression
)
),
Ast.Condition(
Expression.Not(
Expression.TypeIs(
Expression.Assign(
init,
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassTryLookupInit)),
self.Expression,
instTmp
)
),
typeof(OperationFailed)
)
),
DynamicExpression.Dynamic(
PythonContext.GetPythonContext(call).Invoke(
signature
),
typeof(object),
ArrayUtils.Insert<Expression>(codeContext, init, exprArgs)
),
NoInitCheckNoArgs(signature, self, args)
),
instTmp
),
self.Restrictions.Merge(BindingRestrictions.Combine(args))
);
}
private static Expression NoInitCheckNoArgs(CallSignature signature, DynamicMetaObject self, DynamicMetaObject[] args) {
int unusedCount = args.Length;
Expression dictExpr = GetArgumentExpression(signature, ArgumentType.Dictionary, ref unusedCount, args);
Expression listExpr = GetArgumentExpression(signature, ArgumentType.List, ref unusedCount, args);
if (signature.IsSimple || unusedCount > 0) {
if (args.Length > 0) {
return Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassMakeCallError)),
self.Expression
);
}
return AstUtils.Constant(null);
}
return Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassCheckCallError)),
self.Expression,
dictExpr,
listExpr
);
}
private static Expression GetArgumentExpression(CallSignature signature, ArgumentType kind, ref int unusedCount, DynamicMetaObject/*!*/[]/*!*/ args) {
int index = signature.IndexOf(kind);
if (index != -1) {
unusedCount--;
return args[index].Expression;
}
return AstUtils.Constant(null);
}
public static object MakeCallError() {
// Normally, if we have an __init__ method, the method binder detects signature mismatches.
// This can happen when a class does not define __init__ and therefore does not take any arguments.
// Beware that calls like F(*(), **{}) have 2 arguments but they're empty and so it should still
// match against def F().
throw PythonOps.TypeError("this constructor takes no arguments");
}
#endregion
#region Member Access
private DynamicMetaObject/*!*/ MakeSetMember(string/*!*/ name, DynamicMetaObject/*!*/ value) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass SetMember");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass SetMember");
DynamicMetaObject self = Restrict(typeof(OldClass));
Expression call, valueExpr = AstUtils.Convert(value.Expression, typeof(object));
switch (name) {
case "__bases__":
call = Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassSetBases)),
self.Expression,
valueExpr
);
break;
case "__name__":
call = Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassSetName)),
self.Expression,
valueExpr
);
break;
case "__dict__":
call = Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassSetDictionary)),
self.Expression,
valueExpr
);
break;
default:
call = Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassSetNameHelper)),
self.Expression,
AstUtils.Constant(name),
valueExpr
);
break;
}
return new DynamicMetaObject(
call,
self.Restrictions.Merge(value.Restrictions)
);
}
private DynamicMetaObject/*!*/ MakeDeleteMember(DeleteMemberBinder/*!*/ member) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass DeleteMember");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass DeleteMember");
DynamicMetaObject self = Restrict(typeof(OldClass));
return new DynamicMetaObject(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassDeleteMember)),
AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext),
self.Expression,
AstUtils.Constant(member.Name)
),
self.Restrictions
);
}
private DynamicMetaObject/*!*/ MakeGetMember(DynamicMetaObjectBinder/*!*/ member, DynamicMetaObject codeContext) {
PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass GetMember");
PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "OldClass GetMember");
DynamicMetaObject self = Restrict(typeof(OldClass));
Expression target;
string memberName = GetGetMemberName(member);
switch (memberName) {
case "__dict__":
target = Ast.Block(
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassDictionaryIsPublic)),
self.Expression
),
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassGetDictionary)),
self.Expression
)
);
break;
case "__bases__":
target = Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassGetBaseClasses)),
self.Expression
);
break;
case "__name__":
target = Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassGetName)),
self.Expression
);
break;
default:
ParameterExpression tmp = Ast.Variable(typeof(object), "lookupVal");
return new DynamicMetaObject(
Ast.Block(
new ParameterExpression[] { tmp },
Ast.Condition(
Expression.Not(
Expression.TypeIs(
Expression.Assign(
tmp,
Ast.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.OldClassTryLookupValue)),
AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext),
self.Expression,
AstUtils.Constant(memberName)
)
),
typeof(OperationFailed)
)
),
tmp,
AstUtils.Convert(
GetMemberFallback(this, member, codeContext).Expression,
typeof(object)
)
)
),
self.Restrictions
);
}
return new DynamicMetaObject(
target,
self.Restrictions
);
}
#endregion
#region Helpers
public new OldClass/*!*/ Value {
get {
return (OldClass)base.Value;
}
}
#endregion
#region IPythonOperable Members
DynamicMetaObject IPythonOperable.BindOperation(PythonOperationBinder action, DynamicMetaObject[] args) {
if (action.Operation == PythonOperationKind.IsCallable) {
return new DynamicMetaObject(
AstUtils.Constant(true),
Restrictions.Merge(BindingRestrictions.GetTypeRestriction(Expression, typeof(OldClass)))
);
}
return null;
}
#endregion
}
}
| |
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace com.adjust.sdk
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add(string aKey, JSONNode aItem){ }
public virtual JSONNode this[int aIndex] { get { return null; } set { } }
public virtual JSONNode this[string aKey] { get { return null; } set { } }
public virtual string Value { get { return ""; } set { } }
public virtual int Count { get { return 0; } }
public virtual void Add(JSONNode aItem)
{
Add("", aItem);
}
public virtual JSONNode Remove(string aKey) { return null; }
public virtual JSONNode Remove(int aIndex) { return null; }
public virtual JSONNode Remove(JSONNode aNode) { return aNode; }
public virtual IEnumerable<JSONNode> Childs { get { yield break;} }
public IEnumerable<JSONNode> DeepChilds
{
get
{
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString()
{
return "JSONNode";
}
public virtual string ToString(string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt
{
get
{
int v = 0;
if (int.TryParse(Value,out v))
return v;
return 0;
}
set
{
Value = value.ToString();
}
}
public virtual float AsFloat
{
get
{
float v = 0.0f;
if (float.TryParse(Value,out v))
return v;
return 0.0f;
}
set
{
Value = value.ToString();
}
}
public virtual double AsDouble
{
get
{
double v = 0.0;
if (double.TryParse(Value,out v))
return v;
return 0.0;
}
set
{
Value = value.ToString();
}
}
public virtual bool AsBool
{
get
{
bool v = false;
if (bool.TryParse(Value,out v))
return v;
return !string.IsNullOrEmpty(Value);
}
set
{
Value = (value)?"true":"false";
}
}
public virtual JSONArray AsArray
{
get
{
return this as JSONArray;
}
}
public virtual JSONClass AsObject
{
get
{
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode(string s)
{
return new JSONData(s);
}
public static implicit operator string(JSONNode d)
{
return (d == null)?null:d.Value;
}
public static bool operator ==(JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
#endregion operators
internal static string Escape(string aText)
{
string result = "";
foreach(char c in aText)
{
switch(c)
{
case '\\' : result += "\\\\"; break;
case '\"' : result += "\\\""; break;
case '\n' : result += "\\n" ; break;
case '\r' : result += "\\r" ; break;
case '\t' : result += "\\t" ; break;
case '\b' : result += "\\b" ; break;
case '\f' : result += "\\f" ; break;
default : result += c ; break;
}
}
return result;
}
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONClass());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(stack.Peek());
else if (TokenName != "")
ctx.Add(TokenName,stack.Peek());
}
TokenName = "";
Token = "";
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token != "")
{
TokenName = TokenName.Trim();
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName,Token);
}
TokenName = "";
Token = "";
if (stack.Count>0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode)
{
Token += aJSON[i];
break;
}
if (Token != "")
{
if (ctx is JSONArray)
ctx.Add(Token);
else if (TokenName != "")
ctx.Add(TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON[i];
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't' : Token += '\t'; break;
case 'r' : Token += '\r'; break;
case 'n' : Token += '\n'; break;
case 'b' : Token += '\b'; break;
case 'f' : Token += '\f'; break;
case 'u':
{
string s = aJSON.Substring(i+1,4);
Token += (char)int.Parse(s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default : Token += C; break;
}
}
break;
default:
Token += aJSON[i];
break;
}
++i;
}
if (QuoteMode)
{
throw new Exception("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize(System.IO.BinaryWriter aWriter) {}
public void SaveToStream(System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter(aData);
Serialize(W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64()
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile(string aFileName)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
throw new Exception("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream(System.IO.Stream aData)
{
using(var R = new System.IO.BinaryReader(aData))
{
return Deserialize(R);
}
}
public static JSONNode LoadFromBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromStream(stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode>();
public override JSONNode this[int aIndex]
{
get
{
if (aIndex<0 || aIndex >= m_List.Count)
return new JSONLazyCreator(this);
return m_List[aIndex];
}
set
{
if (aIndex<0 || aIndex >= m_List.Count)
m_List.Add(value);
else
m_List[aIndex] = value;
}
}
public override JSONNode this[string aKey]
{
get{ return new JSONLazyCreator(this);}
set{ m_List.Add(value); }
}
public override int Count
{
get { return m_List.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
m_List.Add(aItem);
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List[aIndex];
m_List.RemoveAt(aIndex);
return tmp;
}
public override JSONNode Remove(JSONNode aNode)
{
m_List.Remove(aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator()
{
foreach(JSONNode N in m_List)
yield return N;
}
public override string ToString()
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 2)
result += ", ";
result += N.ToString();
}
result += " ]";
return result;
}
public override string ToString(string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Array);
aWriter.Write(m_List.Count);
for(int i = 0; i < m_List.Count; i++)
{
m_List[i].Serialize(aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode>();
public override JSONNode this[string aKey]
{
get
{
if (m_Dict.ContainsKey(aKey))
return m_Dict[aKey];
else
return new JSONLazyCreator(this, aKey);
}
set
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = value;
else
m_Dict.Add(aKey,value);
}
}
public override JSONNode this[int aIndex]
{
get
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt(aIndex).Value;
}
set
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt(aIndex).Key;
m_Dict[key] = value;
}
}
public override int Count
{
get { return m_Dict.Count; }
}
public override void Add(string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty(aKey))
{
if (m_Dict.ContainsKey(aKey))
m_Dict[aKey] = aItem;
else
m_Dict.Add(aKey, aItem);
}
else
m_Dict.Add(Guid.NewGuid().ToString(), aItem);
}
public override JSONNode Remove(string aKey)
{
if (!m_Dict.ContainsKey(aKey))
return null;
JSONNode tmp = m_Dict[aKey];
m_Dict.Remove(aKey);
return tmp;
}
public override JSONNode Remove(int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt(aIndex);
m_Dict.Remove(item.Key);
return item.Value;
}
public override JSONNode Remove(JSONNode aNode)
{
try
{
var item = m_Dict.Where(k => k.Value == aNode).First();
m_Dict.Remove(item.Key);
return aNode;
}
catch
{
return null;
}
}
public override IEnumerable<JSONNode> Childs
{
get
{
foreach(KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator()
{
foreach(KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 2)
result += ", ";
result += "\"" + Escape(N.Key) + "\":" + N.Value.ToString();
}
result += "}";
return result;
}
public override string ToString(string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
{
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape(N.Key) + "\" : " + N.Value.ToString(aPrefix+" ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write((byte)JSONBinaryTag.Class);
aWriter.Write(m_Dict.Count);
foreach(string K in m_Dict.Keys)
{
aWriter.Write(K);
m_Dict[K].Serialize(aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value
{
get { return m_Data; }
set { m_Data = value; }
}
public JSONData(string aData)
{
m_Data = aData;
}
public JSONData(float aData)
{
AsFloat = aData;
}
public JSONData(double aData)
{
AsDouble = aData;
}
public JSONData(bool aData)
{
AsBool = aData;
}
public JSONData(int aData)
{
AsInt = aData;
}
public override string ToString()
{
return "\"" + Escape(m_Data) + "\"";
}
public override string ToString(string aPrefix)
{
return "\"" + Escape(m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.IntValue);
aWriter.Write(AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.FloatValue);
aWriter.Write(AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.DoubleValue);
aWriter.Write(AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data)
{
aWriter.Write((byte)JSONBinaryTag.BoolValue);
aWriter.Write(AsBool);
return;
}
aWriter.Write((byte)JSONBinaryTag.Value);
aWriter.Write(m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator(JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator(JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set(JSONNode aVal)
{
if (m_Key == null)
{
m_Node.Add(aVal);
}
else
{
m_Node.Add(m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this[int aIndex]
{
get
{
return new JSONLazyCreator(this);
}
set
{
var tmp = new JSONArray();
tmp.Add(value);
Set(tmp);
}
}
public override JSONNode this[string aKey]
{
get
{
return new JSONLazyCreator(this, aKey);
}
set
{
var tmp = new JSONClass();
tmp.Add(aKey, value);
Set(tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray();
tmp.Add(aItem);
Set(tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass();
tmp.Add(aKey, aItem);
Set(tmp);
}
public static bool operator ==(JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals(a,b);
}
public static bool operator !=(JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals(this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode();
}
public override string ToString()
{
return "";
}
public override string ToString(string aPrefix)
{
return "";
}
public override int AsInt
{
get
{
JSONData tmp = new JSONData(0);
Set(tmp);
return 0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override float AsFloat
{
get
{
JSONData tmp = new JSONData(0.0f);
Set(tmp);
return 0.0f;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override double AsDouble
{
get
{
JSONData tmp = new JSONData(0.0);
Set(tmp);
return 0.0;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override bool AsBool
{
get
{
JSONData tmp = new JSONData(false);
Set(tmp);
return false;
}
set
{
JSONData tmp = new JSONData(value);
Set(tmp);
}
}
public override JSONArray AsArray
{
get
{
JSONArray tmp = new JSONArray();
Set(tmp);
return tmp;
}
}
public override JSONClass AsObject
{
get
{
JSONClass tmp = new JSONClass();
Set(tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse(string aJSON)
{
return JSONNode.Parse(aJSON);
}
}
}
| |
using System;
using System.Runtime.Serialization;
using Hammock.Model;
using Newtonsoft.Json;
namespace TweetSharp
{
/*
<list>
<id>2029636</id>
<name>firemen</name>
<full_name>@twitterapidocs/firemen</full_name>
<slug>firemen</slug>
<subscriber_count>0</subscriber_count>
<member_count>0</member_count>
<uri>/twitterapidocs/firemen</uri>
<mode>public</mode>
<user/>
</list>
*/
#if !SILVERLIGHT
/// <summary>
/// Represents a user-curated list of Twitter members,
/// that other users can subscribe to and see the aggregated
/// list of member tweets in a dedicated timeline.
/// </summary>
[Serializable]
#endif
#if !Smartphone && !NET20
[DataContract]
#endif
[JsonObject(MemberSerialization.OptIn)]
public class TwitterList : PropertyChangedBase, ITwitterModel
{
private long _id;
private string _idStr;
private string _name;
private string _fullName;
private string _slug;
private string _description;
private int _subscriberCount;
private int _memberCount;
private string _uri;
private string _mode;
private TwitterUser _user;
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the ID of the list.
/// </summary>
/// <value>The list ID.</value>
[DataMember]
#endif
public virtual long Id
{
get { return _id; }
set
{
if (_id == value)
{
return;
}
_id = value;
OnPropertyChanged("Id");
}
}
[JsonProperty("id_str")]
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string IdStr
{
get { return _idStr; }
set
{
if (_idStr == value)
{
return;
}
_idStr = value;
OnPropertyChanged("IdStr");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the descriptive name of the list.
/// </summary>
/// <value>The name.</value>
[DataMember]
#endif
public virtual string Name
{
get { return _name; }
set
{
if (_name == value)
{
return;
}
_name = value;
OnPropertyChanged("Name");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the full name of the list including the list owner.
/// </summary>
/// <value>The full name of the list.</value>
[DataMember]
#endif
public virtual string FullName
{
get { return _fullName; }
set
{
if (_fullName == value)
{
return;
}
_fullName = value;
OnPropertyChanged("FullName");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the user-supplied list description.
/// </summary>
/// <value>The list description.</value>
[DataMember]
#endif
public virtual string Description
{
get { return _description; }
set
{
if (_description == value)
{
return;
}
_description = value;
OnPropertyChanged("Description");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the list URL slug.
/// </summary>
/// <value>The list slug.</value>
[DataMember]
#endif
public virtual string Slug
{
get { return _slug; }
set
{
if (_slug == value)
{
return;
}
_slug = value;
OnPropertyChanged("Slug");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the subscriber count.
/// A subscriber follows the list's updates.
/// </summary>
/// <value>The subscriber count.</value>
[DataMember]
#endif
public virtual int SubscriberCount
{
get { return _subscriberCount; }
set
{
if (_subscriberCount == value)
{
return;
}
_subscriberCount = value;
OnPropertyChanged("SubscriberCount");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the member count.
/// A member's updates appear in the list.
/// </summary>
/// <value>The member count.</value>
[DataMember]
#endif
public virtual int MemberCount
{
get { return _memberCount; }
set
{
if (_memberCount == value)
{
return;
}
_memberCount = value;
OnPropertyChanged("MemberCount");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the URI of the list.
/// </summary>
/// <value>The URI of the list.</value>
[DataMember]
#endif
public virtual string Uri
{
get { return _uri; }
set
{
if (_uri == value)
{
return;
}
_uri = value;
OnPropertyChanged("Uri");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the mode.
/// The list can be "public", visible to everyone,
/// or "private", visible only to the authenticating user.
/// </summary>
/// <value>The mode.</value>
[DataMember]
#endif
public virtual string Mode
{
get { return _mode; }
set
{
if (_mode == value)
{
return;
}
_mode = value;
OnPropertyChanged("Mode");
}
}
#if !Smartphone && !NET20
/// <summary>
/// Gets or sets the user who created the list.
/// </summary>
/// <value>The user.</value>
[DataMember]
#endif
public virtual TwitterUser User
{
get { return _user; }
set
{
if (_user == value)
{
return;
}
_user = value;
OnPropertyChanged("User");
}
}
#if !Smartphone && !NET20
[DataMember]
#endif
public virtual string RawSource { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ObjectFiller.Test.TestPoco.Person;
using Tynamix.ObjectFiller;
using Random = Tynamix.ObjectFiller.Random;
namespace ObjectFiller.Test
{
[TestClass]
public class PersonFillingTest
{
[TestMethod]
public void TestFillPerson()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>();
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.Address);
Assert.IsNotNull(filledPerson.Addresses);
Assert.IsNotNull(filledPerson.StringToIAddress);
Assert.IsNotNull(filledPerson.SureNames);
}
[TestMethod]
public void TestFillPersonWithEnumerable()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(x => x.Age).Use(Enumerable.Range(18, 60));
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.Address);
Assert.IsNotNull(filledPerson.Addresses);
Assert.IsNotNull(filledPerson.StringToIAddress);
Assert.IsNotNull(filledPerson.SureNames);
}
[TestMethod]
public void TestNameListStringRandomizer()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup().OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.FirstName).Use(new RealNames(NameStyle.FirstName))
.OnProperty(p => p.LastName).Use(new RealNames(NameStyle.LastName));
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.FirstName);
Assert.IsNotNull(filledPerson.LastName);
}
[TestMethod]
public void TestFirstNameAsConstantLastNameAsRealName()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.FirstName).Use(() => "John")
.OnProperty(p => p.LastName).Use(new RealNames(NameStyle.LastName));
Person filledPerson = pFiller.Create();
Assert.IsNotNull(filledPerson.FirstName);
Assert.AreEqual("John", filledPerson.FirstName);
Assert.IsNotNull(filledPerson.LastName);
}
[TestMethod]
public void GeneratePersonWithGivenSetOfNamesAndAges()
{
List<string> names = new List<string> { "Tom", "Maik", "John", "Leo" };
List<int> ages = new List<int> { 10, 15, 18, 22, 26 };
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.FirstName).Use(new RandomListItem<string>(names))
.OnProperty(p => p.Age).Use(new RandomListItem<int>(ages));
var pF = pFiller.Create();
Assert.IsTrue(names.Contains(pF.FirstName));
Assert.IsTrue(ages.Contains(pF.Age));
}
[TestMethod]
public void BigComplicated()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnProperty(p => p.LastName, p => p.FirstName).DoIt(At.TheEnd).Use(new RealNames(NameStyle.FirstName))
.OnProperty(p => p.Age).Use(() => Random.Next(10, 32))
.SetupFor<Address>()
.OnProperty(a => a.City).Use(new MnemonicString(1))
.OnProperty(a => a.Street).IgnoreIt();
var pF = pFiller.Create();
Assert.IsNotNull(pF);
Assert.IsNotNull(pF.Address);
Assert.IsNull(pF.Address.Street);
}
[TestMethod]
public void FluentTest()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnProperty(x => x.Age).Use(() => 18)
.OnType<IAddress>().CreateInstanceOf<Address>();
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.AreEqual(18, p.Age);
}
[TestMethod]
public void TestSetupForTypeOverrideSettings()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<int>().Use(() => 1)
.SetupFor<Address>(true);
Person p = pFiller.Create();
Assert.AreEqual(1, p.Age);
Assert.AreNotEqual(1, p.Address.HouseNumber);
}
[TestMethod]
public void TestSetupForTypeWithoutOverrideSettings()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<int>().Use(() => 1)
.SetupFor<Address>();
Person p = pFiller.Create();
Assert.AreEqual(1, p.Age);
Assert.AreEqual(1, p.Address.HouseNumber);
}
[TestMethod]
public void TestIgnoreAllOfType()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<string>().IgnoreIt()
;
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.IsNull(p.FirstName);
Assert.IsNotNull(p.Address);
Assert.IsNull(p.Address.City);
}
[TestMethod]
public void TestIgnoreAllOfComplexType()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<Address>().IgnoreIt()
.OnType<IAddress>().IgnoreIt();
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.IsNull(p.Address);
}
[TestMethod]
public void TestIgnoreAllOfTypeDictionary()
{
Filler<Person> pFiller = new Filler<Person>();
pFiller.Setup()
.OnType<IAddress>().CreateInstanceOf<Address>()
.OnType<Address>().IgnoreIt()
.OnType<IAddress>().IgnoreIt()
.OnType<Dictionary<string, IAddress>>().IgnoreIt();
Person p = pFiller.Create();
Assert.IsNotNull(p);
Assert.IsNull(p.Address);
Assert.IsNull(p.StringToIAddress);
}
[TestMethod]
public void TestPropertyOrderDoNameLast()
{
Filler<OrderedPersonProperties> filler = new Filler<OrderedPersonProperties>();
filler.Setup()
.OnProperty(x => x.Name).DoIt(At.TheEnd).UseDefault();
var p = filler.Create();
Assert.IsNotNull(p);
Assert.AreEqual(3, p.NameCount);
}
[TestMethod]
public void TestPropertyOrderDoNameFirst()
{
Filler<OrderedPersonProperties> filler = new Filler<OrderedPersonProperties>();
filler.Setup()
.OnProperty(x => x.Name).DoIt(At.TheBegin).UseDefault();
var p = filler.Create();
Assert.IsNotNull(p);
Assert.AreEqual(1, p.NameCount);
}
}
}
| |
// 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.Text;
namespace System.Net.Libuv
{
unsafe public class UVException : Exception
{
// OS specific error code
int _errorCode;
public UVException(int errorCode)
{
_errorCode = errorCode;
}
public UVError Error {
get
{
return ErrorNameToError(Text);
}
}
public string Text {
get
{
return ErrorCodeToText(_errorCode);
}
}
public string Description {
get
{
return ErrorCodeToDescription(_errorCode);
}
}
public static UVError ErrorCodeToError(int errorCode)
{
if (errorCode == 0)
{
return UVError.OK;
}
// TODO: need to figure out how to do this more efficiently
return ErrorNameToError(ErrorCodeToText(errorCode));
}
internal static void ThrowIfError(int errorCode)
{
if (errorCode >= 0)
{
return;
}
throw new UVException(errorCode);
}
static string ErrorCodeToDescription(int errorCode)
{
var nullTerminatedUtf8 = (byte*)UVInterop.uv_strerror(errorCode);
return NullTerminatedUtf8ToString(nullTerminatedUtf8);
}
static string ErrorCodeToText(int errorCode)
{
var nullTerminatedUtf8 = (byte*)UVInterop.uv_err_name(errorCode);
return NullTerminatedUtf8ToString(nullTerminatedUtf8);
}
static UVError ErrorNameToError(string errorName)
{
try
{
return (UVError)Enum.Parse(typeof(UVError), errorName);
}
catch
{
return UVError.UNKNOWN;
}
}
static string NullTerminatedUtf8ToString(byte* nullTerminatedUtf8)
{
int nullTerminator = 0;
for (; ; nullTerminator++)
{
if (nullTerminatedUtf8[nullTerminator] == 0) break;
}
byte[] array = new byte[nullTerminator];
for(int i=0; i<nullTerminator; i++)
{
array[i] = nullTerminatedUtf8[i];
}
var nameString = Encoding.UTF8.GetString(array, 0, array.Length);
return nameString;
}
public override string Message
{
get
{
return Description;
}
}
}
public enum UVError
{
OK = 0,
/// <summary>
/// argument list too long
/// </summary>
E2BIG,
/// <summary>
/// permission denied
/// </summary>
EACCES,
/// <summary>
/// address already in use
/// </summary>
EADDRINUSE,
/// <summary>
/// address not available
/// </summary>
EADDRNOTAVAIL,
/// <summary>
/// address family not supported
/// </summary>
EAFNOSUPPORT,
/// <summary>
/// resource temporarily unavailable
/// </summary>
EAGAIN,
/// <summary>
/// address family not supported
/// </summary>
EAI_ADDRFAMILY,
/// <summary>
/// temporary failure
/// </summary>
EAI_AGAIN,
/// <summary>
/// bad ai_flags value
/// </summary>
EAI_BADFLAGS,
/// <summary>
/// invalid value for hints
/// </summary>
EAI_BADHINTS,
/// <summary>
/// request canceled
/// </summary>
EAI_CANCELED,
/// <summary>
/// permanent failure
/// </summary>
EAI_FAIL,
/// <summary>
/// ai_family not supported
/// </summary>
EAI_FAMILY,
/// <summary>
/// out of memory
/// </summary>
EAI_MEMORY,
/// <summary>
/// no address
/// </summary>
EAI_NODATA,
/// <summary>
/// unknown node or service
/// </summary>
EAI_NONAME,
/// <summary>
/// argument buffer overflow
/// </summary>
EAI_OVERFLOW,
/// <summary>
/// resolved protocol is unknown
/// </summary>
EAI_PROTOCOL,
/// <summary>
/// service not available for socket type
/// </summary>
EAI_SERVICE,
/// <summary>
/// socket type not supported
/// </summary>
EAI_SOCKTYPE,
/// <summary>
/// connection already in progress
/// </summary>
EALREADY,
/// <summary>
/// bad file descriptor
/// </summary>
EBADF,
/// <summary>
/// resource busy or locked
/// </summary>
EBUSY,
/// <summary>
/// operation canceled
/// </summary>
ECANCELED,
/// <summary>
/// invalid Unicode character
/// </summary>
ECHARSET,
/// <summary>
/// software caused connection abort
/// </summary>
ECONNABORTED,
/// <summary>
/// connection refused
/// </summary>
ECONNREFUSED,
/// <summary>
/// connection reset by peer
/// </summary>
ECONNRESET,
/// <summary>
/// destination address required
/// </summary>
EDESTADDRREQ,
/// <summary>
/// file already exists
/// </summary>
EEXIST,
/// <summary>
/// bad address in system call argument
/// </summary>
EFAULT,
/// <summary>
/// file too large
/// </summary>
EFBIG,
/// <summary>
/// host is unreachable
/// </summary>
EHOSTUNREACH,
/// <summary>
/// interrupted system call
/// </summary>
EINTR,
/// <summary>
/// invalid argument
/// </summary>
EINVAL,
/// <summary>
/// i/o error
/// </summary>
EIO,
/// <summary>
/// socket is already connected
/// </summary>
EISCONN,
/// <summary>
/// illegal operation on a directory
/// </summary>
EISDIR,
/// <summary>
/// too many symbolic links encountered
/// </summary>
ELOOP,
/// <summary>
/// too many open files
/// </summary>
EMFILE,
/// <summary>
/// message too long
/// </summary>
EMSGSIZE,
/// <summary>
/// name too long
/// </summary>
ENAMETOOLONG,
/// <summary>
/// network is down
/// </summary>
ENETDOWN,
/// <summary>
/// network is unreachable
/// </summary>
ENETUNREACH,
/// <summary>
/// file table overflow
/// </summary>
ENFILE,
/// <summary>
/// no buffer space available
/// </summary>
ENOBUFS,
/// <summary>
/// no such device
/// </summary>
ENODEV,
/// <summary>
/// no such file or directory
/// </summary>
ENOENT,
/// <summary>
/// not enough memory
/// </summary>
ENOMEM,
/// <summary>
/// machine is not on the network
/// </summary>
ENONET,
/// <summary>
/// protocol not available
/// </summary>
ENOPROTOOPT,
/// <summary>
/// no space left on device
/// </summary>
ENOSPC,
/// <summary>
/// function not implemented
/// </summary>
ENOSYS,
/// <summary>
/// socket is not connected
/// </summary>
ENOTCONN,
/// <summary>
/// not a directory
/// </summary>
ENOTDIR,
/// <summary>
/// directory not empty
/// </summary>
ENOTEMPTY,
/// <summary>
/// socket operation on non-socket
/// </summary>
ENOTSOCK,
/// <summary>
/// operation not supported on socket
/// </summary>
ENOTSUP,
/// <summary>
/// operation not permitted
/// </summary>
EPERM,
/// <summary>
/// broken pipe
/// </summary>
EPIPE,
/// <summary>
/// protocol error
/// </summary>
EPROTO,
/// <summary>
/// protocol not supported
/// </summary>
EPROTONOSUPPORT,
/// <summary>
/// protocol wrong type for socket
/// </summary>
EPROTOTYPE,
/// <summary>
/// result too large
/// </summary>
ERANGE,
/// <summary>
/// read-only file system
/// </summary>
EROFS,
/// <summary>
/// cannot send after transport endpoint shutdown
/// </summary>
ESHUTDOWN,
/// <summary>
/// invalid seek
/// </summary>
ESPIPE,
/// <summary>
/// no such process
/// </summary>
ESRCH,
/// <summary>
/// connection timed out
/// </summary>
ETIMEDOUT,
/// <summary>
/// text file is busy
/// </summary>
ETXTBSY,
/// <summary>
/// cross-device link not permitted
/// </summary>
EXDEV,
/// <summary>
/// unknown error
/// </summary>
UNKNOWN,
/// <summary>
/// end of file
/// </summary>
EOF,
/// <summary>
/// no such device or address
/// </summary>
ENXIO,
/// <summary>
/// too many links
/// </summary>
EMLINK,
}
}
| |
// 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.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class HighPriorityProcessor : IdleProcessor
{
private readonly IncrementalAnalyzerProcessor _processor;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
private Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers;
// whether this processor is running or not
private Task _running;
public HighPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, backOffTimeSpanInMs, shutdownToken)
{
_processor = processor;
_lazyAnalyzers = lazyAnalyzers;
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
Start();
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
public void AddAnalyzer(IIncrementalAnalyzer analyzer)
{
var analyzers = _lazyAnalyzers.Value;
_lazyAnalyzers = new Lazy<ImmutableArray<IIncrementalAnalyzer>>(() => analyzers.Add(analyzer));
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
// we only put workitem in high priority queue if there is a text change.
// this is to prevent things like opening a file, changing in other files keep enqueuing
// expensive high priority work.
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
// check whether given item is for active document, otherwise, nothing to do here
if (_processor._documentTracker == null ||
_processor._documentTracker.GetActiveDocument() != item.DocumentId)
{
return;
}
// we need to clone due to waiter
EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile")));
}
private void EnqueueActiveFileItem(WorkItem item)
{
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_ActiveFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator);
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _workItemQueue.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
// okay, there must be at least one item in the map
// see whether we have work item for the document
WorkItem workItem;
CancellationTokenSource documentCancellation;
Contract.ThrowIfFalse(GetNextWorkItem(out workItem, out documentCancellation));
var solution = _processor.CurrentSolution;
// okay now we have work to do
await ProcessDocumentAsync(solution, _lazyAnalyzers.Value, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation)
{
// GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail.
var documentId = _processor._documentTracker.GetActiveDocument();
if (documentId != null)
{
if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
{
return true;
}
}
return _workItemQueue.TryTakeAnyWork(
preferableProjectId: null,
dependencyGraph: _processor.DependencyGraph,
analyzerService: _processor.DiagnosticAnalyzerService,
workItem: out workItem,
source: out documentCancellation);
}
private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = solution.GetDocument(documentId);
if (document != null)
{
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
public void Shutdown()
{
_workItemQueue.Dispose();
}
}
}
}
}
}
| |
// This file is part of SNMP#NET.
//
// SNMP#NET is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SNMP#NET 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 SNMP#NET. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Text;
namespace SnmpSharpNet
{
/// <summary>SNMP SMI version 1, version 2c and version 3 constants.
/// </summary>
public sealed class SnmpConstants
{
#region Snmp V1 errors
/// <summary>No error</summary>
public const int ErrNoError = 0;
/// <summary>Request too big</summary>
public const int ErrTooBig = 1;
/// <summary>Object identifier does not exist</summary>
public const int ErrNoSuchName = 2;
/// <summary>Invalid value</summary>
public const int ErrBadValue = 3;
/// <summary>Requested invalid operation on a read only table</summary>
public const int ErrReadOnly = 4;
/// <summary>Generic error</summary>
public const int ErrGenError = 5;
/// <summary>Enterprise specific error</summary>
public const int enterpriseSpecific = 6;
#endregion SnmpV1errors
#region SnmpV2errors
/// <summary>Access denied</summary>
public const int ErrNoAccess = 6;
/// <summary>Incorrect type</summary>
public const int ErrWrongType = 7;
/// <summary>Incorrect length</summary>
public const int ErrWrongLength = 8;
/// <summary>Invalid encoding</summary>
public const int ErrWrongEncoding = 9;
/// <summary>Object does not have correct value</summary>
public const int ErrWrongValue = 10;
/// <summary>Insufficient rights to perform create operation</summary>
public const int ErrNoCreation = 11;
/// <summary>Inconsistent value</summary>
public const int ErrInconsistentValue = 12;
/// <summary>Requested resource is not available</summary>
public const int ErrResourceUnavailable = 13;
/// <summary>Unable to commit values</summary>
public const int ErrCommitFailed = 14;
/// <summary>Undo request failed</summary>
public const int ErrUndoFailed = 15;
/// <summary>Authorization failed</summary>
public const int ErrAuthorizationError = 16;
/// <summary>Instance not writable</summary>
public const int ErrNotWritable = 17;
/// <summary>Inconsistent object identifier</summary>
public const int ErrInconsistentName = 18;
#endregion SnmpV2errors
#region SNMP version 1 trap generic error codes
/// <summary>Cold start trap</summary>
public const int ColdStart = 0;
/// <summary>Warm start trap</summary>
public const int WarmStart = 1;
/// <summary>Link down trap</summary>
public const int LinkDown = 2;
/// <summary>Link up trap</summary>
public const int LinkUp = 3;
/// <summary>Authentication-failure trap</summary>
public const int AuthenticationFailure = 4;
/// <summary>EGP Neighbor Loss trap</summary>
public const int EgpNeighborLoss = 5;
/// <summary>Enterprise Specific trap</summary>
public const int EnterpriseSpecific = 6;
#endregion SNMP version 1 trap generic error codes
#region SMI Type codes and type names
/// <summary>Signed 32-bit integer ASN.1 data type. For implementation, see <see cref="Integer32"/></summary>
public static readonly byte SMI_INTEGER = (byte)(AsnType.UNIVERSAL | AsnType.INTEGER);
/// <summary>String representation of the AsnType.INTEGER type.</summary>
public static readonly string SMI_INTEGER_STR = "Integer32";
/// <summary>Data type representing a sequence of zero or more 8-bit byte values. For implementation, see <see cref="OctetString"/></summary>
public static readonly byte SMI_STRING = (byte)(AsnType.UNIVERSAL | AsnType.OCTETSTRING);
/// <summary>String representation of the AsnType.OCTETSTRING type.</summary>
public static readonly string SMI_STRING_STR = "OctetString";
/// <summary>Object id ASN.1 type. For implementation, see <see cref="Oid"/></summary>
public static readonly byte SMI_OBJECTID = (byte)(AsnType.UNIVERSAL | AsnType.OBJECTID);
/// <summary>String representation of the SMI_OBJECTID type.</summary>
public static readonly string SMI_OBJECTID_STR = "ObjectId";
/// <summary>Null ASN.1 value type. For implementation, see <see cref="Null"/>.</summary>
public static readonly byte SMI_NULL = (byte)(AsnType.UNIVERSAL | AsnType.NULL);
/// <summary>String representation of the SMI_NULL type.</summary>
public static readonly string SMI_NULL_STR = "NULL";
/// <summary> An application string is a sequence of octets
/// defined at the application level. Although the SMI
/// does not define an Application String, it does define
/// an IP Address which is an Application String of length
/// four.
/// </summary>
public static readonly byte SMI_APPSTRING = (byte)(AsnType.APPLICATION | 0x00);
/// <summary>String representation of the SMI_APPSTRING type.</summary>
public static readonly string SMI_APPSTRING_STR = "AppString";
/// <summary> An IP Address is an application string of length four
/// and is indistinguishable from the SMI_APPSTRING value.
/// The address is a 32-bit quantity stored in network byte order.
/// </summary>
public static readonly byte SMI_IPADDRESS = (byte)(AsnType.APPLICATION | 0x00);
/// <summary>String representation of the SMI_IPADDRESS type.</summary>
public static readonly string SMI_IPADDRESS_STR = "IPAddress";
/// <summary> A non-negative integer that may be incremented, but not
/// decremented. The value is a 32-bit unsigned quantity representing
/// the range of zero to 2^32-1 (4,294,967,295). When the counter
/// reaches its maximum value it wraps back to zero and starts again.
/// </summary>
public static readonly byte SMI_COUNTER32 = (byte)(AsnType.APPLICATION | 0x01);
/// <summary>String representation of the SMI_COUNTER32 type.</summary>
public static readonly string SMI_COUNTER32_STR = "Counter32";
/// <summary> Represents a non-negative integer that may increase or
/// decrease with a maximum value of 2^32-1. If the maximum
/// value is reached the gauge stays latched until reset.
/// </summary>
public static readonly byte SMI_GAUGE32 = (byte)(AsnType.APPLICATION | 0x02);
/// <summary>String representation of the SMI_GAUGE32 type.</summary>
public static readonly string SMI_GAUGE32_STR = "Gauge32";
/// <summary> Used to represent the integers in the range of 0 to 2^32-1.
/// This type is identical to the SMI_COUNTER32 and are
/// indistinguishable in ASN.1
/// </summary>
public static readonly byte SMI_UNSIGNED32 = (byte)(AsnType.APPLICATION | 0x02); // same as gauge
/// <summary>String representation of the SMI_UNSIGNED32 type.</summary>
public static readonly string SMI_UNSIGNED32_STR = "Unsigned32";
/// <summary> This represents a non-negative integer that counts time, modulo 2^32.
/// The time is represented in hundredths (1/100th) of a second.
/// </summary>
public static readonly byte SMI_TIMETICKS = (byte)(AsnType.APPLICATION | 0x03);
/// <summary>String representation of the SMI_TIMETICKS type.</summary>
public static readonly string SMI_TIMETICKS_STR = "TimeTicks";
/// <summary> Used to support the transport of arbitrary data. The
/// data itself is encoded as an octet string, but may be in
/// any format defined by ASN.1 or another standard.
/// </summary>
public static readonly byte SMI_OPAQUE = (byte)(AsnType.APPLICATION | 0x04);
/// <summary>String representation of the SMI_OPAQUE type.</summary>
public static readonly string SMI_OPAQUE_STR = "Opaque";
/// <summary> Defines a 64-bit unsigned counter. A counter is an integer that
/// can be incremented, but cannot be decremented. A maximum value
/// of 2^64 - 1 (18,446,744,073,709,551,615) can be represented.
/// When the counter reaches it's maximum it wraps back to zero and
/// starts again.
/// </summary>
public static readonly byte SMI_COUNTER64 = (byte)(AsnType.APPLICATION | 0x06); // SMIv2 only
/// <summary>String representation of the SMI_COUNTER64 type.</summary>
public static readonly string SMI_COUNTER64_STR = "Counter64";
/// <summary>String representation of the unknown SMI data type.</summary>
public static readonly string SMI_UNKNOWN_STR = "Unknown";
/// <summary> The SNMPv2 error representing that there is No-Such-Object
/// for a particular object identifier. This error is the result
/// of a requested object identifier that does not exist in the
/// agent's tables
/// </summary>
public static readonly byte SMI_NOSUCHOBJECT = (byte)(AsnType.CONTEXT | AsnType.PRIMITIVE | 0x00);
/// <summary> The SNMPv2 error representing that there is No-Such-Instance
/// for a particular object identifier. This error is the result
/// of a requested object identifier instance does not exist in the
/// agent's tables.
/// </summary>
public static readonly byte SMI_NOSUCHINSTANCE = (byte)(AsnType.CONTEXT | AsnType.PRIMITIVE | 0x01);
/// <summary> The SNMPv2 error representing the End-Of-Mib-View.
/// This error variable will be returned by a SNMPv2 agent
/// if the requested object identifier has reached the
/// end of the agent's mib table and there is no lexicographic
/// successor.
/// </summary>
public static readonly byte SMI_ENDOFMIBVIEW = (byte)(AsnType.CONTEXT | AsnType.PRIMITIVE | 0x02);
/// <summary>
/// SEQUENCE Variable Binding code. Hex value: 0x30
/// </summary>
public static readonly byte SMI_SEQUENCE = (byte)(AsnType.SEQUENCE | AsnType.CONSTRUCTOR);
/// <summary> Defines an SNMPv2 Party Clock. The Party Clock is currently
/// Obsolete, but included for backwards compatibility. Obsoleted in RFC 1902.
/// </summary>
public static readonly byte SMI_PARTY_CLOCK = (byte)(AsnType.APPLICATION | 0x07);
#endregion
#region SNMP version 2 TRAP OIDs
/// <summary>
/// sysUpTime.0 OID is the first value in the VarBind array of SNMP version 2 TRAP packets
/// </summary>
public static Oid SysUpTime = new Oid(new UInt32[] { 1, 3, 6, 1, 2, 1, 1, 3, 0 });
/// <summary>
/// trapObjectID.0 OID is the second value in the VarBind array of SNMP version 2 TRAP packets
/// </summary>
public static Oid TrapObjectId = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 });
#endregion
#region SNMP version 3 error OID values
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid usmStatsUnsupportedSecLevels = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 1, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid usmStatsNotInTimeWindows = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 2, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid usmStatsUnknownSecurityNames = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 3, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid usmStatsUnknownEngineIDs = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 4, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid usmStatsWrongDigests = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 5, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid usmStatsDecryptionErrors = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 15, 1, 1, 6, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid snmpUnknownSecurityModels = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 11, 2, 1, 1, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid snmpInvalidMsgs = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 11, 2, 1, 2, 0 });
/// <summary>
/// SNMP version 3, USM error
/// </summary>
public static Oid snmpUnknownPDUHandlers = new Oid(new UInt32[] { 1, 3, 6, 1, 6, 3, 11, 2, 1, 3, 0 });
/// <summary>
/// Array of all SNMP version 3 REPORT packet error OIDs
/// </summary>
public static Oid[] v3ErrorOids = new Oid[] { usmStatsUnsupportedSecLevels, usmStatsNotInTimeWindows, usmStatsUnknownSecurityNames,
usmStatsUnknownEngineIDs, usmStatsWrongDigests, usmStatsDecryptionErrors, snmpUnknownSecurityModels, snmpUnknownPDUHandlers };
#endregion SNMP version 3 error OID values
#region Helper methods
/// <summary>Used to create correct variable type object for the specified encoded type</summary>
/// <param name="asnType">ASN.1 type code</param>
/// <returns>A new object matching type supplied or null if type was not recognized.</returns>
public static AsnType GetSyntaxObject(byte asnType)
{
AsnType obj = null;
if (asnType == SnmpConstants.SMI_INTEGER)
obj = new Integer32();
else if (asnType == SnmpConstants.SMI_COUNTER32)
obj = new Counter32();
else if (asnType == SnmpConstants.SMI_GAUGE32)
obj = new Gauge32();
else if (asnType == SnmpConstants.SMI_COUNTER64)
obj = new Counter64();
else if (asnType == SnmpConstants.SMI_TIMETICKS)
obj = new TimeTicks();
else if (asnType == SnmpConstants.SMI_STRING)
obj = new OctetString();
else if (asnType == SnmpConstants.SMI_OPAQUE)
obj = new Opaque();
else if (asnType == SnmpConstants.SMI_IPADDRESS)
obj = new IpAddress();
else if (asnType == SnmpConstants.SMI_OBJECTID)
obj = new Oid();
else if (asnType == SnmpConstants.SMI_PARTY_CLOCK)
obj = new V2PartyClock();
else if (asnType == SnmpConstants.SMI_NOSUCHINSTANCE)
obj = new NoSuchInstance();
else if (asnType == SnmpConstants.SMI_NOSUCHOBJECT)
obj = new NoSuchObject();
else if (asnType == SnmpConstants.SMI_ENDOFMIBVIEW)
obj = new EndOfMibView();
else if (asnType == SnmpConstants.SMI_NULL)
{
obj = new Null();
}
return obj;
}
/// <summary>
/// Return SNMP type object of the type specified by name. Supported variable types are:
/// * <see cref="Integer32"/>
/// * <see cref="Counter32"/>
/// * <see cref="Gauge32"/>
/// * <see cref="Counter64"/>
/// * <see cref="TimeTicks"/>
/// * <see cref="OctetString"/>
/// * <see cref="IpAddress"/>
/// * <see cref="Oid"/>
/// * <see cref="Null"/>
/// </summary>
/// <param name="name">Name of the object type</param>
/// <returns>New <see cref="AsnType"/> object.</returns>
public static AsnType GetSyntaxObject(string name)
{
AsnType obj = null;
if (name == "Integer32")
obj = new Integer32();
else if (name == "Counter32")
obj = new Counter32();
else if (name == "Gauge32")
obj = new Gauge32();
else if (name == "Counter64")
obj = new Counter64();
else if (name == "TimeTicks")
obj = new TimeTicks();
else if (name == "OctetString")
obj = new OctetString();
else if (name == "IpAddress")
obj = new IpAddress();
else if (name == "Oid")
obj = new Oid();
else if (name == "Null")
obj = new Null();
else
throw new ArgumentException("Invalid value type name");
return obj;
}
/// <summary>
/// Return string representation of the SMI value type.
/// </summary>
/// <param name="type">AsnType class Type member function value.</param>
/// <returns>String formatted name of the SMI type.</returns>
public static string GetTypeName(byte type)
{
if( type == SMI_IPADDRESS)
return SMI_IPADDRESS_STR;
else if( type == SMI_APPSTRING)
return SMI_APPSTRING_STR;
else if( type == SMI_COUNTER32)
return SMI_COUNTER32_STR;
else if( type == SMI_COUNTER64)
return SMI_COUNTER64_STR;
else if( type == SMI_GAUGE32)
return SMI_GAUGE32_STR;
else if( type == SMI_INTEGER)
return SMI_INTEGER_STR;
else if( type == SMI_NULL)
return SMI_NULL_STR;
else if( type == SMI_OBJECTID)
return SMI_OBJECTID_STR;
else if( type == SMI_OPAQUE)
return SMI_OPAQUE_STR;
else if( type == SMI_STRING)
return SMI_STRING_STR;
else if( type == SMI_TIMETICKS)
return SMI_TIMETICKS_STR;
else if( type == SMI_UNSIGNED32)
return SMI_UNSIGNED32_STR;
else
return SMI_UNKNOWN_STR;
}
/// <summary>
/// Debugging function used to dump on the console supplied byte array in a format suitable for console output.
/// </summary>
/// <param name="data">Byte array data</param>
public static void DumpHex(byte[] data) {
int val = 0;
for(int i=0; i<data.Length; i++ ) {
if( val == 0 ) {
Console.Write("{0:d04} ", i);
}
Console.Write("{0:x2}", data[i]);
val += 1;
if( val == 16 ) {
val = 0;
Console.Write("\n");
} else {
Console.Write(" ");
}
}
if (val != 0)
Console.WriteLine("\n");
}
/// <summary>
/// Check if SNMP version value is correct
/// </summary>
/// <param name="version">SNMP version value</param>
/// <returns>true if valid SNMP version, otherwise false</returns>
public static bool IsValidVersion(int version)
{
if (version == (int)SnmpVersion.Ver1 || version == (int)SnmpVersion.Ver2 || version == (int)SnmpVersion.Ver3)
return true;
return false;
}
#endregion
/// <summary>
/// Private constructor to prevent the class with all static members from being instantiated.
/// </summary>
private SnmpConstants()
{
// nothing
}
}
}
| |
using System;
using System.Text;
using UnityEngine;
using ChartboostSDK;
using System.Collections.Generic;
public class ChartboostExample: MonoBehaviour
{
public GameObject inPlayIcon;
public GameObject inPlayText;
public Texture2D logo;
private CBInPlay inPlayAd;
public Vector2 scrollPosition = Vector2.zero;
private List<string> delegateHistory;
private bool hasInterstitial = false;
private bool hasMoreApps = false;
private bool hasRewardedVideo = false;
private bool hasInPlay = false;
private int frameCount = 0;
private bool ageGate = false;
private bool autocache = true;
private bool activeAgeGate = false;
private bool showInterstitial = true;
private bool showMoreApps = true;
private bool showRewardedVideo = true;
private int BANNER_HEIGHT = 110;
private int REQUIRED_HEIGHT = 650;
private int ELEMENT_WIDTH = 190;
private Rect scrollRect;
private Rect scrollArea;
private Vector3 guiScale;
private float scale;
#if UNITY_IPHONE
private CBStatusBarBehavior statusBar = CBStatusBarBehavior.Ignore;
#endif
void OnEnable() {
SetupDelegates();
}
void Start() {
delegateHistory = new List<string>();
Chartboost.setShouldPauseClickForConfirmation(ageGate);
Chartboost.setAutoCacheAds(autocache);
AddLog("Is Initialized: " + Chartboost.isInitialized());
/*
// Create the Chartboost gameobject with the editor AppId and AppSignature
// Remove the Chartboost gameobject from the sample first
Chartboost.Create();
*/
/*
// Sample to create Chartboost gameobject from code overriding editor AppId and AppSignature
// Remove the Chartboost gameobject from the sample first
#if UNITY_IPHONE
Chartboost.CreateWithAppId("4f21c409cd1cb2fb7000001b", "92e2de2fd7070327bdeb54c15a5295309c6fcd2d");
#elif UNITY_ANDROID
Chartboost.CreateWithAppId("4f7b433509b6025804000002", "dd2d41b69ac01b80f443f5b6cf06096d457f82bd");
#endif
*/
}
void SetupDelegates()
{
// Listen to all impression-related events
Chartboost.didInitialize += didInitialize;
Chartboost.didFailToLoadInterstitial += didFailToLoadInterstitial;
Chartboost.didDismissInterstitial += didDismissInterstitial;
Chartboost.didCloseInterstitial += didCloseInterstitial;
Chartboost.didClickInterstitial += didClickInterstitial;
Chartboost.didCacheInterstitial += didCacheInterstitial;
Chartboost.shouldDisplayInterstitial += shouldDisplayInterstitial;
Chartboost.didDisplayInterstitial += didDisplayInterstitial;
Chartboost.didFailToLoadMoreApps += didFailToLoadMoreApps;
Chartboost.didDismissMoreApps += didDismissMoreApps;
Chartboost.didCloseMoreApps += didCloseMoreApps;
Chartboost.didClickMoreApps += didClickMoreApps;
Chartboost.didCacheMoreApps += didCacheMoreApps;
Chartboost.shouldDisplayMoreApps += shouldDisplayMoreApps;
Chartboost.didDisplayMoreApps += didDisplayMoreApps;
Chartboost.didFailToRecordClick += didFailToRecordClick;
Chartboost.didFailToLoadRewardedVideo += didFailToLoadRewardedVideo;
Chartboost.didDismissRewardedVideo += didDismissRewardedVideo;
Chartboost.didCloseRewardedVideo += didCloseRewardedVideo;
Chartboost.didClickRewardedVideo += didClickRewardedVideo;
Chartboost.didCacheRewardedVideo += didCacheRewardedVideo;
Chartboost.shouldDisplayRewardedVideo += shouldDisplayRewardedVideo;
Chartboost.didCompleteRewardedVideo += didCompleteRewardedVideo;
Chartboost.didDisplayRewardedVideo += didDisplayRewardedVideo;
Chartboost.didCacheInPlay += didCacheInPlay;
Chartboost.didFailToLoadInPlay += didFailToLoadInPlay;
Chartboost.didPauseClickForConfirmation += didPauseClickForConfirmation;
Chartboost.willDisplayVideo += willDisplayVideo;
#if UNITY_IPHONE
Chartboost.didCompleteAppStoreSheetFlow += didCompleteAppStoreSheetFlow;
#endif
}
private Vector2 beginFinger; // finger
private float deltaFingerY; // finger
private Vector2 beginPanel; // scrollpanel
private Vector2 latestPanel; // scrollpanel
void Update() {
UpdateScrolling();
frameCount++;
if( frameCount > 30 )
{
// update these periodically and not every frame
hasInterstitial = Chartboost.hasInterstitial(CBLocation.Default);
hasMoreApps = Chartboost.hasMoreApps(CBLocation.Default);
hasRewardedVideo = Chartboost.hasRewardedVideo(CBLocation.Default);
hasInPlay = Chartboost.hasInPlay(CBLocation.Default);
frameCount = 0;
}
}
void UpdateScrolling()
{
if ( Input.touchCount != 1 ) return;
Touch touch = Input.touches[0];
if ( touch.phase == TouchPhase.Began )
{
beginFinger = touch.position;
beginPanel = scrollPosition;
}
if ( touch.phase == TouchPhase.Moved )
{
Vector2 newFingerScreenPos = touch.position;
deltaFingerY = newFingerScreenPos.y - beginFinger.y;
float newY = beginPanel.y + (deltaFingerY / scale);
latestPanel = beginPanel;
latestPanel.y = newY;
scrollPosition = latestPanel;
}
}
void AddLog(string text)
{
Debug.Log(text);
delegateHistory.Insert(0, text + "\n");
int count = delegateHistory.Count;
if( count > 20 )
{
delegateHistory.RemoveRange(20, count-20);
}
}
void OnGUI() {
/*
#if UNITY_ANDROID
// Disable user input for GUI when impressions are visible
// This is only necessary on Android if we have disabled impression activities
// by having called CBBinding.init(ID, SIG, false), as that allows touch
// events to leak through Chartboost impressions
GUI.enabled = !Chartboost.isImpressionVisible();
#endif
*/
//get the screen's width
float sWidth = Screen.width;
float sHeight = Screen.height;
//calculate the rescale ratio
float guiRatioX = sWidth/240.0f;
float guiRatioY = sHeight/210.0f;
float myScale = Mathf.Min(6.0f, Mathf.Min(guiRatioX, guiRatioY));
if(scale != myScale) {
scale = myScale;
guiScale = new Vector3(scale,scale,1);
}
GUI.matrix = Matrix4x4.Scale(guiScale);
ELEMENT_WIDTH = (int)(sWidth/scale)-30;
float height = REQUIRED_HEIGHT;
if(inPlayAd != null) {
// add space for the icon
height += 60;
}
scrollRect = new Rect(0, BANNER_HEIGHT, ELEMENT_WIDTH+30, sHeight/scale-BANNER_HEIGHT);
scrollArea = new Rect(-10, BANNER_HEIGHT, ELEMENT_WIDTH, height);
LayoutHeader();
if( activeAgeGate )
{
GUI.ModalWindow(1, new Rect(0, 0, Screen.width, Screen.height), LayoutAgeGate, "Age Gate");
return;
}
scrollPosition = GUI.BeginScrollView(scrollRect, scrollPosition, scrollArea);
LayoutButtons();
LayoutToggles();
GUI.EndScrollView();
}
void LayoutHeader()
{
// A view with some debug information
GUILayout.Label(logo, GUILayout.Height(30), GUILayout.Width(ELEMENT_WIDTH+20));
String text = "";
foreach( String entry in delegateHistory)
{
text += entry;
}
GUILayout.TextArea( text, GUILayout.Height(70), GUILayout.Width(ELEMENT_WIDTH+20));
}
void LayoutToggles()
{
GUILayout.Space(5);
GUILayout.Label("Options:");
showInterstitial = GUILayout.Toggle(showInterstitial, "Should Display Interstitial");
showMoreApps = GUILayout.Toggle(showMoreApps, "Should Display More Apps");
showRewardedVideo = GUILayout.Toggle(showRewardedVideo, "Should Display Rewarded Video");
if( GUILayout.Toggle(ageGate, "Should Pause for AgeGate") != ageGate )
{
ageGate = !ageGate; // toggle
Chartboost.setShouldPauseClickForConfirmation(ageGate);
}
if( GUILayout.Toggle(autocache, "Auto cache ads") != autocache )
{
autocache = !autocache; // toggle
Chartboost.setAutoCacheAds(autocache);
}
#if UNITY_IPHONE
GUILayout.Label("Status Bar Behavior:");
int slider = Mathf.RoundToInt(GUILayout.HorizontalSlider((int)statusBar, 0, 2, GUILayout.Width(ELEMENT_WIDTH/2)));
if( slider != (int)statusBar )
{
statusBar = (CBStatusBarBehavior)slider;
Chartboost.setStatusBarBehavior(statusBar);
switch(statusBar)
{
case CBStatusBarBehavior.Ignore:
AddLog("set to Ignore");
break;
case CBStatusBarBehavior.RespectButtons:
AddLog("set to RespectButtons");
break;
case CBStatusBarBehavior.Respect:
AddLog("set to Respect");
break;
}
}
#endif
}
void LayoutButtons()
{
// The view with buttons to trigger the main Chartboost API calls
GUILayout.Space(5);
GUILayout.Label("Has Interstitial: " + hasInterstitial);
if (GUILayout.Button("Cache Interstitial", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.cacheInterstitial(CBLocation.Default);
}
if (GUILayout.Button("Show Interstitial", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.showInterstitial(CBLocation.Default);
}
GUILayout.Space(5);
GUILayout.Label("Has MoreApps: " + hasMoreApps);
if (GUILayout.Button("Cache More Apps", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.cacheMoreApps(CBLocation.Default);
}
if (GUILayout.Button("Show More Apps", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.showMoreApps(CBLocation.Default);
}
GUILayout.Space(5);
GUILayout.Label("Has Rewarded Video: " + hasRewardedVideo);
if (GUILayout.Button("Cache Rewarded Video", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.cacheRewardedVideo(CBLocation.Default);
}
if (GUILayout.Button("Show Rewarded Video", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.showRewardedVideo(CBLocation.Default);
}
GUILayout.Space(5);
GUILayout.Label("Has InPlay: " + hasInPlay);
if (GUILayout.Button("Cache InPlay Ad", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.cacheInPlay(CBLocation.Default);
}
if (GUILayout.Button("Show InPlay Ad", GUILayout.Width(ELEMENT_WIDTH))) {
inPlayAd = Chartboost.getInPlay(CBLocation.Default);
if(inPlayAd != null) {
inPlayAd.show();
}
}
if(inPlayAd != null) {
// Set the texture of InPlay Ad Icon
// Link its onClick() event with inPlay's click()
GUILayout.Label("app: " + inPlayAd.appName);
if(GUILayout.Button(inPlayAd.appIcon, GUILayout.Width(ELEMENT_WIDTH))) {
inPlayAd.click();
}
}
GUILayout.Space(5);
GUILayout.Label("Post install events:");
if (GUILayout.Button("Send PIA Main Level Event", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.trackLevelInfo("Test Data", CBLevelType.HIGHEST_LEVEL_REACHED, 1, "Test Send mail level Information");
}
if (GUILayout.Button("Send PIA Sub Level Event", GUILayout.Width(ELEMENT_WIDTH))) {
Chartboost.trackLevelInfo("Test Data", CBLevelType.HIGHEST_LEVEL_REACHED, 1, 2, "Test Send sub level Information");
}
if (GUILayout.Button("Track IAP", GUILayout.Width(ELEMENT_WIDTH))) {
TrackIAP();
}
}
void LayoutAgeGate(int windowID)
{
GUILayout.Space(BANNER_HEIGHT);
GUILayout.Label("Want to pass the age gate?");
GUILayout.BeginHorizontal(GUILayout.Width(ELEMENT_WIDTH));
if( GUILayout.Button("YES") )
{
Chartboost.didPassAgeGate(true);
activeAgeGate = false;
}
if( GUILayout.Button("NO") )
{
Chartboost.didPassAgeGate(false);
activeAgeGate = false;
}
GUILayout.EndHorizontal();
}
void OnDisable() {
// Remove event handlers
Chartboost.didInitialize -= didInitialize;
Chartboost.didFailToLoadInterstitial -= didFailToLoadInterstitial;
Chartboost.didDismissInterstitial -= didDismissInterstitial;
Chartboost.didCloseInterstitial -= didCloseInterstitial;
Chartboost.didClickInterstitial -= didClickInterstitial;
Chartboost.didCacheInterstitial -= didCacheInterstitial;
Chartboost.shouldDisplayInterstitial -= shouldDisplayInterstitial;
Chartboost.didDisplayInterstitial -= didDisplayInterstitial;
Chartboost.didFailToLoadMoreApps -= didFailToLoadMoreApps;
Chartboost.didDismissMoreApps -= didDismissMoreApps;
Chartboost.didCloseMoreApps -= didCloseMoreApps;
Chartboost.didClickMoreApps -= didClickMoreApps;
Chartboost.didCacheMoreApps -= didCacheMoreApps;
Chartboost.shouldDisplayMoreApps -= shouldDisplayMoreApps;
Chartboost.didDisplayMoreApps -= didDisplayMoreApps;
Chartboost.didFailToRecordClick -= didFailToRecordClick;
Chartboost.didFailToLoadRewardedVideo -= didFailToLoadRewardedVideo;
Chartboost.didDismissRewardedVideo -= didDismissRewardedVideo;
Chartboost.didCloseRewardedVideo -= didCloseRewardedVideo;
Chartboost.didClickRewardedVideo -= didClickRewardedVideo;
Chartboost.didCacheRewardedVideo -= didCacheRewardedVideo;
Chartboost.shouldDisplayRewardedVideo -= shouldDisplayRewardedVideo;
Chartboost.didCompleteRewardedVideo -= didCompleteRewardedVideo;
Chartboost.didDisplayRewardedVideo -= didDisplayRewardedVideo;
Chartboost.didCacheInPlay -= didCacheInPlay;
Chartboost.didFailToLoadInPlay -= didFailToLoadInPlay;
Chartboost.didPauseClickForConfirmation -= didPauseClickForConfirmation;
Chartboost.willDisplayVideo -= willDisplayVideo;
#if UNITY_IPHONE
Chartboost.didCompleteAppStoreSheetFlow -= didCompleteAppStoreSheetFlow;
#endif
}
void didInitialize(bool status) {
AddLog(string.Format("didInitialize: {0}", status));
}
void didFailToLoadInterstitial(CBLocation location, CBImpressionError error) {
AddLog(string.Format("didFailToLoadInterstitial: {0} at location {1}", error, location));
}
void didDismissInterstitial(CBLocation location) {
AddLog("didDismissInterstitial: " + location);
}
void didCloseInterstitial(CBLocation location) {
AddLog("didCloseInterstitial: " + location);
}
void didClickInterstitial(CBLocation location) {
AddLog("didClickInterstitial: " + location);
}
void didCacheInterstitial(CBLocation location) {
AddLog("didCacheInterstitial: " + location);
}
bool shouldDisplayInterstitial(CBLocation location) {
// return true if you want to allow the interstitial to be displayed
AddLog("shouldDisplayInterstitial @" + location + " : " + showInterstitial);
return showInterstitial;
}
void didDisplayInterstitial(CBLocation location){
AddLog("didDisplayInterstitial: " + location);
}
void didFailToLoadMoreApps(CBLocation location, CBImpressionError error) {
AddLog(string.Format("didFailToLoadMoreApps: {0} at location: {1}", error, location));
}
void didDismissMoreApps(CBLocation location) {
AddLog(string.Format("didDismissMoreApps at location: {0}", location));
}
void didCloseMoreApps(CBLocation location) {
AddLog(string.Format("didCloseMoreApps at location: {0}", location));
}
void didClickMoreApps(CBLocation location) {
AddLog(string.Format("didClickMoreApps at location: {0}", location));
}
void didCacheMoreApps(CBLocation location) {
AddLog(string.Format("didCacheMoreApps at location: {0}", location));
}
bool shouldDisplayMoreApps(CBLocation location) {
AddLog(string.Format("shouldDisplayMoreApps at location: {0}: {1}", location, showMoreApps));
return showMoreApps;
}
void didDisplayMoreApps(CBLocation location){
AddLog("didDisplayMoreApps: " + location);
}
void didFailToRecordClick(CBLocation location, CBClickError error) {
AddLog(string.Format("didFailToRecordClick: {0} at location: {1}", error, location));
}
void didFailToLoadRewardedVideo(CBLocation location, CBImpressionError error) {
AddLog(string.Format("didFailToLoadRewardedVideo: {0} at location {1}", error, location));
}
void didDismissRewardedVideo(CBLocation location) {
AddLog("didDismissRewardedVideo: " + location);
}
void didCloseRewardedVideo(CBLocation location) {
AddLog("didCloseRewardedVideo: " + location);
}
void didClickRewardedVideo(CBLocation location) {
AddLog("didClickRewardedVideo: " + location);
}
void didCacheRewardedVideo(CBLocation location) {
AddLog("didCacheRewardedVideo: " + location);
}
bool shouldDisplayRewardedVideo(CBLocation location) {
AddLog("shouldDisplayRewardedVideo @" + location + " : " + showRewardedVideo);
return showRewardedVideo;
}
void didCompleteRewardedVideo(CBLocation location, int reward) {
AddLog(string.Format("didCompleteRewardedVideo: reward {0} at location {1}", reward, location));
}
void didDisplayRewardedVideo(CBLocation location){
AddLog("didDisplayRewardedVideo: " + location);
}
void didCacheInPlay(CBLocation location) {
AddLog("didCacheInPlay called: "+location);
}
void didFailToLoadInPlay(CBLocation location, CBImpressionError error) {
AddLog(string.Format("didFailToLoadInPlay: {0} at location: {1}", error, location));
}
void didPauseClickForConfirmation() {
AddLog("didPauseClickForConfirmation called");
activeAgeGate = true;
}
void willDisplayVideo(CBLocation location) {
AddLog("willDisplayVideo: " + location);
}
#if UNITY_IPHONE
void didCompleteAppStoreSheetFlow() {
AddLog("didCompleteAppStoreSheetFlow");
}
void TrackIAP() {
// The iOS receipt data from Unibill is already base64 encoded.
// Others store kit plugins may be different.
// This is a sample sandbox receipt.
string sampleReceipt = @"ewoJInNpZ25hdHVyZSIgPSAiQXBNVUJDODZBbHpOaWtWNVl0clpBTWlKUWJLOEVk
ZVhrNjNrV0JBWHpsQzhkWEd1anE0N1puSVlLb0ZFMW9OL0ZTOGNYbEZmcDlZWHQ5
aU1CZEwyNTBsUlJtaU5HYnloaXRyeVlWQVFvcmkzMlc5YVIwVDhML2FZVkJkZlcr
T3kvUXlQWkVtb05LeGhudDJXTlNVRG9VaFo4Wis0cFA3MHBlNWtVUWxiZElWaEFB
QURWekNDQTFNd2dnSTdvQU1DQVFJQ0NHVVVrVTNaV0FTMU1BMEdDU3FHU0liM0RR
RUJCUVVBTUg4eEN6QUpCZ05WQkFZVEFsVlRNUk13RVFZRFZRUUtEQXBCY0hCc1pT
QkpibU11TVNZd0pBWURWUVFMREIxQmNIQnNaU0JEWlhKMGFXWnBZMkYwYVc5dUlF
RjFkR2h2Y21sMGVURXpNREVHQTFVRUF3d3FRWEJ3YkdVZ2FWUjFibVZ6SUZOMGIz
SmxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1CNFhEVEE1TURZeE5U
SXlNRFUxTmxvWERURTBNRFl4TkRJeU1EVTFObG93WkRFak1DRUdBMVVFQXd3YVVI
VnlZMmhoYzJWU1pXTmxhWEIwUTJWeWRHbG1hV05oZEdVeEd6QVpCZ05WQkFzTUVr
RndjR3hsSUdsVWRXNWxjeUJUZEc5eVpURVRNQkVHQTFVRUNnd0tRWEJ3YkdVZ1NX
NWpMakVMTUFrR0ExVUVCaE1DVlZNd2daOHdEUVlKS29aSWh2Y05BUUVCQlFBRGdZ
MEFNSUdKQW9HQkFNclJqRjJjdDRJclNkaVRDaGFJMGc4cHd2L2NtSHM4cC9Sd1Yv
cnQvOTFYS1ZoTmw0WElCaW1LalFRTmZnSHNEczZ5anUrK0RyS0pFN3VLc3BoTWRk
S1lmRkU1ckdYc0FkQkVqQndSSXhleFRldngzSExFRkdBdDFtb0t4NTA5ZGh4dGlJ
ZERnSnYyWWFWczQ5QjB1SnZOZHk2U01xTk5MSHNETHpEUzlvWkhBZ01CQUFHamNq
QndNQXdHQTFVZEV3RUIvd1FDTUFBd0h3WURWUjBqQkJnd0ZvQVVOaDNvNHAyQzBn
RVl0VEpyRHRkREM1RllRem93RGdZRFZSMFBBUUgvQkFRREFnZUFNQjBHQTFVZERn
UVdCQlNwZzRQeUdVakZQaEpYQ0JUTXphTittVjhrOVRBUUJnb3Foa2lHOTJOa0Jn
VUJCQUlGQURBTkJna3Foa2lHOXcwQkFRVUZBQU9DQVFFQUVhU2JQanRtTjRDL0lC
M1FFcEszMlJ4YWNDRFhkVlhBZVZSZVM1RmFaeGMrdDg4cFFQOTNCaUF4dmRXLzNl
VFNNR1k1RmJlQVlMM2V0cVA1Z204d3JGb2pYMGlreVZSU3RRKy9BUTBLRWp0cUIw
N2tMczlRVWU4Y3pSOFVHZmRNMUV1bVYvVWd2RGQ0TndOWXhMUU1nNFdUUWZna1FR
Vnk4R1had1ZIZ2JFL1VDNlk3MDUzcEdYQms1MU5QTTN3b3hoZDNnU1JMdlhqK2xv
SHNTdGNURXFlOXBCRHBtRzUrc2s0dHcrR0szR01lRU41LytlMVFUOW5wL0tsMW5q
K2FCdzdDMHhzeTBiRm5hQWQxY1NTNnhkb3J5L0NVdk02Z3RLc21uT09kcVRlc2Jw
MGJzOHNuNldxczBDOWRnY3hSSHVPTVoydG04bnBMVW03YXJnT1N6UT09IjsKCSJw
dXJjaGFzZS1pbmZvIiA9ICJld29KSW05eWFXZHBibUZzTFhCMWNtTm9ZWE5sTFdS
aGRHVXRjSE4wSWlBOUlDSXlNREV5TFRBMExUTXdJREE0T2pBMU9qVTFJRUZ0WlhK
cFkyRXZURzl6WDBGdVoyVnNaWE1pT3dvSkltOXlhV2RwYm1Gc0xYUnlZVzV6WVdO
MGFXOXVMV2xrSWlBOUlDSXhNREF3TURBd01EUTJNVGM0T0RFM0lqc0tDU0ppZG5K
eklpQTlJQ0l5TURFeU1EUXlOeUk3Q2draWRISmhibk5oWTNScGIyNHRhV1FpSUQw
Z0lqRXdNREF3TURBd05EWXhOemc0TVRjaU93b0pJbkYxWVc1MGFYUjVJaUE5SUNJ
eElqc0tDU0p2Y21sbmFXNWhiQzF3ZFhKamFHRnpaUzFrWVhSbExXMXpJaUE5SUNJ
eE16TTFOems0TXpVMU9EWTRJanNLQ1NKd2NtOWtkV04wTFdsa0lpQTlJQ0pqYjIw
dWJXbHVaRzF2WW1Gd2NDNWtiM2R1Ykc5aFpDSTdDZ2tpYVhSbGJTMXBaQ0lnUFNB
aU5USXhNVEk1T0RFeUlqc0tDU0ppYVdRaUlEMGdJbU52YlM1dGFXNWtiVzlpWVhC
d0xrMXBibVJOYjJJaU93b0pJbkIxY21Ob1lYTmxMV1JoZEdVdGJYTWlJRDBnSWpF
ek16VTNPVGd6TlRVNE5qZ2lPd29KSW5CMWNtTm9ZWE5sTFdSaGRHVWlJRDBnSWpJ
d01USXRNRFF0TXpBZ01UVTZNRFU2TlRVZ1JYUmpMMGROVkNJN0Nna2ljSFZ5WTJo
aGMyVXRaR0YwWlMxd2MzUWlJRDBnSWpJd01USXRNRFF0TXpBZ01EZzZNRFU2TlRV
Z1FXMWxjbWxqWVM5TWIzTmZRVzVuWld4bGN5STdDZ2tpYjNKcFoybHVZV3d0Y0hW
eVkyaGhjMlV0WkdGMFpTSWdQU0FpTWpBeE1pMHdOQzB6TUNBeE5Ub3dOVG8xTlNC
RmRHTXZSMDFVSWpzS2ZRPT0iOwoJImVudmlyb25tZW50IiA9ICJTYW5kYm94IjsK
CSJwb2QiID0gIjEwMCI7Cgkic2lnbmluZy1zdGF0dXMiID0gIjAiOwp9";
// Demonstrate Base64 encoding. Not necessary for the data above
// If the receipt was not base64 encoded, send encodedText not sampleReceipt
//byte[] bytesToEncode = Encoding.UTF8.GetBytes(sampleReceipt);
//string encodedText = Convert.ToBase64String(bytesToEncode);
// Send the receipt for track an In App Purchase Event
Chartboost.trackInAppAppleStorePurchaseEvent(sampleReceipt,
"sample product title", "sample product description", "1.99", "USD", "sample product identifier" );
//byte[] decodedText = Convert.FromBase64String(sampleReceipt);
//Debug.Log("Decoded: " + System.Text.Encoding.UTF8.GetString(decodedText));
//Debug.Log("Encoded: " + encodedText);
}
#elif UNITY_ANDROID
void TrackIAP() {
Debug.Log("TrackIAP");
// title, description, price, currency, productID, purchaseData, purchaseSignature
// This data should be sent after handling the results from the google store.
// This is fake data and doesn't represent a real or even imaginary purchase
Chartboost.trackInAppGooglePlayPurchaseEvent("SampleItem", "TestPurchase", "0.99", "USD", "ProductID", "PurchaseData", "PurchaseSignature");
// If you are using the Amazon store...
//Chartboost.trackInAppAmazonStorePurchaseEvent("SampleItem", "TestPurchase", "0.99", "ProductID", "UserId", "PurchaseToken");
}
#else
void TrackIAP() {
Debug.Log("TrackIAP on unsupported platform");
}
#endif
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace NServiceKit.Redis.Tests
{
[TestFixture]
public class RedisPipelineTests
: RedisClientTestsBase
{
private const string Key = "pipemultitest";
private const string ListKey = "pipemultitest-list";
private const string SetKey = "pipemultitest-set";
private const string SortedSetKey = "pipemultitest-sortedset";
public override void TearDown()
{
CleanMask = Key + "*";
base.TearDown();
}
[Test]
public void Can_call_single_operation_in_pipeline()
{
Assert.That(Redis.GetValue(Key), Is.Null);
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key));
var map = new Dictionary<string, int>();
pipeline.QueueCommand(r => r.Get<int>(Key), y => map[Key] = y);
pipeline.Flush();
}
Assert.That(Redis.GetValue(Key), Is.EqualTo("1"));
}
[Test]
public void No_commit_of_atomic_pipelines_discards_all_commands()
{
Assert.That(Redis.GetValue(Key), Is.Null);
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key));
}
Assert.That(Redis.GetValue(Key), Is.Null);
}
[Test]
public void Exception_in_atomic_pipelines_discards_all_commands()
{
Assert.That(Redis.GetValue(Key), Is.Null);
try
{
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key));
throw new NotSupportedException();
}
}
catch (NotSupportedException ignore)
{
Assert.That(Redis.GetValue(Key), Is.Null);
}
}
[Test]
public void Can_call_single_operation_3_Times_in_pipeline()
{
Assert.That(Redis.GetValue(Key), Is.Null);
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key));
pipeline.QueueCommand(r => r.IncrementValue(Key));
pipeline.QueueCommand(r => r.IncrementValue(Key));
pipeline.Flush();
}
Assert.That(Redis.GetValue(Key), Is.EqualTo("3"));
}
[Test]
public void Can_call_hash_operations_in_pipeline()
{
Assert.That(Redis.GetValue(Key), Is.Null);
var fields = new[] { "field1", "field2", "field3" };
var values = new[] { "1", "2", "3" };
var fieldBytes = new byte[fields.Length][];
for (int i = 0; i < fields.Length; ++i)
{
fieldBytes[i] = GetBytes(fields[i]);
}
var valueBytes = new byte[values.Length][];
for (int i = 0; i < values.Length; ++i)
{
valueBytes[i] = GetBytes(values[i]);
}
byte[][] members = null;
var pipeline = Redis.CreatePipeline();
pipeline.QueueCommand(r => ((RedisNativeClient)r).HMSet(Key, fieldBytes, valueBytes));
pipeline.QueueCommand(r => ((RedisNativeClient)r).HGetAll(Key), x => members = x);
pipeline.Flush();
for (var i = 0; i < members.Length; i += 2)
{
Assert.AreEqual(members[i], fieldBytes[i / 2]);
Assert.AreEqual(members[i + 1], valueBytes[i / 2]);
}
pipeline.Dispose();
}
[Test]
public void Can_call_multiple_setexs_in_pipeline()
{
Assert.That(Redis.GetValue(Key), Is.Null);
var keys = new[] {Key + "key1", Key + "key2", Key + "key3"};
var values = new[] { "1","2","3" };
var pipeline = Redis.CreatePipeline();
for (int i = 0; i < 3; ++i )
{
int index0 = i;
pipeline.QueueCommand(r => ((RedisNativeClient)r).SetEx(keys[index0], 100, GetBytes(values[index0])));
}
pipeline.Flush();
pipeline.Replay();
for (int i = 0; i < 3; ++i )
Assert.AreEqual(Redis.GetValue(keys[i]), values[i]);
pipeline.Dispose();
}
[Test]
public void Can_call_single_operation_with_callback_3_Times_in_pipeline()
{
var results = new List<long>();
Assert.That(Redis.GetValue(Key), Is.Null);
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key), results.Add);
pipeline.QueueCommand(r => r.IncrementValue(Key), results.Add);
pipeline.QueueCommand(r => r.IncrementValue(Key), results.Add);
pipeline.Flush();
}
Assert.That(Redis.GetValue(Key), Is.EqualTo("3"));
Assert.That(results, Is.EquivalentTo(new List<long> { 1, 2, 3 }));
}
[Test]
public void Supports_different_operation_types_in_same_pipeline()
{
var incrementResults = new List<long>();
var collectionCounts = new List<long>();
var containsItem = false;
Assert.That(Redis.GetValue(Key), Is.Null);
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult));
pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem1"));
pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem2"));
pipeline.QueueCommand(r => r.AddItemToSet(SetKey, "setitem"));
pipeline.QueueCommand(r => r.SetContainsItem(SetKey, "setitem"), b => containsItem = b);
pipeline.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem1"));
pipeline.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem2"));
pipeline.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, "sortedsetitem3"));
pipeline.QueueCommand(r => r.GetListCount(ListKey), intResult => collectionCounts.Add(intResult));
pipeline.QueueCommand(r => r.GetSetCount(SetKey), intResult => collectionCounts.Add(intResult));
pipeline.QueueCommand(r => r.GetSortedSetCount(SortedSetKey), intResult => collectionCounts.Add(intResult));
pipeline.QueueCommand(r => r.IncrementValue(Key), intResult => incrementResults.Add(intResult));
pipeline.Flush();
}
Assert.That(containsItem, Is.True);
Assert.That(Redis.GetValue(Key), Is.EqualTo("2"));
Assert.That(incrementResults, Is.EquivalentTo(new List<long> { 1, 2 }));
Assert.That(collectionCounts, Is.EquivalentTo(new List<int> { 2, 1, 3 }));
Assert.That(Redis.GetAllItemsFromList(ListKey), Is.EquivalentTo(new List<string> { "listitem1", "listitem2" }));
Assert.That(Redis.GetAllItemsFromSet(SetKey), Is.EquivalentTo(new List<string> { "setitem" }));
Assert.That(Redis.GetAllItemsFromSortedSet(SortedSetKey), Is.EquivalentTo(new List<string> { "sortedsetitem1", "sortedsetitem2", "sortedsetitem3" }));
}
[Test]
public void Can_call_multi_string_operations_in_pipeline()
{
string item1 = null;
string item4 = null;
var results = new List<string>();
Assert.That(Redis.GetListCount(ListKey), Is.EqualTo(0));
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem1"));
pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem2"));
pipeline.QueueCommand(r => r.AddItemToList(ListKey, "listitem3"));
pipeline.QueueCommand(r => r.GetAllItemsFromList(ListKey), x => results = x);
pipeline.QueueCommand(r => r.GetItemFromList(ListKey, 0), x => item1 = x);
pipeline.QueueCommand(r => r.GetItemFromList(ListKey, 4), x => item4 = x);
pipeline.Flush();
}
Assert.That(Redis.GetListCount(ListKey), Is.EqualTo(3));
Assert.That(results, Is.EquivalentTo(new List<string> { "listitem1", "listitem2", "listitem3" }));
Assert.That(item1, Is.EqualTo("listitem1"));
Assert.That(item4, Is.Null);
}
[Test]
// Operations that are not supported in older versions will look at server info to determine what to do.
// If server info is fetched each time, then it will interfer with pipeline
public void Can_call_operation_not_supported_on_older_servers_in_pipeline()
{
var temp = new byte[1];
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => ((RedisNativeClient)r).SetEx(Key + "key",5,temp));
pipeline.Flush();
}
}
[Test]
public void Pipeline_can_be_replayed()
{
string KeySquared = Key + Key;
Assert.That(Redis.GetValue(Key), Is.Null);
Assert.That(Redis.GetValue(KeySquared), Is.Null);
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key));
pipeline.QueueCommand(r => r.IncrementValue(KeySquared));
pipeline.Flush();
Assert.That(Redis.GetValue(Key), Is.EqualTo("1"));
Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1"));
Redis.Del(Key);
Redis.Del(KeySquared);
Assert.That(Redis.GetValue(Key), Is.Null);
Assert.That(Redis.GetValue(KeySquared), Is.Null);
pipeline.Replay();
pipeline.Dispose();
Assert.That(Redis.GetValue(Key), Is.EqualTo("1"));
Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1"));
}
}
[Test]
public void Pipeline_can_be_contain_watch()
{
string KeySquared = Key + Key;
Assert.That(Redis.GetValue(Key), Is.Null);
Assert.That(Redis.GetValue(KeySquared), Is.Null);
using (var pipeline = Redis.CreatePipeline())
{
pipeline.QueueCommand(r => r.IncrementValue(Key));
pipeline.QueueCommand(r => r.IncrementValue(KeySquared));
pipeline.QueueCommand(r => ((RedisNativeClient)r).Watch(Key + "FOO"));
pipeline.Flush();
Assert.That(Redis.GetValue(Key), Is.EqualTo("1"));
Assert.That(Redis.GetValue(KeySquared), Is.EqualTo("1"));
}
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Erik Ejlskov Jensen, http://erikej.blogspot.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// All code in this file requires .NET Framework 2.0 or later.
#if !NET_1_1 && !NET_1_0
[assembly: Elmah.Scc("$Id: SqlServerCompactErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Data;
using System.Data.SqlServerCe;
using System.IO;
using IDictionary = System.Collections.IDictionary;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses SQL Server
/// Compact 4 as its backing store.
/// </summary>
public class SqlServerCompactErrorLog : ErrorLog
{
private readonly string _connectionString;
/// <summary>
/// Initializes a new instance of the <see cref="SqlServerCompactErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public SqlServerCompactErrorLog(IDictionary config)
{
if (config == null)
throw new ArgumentNullException("config");
string connectionString = ConnectionStringHelper.GetConnectionString(config, true);
//
// If there is no connection string to use then throw an
// exception to abort construction.
//
if (connectionString.Length == 0)
throw new Elmah.ApplicationException("Connection string is missing for the SQL Server Compact error log.");
_connectionString = connectionString;
InitializeDatabase();
ApplicationName = Mask.NullString((string) config["applicationName"]);
}
/// <summary>
/// Initializes a new instance of the <see cref="SqlServerCompactErrorLog"/> class
/// to use a specific connection string for connecting to the database.
/// </summary>
public SqlServerCompactErrorLog(string connectionString)
{
if (connectionString == null)
throw new ArgumentNullException("connectionString");
if (connectionString.Length == 0)
throw new ArgumentException(null, "connectionString");
_connectionString = ConnectionStringHelper.GetResolvedConnectionString(connectionString);
InitializeDatabase();
}
private void InitializeDatabase()
{
string connectionString = ConnectionString;
Debug.AssertStringNotEmpty(connectionString);
string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString);
if (File.Exists(dbFilePath))
return;
using (SqlCeEngine engine = new SqlCeEngine(ConnectionString))
{
engine.CreateDatabase();
}
using (SqlCeConnection conn = new SqlCeConnection(ConnectionString))
{
using (SqlCeCommand cmd = new SqlCeCommand())
{
conn.Open();
SqlCeTransaction transaction = conn.BeginTransaction();
try
{
cmd.Connection = conn;
cmd.Transaction = transaction;
cmd.CommandText = @"
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'ELMAH_Error'";
object obj = cmd.ExecuteScalar();
if (obj == null)
{
cmd.CommandText = @"
CREATE TABLE ELMAH_Error (
[ErrorId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(),
[Application] NVARCHAR(60) NOT NULL,
[Host] NVARCHAR(50) NOT NULL,
[Type] NVARCHAR(100) NOT NULL,
[Source] NVARCHAR(60) NOT NULL,
[Message] NVARCHAR(500) NOT NULL,
[User] NVARCHAR(50) NOT NULL,
[StatusCode] INT NOT NULL,
[TimeUtc] DATETIME NOT NULL,
[Sequence] INT IDENTITY (1, 1) NOT NULL,
[AllXml] NTEXT NOT NULL
)";
cmd.ExecuteNonQuery();
cmd.CommandText = @"
CREATE NONCLUSTERED INDEX [IX_Error_App_Time_Seq] ON [ELMAH_Error]
(
[Application] ASC,
[TimeUtc] DESC,
[Sequence] DESC
)";
cmd.ExecuteNonQuery();
}
transaction.Commit(CommitMode.Immediate);
}
catch (SqlCeException)
{
transaction.Rollback();
throw;
}
}
}
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "SQL Server Compact Error Log"; }
}
/// <summary>
/// Gets the connection string used by the log to connect to the database.
/// </summary>
public virtual string ConnectionString
{
get { return _connectionString; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Use the stored procedure called by this implementation to set a
/// policy on how long errors are kept in the log. The default
/// implementation stores all errors for an indefinite time.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
string errorXml = ErrorXml.EncodeString(error);
Guid id = Guid.NewGuid();
const string query = @"
INSERT INTO ELMAH_Error (
[ErrorId], [Application], [Host],
[Type], [Source], [Message], [User], [StatusCode],
[TimeUtc], [AllXml] )
VALUES (
@ErrorId, @Application, @Host,
@Type, @Source, @Message, @User, @StatusCode,
@TimeUtc, @AllXml);";
using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
{
using (SqlCeCommand command = new SqlCeCommand(query, connection))
{
SqlCeParameterCollection parameters = command.Parameters;
parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = id;
parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = string.IsNullOrEmpty(error.ApplicationName) ? this.ApplicationName : error.ApplicationName;;
parameters.Add("@Host", SqlDbType.NVarChar, 30).Value = error.HostName;
parameters.Add("@Type", SqlDbType.NVarChar, 100).Value = error.Type;
parameters.Add("@Source", SqlDbType.NVarChar, 60).Value = error.Source;
parameters.Add("@Message", SqlDbType.NVarChar, 500).Value = error.Message;
parameters.Add("@User", SqlDbType.NVarChar, 50).Value = error.User;
parameters.Add("@StatusCode", SqlDbType.Int).Value = error.StatusCode;
parameters.Add("@TimeUtc", SqlDbType.DateTime).Value = error.Time.ToUniversalTime();
parameters.Add("@AllXml", SqlDbType.NText).Value = errorXml;
command.Connection = connection;
connection.Open();
command.ExecuteNonQuery();
return id.ToString();
}
}
}
/// <summary>
/// Returns a page of errors from the databse in descending order
/// of logged time.
/// </summary>
///
public override int GetErrors(int pageIndex, int pageSize, System.Collections.IList errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
const string sql = @"
SELECT
[ErrorId],
[Application],
[Host],
[Type],
[Source],
[Message],
[User],
[StatusCode],
[TimeUtc]
FROM
[ELMAH_Error]
ORDER BY
[TimeUtc] DESC,
[Sequence] DESC
OFFSET @PageSize * @PageIndex ROWS FETCH NEXT @PageSize ROWS ONLY;
";
const string getCount = @"
SELECT COUNT(*) FROM [ELMAH_Error]";
using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
{
connection.Open();
using (SqlCeCommand command = new SqlCeCommand(sql, connection))
{
SqlCeParameterCollection parameters = command.Parameters;
parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex;
parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName;
using (SqlCeDataReader reader = command.ExecuteReader())
{
if (errorEntryList != null)
{
while (reader.Read())
{
string id = reader["ErrorId"].ToString();
Elmah.Error error = new Elmah.Error();
error.ApplicationName = reader["Application"].ToString();
error.HostName = reader["Host"].ToString();
error.Type = reader["Type"].ToString();
error.Source = reader["Source"].ToString();
error.Message = reader["Message"].ToString();
error.User = reader["User"].ToString();
error.StatusCode = Convert.ToInt32(reader["StatusCode"]);
error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime();
errorEntryList.Add(new ErrorLogEntry(this, id, error));
}
}
}
}
using (SqlCeCommand command = new SqlCeCommand(getCount, connection))
{
return (int)command.ExecuteScalar();
}
}
}
/// <summary>
/// Returns the specified error from the database, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
if (id == null)
throw new ArgumentNullException("id");
if (id.Length == 0)
throw new ArgumentException(null, "id");
Guid errorGuid;
try
{
errorGuid = new Guid(id);
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, "id", e);
}
const string sql = @"
SELECT
[AllXml]
FROM
[ELMAH_Error]
WHERE
[ErrorId] = @ErrorId";
using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
{
using (SqlCeCommand command = new SqlCeCommand(sql, connection))
{
command.Parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = errorGuid;
connection.Open();
string errorXml = (string)command.ExecuteScalar();
if (errorXml == null)
return null;
Error error = ErrorXml.DecodeString(errorXml);
return new ErrorLogEntry(this, id, error);
}
}
}
}
}
#endif // !NET_1_1 && !NET_1_0
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
function TextSpriteToy::create( %this )
{
// Reset the toy.
TextSpriteToy.reset();
}
//-----------------------------------------------------------------------------
function TextSpriteToy::destroy( %this )
{
}
//-----------------------------------------------------------------------------
function TextSpriteToy::reset( %this )
{
// Clear the scene.
SandboxScene.clear();
//Title
new TextSprite()
{
Scene = SandboxScene;
Font = "ToyAssets:TrajanProFont";
FontSize = 6.5;
Text = "Presenting the TextSprite!";
Position = "0 30";
Size = "90 7";
OverflowModeX = "visible";
TextAlignment = "center";
BlendColor = "0.2 0.5 1 1";
};
//Opening Description
new TextSprite()
{
Scene = SandboxScene;
Font = "ToyAssets:ArialFont";
FontSize = 3;
Text = "The TextSprite takes a FontAsset which directly loads a bitmap font file, so adding a new font is super easy! The TextSprite let's you align the text to the left, right, center or even justified. It can also be vertically aligned to the top, middle, or bottom. There's multiple overflow options including automatically shrinking text fit the box. Finally, you can control the color, offset, and scale of each character individually! Check out these examples!";
Position = "0 19";
Size = "90 15";
OverflowModeY = "visible";
BlendColor = "1 1 1 0.8";
};
%example1 = new TextSprite()
{
Scene = SandboxScene;
Font = "ToyAssets:OratorBoldFont";
FontSize = 5;
Text = "You can make any letter big or small!";
Position = "-30 -8";
Size = "24 24";
BlendColor = "1 1 1 1";
};
for(%i = 24; %i <= 26; %i++)
{
%example1.setCharacterScale(%i, "1.7 2");
}
for(%i = 31; %i <= 35; %i++)
{
%example1.setCharacterScale(%i, "0.8 0.6");
}
%example2 = new TextSprite()
{
Scene = SandboxScene;
Font = "ToyAssets:TrajanProFont";
FontSize = 4.3;
Text = "Don't be boring! Add some COLOR and let it spin!";
Position = "0 -5";
Size = "24 24";
BlendColor = "1 1 1 1";
AngularVelocity = 30;
TextAlignment = "center";
TextVAlignment = "middle";
autoLineHeight = false;
customLineHeight = 3.8;
};
%example2.setCharacterBlendColor(26, "1 0 0 1");
%example2.setCharacterBlendColor(27, "1 0.5 0 1");
%example2.setCharacterBlendColor(28, "1 1 0 1");
%example2.setCharacterBlendColor(29, "0.2 1 0.2 1");
%example2.setCharacterBlendColor(30, "0 0.2 1 1");
%example3 = new TextSprite()
{
Scene = SandboxScene;
Font = "ToyAssets:ArialFont";
FontSize = 3.5;
Text = "With a little work you can get your text to jump out at your readers!";
Position = "30 -8";
Size = "24 24";
BlendColor = "1 1 1 1";
TextAlignment = "right";
TextVAlignment = "bottom";
Class = "JumpingText";
start = 44;
end = 47;
jumpSpeed = 0;
letterHeight = 0;
UpdateCallback = true;
autoLineHeight = false;
customLineHeight = 6;
};
%example4 = new TextSprite()
{
Scene = SandboxScene;
Font = "ToyAssets:ArialFont";
FontSize = 3.7;
Text = "You could build a dialog box that shows one letter at a time!";
Position = "-24 -27";
Size = "45 10";
OverflowModeY = "visible";
BlendColor = "1 1 1 0";
Class = "DialogText";
pen = 0;
};
%example4.showLetter();
%example5 = new TextSprite()
{
Scene = SandboxScene;
Font = "ToyAssets:OratorBoldFont";
FontSize = 3.4;
Text = "AJDIORQNAKMAKENZCBADTWOLFJEI PEPWQFDNWORDFHISUDFBHAKLSBLH RUEBNAJDUIOQPSEARCHUIRDFBUYJ MBPIRATEIDBGVMCODEWHTKEIAVIE";
Position = "24 -25.5";
Size = "45 10";
OverflowModeY = "visible";
BlendColor = "1 1 1 1";
Class = "WordSearchText";
};
%example5.setCharacterBlendColor(4, "1 1 1 1");
%example5.setCharacterBlendColor(5, "1 1 1 1");
for(%i = 10; %i <= 13; %i++)
{
%example5.setCharacterBlendColor(%i, "1 1 1 1");
}
%example5.setCharacterBlendColor(18, "1 1 1 1");
for(%i = 37; %i <= 40; %i++)
{
%example5.setCharacterBlendColor(%i, "1 1 1 1");
}
for(%i = 71; %i <= 76; %i++)
{
%example5.setCharacterBlendColor(%i, "1 1 1 1");
}
%example5.schedule(6000, "fadeOut");
}
//-----------------------------------------------------------------------------
function JumpingText::onUpdate(%this)
{
if(%this.jumpSpeed == 0 && %this.letterHeight == 0)
{
//jump again!
%this.jumpSpeed = 0.7;
}
%this.letterHeight += %this.jumpSpeed;
if(%this.jumpSpeed > 0)
{
%this.jumpSpeed *= 0.8;
if(%this.jumpSpeed < 0.1)
{
%this.jumpSpeed = -0.1;
}
}
else if(%this.jumpSpeed < 0)
{
%this.jumpSpeed *= 1.2;
if(%this.letterHeight < 0)
{
%this.letterHeight = 0;
%this.jumpSpeed = 0;
%this.setUpdateCallback(false);
%this.schedule(1000, "setUpdateCallback", true);
}
}
for(%i = %this.start; %i <= %this.end; %i++)
{
%this.setCharacterOffset(%i, "0" SPC %this.letterHeight);
}
}
//-----------------------------------------------------------------------------
function DialogText::showLetter(%this)
{
if(%this.pen == 0)
{
%this.resetCharacterSettings();
}
%this.setCharacterBlendColor(%this.pen, "1 1 1 1");
%this.pen++;
if(%this.pen >= strlen(%this.getText()))
{
%this.pen = 0;
%this.schedule(3000, "showLetter");
}
else
{
%this.schedule(80, "showLetter");
}
}
//-----------------------------------------------------------------------------
function WordSearchText::fadeOut(%this)
{
%this.fadeTo("1 1 1 0", 0.6);
%this.schedule(6000, "fadeIn");
}
//-----------------------------------------------------------------------------
function WordSearchText::fadeIn(%this)
{
%this.fadeTo("1 1 1 1", 0.6);
%this.schedule(6000, "fadeOut");
}
| |
// 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;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class AttributeNamedParameterCompletionProvider : CompletionListProvider
{
private const string EqualsString = "=";
private const string SpaceEqualsString = " =";
private const string ColonString = ":";
public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options);
}
public override async Task ProduceCompletionListAsync(CompletionListContext context)
{
var document = context.Document;
var position = context.Position;
var cancellationToken = context.CancellationToken;
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (syntaxTree.IsInNonUserCode(position, cancellationToken))
{
return;
}
var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken);
token = token.GetPreviousTokenIfTouchingWord(position);
if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken))
{
return;
}
var attributeArgumentList = token.Parent as AttributeArgumentListSyntax;
var attributeSyntax = token.Parent.Parent as AttributeSyntax;
if (attributeSyntax == null || attributeArgumentList == null)
{
return;
}
if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token))
{
context.MakeExclusive(true);
}
// We actually want to collect two sets of named parameters to present the user. The
// normal named parameters that come from the attribute constructors. These will be
// presented like "foo:". And also the named parameters that come from the writable
// fields/properties in the attribute. These will be presented like "bar =".
var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position);
var workspace = document.Project.Solution.Workspace;
var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false);
var nameColonItems = await GetNameColonItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false);
var nameEqualsItems = await GetNameEqualsItemsAsync(workspace, semanticModel, position, token, attributeSyntax, existingNamedParameters, cancellationToken).ConfigureAwait(false);
context.AddItems(nameEqualsItems);
// If we're after a name= parameter, then we only want to show name= parameters.
// Otherwise, show name: parameters too.
if (!IsAfterNameEqualsArgument(token))
{
context.AddItems(nameColonItems);
}
}
private bool IsAfterNameColonArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
private bool IsAfterNameEqualsArgument(SyntaxToken token)
{
var argumentList = token.Parent as AttributeArgumentListSyntax;
if (token.Kind() == SyntaxKind.CommaToken && argumentList != null)
{
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
var node = item.AsNode() as AttributeArgumentSyntax;
if (node.NameEquals != null)
{
return true;
}
}
}
}
return false;
}
private async Task<IEnumerable<CompletionItem>> GetNameEqualsItemsAsync(Workspace workspace, SemanticModel semanticModel,
int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters,
CancellationToken cancellationToken)
{
var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, position, attributeSyntax, cancellationToken);
var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name));
var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return from p in attributeNamedParameters
where !existingNamedParameters.Contains(p.Name)
select new CompletionItem(
this,
p.Name.ToIdentifierToken().ToString() + SpaceEqualsString,
CompletionUtilities.GetTextChangeSpan(text, position),
CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p),
p.GetGlyph(),
sortText: p.Name,
rules: ItemRules.Instance);
}
private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync(
Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters,
CancellationToken cancellationToken)
{
var parameterLists = GetParameterLists(semanticModel, position, attributeSyntax, cancellationToken);
parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters));
var text = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return from pl in parameterLists
from p in pl
where !existingNamedParameters.Contains(p.Name)
select new CompletionItem(
this,
p.Name.ToIdentifierToken().ToString() + ColonString,
CompletionUtilities.GetTextChangeSpan(text, position),
CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, token.SpanStart, p),
p.GetGlyph(),
sortText: p.Name,
rules: ItemRules.Instance);
}
private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters)
{
return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty();
}
private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position)
{
var existingArguments1 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameColon != null)
.Select(a => a.NameColon.Name.Identifier.ValueText);
var existingArguments2 =
argumentList.Arguments.Where(a => a.Span.End <= position)
.Where(a => a.NameEquals != null)
.Select(a => a.NameEquals.Name.Identifier.ValueText);
return existingArguments1.Concat(existingArguments2).ToSet();
}
private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
if (within != null && attributeType != null)
{
return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within))
.Select(c => c.Parameters);
}
return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>();
}
private IEnumerable<ISymbol> GetAttributeNamedParameters(
SemanticModel semanticModel,
int position,
AttributeSyntax attribute,
CancellationToken cancellationToken)
{
var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken);
var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol;
return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within);
}
}
}
| |
#region Header
//
// CmdWallOpeningProfiles.cs - determine and display all wall opening face edges including elevation profile lines
//
// Copyright (C) 2015-2021 by Jeremy Tammik, Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using OperationCanceledException = Autodesk.Revit.Exceptions.OperationCanceledException;
#endregion // Namespaces
namespace BuildingCoder
{
[Transaction(TransactionMode.Manual)]
internal class CmdWallOpeningProfiles : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var uiapp = commandData.Application;
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
var commandResult = Result.Succeeded;
var cats = doc.Settings.Categories;
var catDoorsId = cats.get_Item(
BuiltInCategory.OST_Doors).Id;
var catWindowsId = cats.get_Item(
BuiltInCategory.OST_Windows).Id;
try
{
var selectedIds = uidoc.Selection
.GetElementIds().ToList();
using var trans = new Transaction(doc);
trans.Start("Cmd: GetOpeningProfiles");
var newIds = new List<ElementId>();
foreach (var selectedId in selectedIds)
if (doc.GetElement(selectedId) is Wall wall)
{
var faceList = new List<PlanarFace>();
var insertIds = wall.FindInserts(
true, false, false, false).ToList();
foreach (var insertId in insertIds)
{
var elem = doc.GetElement(insertId);
switch (elem)
{
case FamilyInstance inst:
{
var catType = inst.Category
.CategoryType;
var cat = inst.Category;
if (catType == CategoryType.Model
&& (cat.Id == catDoorsId
|| cat.Id == catWindowsId))
faceList.AddRange(
GetWallOpeningPlanarFaces(
wall, insertId));
break;
}
case Opening:
faceList.AddRange(
GetWallOpeningPlanarFaces(
wall, insertId));
break;
}
}
foreach (var face in faceList)
{
//Plane facePlane = new Plane(
// face.ComputeNormal( UV.Zero ),
// face.Origin ); // 2016
var facePlane = Plane.CreateByNormalAndOrigin(
face.ComputeNormal(UV.Zero),
face.Origin); // 2017
var sketchPlane
= SketchPlane.Create(doc, facePlane);
foreach (var curveLoop in
face.GetEdgesAsCurveLoops())
foreach (var curve in curveLoop)
{
var modelCurve = doc.Create
.NewModelCurve(curve, sketchPlane);
newIds.Add(modelCurve.Id);
}
}
}
if (newIds.Count > 0)
{
var activeView = uidoc.ActiveGraphicalView;
activeView.IsolateElementsTemporary(newIds);
}
trans.Commit();
}
#region Exception Handling
catch (ExternalApplicationException e)
{
message = e.Message;
Debug.WriteLine(
$"Exception Encountered (Application)\n{e.Message}\nStack Trace: {e.StackTrace}");
commandResult = Result.Failed;
}
catch (OperationCanceledException e)
{
Debug.WriteLine($"Operation cancelled. {e.Message}");
message = "Operation cancelled.";
commandResult = Result.Succeeded;
}
catch (Exception e)
{
message = e.Message;
Debug.WriteLine(
$"Exception Encountered (General)\n{e.Message}\nStack Trace: {e.StackTrace}");
commandResult = Result.Failed;
}
#endregion
return commandResult;
}
#region Isolate element in new view
public void testTwo(UIDocument uidoc)
{
var doc = uidoc.Document;
View newView;
using (var t = new Transaction(doc))
{
t.Start("Trans");
// Get Floorplan for Level1 and copy its
// properties for ouw newly to create ViewPlan.
var existingView = doc.GetElement(
new ElementId(312)) as View;
// Create new Floorplan.
newView = doc.GetElement(existingView.Duplicate(
ViewDuplicateOption.Duplicate)) as View;
t.Commit();
// Important to set new view as active view.
uidoc.ActiveView = newView;
t.Start("Trans 2");
// Try to isolate a Wall. Fails.
newView.IsolateElementTemporary(new ElementId(317443));
t.Commit();
}
// Change the View to the new View.
uidoc.ActiveView = newView;
}
#endregion // Isolate element in new view
/// <summary>
/// Retrieve all planar faces belonging to the
/// specified opening in the given wall.
/// </summary>
private static List<PlanarFace> GetWallOpeningPlanarFaces(
Wall wall,
ElementId openingId)
{
var faceList = new List<PlanarFace>();
var solidList = new List<Solid>();
var geomOptions = wall.Document.Application.Create.NewGeometryOptions();
if (geomOptions != null)
{
//geomOptions.ComputeReferences = true; // expensive, avoid if not needed
//geomOptions.DetailLevel = ViewDetailLevel.Fine;
//geomOptions.IncludeNonVisibleObjects = false;
var geoElem = wall.get_Geometry(geomOptions);
if (geoElem != null)
foreach (var geomObj in geoElem)
if (geomObj is Solid obj)
solidList.Add(obj);
}
foreach (var solid in solidList)
foreach (Face face in solid.Faces)
if (face is PlanarFace planarFace)
if (wall.GetGeneratingElementIds(face)
.Any(x => x == openingId))
faceList.Add(planarFace);
return faceList;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
using System.Numerics;
#endif
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Text;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
#if (DOTNET || PORTABLE || PORTABLE40)
internal enum MemberTypes
{
Property = 0,
Field = 1,
Event = 2,
Method = 3,
Other = 4
}
#endif
#if PORTABLE
[Flags]
internal enum BindingFlags
{
Default = 0,
IgnoreCase = 1,
DeclaredOnly = 2,
Instance = 4,
Static = 8,
Public = 16,
NonPublic = 32,
FlattenHierarchy = 64,
InvokeMethod = 256,
CreateInstance = 512,
GetField = 1024,
SetField = 2048,
GetProperty = 4096,
SetProperty = 8192,
PutDispProperty = 16384,
ExactBinding = 65536,
PutRefDispProperty = 32768,
SuppressChangeType = 131072,
OptionalParamBinding = 262144,
IgnoreReturn = 16777216
}
#endif
internal static class ReflectionUtils
{
public static readonly Type[] EmptyTypes;
static ReflectionUtils()
{
#if !(PORTABLE40 || PORTABLE)
EmptyTypes = Type.EmptyTypes;
#else
EmptyTypes = new Type[0];
#endif
}
public static bool IsVirtual(this PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
MethodInfo m = propertyInfo.GetGetMethod();
if (m != null && m.IsVirtual)
{
return true;
}
m = propertyInfo.GetSetMethod();
if (m != null && m.IsVirtual)
{
return true;
}
return false;
}
public static MethodInfo GetBaseDefinition(this PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo");
MethodInfo m = propertyInfo.GetGetMethod();
if (m != null)
{
return m.GetBaseDefinition();
}
m = propertyInfo.GetSetMethod();
if (m != null)
{
return m.GetBaseDefinition();
}
return null;
}
public static bool IsPublic(PropertyInfo property)
{
if (property.GetGetMethod() != null && property.GetGetMethod().IsPublic)
{
return true;
}
if (property.GetSetMethod() != null && property.GetSetMethod().IsPublic)
{
return true;
}
return false;
}
public static Type GetObjectType(object v)
{
return (v != null) ? v.GetType() : null;
}
public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder)
{
string fullyQualifiedTypeName;
#if !(NET20 || NET35)
if (binder != null)
{
string assemblyName, typeName;
binder.BindToName(t, out assemblyName, out typeName);
fullyQualifiedTypeName = typeName + (assemblyName == null ? "" : ", " + assemblyName);
}
else
{
fullyQualifiedTypeName = t.AssemblyQualifiedName;
}
#else
fullyQualifiedTypeName = t.AssemblyQualifiedName;
#endif
switch (assemblyFormat)
{
case FormatterAssemblyStyle.Simple:
return RemoveAssemblyDetails(fullyQualifiedTypeName);
case FormatterAssemblyStyle.Full:
return fullyQualifiedTypeName;
default:
throw new ArgumentOutOfRangeException();
}
}
private static string RemoveAssemblyDetails(string fullyQualifiedTypeName)
{
StringBuilder builder = new StringBuilder();
// loop through the type name and filter out qualified assembly details from nested type names
bool writingAssemblyName = false;
bool skippingAssemblyDetails = false;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ']':
writingAssemblyName = false;
skippingAssemblyDetails = false;
builder.Append(current);
break;
case ',':
if (!writingAssemblyName)
{
writingAssemblyName = true;
builder.Append(current);
}
else
{
skippingAssemblyDetails = true;
}
break;
default:
if (!skippingAssemblyDetails)
{
builder.Append(current);
}
break;
}
}
return builder.ToString();
}
public static bool HasDefaultConstructor(Type t, bool nonPublic)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsValueType())
{
return true;
}
return (GetDefaultConstructor(t, nonPublic) != null);
}
public static ConstructorInfo GetDefaultConstructor(Type t)
{
return GetDefaultConstructor(t, false);
}
public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (nonPublic)
{
bindingFlags = bindingFlags | BindingFlags.NonPublic;
}
return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any());
}
public static bool IsNullable(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
if (t.IsValueType())
{
return IsNullableType(t);
}
return true;
}
public static bool IsNullableType(Type t)
{
ValidationUtils.ArgumentNotNull(t, "t");
return (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
public static Type EnsureNotNullableType(Type t)
{
return (IsNullableType(t))
? Nullable.GetUnderlyingType(t)
: t;
}
public static bool IsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
if (!type.IsGenericType())
{
return false;
}
Type t = type.GetGenericTypeDefinition();
return (t == genericInterfaceDefinition);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition)
{
Type implementingType;
return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType);
}
public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition");
if (!genericInterfaceDefinition.IsInterface() || !genericInterfaceDefinition.IsGenericTypeDefinition())
{
throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition));
}
if (type.IsInterface())
{
if (type.IsGenericType())
{
Type interfaceDefinition = type.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = type;
return true;
}
}
}
foreach (Type i in type.GetInterfaces())
{
if (i.IsGenericType())
{
Type interfaceDefinition = i.GetGenericTypeDefinition();
if (genericInterfaceDefinition == interfaceDefinition)
{
implementingType = i;
return true;
}
}
}
implementingType = null;
return false;
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition)
{
Type implementingType;
return InheritsGenericDefinition(type, genericClassDefinition, out implementingType);
}
public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition");
if (!genericClassDefinition.IsClass() || !genericClassDefinition.IsGenericTypeDefinition())
{
throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition));
}
return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType);
}
private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType)
{
if (currentType.IsGenericType())
{
Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition();
if (genericClassDefinition == currentGenericClassDefinition)
{
implementingType = currentType;
return true;
}
}
if (currentType.BaseType() == null)
{
implementingType = null;
return false;
}
return InheritsGenericDefinitionInternal(currentType.BaseType(), genericClassDefinition, out implementingType);
}
/// <summary>
/// Gets the type of the typed collection's items.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The type of the typed collection's items.</returns>
public static Type GetCollectionItemType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
Type genericListType;
if (type.IsArray)
{
return type.GetElementType();
}
if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType))
{
if (genericListType.IsGenericTypeDefinition())
{
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
return genericListType.GetGenericArguments()[0];
}
if (typeof(IEnumerable).IsAssignableFrom(type))
{
return null;
}
throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type));
}
public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType)
{
ValidationUtils.ArgumentNotNull(dictionaryType, "type");
Type genericDictionaryType;
if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType))
{
if (genericDictionaryType.IsGenericTypeDefinition())
{
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments();
keyType = dictionaryGenericArguments[0];
valueType = dictionaryGenericArguments[1];
return;
}
if (typeof(IDictionary).IsAssignableFrom(dictionaryType))
{
keyType = null;
valueType = null;
return;
}
throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType));
}
/// <summary>
/// Gets the member's underlying type.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>The underlying type of the member.</returns>
public static Type GetMemberUnderlyingType(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, "member");
switch (member.MemberType())
{
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
case MemberTypes.Method:
return ((MethodInfo)member).ReturnType;
default:
throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo, EventInfo or MethodInfo", nameof(member));
}
}
/// <summary>
/// Determines whether the member is an indexed property.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(MemberInfo member)
{
ValidationUtils.ArgumentNotNull(member, "member");
PropertyInfo propertyInfo = member as PropertyInfo;
if (propertyInfo != null)
{
return IsIndexedProperty(propertyInfo);
}
else
{
return false;
}
}
/// <summary>
/// Determines whether the property is an indexed property.
/// </summary>
/// <param name="property">The property.</param>
/// <returns>
/// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>.
/// </returns>
public static bool IsIndexedProperty(PropertyInfo property)
{
ValidationUtils.ArgumentNotNull(property, "property");
return (property.GetIndexParameters().Length > 0);
}
/// <summary>
/// Gets the member's value on the object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target object.</param>
/// <returns>The member's value on the object.</returns>
public static object GetMemberValue(MemberInfo member, object target)
{
ValidationUtils.ArgumentNotNull(member, "member");
ValidationUtils.ArgumentNotNull(target, "target");
switch (member.MemberType())
{
case MemberTypes.Field:
return ((FieldInfo)member).GetValue(target);
case MemberTypes.Property:
try
{
return ((PropertyInfo)member).GetValue(target, null);
}
catch (TargetParameterCountException e)
{
throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e);
}
default:
throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), nameof(member));
}
}
/// <summary>
/// Sets the member's value on the target object.
/// </summary>
/// <param name="member">The member.</param>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
public static void SetMemberValue(MemberInfo member, object target, object value)
{
ValidationUtils.ArgumentNotNull(member, "member");
ValidationUtils.ArgumentNotNull(target, "target");
switch (member.MemberType())
{
case MemberTypes.Field:
((FieldInfo)member).SetValue(target, value);
break;
case MemberTypes.Property:
((PropertyInfo)member).SetValue(target, value, null);
break;
default:
throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), nameof(member));
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be read.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be read.</param>
/// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>.
/// </returns>
public static bool CanReadMemberValue(MemberInfo member, bool nonPublic)
{
switch (member.MemberType())
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (nonPublic)
{
return true;
}
else if (fieldInfo.IsPublic)
{
return true;
}
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)member;
if (!propertyInfo.CanRead)
{
return false;
}
if (nonPublic)
{
return true;
}
return (propertyInfo.GetGetMethod(nonPublic) != null);
default:
return false;
}
}
/// <summary>
/// Determines whether the specified MemberInfo can be set.
/// </summary>
/// <param name="member">The MemberInfo to determine whether can be set.</param>
/// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param>
/// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param>
/// <returns>
/// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>.
/// </returns>
public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly)
{
switch (member.MemberType())
{
case MemberTypes.Field:
FieldInfo fieldInfo = (FieldInfo)member;
if (fieldInfo.IsLiteral)
{
return false;
}
if (fieldInfo.IsInitOnly && !canSetReadOnly)
{
return false;
}
if (nonPublic)
{
return true;
}
if (fieldInfo.IsPublic)
{
return true;
}
return false;
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)member;
if (!propertyInfo.CanWrite)
{
return false;
}
if (nonPublic)
{
return true;
}
return (propertyInfo.GetSetMethod(nonPublic) != null);
default:
return false;
}
}
public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr)
{
List<MemberInfo> targetMembers = new List<MemberInfo>();
targetMembers.AddRange(GetFields(type, bindingAttr));
targetMembers.AddRange(GetProperties(type, bindingAttr));
// for some reason .NET returns multiple members when overriding a generic member on a base class
// http://social.msdn.microsoft.com/Forums/en-US/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/reflection-overriden-abstract-generic-properties?forum=netfxbcl
// filter members to only return the override on the topmost class
// update: I think this is fixed in .NET 3.5 SP1 - leave this in for now...
List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count);
foreach (var groupedMember in targetMembers.GroupBy(m => m.Name))
{
int count = groupedMember.Count();
IList<MemberInfo> members = groupedMember.ToList();
if (count == 1)
{
distinctMembers.Add(members.First());
}
else
{
IList<MemberInfo> resolvedMembers = new List<MemberInfo>();
foreach (MemberInfo memberInfo in members)
{
// this is a bit hacky
// if the hiding property is hiding a base property and it is virtual
// then this ensures the derived property gets used
if (resolvedMembers.Count == 0)
{
resolvedMembers.Add(memberInfo);
}
else if (!IsOverridenGenericMember(memberInfo, bindingAttr) || memberInfo.Name == "Item")
{
resolvedMembers.Add(memberInfo);
}
}
distinctMembers.AddRange(resolvedMembers);
}
}
return distinctMembers;
}
private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr)
{
if (memberInfo.MemberType() != MemberTypes.Property)
{
return false;
}
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
if (!IsVirtual(propertyInfo))
{
return false;
}
Type declaringType = propertyInfo.DeclaringType;
if (!declaringType.IsGenericType())
{
return false;
}
Type genericTypeDefinition = declaringType.GetGenericTypeDefinition();
if (genericTypeDefinition == null)
{
return false;
}
MemberInfo[] members = genericTypeDefinition.GetMember(propertyInfo.Name, bindingAttr);
if (members.Length == 0)
{
return false;
}
Type memberUnderlyingType = GetMemberUnderlyingType(members[0]);
if (!memberUnderlyingType.IsGenericParameter)
{
return false;
}
return true;
}
public static T GetAttribute<T>(object attributeProvider) where T : Attribute
{
return GetAttribute<T>(attributeProvider, true);
}
public static T GetAttribute<T>(object attributeProvider, bool inherit) where T : Attribute
{
T[] attributes = GetAttributes<T>(attributeProvider, inherit);
return (attributes != null) ? attributes.FirstOrDefault() : null;
}
#if !(DOTNET || PORTABLE)
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
Attribute[] a = GetAttributes(attributeProvider, typeof(T), inherit);
T[] attributes = a as T[];
if (attributes != null)
{
return attributes;
}
return a.Cast<T>().ToArray();
}
public static Attribute[] GetAttributes(object attributeProvider, Type attributeType, bool inherit)
{
ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider");
object provider = attributeProvider;
// http://hyperthink.net/blog/getcustomattributes-gotcha/
// ICustomAttributeProvider doesn't do inheritance
if (provider is Type)
{
Type t = (Type)provider;
object[] a = (attributeType != null) ? t.GetCustomAttributes(attributeType, inherit) : t.GetCustomAttributes(inherit);
Attribute[] attributes = a.Cast<Attribute>().ToArray();
#if (NET20 || NET35)
// ye olde .NET GetCustomAttributes doesn't respect the inherit argument
if (inherit && t.BaseType != null)
attributes = attributes.Union(GetAttributes(t.BaseType, attributeType, inherit)).ToArray();
#endif
return attributes;
}
if (provider is Assembly)
{
Assembly a = (Assembly)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(a, attributeType) : Attribute.GetCustomAttributes(a);
}
if (provider is MemberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#if !PORTABLE40
if (provider is Module)
{
Module m = (Module)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(m, attributeType, inherit) : Attribute.GetCustomAttributes(m, inherit);
}
#endif
if (provider is ParameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? Attribute.GetCustomAttributes(p, attributeType, inherit) : Attribute.GetCustomAttributes(p, inherit);
}
#if !PORTABLE40
ICustomAttributeProvider customAttributeProvider = (ICustomAttributeProvider)attributeProvider;
object[] result = (attributeType != null) ? customAttributeProvider.GetCustomAttributes(attributeType, inherit) : customAttributeProvider.GetCustomAttributes(inherit);
return (Attribute[])result;
#else
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
#endif
}
#else
public static T[] GetAttributes<T>(object attributeProvider, bool inherit) where T : Attribute
{
return GetAttributes(attributeProvider, typeof(T), inherit).Cast<T>().ToArray();
}
public static Attribute[] GetAttributes(object provider, Type attributeType, bool inherit)
{
if (provider is Type)
{
Type t = (Type)provider;
return (attributeType != null)
? t.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray()
: t.GetTypeInfo().GetCustomAttributes(inherit).ToArray();
}
if (provider is Assembly)
{
Assembly a = (Assembly)provider;
return (attributeType != null) ? a.GetCustomAttributes(attributeType).ToArray() : a.GetCustomAttributes().ToArray();
}
if (provider is MemberInfo)
{
MemberInfo m = (MemberInfo)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType, inherit).ToArray() : m.GetCustomAttributes(inherit).ToArray();
}
if (provider is Module)
{
Module m = (Module)provider;
return (attributeType != null) ? m.GetCustomAttributes(attributeType).ToArray() : m.GetCustomAttributes().ToArray();
}
if (provider is ParameterInfo)
{
ParameterInfo p = (ParameterInfo)provider;
return (attributeType != null) ? p.GetCustomAttributes(attributeType, inherit).ToArray() : p.GetCustomAttributes(inherit).ToArray();
}
throw new Exception("Cannot get attributes from '{0}'.".FormatWith(CultureInfo.InvariantCulture, provider));
}
#endif
public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName)
{
int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName);
if (assemblyDelimiterIndex != null)
{
typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.GetValueOrDefault()).Trim();
assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.GetValueOrDefault() + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.GetValueOrDefault() - 1).Trim();
}
else
{
typeName = fullyQualifiedTypeName;
assemblyName = null;
}
}
private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName)
{
// we need to get the first comma following all surrounded in brackets because of generic types
// e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
int scope = 0;
for (int i = 0; i < fullyQualifiedTypeName.Length; i++)
{
char current = fullyQualifiedTypeName[i];
switch (current)
{
case '[':
scope++;
break;
case ']':
scope--;
break;
case ',':
if (scope == 0)
{
return i;
}
break;
}
}
return null;
}
public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo)
{
const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
switch (memberInfo.MemberType())
{
case MemberTypes.Property:
PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray();
return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null);
default:
return targetType.GetMember(memberInfo.Name, memberInfo.MemberType(), bindingAttr).SingleOrDefault();
}
}
public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, "targetType");
List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr));
#if !PORTABLE
// Type.GetFields doesn't return inherited private fields
// manually find private fields from base class
GetChildPrivateFields(fieldInfos, targetType, bindingAttr);
#endif
return fieldInfos.Cast<FieldInfo>();
}
#if !PORTABLE
private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private FieldInfos only being returned for the current Type
// find base type fields and add them to result
if ((bindingAttr & BindingFlags.NonPublic) != 0)
{
// modify flags to not search for public fields
BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public);
while ((targetType = targetType.BaseType()) != null)
{
// filter out protected fields
IEnumerable<MemberInfo> childPrivateFields =
targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>();
initialFields.AddRange(childPrivateFields);
}
}
}
#endif
public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr)
{
ValidationUtils.ArgumentNotNull(targetType, "targetType");
List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr));
// GetProperties on an interface doesn't return properties from its interfaces
if (targetType.IsInterface())
{
foreach (Type i in targetType.GetInterfaces())
{
propertyInfos.AddRange(i.GetProperties(bindingAttr));
}
}
GetChildPrivateProperties(propertyInfos, targetType, bindingAttr);
// a base class private getter/setter will be inaccessable unless the property was gotten from the base class
for (int i = 0; i < propertyInfos.Count; i++)
{
PropertyInfo member = propertyInfos[i];
if (member.DeclaringType != targetType)
{
PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member);
propertyInfos[i] = declaredMember;
}
}
return propertyInfos;
}
public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag)
{
return ((bindingAttr & flag) == flag)
? bindingAttr ^ flag
: bindingAttr;
}
private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr)
{
// fix weirdness with private PropertyInfos only being returned for the current Type
// find base type properties and add them to result
// also find base properties that have been hidden by subtype properties with the same name
while ((targetType = targetType.BaseType()) != null)
{
foreach (PropertyInfo propertyInfo in targetType.GetProperties(bindingAttr))
{
PropertyInfo subTypeProperty = propertyInfo;
if (!IsPublic(subTypeProperty))
{
// have to test on name rather than reference because instances are different
// depending on the type that GetProperties was called on
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
else
{
PropertyInfo childProperty = initialProperties[index];
// don't replace public child with private base
if (!IsPublic(childProperty))
{
// replace nonpublic properties for a child, but gotten from
// the parent with the one from the child
// the property gotten from the child will have access to private getter/setter
initialProperties[index] = subTypeProperty;
}
}
}
else
{
if (!subTypeProperty.IsVirtual())
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.DeclaringType == subTypeProperty.DeclaringType);
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
else
{
int index = initialProperties.IndexOf(p => p.Name == subTypeProperty.Name
&& p.IsVirtual()
&& p.GetBaseDefinition() != null
&& p.GetBaseDefinition().DeclaringType.IsAssignableFrom(subTypeProperty.GetBaseDefinition().DeclaringType));
if (index == -1)
{
initialProperties.Add(subTypeProperty);
}
}
}
}
}
}
public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method)
{
bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Any(info =>
info.Name == method &&
// check that the method overrides the original on DynamicObjectProxy
info.DeclaringType != methodDeclaringType
&& info.GetBaseDefinition().DeclaringType == methodDeclaringType
);
return isMethodOverriden;
}
public static object GetDefaultValue(Type type)
{
if (!type.IsValueType())
{
return null;
}
switch (ConvertUtils.GetTypeCode(type))
{
case PrimitiveTypeCode.Boolean:
return false;
case PrimitiveTypeCode.Char:
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
return 0;
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
return 0L;
case PrimitiveTypeCode.Single:
return 0f;
case PrimitiveTypeCode.Double:
return 0.0;
case PrimitiveTypeCode.Decimal:
return 0m;
case PrimitiveTypeCode.DateTime:
return new DateTime();
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
return new BigInteger();
#endif
case PrimitiveTypeCode.Guid:
return new Guid();
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
return new DateTimeOffset();
#endif
}
if (IsNullable(type))
{
return null;
}
// possibly use IL initobj for perf here?
return Activator.CreateInstance(type);
}
}
}
| |
//
// TestBatcherSingleBatch.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// 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 (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections.Generic;
using Couchbase.Lite;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Support
{
public class BatcherTest : LiteTestCase
{
/// <exception cref="System.Exception"></exception>
public virtual void TestBatcherSingleBatch()
{
CountDownLatch doneSignal = new CountDownLatch(10);
ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1);
int inboxCapacity = 10;
int processorDelay = 1000;
Batcher batcher = new Batcher<string>(workExecutor, inboxCapacity, processorDelay
, new _BatchProcessor_25(doneSignal));
// add this to make it a bit more realistic
AList<string> objectsToQueue = new AList<string>();
for (int i = 0; i < inboxCapacity * 10; i++)
{
objectsToQueue.AddItem(Sharpen.Extensions.ToString(i));
}
batcher.QueueObjects(objectsToQueue);
bool didNotTimeOut = doneSignal.Await(5, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(didNotTimeOut);
}
private sealed class _BatchProcessor_25 : BatchProcessor<string>
{
public _BatchProcessor_25(CountDownLatch doneSignal)
{
this.doneSignal = doneSignal;
}
public void Process(IList<string> itemsToProcess)
{
Log.V(Database.Tag, "process called with: " + itemsToProcess);
try
{
Sharpen.Thread.Sleep(100);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
BatcherTest.AssertNumbersConsecutive(itemsToProcess);
doneSignal.CountDown();
}
private readonly CountDownLatch doneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestBatcherBatchSize5()
{
CountDownLatch doneSignal = new CountDownLatch(10);
ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1);
int inboxCapacity = 10;
int processorDelay = 1000;
Batcher batcher = new Batcher<string>(workExecutor, inboxCapacity, processorDelay
, new _BatchProcessor_64(processorDelay, doneSignal));
// add this to make it a bit more realistic
AList<string> objectsToQueue = new AList<string>();
for (int i = 0; i < inboxCapacity * 10; i++)
{
objectsToQueue.AddItem(Sharpen.Extensions.ToString(i));
if (objectsToQueue.Count == 5)
{
batcher.QueueObjects(objectsToQueue);
objectsToQueue = new AList<string>();
}
}
bool didNotTimeOut = doneSignal.Await(35, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(didNotTimeOut);
}
private sealed class _BatchProcessor_64 : BatchProcessor<string>
{
public _BatchProcessor_64(int processorDelay, CountDownLatch doneSignal)
{
this.processorDelay = processorDelay;
this.doneSignal = doneSignal;
}
public void Process(IList<string> itemsToProcess)
{
Log.V(Database.Tag, "process called with: " + itemsToProcess);
try
{
Sharpen.Thread.Sleep(processorDelay * 2);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
BatcherTest.AssertNumbersConsecutive(itemsToProcess);
doneSignal.CountDown();
}
private readonly int processorDelay;
private readonly CountDownLatch doneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestBatcherBatchSize1()
{
CountDownLatch doneSignal = new CountDownLatch(1);
ScheduledExecutorService workExecutor = new ScheduledThreadPoolExecutor(1);
int inboxCapacity = 100;
int processorDelay = 1000;
Batcher batcher = new Batcher<string>(workExecutor, inboxCapacity, processorDelay
, new _BatchProcessor_106(processorDelay, doneSignal));
// add this to make it a bit more realistic
AList<string> objectsToQueue = new AList<string>();
for (int i = 0; i < inboxCapacity; i++)
{
objectsToQueue.AddItem(Sharpen.Extensions.ToString(i));
if (objectsToQueue.Count == 5)
{
batcher.QueueObjects(objectsToQueue);
objectsToQueue = new AList<string>();
}
}
bool didNotTimeOut = doneSignal.Await(35, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(didNotTimeOut);
}
private sealed class _BatchProcessor_106 : BatchProcessor<string>
{
public _BatchProcessor_106(int processorDelay, CountDownLatch doneSignal)
{
this.processorDelay = processorDelay;
this.doneSignal = doneSignal;
}
public void Process(IList<string> itemsToProcess)
{
Log.V(Database.Tag, "process called with: " + itemsToProcess);
try
{
Sharpen.Thread.Sleep(processorDelay * 2);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
BatcherTest.AssertNumbersConsecutive(itemsToProcess);
doneSignal.CountDown();
}
private readonly int processorDelay;
private readonly CountDownLatch doneSignal;
}
private static void AssertNumbersConsecutive(IList<string> itemsToProcess)
{
int previousItemNumber = -1;
foreach (string itemString in itemsToProcess)
{
if (previousItemNumber == -1)
{
previousItemNumber = System.Convert.ToInt32(itemString);
}
else
{
int curItemNumber = System.Convert.ToInt32(itemString);
NUnit.Framework.Assert.IsTrue(curItemNumber == previousItemNumber + 1);
previousItemNumber = curItemNumber;
}
}
}
}
}
| |
/*
* Location Intelligence APIs
*
* Incorporate our extensive geodata into everyday applications, business processes and workflows.
*
* OpenAPI spec version: 8.5.0
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace pb.locationIntelligence.Model
{
/// <summary>
/// GeocodeAddress
/// </summary>
[DataContract]
public partial class GeocodeAddress : IEquatable<GeocodeAddress>
{
/// <summary>
/// Initializes a new instance of the <see cref="GeocodeAddress" /> class.
/// </summary>
/// <param name="MainAddressLine">MainAddressLine.</param>
/// <param name="AddressLastLine">AddressLastLine.</param>
/// <param name="PlaceName">PlaceName.</param>
/// <param name="AreaName1">AreaName1.</param>
/// <param name="AreaName2">AreaName2.</param>
/// <param name="AreaName3">AreaName3.</param>
/// <param name="AreaName4">AreaName4.</param>
/// <param name="PostCode1">PostCode1.</param>
/// <param name="PostCode2">PostCode2.</param>
/// <param name="Country">Country.</param>
/// <param name="AddressNumber">AddressNumber.</param>
/// <param name="StreetName">StreetName.</param>
/// <param name="UnitType">UnitType.</param>
/// <param name="UnitValue">UnitValue.</param>
/// <param name="CustomFields">CustomFields.</param>
public GeocodeAddress(string MainAddressLine = null, string AddressLastLine = null, string PlaceName = null, string AreaName1 = null, string AreaName2 = null, string AreaName3 = null, string AreaName4 = null, string PostCode1 = null, string PostCode2 = null, string Country = null, string AddressNumber = null, string StreetName = null, string UnitType = null, string UnitValue = null, Dictionary<string, Object> CustomFields = null)
{
this.MainAddressLine = MainAddressLine;
this.AddressLastLine = AddressLastLine;
this.PlaceName = PlaceName;
this.AreaName1 = AreaName1;
this.AreaName2 = AreaName2;
this.AreaName3 = AreaName3;
this.AreaName4 = AreaName4;
this.PostCode1 = PostCode1;
this.PostCode2 = PostCode2;
this.Country = Country;
this.AddressNumber = AddressNumber;
this.StreetName = StreetName;
this.UnitType = UnitType;
this.UnitValue = UnitValue;
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets MainAddressLine
/// </summary>
[DataMember(Name="mainAddressLine", EmitDefaultValue=false)]
public string MainAddressLine { get; set; }
/// <summary>
/// Gets or Sets AddressLastLine
/// </summary>
[DataMember(Name="addressLastLine", EmitDefaultValue=false)]
public string AddressLastLine { get; set; }
/// <summary>
/// Gets or Sets PlaceName
/// </summary>
[DataMember(Name="placeName", EmitDefaultValue=false)]
public string PlaceName { get; set; }
/// <summary>
/// Gets or Sets AreaName1
/// </summary>
[DataMember(Name="areaName1", EmitDefaultValue=false)]
public string AreaName1 { get; set; }
/// <summary>
/// Gets or Sets AreaName2
/// </summary>
[DataMember(Name="areaName2", EmitDefaultValue=false)]
public string AreaName2 { get; set; }
/// <summary>
/// Gets or Sets AreaName3
/// </summary>
[DataMember(Name="areaName3", EmitDefaultValue=false)]
public string AreaName3 { get; set; }
/// <summary>
/// Gets or Sets AreaName4
/// </summary>
[DataMember(Name="areaName4", EmitDefaultValue=false)]
public string AreaName4 { get; set; }
/// <summary>
/// Gets or Sets PostCode1
/// </summary>
[DataMember(Name="postCode1", EmitDefaultValue=false)]
public string PostCode1 { get; set; }
/// <summary>
/// Gets or Sets PostCode2
/// </summary>
[DataMember(Name="postCode2", EmitDefaultValue=false)]
public string PostCode2 { get; set; }
/// <summary>
/// Gets or Sets Country
/// </summary>
[DataMember(Name="country", EmitDefaultValue=false)]
public string Country { get; set; }
/// <summary>
/// Gets or Sets AddressNumber
/// </summary>
[DataMember(Name="addressNumber", EmitDefaultValue=false)]
public string AddressNumber { get; set; }
/// <summary>
/// Gets or Sets StreetName
/// </summary>
[DataMember(Name="streetName", EmitDefaultValue=false)]
public string StreetName { get; set; }
/// <summary>
/// Gets or Sets UnitType
/// </summary>
[DataMember(Name="unitType", EmitDefaultValue=false)]
public string UnitType { get; set; }
/// <summary>
/// Gets or Sets UnitValue
/// </summary>
[DataMember(Name="unitValue", EmitDefaultValue=false)]
public string UnitValue { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class GeocodeAddress {\n");
sb.Append(" MainAddressLine: ").Append(MainAddressLine).Append("\n");
sb.Append(" AddressLastLine: ").Append(AddressLastLine).Append("\n");
sb.Append(" PlaceName: ").Append(PlaceName).Append("\n");
sb.Append(" AreaName1: ").Append(AreaName1).Append("\n");
sb.Append(" AreaName2: ").Append(AreaName2).Append("\n");
sb.Append(" AreaName3: ").Append(AreaName3).Append("\n");
sb.Append(" AreaName4: ").Append(AreaName4).Append("\n");
sb.Append(" PostCode1: ").Append(PostCode1).Append("\n");
sb.Append(" PostCode2: ").Append(PostCode2).Append("\n");
sb.Append(" Country: ").Append(Country).Append("\n");
sb.Append(" AddressNumber: ").Append(AddressNumber).Append("\n");
sb.Append(" StreetName: ").Append(StreetName).Append("\n");
sb.Append(" UnitType: ").Append(UnitType).Append("\n");
sb.Append(" UnitValue: ").Append(UnitValue).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as GeocodeAddress);
}
/// <summary>
/// Returns true if GeocodeAddress instances are equal
/// </summary>
/// <param name="other">Instance of GeocodeAddress to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GeocodeAddress other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.MainAddressLine == other.MainAddressLine ||
this.MainAddressLine != null &&
this.MainAddressLine.Equals(other.MainAddressLine)
) &&
(
this.AddressLastLine == other.AddressLastLine ||
this.AddressLastLine != null &&
this.AddressLastLine.Equals(other.AddressLastLine)
) &&
(
this.PlaceName == other.PlaceName ||
this.PlaceName != null &&
this.PlaceName.Equals(other.PlaceName)
) &&
(
this.AreaName1 == other.AreaName1 ||
this.AreaName1 != null &&
this.AreaName1.Equals(other.AreaName1)
) &&
(
this.AreaName2 == other.AreaName2 ||
this.AreaName2 != null &&
this.AreaName2.Equals(other.AreaName2)
) &&
(
this.AreaName3 == other.AreaName3 ||
this.AreaName3 != null &&
this.AreaName3.Equals(other.AreaName3)
) &&
(
this.AreaName4 == other.AreaName4 ||
this.AreaName4 != null &&
this.AreaName4.Equals(other.AreaName4)
) &&
(
this.PostCode1 == other.PostCode1 ||
this.PostCode1 != null &&
this.PostCode1.Equals(other.PostCode1)
) &&
(
this.PostCode2 == other.PostCode2 ||
this.PostCode2 != null &&
this.PostCode2.Equals(other.PostCode2)
) &&
(
this.Country == other.Country ||
this.Country != null &&
this.Country.Equals(other.Country)
) &&
(
this.AddressNumber == other.AddressNumber ||
this.AddressNumber != null &&
this.AddressNumber.Equals(other.AddressNumber)
) &&
(
this.StreetName == other.StreetName ||
this.StreetName != null &&
this.StreetName.Equals(other.StreetName)
) &&
(
this.UnitType == other.UnitType ||
this.UnitType != null &&
this.UnitType.Equals(other.UnitType)
) &&
(
this.UnitValue == other.UnitValue ||
this.UnitValue != null &&
this.UnitValue.Equals(other.UnitValue)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.MainAddressLine != null)
hash = hash * 59 + this.MainAddressLine.GetHashCode();
if (this.AddressLastLine != null)
hash = hash * 59 + this.AddressLastLine.GetHashCode();
if (this.PlaceName != null)
hash = hash * 59 + this.PlaceName.GetHashCode();
if (this.AreaName1 != null)
hash = hash * 59 + this.AreaName1.GetHashCode();
if (this.AreaName2 != null)
hash = hash * 59 + this.AreaName2.GetHashCode();
if (this.AreaName3 != null)
hash = hash * 59 + this.AreaName3.GetHashCode();
if (this.AreaName4 != null)
hash = hash * 59 + this.AreaName4.GetHashCode();
if (this.PostCode1 != null)
hash = hash * 59 + this.PostCode1.GetHashCode();
if (this.PostCode2 != null)
hash = hash * 59 + this.PostCode2.GetHashCode();
if (this.Country != null)
hash = hash * 59 + this.Country.GetHashCode();
if (this.AddressNumber != null)
hash = hash * 59 + this.AddressNumber.GetHashCode();
if (this.StreetName != null)
hash = hash * 59 + this.StreetName.GetHashCode();
if (this.UnitType != null)
hash = hash * 59 + this.UnitType.GetHashCode();
if (this.UnitValue != null)
hash = hash * 59 + this.UnitValue.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
// ============================================================
// Name: UMABonePoseBuildWindow
// Author: Eli Curtz
// Copyright: (c) 2013 Eli Curtz
// ============================================================
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace UMA.PoseTools
{
public class UMABonePoseBuildWindow : EditorWindow
{
public Transform sourceSkeleton;
public UnityEngine.Object poseFolder;
private Transform poseSkeleton;
private string skelPoseID;
private bool skelOpen;
private AnimationClip poseAnimation;
public class AnimationPose
{
[XmlAttribute("ID")]
public string ID = "";
public int frame = 0;
}
private List<AnimationPose> poses;
private bool animOpen;
private Vector2 scrollPosition;
public void SavePoseSet()
{
string folderPath = "";
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else if (poseAnimation != null)
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
string filePath = EditorUtility.SaveFilePanel("Save pose set", folderPath, poseAnimation.name + "_Poses.xml", "xml");
if (filePath.Length != 0)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AnimationPose>));
using (var stream = new FileStream(filePath, FileMode.Create))
{
serializer.Serialize(stream, poses);
}
}
}
public void LoadPoseSet()
{
string folderPath = "";
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else if (poseAnimation != null)
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
string filePath = EditorUtility.OpenFilePanel("Load pose set", folderPath, "xml");
if (filePath.Length != 0)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<AnimationPose>));
using (var stream = new FileStream(filePath, FileMode.Open))
{
poses = serializer.Deserialize(stream) as List<AnimationPose>;
}
}
}
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = AssetDatabase.LoadMainAssetAtPath(destpath);
}
}
}
void OnGUI()
{
sourceSkeleton = EditorGUILayout.ObjectField("Rig Prefab", sourceSkeleton, typeof(Transform), true) as Transform;
poseFolder = EditorGUILayout.ObjectField("Pose Folder", poseFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
EnforceFolder(ref poseFolder);
EditorGUILayout.Space();
// Single pose from skeleton
if (skelOpen = EditorGUILayout.Foldout(skelOpen, "Rig Source"))
{
EditorGUI.indentLevel++;
poseSkeleton = EditorGUILayout.ObjectField("Pose Rig", poseSkeleton, typeof(Transform), false) as Transform;
skelPoseID = EditorGUILayout.TextField("ID", skelPoseID);
if ((sourceSkeleton == null) || (poseSkeleton == null) || (skelPoseID == null) || (skelPoseID.Length < 1))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build Pose"))
{
string folderPath;
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
UMABonePose bonePose = CreatePoseAsset(folderPath, skelPoseID);
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(sourceSkeleton);
Transform[] poseBones = UMABonePose.GetTransformsInPrefab(poseSkeleton);
List<UMABonePose.PoseBone> poseList = new List<UMABonePose.PoseBone>();
foreach (Transform bone in poseBones)
{
Transform source = System.Array.Find<Transform>(sourceBones, entry => entry.name == bone.name);
if (source)
{
if ((bone.localPosition != source.localPosition) ||
(bone.localRotation != source.localRotation) ||
(bone.localScale != source.localScale))
{
UMABonePose.PoseBone poseB = new UMABonePose.PoseBone();
poseB.bone = bone.name;
poseB.position = bone.localPosition - source.localPosition;
poseB.rotation = bone.localRotation * Quaternion.Inverse(source.localRotation);
poseB.scale = new Vector3(bone.localScale.x / source.localScale.x,
bone.localScale.y / source.localScale.y,
bone.localScale.z / source.localScale.z);
poseList.Add(poseB);
}
}
else
{
Debug.Log("Unmatched bone: " + bone.name);
}
}
bonePose.poses = poseList.ToArray();
EditorUtility.SetDirty(bonePose);
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
// Multiple poses from animation frames
if (animOpen = EditorGUILayout.Foldout(animOpen, "Animation Source"))
{
EditorGUI.indentLevel++;
poseAnimation = EditorGUILayout.ObjectField("Pose Animation", poseAnimation, typeof(AnimationClip), false) as AnimationClip;
if (poses == null)
{
poses = new List<AnimationPose>();
poses.Add(new AnimationPose());
}
bool validPose = false;
AnimationPose deletedPose = null;
scrollPosition = GUILayout.BeginScrollView(scrollPosition);
foreach (AnimationPose pose in poses)
{
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("ID", GUILayout.Width(50f));
pose.ID = EditorGUILayout.TextField(pose.ID);
EditorGUILayout.LabelField("Frame", GUILayout.Width(60f));
pose.frame = EditorGUILayout.IntField(pose.frame, GUILayout.Width(50f));
if ((pose.ID != null) && (pose.ID.Length > 0))
{
validPose = true;
}
if (GUILayout.Button("-", GUILayout.Width(20f)))
{
deletedPose = pose;
validPose = false;
break;
}
GUILayout.EndHorizontal();
}
if (deletedPose != null)
{
poses.Remove(deletedPose);
}
GUILayout.EndScrollView();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("+", GUILayout.Width(30f)))
{
poses.Add(new AnimationPose());
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Load Pose Set"))
{
LoadPoseSet();
}
if (!validPose)
{
GUI.enabled = false;
}
if (GUILayout.Button("Save Pose Set"))
{
SavePoseSet();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
if ((sourceSkeleton == null) || (poseAnimation == null) || (!validPose))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build Poses"))
{
string folderPath;
if (poseFolder != null)
{
folderPath = AssetDatabase.GetAssetPath(poseFolder);
}
else
{
folderPath = AssetDatabase.GetAssetPath(poseAnimation);
folderPath = folderPath.Substring(0, folderPath.LastIndexOf('/'));
}
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(sourceSkeleton);
EditorCurveBinding[] bindings = AnimationUtility.GetCurveBindings(poseAnimation);
Dictionary<string, Vector3> positions = new Dictionary<string, Vector3>();
Dictionary<string, Quaternion> rotations = new Dictionary<string, Quaternion>();
Dictionary<string, Vector3> scales = new Dictionary<string, Vector3>();
foreach (AnimationPose pose in poses)
{
if ((pose.ID == null) || (pose.ID.Length < 1))
{
Debug.LogWarning("Bad pose identifier, not building for frame: " + pose.frame);
continue;
}
float time = (float)pose.frame / poseAnimation.frameRate;
if ((time < 0f) || (time > poseAnimation.length))
{
Debug.LogWarning("Bad frame number, not building for pose: " + pose.ID);
continue;
}
positions.Clear();
rotations.Clear();
scales.Clear();
foreach (EditorCurveBinding binding in bindings)
{
if (binding.type == typeof(Transform))
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(poseAnimation, binding);
float val = curve.Evaluate(time);
Vector3 position;
Quaternion rotation;
Vector3 scale;
switch (binding.propertyName)
{
case "m_LocalPosition.x":
if (positions.TryGetValue(binding.path, out position))
{
position.x = val;
positions[binding.path] = position;
}
else
{
position = new Vector3();
position.x = val;
positions.Add(binding.path, position);
}
break;
case "m_LocalPosition.y":
if (positions.TryGetValue(binding.path, out position))
{
position.y = val;
positions[binding.path] = position;
}
else
{
position = new Vector3();
position.y = val;
positions.Add(binding.path, position);
}
break;
case "m_LocalPosition.z":
if (positions.TryGetValue(binding.path, out position))
{
position.z = val;
positions[binding.path] = position;
}
else
{
position = new Vector3();
position.z = val;
positions.Add(binding.path, position);
}
break;
case "m_LocalRotation.w":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.w = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.w = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalRotation.x":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.x = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.x = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalRotation.y":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.y = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.y = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalRotation.z":
if (rotations.TryGetValue(binding.path, out rotation))
{
rotation.z = val;
rotations[binding.path] = rotation;
}
else
{
rotation = new Quaternion();
rotation.z = val;
rotations.Add(binding.path, rotation);
}
break;
case "m_LocalScale.x":
if (scales.TryGetValue(binding.path, out scale))
{
scale.x = val;
scales[binding.path] = scale;
}
else
{
scale = new Vector3();
scale.x = val;
scales.Add(binding.path, scale);
}
break;
case "m_LocalScale.y":
if (scales.TryGetValue(binding.path, out scale))
{
scale.y = val;
scales[binding.path] = scale;
}
else
{
scale = new Vector3();
scale.y = val;
scales.Add(binding.path, scale);
}
break;
case "m_LocalScale.z":
if (scales.TryGetValue(binding.path, out scale))
{
scale.z = val;
scales[binding.path] = scale;
}
else
{
scale = new Vector3();
scale.z = val;
scales.Add(binding.path, scale);
}
break;
default:
Debug.LogError("Unexpected property:" + binding.propertyName);
break;
}
}
}
UMABonePose bonePose = CreatePoseAsset(folderPath, pose.ID);
foreach (Transform bone in sourceBones)
{
string path = AnimationUtility.CalculateTransformPath(bone, sourceSkeleton.parent);
Vector3 position;
Quaternion rotation;
Vector3 scale;
if (!positions.TryGetValue(path, out position))
{
position = bone.localPosition;
}
if (!rotations.TryGetValue(path, out rotation))
{
rotation = bone.localRotation;
}
if (!scales.TryGetValue(path, out scale))
{
scale = bone.localScale;
}
if ((bone.localPosition != position) ||
(bone.localRotation != rotation) ||
(bone.localScale != scale))
{
bonePose.AddBone(bone, position, rotation, scale);
}
}
EditorUtility.SetDirty(bonePose);
}
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
EditorGUI.indentLevel--;
}
}
public static UMABonePose CreatePoseAsset(string assetFolder, string assetName)
{
if (!System.IO.Directory.Exists(assetFolder))
{
System.IO.Directory.CreateDirectory(assetFolder);
}
UMABonePose asset = ScriptableObject.CreateInstance<UMABonePose>();
AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset");
AssetDatabase.SaveAssets();
return asset;
}
[MenuItem("UMA/Pose Tools/UMA Bone Pose Builder")]
public static void OpenUMABonePoseBuildWindow()
{
EditorWindow win = EditorWindow.GetWindow(typeof(UMABonePoseBuildWindow));
#if !UNITY_4_6 && !UNITY_5_0
win.titleContent.text = "Pose Builder";
#else
win.title = "Pose Builder";
#endif
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.CommandLine;
using System.Runtime.InteropServices;
using Internal.IL;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.CommandLine;
namespace ILCompiler
{
internal class Program
{
private const string DefaultSystemModule = "System.Private.CoreLib";
private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private string _outputFilePath;
private bool _isInputVersionBubble;
private bool _includeGenericsFromVersionBubble;
private bool _isVerbose;
private string _dgmlLogFileName;
private bool _generateFullDgmlLog;
private TargetArchitecture _targetArchitecture;
private string _targetArchitectureStr;
private TargetOS _targetOS;
private string _targetOSStr;
private string _jitPath;
private OptimizationMode _optimizationMode;
private string _systemModuleName = DefaultSystemModule;
private bool _tuning;
private bool _partial;
private bool _resilient;
private string _singleMethodTypeName;
private string _singleMethodName;
private IReadOnlyList<string> _singleMethodGenericArgs;
private IReadOnlyList<string> _codegenOptions = Array.Empty<string>();
private bool _help;
private Program()
{
}
private void Help(string helpText)
{
Console.WriteLine();
Console.Write("Microsoft (R) CoreCLR Native Image Generator");
Console.Write(" ");
Console.Write(typeof(Program).GetTypeInfo().Assembly.GetName().Version);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(helpText);
}
private void InitializeDefaultOptions()
{
// We could offer this as a command line option, but then we also need to
// load a different RyuJIT, so this is a future nice to have...
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
_targetOS = TargetOS.Windows;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
_targetOS = TargetOS.Linux;
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
_targetOS = TargetOS.OSX;
else
throw new NotImplementedException();
switch (RuntimeInformation.ProcessArchitecture)
{
case Architecture.X86:
_targetArchitecture = TargetArchitecture.X86;
break;
case Architecture.X64:
_targetArchitecture = TargetArchitecture.X64;
break;
case Architecture.Arm:
_targetArchitecture = TargetArchitecture.ARM;
break;
case Architecture.Arm64:
_targetArchitecture = TargetArchitecture.ARM64;
break;
default:
throw new NotImplementedException();
}
// Workaround for https://github.com/dotnet/corefx/issues/25267
// If pointer size is 8, we're obviously not an X86 process...
if (_targetArchitecture == TargetArchitecture.X86 && IntPtr.Size == 8)
_targetArchitecture = TargetArchitecture.X64;
}
private ArgumentSyntax ParseCommandLine(string[] args)
{
IReadOnlyList<string> inputFiles = Array.Empty<string>();
IReadOnlyList<string> referenceFiles = Array.Empty<string>();
bool optimize = false;
bool optimizeSpace = false;
bool optimizeTime = false;
bool waitForDebugger = false;
AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName();
ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax =>
{
syntax.ApplicationName = name.Name.ToString();
// HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting.
syntax.HandleHelp = false;
syntax.HandleErrors = true;
syntax.DefineOption("h|help", ref _help, "Help message for ILC");
syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation");
syntax.DefineOption("o|out", ref _outputFilePath, "Output file path");
syntax.DefineOption("O", ref optimize, "Enable optimizations");
syntax.DefineOption("Os", ref optimizeSpace, "Enable optimizations, favor code space");
syntax.DefineOption("Ot", ref optimizeTime, "Enable optimizations, favor code speed");
syntax.DefineOption("inputbubble", ref _isInputVersionBubble, "True when the entire input forms a version bubble (default = per-assembly bubble)");
syntax.DefineOption("tuning", ref _tuning, "Generate IBC tuning image");
syntax.DefineOption("partial", ref _partial, "Generate partial image driven by profile");
syntax.DefineOption("compilebubblegenerics", ref _includeGenericsFromVersionBubble, "Compile instantiations from reference modules used in the current module");
syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML");
syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis");
syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging");
syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)");
syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger");
syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option");
syntax.DefineOption("resilient", ref _resilient, "Disable behavior where unexpected compilation failures cause overall compilation failure");
syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation");
syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation");
syntax.DefineOption("jitpath", ref _jitPath, "Path to JIT compiler library");
syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type");
syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method");
syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method");
syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile");
});
if (waitForDebugger)
{
Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue");
Console.ReadLine();
}
if (_includeGenericsFromVersionBubble)
{
if (!_isInputVersionBubble)
{
Console.WriteLine("Warning: ignoring --compilebubblegenerics because --inputbubble was not specified");
_includeGenericsFromVersionBubble = false;
}
}
_optimizationMode = OptimizationMode.None;
if (optimizeSpace)
{
if (optimizeTime)
Console.WriteLine("Warning: overriding -Ot with -Os");
_optimizationMode = OptimizationMode.PreferSize;
}
else if (optimizeTime)
_optimizationMode = OptimizationMode.PreferSpeed;
else if (optimize)
_optimizationMode = OptimizationMode.Blended;
foreach (var input in inputFiles)
Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
foreach (var reference in referenceFiles)
Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
return argSyntax;
}
private int Run(string[] args)
{
InitializeDefaultOptions();
ArgumentSyntax syntax = ParseCommandLine(args);
if (_help)
{
Help(syntax.GetHelpText());
return 1;
}
if (_outputFilePath == null)
throw new CommandLineException("Output filename must be specified (/out <file>)");
//
// Set target Architecture and OS
//
if (_targetArchitectureStr != null)
{
if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.X86;
else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.X64;
else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARM;
else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARM;
else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase))
_targetArchitecture = TargetArchitecture.ARM64;
else
throw new CommandLineException("Target architecture is not supported");
}
if (_targetOSStr != null)
{
if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.Windows;
else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.Linux;
else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase))
_targetOS = TargetOS.OSX;
else
throw new CommandLineException("Target OS is not supported");
}
using (PerfEventSource.StartStopEvents.CompilationEvents())
{
ICompilation compilation;
using (PerfEventSource.StartStopEvents.LoadingEvents())
{
//
// Initialize type system context
//
SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes;
var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, SimdVectorLength.None);
CompilerTypeSystemContext typeSystemContext = new ReadyToRunCompilerContext(targetDetails, genericsMode);
//
// TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since
// some tests contain a mixture of both managed and native binaries.
//
// See: https://github.com/dotnet/corert/issues/2785
//
// When we undo this this hack, replace this foreach with
// typeSystemContext.InputFilePaths = _inputFilePaths;
//
Dictionary<string, string> inputFilePaths = new Dictionary<string, string>();
foreach (var inputFile in _inputFilePaths)
{
try
{
var module = typeSystemContext.GetModuleFromPath(inputFile.Value);
inputFilePaths.Add(inputFile.Key, inputFile.Value);
}
catch (TypeSystemException.BadImageFormatException)
{
// Keep calm and carry on.
}
}
typeSystemContext.InputFilePaths = inputFilePaths;
typeSystemContext.ReferenceFilePaths = _referenceFilePaths;
typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName));
if (typeSystemContext.InputFilePaths.Count == 0)
throw new CommandLineException("No input files specified");
//
// Initialize compilation group and compilation roots
//
// Single method mode?
MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext);
var logger = new Logger(Console.Out, _isVerbose);
List<ModuleDesc> referenceableModules = new List<ModuleDesc>();
foreach (var inputFile in inputFilePaths)
{
try
{
referenceableModules.Add(typeSystemContext.GetModuleFromPath(inputFile.Value));
}
catch { } // Ignore non-managed pe files
}
foreach (var referenceFile in _referenceFilePaths.Values)
{
try
{
referenceableModules.Add(typeSystemContext.GetModuleFromPath(referenceFile));
}
catch { } // Ignore non-managed pe files
}
ProfileDataManager profileDataManager = new ProfileDataManager(logger, referenceableModules);
CompilationModuleGroup compilationGroup;
List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>();
if (singleMethod != null)
{
// Compiling just a single method
compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod);
compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
}
else
{
// Either single file, or multifile library, or multifile consumption.
EcmaModule entrypointModule = null;
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
if (module.PEReader.PEHeaders.IsExe)
{
if (entrypointModule != null)
throw new Exception("Multiple EXE modules");
entrypointModule = module;
}
}
List<EcmaModule> inputModules = new List<EcmaModule>();
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
compilationRoots.Add(new ReadyToRunRootProvider(module, profileDataManager));
inputModules.Add(module);
if (!_isInputVersionBubble)
{
break;
}
}
List<ModuleDesc> versionBubbleModules = new List<ModuleDesc>();
if (_isInputVersionBubble)
{
// In large version bubble mode add reference paths to the compilation group
foreach (string referenceFile in _referenceFilePaths.Values)
{
try
{
// Currently SimpleTest.targets has no easy way to filter out non-managed assemblies
// from the reference list.
EcmaModule module = typeSystemContext.GetModuleFromPath(referenceFile);
versionBubbleModules.Add(module);
}
catch (TypeSystemException.BadImageFormatException ex)
{
Console.WriteLine("Warning: cannot open reference assembly '{0}': {1}", referenceFile, ex.Message);
}
}
}
compilationGroup = new ReadyToRunSingleAssemblyCompilationModuleGroup(
typeSystemContext, inputModules, versionBubbleModules, _includeGenericsFromVersionBubble,
_partial ? profileDataManager : null);
}
//
// Compile
//
string inputFilePath = "";
foreach (var input in typeSystemContext.InputFilePaths)
{
inputFilePath = input.Value;
break;
}
CompilationBuilder builder = new ReadyToRunCodegenCompilationBuilder(typeSystemContext, compilationGroup, inputFilePath,
ibcTuning: _tuning,
resilient: _resilient);
string compilationUnitPrefix = "";
builder.UseCompilationUnitPrefix(compilationUnitPrefix);
ILProvider ilProvider = new ReadyToRunILProvider();
DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ?
DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);
builder
.UseILProvider(ilProvider)
.UseJitPath(_jitPath)
.UseBackendOptions(_codegenOptions)
.UseLogger(logger)
.UseDependencyTracking(trackingLevel)
.UseCompilationRoots(compilationRoots)
.UseOptimizationMode(_optimizationMode);
compilation = builder.ToCompilation();
}
compilation.Compile(_outputFilePath);
}
return 0;
}
private TypeDesc FindType(CompilerTypeSystemContext context, string typeName)
{
ModuleDesc systemModule = context.SystemModule;
TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName, false, (typeDefName, module, throwIfNotFound) =>
{
return (MetadataType)context.GetCanonType(typeDefName)
?? CustomAttributeTypeNameParser.ResolveCustomAttributeTypeDefinitionName(typeDefName, module, throwIfNotFound);
});
if (foundType == null)
throw new CommandLineException($"Type '{typeName}' not found");
return foundType;
}
private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context)
{
if (_singleMethodName == null && _singleMethodTypeName == null && _singleMethodGenericArgs == null)
return null;
if (_singleMethodName == null || _singleMethodTypeName == null)
throw new CommandLineException("Both method name and type name are required parameters for single method mode");
TypeDesc owningType = FindType(context, _singleMethodTypeName);
// TODO: allow specifying signature to distinguish overloads
MethodDesc method = owningType.GetMethod(_singleMethodName, null);
if (method == null)
throw new CommandLineException($"Method '{_singleMethodName}' not found in '{_singleMethodTypeName}'");
if (method.HasInstantiation != (_singleMethodGenericArgs != null) ||
(method.HasInstantiation && (method.Instantiation.Length != _singleMethodGenericArgs.Count)))
{
throw new CommandLineException(
$"Expected {method.Instantiation.Length} generic arguments for method '{_singleMethodName}' on type '{_singleMethodTypeName}'");
}
if (method.HasInstantiation)
{
List<TypeDesc> genericArguments = new List<TypeDesc>();
foreach (var argString in _singleMethodGenericArgs)
genericArguments.Add(FindType(context, argString));
method = method.MakeInstantiatedMethod(genericArguments.ToArray());
}
return method;
}
private static bool DumpReproArguments(CodeGenerationFailedException ex)
{
Console.WriteLine("To repro, add following arguments to the command line:");
MethodDesc failingMethod = ex.Method;
var formatter = new CustomAttributeTypeNameFormatter((IAssemblyDesc)failingMethod.Context.SystemModule);
Console.Write($"--singlemethodtypename \"{formatter.FormatName(failingMethod.OwningType, true)}\"");
Console.Write($" --singlemethodname {failingMethod.Name}");
for (int i = 0; i < failingMethod.Instantiation.Length; i++)
Console.Write($" --singlemethodgenericarg \"{formatter.FormatName(failingMethod.Instantiation[i], true)}\"");
return false;
}
private static int Main(string[] args)
{
#if DEBUG
try
{
return new Program().Run(args);
}
catch (CodeGenerationFailedException ex) when (DumpReproArguments(ex))
{
throw new NotSupportedException(); // Unreachable
}
#else
try
{
return new Program().Run(args);
}
catch (Exception e)
{
Console.Error.WriteLine("Error: " + e.Message);
Console.Error.WriteLine(e.ToString());
return 1;
}
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.Xml
{
using System;
// This is mostly just a copy of code in SqlTypes.SqlDecimal
internal struct BinXmlSqlDecimal
{
internal byte m_bLen;
internal byte m_bPrec;
internal byte m_bScale;
internal byte m_bSign;
internal uint m_data1;
internal uint m_data2;
internal uint m_data3;
internal uint m_data4;
public bool IsPositive
{
get
{
return (m_bSign == 0);
}
}
private static readonly byte s_NUMERIC_MAX_PRECISION = 38; // Maximum precision of numeric
private static readonly byte s_maxPrecision = s_NUMERIC_MAX_PRECISION; // max SS precision
private static readonly byte s_maxScale = s_NUMERIC_MAX_PRECISION; // max SS scale
private static readonly int s_cNumeMax = 4;
private static readonly long s_lInt32Base = ((long)1) << 32; // 2**32
private static readonly ulong s_ulInt32Base = ((ulong)1) << 32; // 2**32
private static readonly ulong s_ulInt32BaseForMod = s_ulInt32Base - 1; // 2**32 - 1 (0xFFF...FF)
internal static readonly ulong x_llMax = Int64.MaxValue; // Max of Int64
//private static readonly uint x_ulBase10 = 10;
private static readonly double s_DUINT_BASE = (double)s_lInt32Base; // 2**32
private static readonly double s_DUINT_BASE2 = s_DUINT_BASE * s_DUINT_BASE; // 2**64
private static readonly double s_DUINT_BASE3 = s_DUINT_BASE2 * s_DUINT_BASE; // 2**96
//private static readonly double DMAX_NUME = 1.0e+38; // Max value of numeric
//private static readonly uint DBL_DIG = 17; // Max decimal digits of double
//private static readonly byte x_cNumeDivScaleMin = 6; // Minimum result scale of numeric division
// Array of multipliers for lAdjust and Ceiling/Floor.
private static readonly uint[] s_rgulShiftBase = new uint[9] {
10,
10 * 10,
10 * 10 * 10,
10 * 10 * 10 * 10,
10 * 10 * 10 * 10 * 10,
10 * 10 * 10 * 10 * 10 * 10,
10 * 10 * 10 * 10 * 10 * 10 * 10,
10 * 10 * 10 * 10 * 10 * 10 * 10 * 10,
10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10
};
public BinXmlSqlDecimal(byte[] data, int offset, bool trim)
{
byte b = data[offset];
switch (b)
{
case 7: m_bLen = 1; break;
case 11: m_bLen = 2; break;
case 15: m_bLen = 3; break;
case 19: m_bLen = 4; break;
default: throw new XmlException(ResXml.XmlBinary_InvalidSqlDecimal, (string[])null);
}
m_bPrec = data[offset + 1];
m_bScale = data[offset + 2];
m_bSign = 0 == data[offset + 3] ? (byte)1 : (byte)0;
m_data1 = UIntFromByteArray(data, offset + 4);
m_data2 = (m_bLen > 1) ? UIntFromByteArray(data, offset + 8) : 0;
m_data3 = (m_bLen > 2) ? UIntFromByteArray(data, offset + 12) : 0;
m_data4 = (m_bLen > 3) ? UIntFromByteArray(data, offset + 16) : 0;
if (m_bLen == 4 && m_data4 == 0)
m_bLen = 3;
if (m_bLen == 3 && m_data3 == 0)
m_bLen = 2;
if (m_bLen == 2 && m_data2 == 0)
m_bLen = 1;
AssertValid();
if (trim)
{
TrimTrailingZeros();
AssertValid();
}
}
public void Write(Stream strm)
{
strm.WriteByte((byte)(this.m_bLen * 4 + 3));
strm.WriteByte(this.m_bPrec);
strm.WriteByte(this.m_bScale);
strm.WriteByte(0 == this.m_bSign ? (byte)1 : (byte)0);
WriteUI4(this.m_data1, strm);
if (this.m_bLen > 1)
{
WriteUI4(this.m_data2, strm);
if (this.m_bLen > 2)
{
WriteUI4(this.m_data3, strm);
if (this.m_bLen > 3)
{
WriteUI4(this.m_data4, strm);
}
}
}
}
private void WriteUI4(uint val, Stream strm)
{
strm.WriteByte((byte)(val & 0xFF));
strm.WriteByte((byte)((val >> 8) & 0xFF));
strm.WriteByte((byte)((val >> 16) & 0xFF));
strm.WriteByte((byte)((val >> 24) & 0xFF));
}
private static uint UIntFromByteArray(byte[] data, int offset)
{
int val = (data[offset]) << 0;
val |= (data[offset + 1]) << 8;
val |= (data[offset + 2]) << 16;
val |= (data[offset + 3]) << 24;
return unchecked((uint)val);
}
// check whether is zero
private bool FZero()
{
return (m_data1 == 0) && (m_bLen <= 1);
}
// Store data back from rguiData[] to m_data*
private void StoreFromWorkingArray(uint[] rguiData)
{
Debug.Assert(rguiData.Length == 4);
m_data1 = rguiData[0];
m_data2 = rguiData[1];
m_data3 = rguiData[2];
m_data4 = rguiData[3];
}
// Find the case where we overflowed 10**38, but not 2**128
private bool FGt10_38(uint[] rglData)
{
//Debug.Assert(rglData.Length == 4, "rglData.Length == 4", "Wrong array length: " + rglData.Length.ToString());
return rglData[3] >= 0x4b3b4ca8L && ((rglData[3] > 0x4b3b4ca8L) || (rglData[2] > 0x5a86c47aL) || (rglData[2] == 0x5a86c47aL) && (rglData[1] >= 0x098a2240L));
}
// Multi-precision one super-digit divide in place.
// U = U / D,
// R = U % D
// Length of U can decrease
private static void MpDiv1(uint[] rgulU, // InOut| U
ref int ciulU, // InOut| # of digits in U
uint iulD, // In | D
out uint iulR // Out | R
)
{
Debug.Assert(rgulU.Length == s_cNumeMax);
uint ulCarry = 0;
ulong dwlAccum;
ulong ulD = (ulong)iulD;
int idU = ciulU;
Debug.Assert(iulD != 0, "iulD != 0", "Divided by zero!");
Debug.Assert(iulD > 0, "iulD > 0", "Invalid data: less than zero");
Debug.Assert(ciulU > 0, "ciulU > 0", "No data in the array");
while (idU > 0)
{
idU--;
dwlAccum = (((ulong)ulCarry) << 32) + (ulong)(rgulU[idU]);
rgulU[idU] = (uint)(dwlAccum / ulD);
ulCarry = (uint)(dwlAccum - (ulong)rgulU[idU] * ulD); // (ULONG) (dwlAccum % iulD)
}
iulR = ulCarry;
MpNormalize(rgulU, ref ciulU);
}
// Normalize multi-precision number - remove leading zeroes
private static void MpNormalize(uint[] rgulU, // In | Number
ref int ciulU // InOut| # of digits
)
{
while (ciulU > 1 && rgulU[ciulU - 1] == 0)
ciulU--;
}
// AdjustScale()
//
// Adjust number of digits to the right of the decimal point.
// A positive adjustment increases the scale of the numeric value
// while a negative adjustment decreases the scale. When decreasing
// the scale for the numeric value, the remainder is checked and
// rounded accordingly.
//
internal void AdjustScale(int digits, bool fRound)
{
uint ulRem; //Remainder when downshifting
uint ulShiftBase; //What to multiply by to effect scale adjust
bool fNeedRound = false; //Do we really need to round?
byte bNewScale, bNewPrec;
int lAdjust = digits;
//If downshifting causes truncation of data
if (lAdjust + m_bScale < 0)
throw new XmlException(ResXml.SqlTypes_ArithTruncation, (string)null);
//If uphifting causes scale overflow
if (lAdjust + m_bScale > s_NUMERIC_MAX_PRECISION)
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
bNewScale = (byte)(lAdjust + m_bScale);
bNewPrec = (byte)(Math.Min(s_NUMERIC_MAX_PRECISION, Math.Max(1, lAdjust + m_bPrec)));
if (lAdjust > 0)
{
m_bScale = bNewScale;
m_bPrec = bNewPrec;
while (lAdjust > 0)
{
//if lAdjust>=9, downshift by 10^9 each time, otherwise by the full amount
if (lAdjust >= 9)
{
ulShiftBase = s_rgulShiftBase[8];
lAdjust -= 9;
}
else
{
ulShiftBase = s_rgulShiftBase[lAdjust - 1];
lAdjust = 0;
}
MultByULong(ulShiftBase);
}
}
else if (lAdjust < 0)
{
do
{
if (lAdjust <= -9)
{
ulShiftBase = s_rgulShiftBase[8];
lAdjust += 9;
}
else
{
ulShiftBase = s_rgulShiftBase[-lAdjust - 1];
lAdjust = 0;
}
ulRem = DivByULong(ulShiftBase);
} while (lAdjust < 0);
// Do we really need to round?
fNeedRound = (ulRem >= ulShiftBase / 2);
m_bScale = bNewScale;
m_bPrec = bNewPrec;
}
AssertValid();
// After adjusting, if the result is 0 and remainder is less than 5,
// set the sign to be positive and return.
if (fNeedRound && fRound)
{
// If remainder is 5 or above, increment/decrement by 1.
AddULong(1);
}
else if (FZero())
this.m_bSign = 0;
}
// AddULong()
//
// Add ulAdd to this numeric. The result will be returned in *this.
//
// Parameters:
// this - IN Operand1 & OUT Result
// ulAdd - IN operand2.
//
private void AddULong(uint ulAdd)
{
ulong dwlAccum = (ulong)ulAdd;
int iData; // which UI4 in this we are on
int iDataMax = (int)m_bLen; // # of UI4s in this
uint[] rguiData = new uint[4] { m_data1, m_data2, m_data3, m_data4 };
// Add, starting at the LS UI4 until out of UI4s or no carry
iData = 0;
do
{
dwlAccum += (ulong)rguiData[iData];
rguiData[iData] = (uint)dwlAccum; // equivalent to mod x_dwlBaseUI4
dwlAccum >>= 32; // equivalent to dwlAccum /= x_dwlBaseUI4;
if (0 == dwlAccum)
{
StoreFromWorkingArray(rguiData);
return;
}
iData++;
} while (iData < iDataMax);
// There is carry at the end
Debug.Assert(dwlAccum < s_ulInt32Base, "dwlAccum < x_lInt32Base", "");
// Either overflowed
if (iData == s_cNumeMax)
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
// Or need to extend length by 1 UI4
rguiData[iData] = (uint)dwlAccum;
m_bLen++;
if (FGt10_38(rguiData))
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
StoreFromWorkingArray(rguiData);
}
// multiply by a long integer
private void MultByULong(uint uiMultiplier)
{
int iDataMax = m_bLen; // How many UI4s currently in *this
ulong dwlAccum = 0; // accumulated sum
ulong dwlNextAccum = 0; // accumulation past dwlAccum
int iData; // which UI4 in *This we are on.
uint[] rguiData = new uint[4] { m_data1, m_data2, m_data3, m_data4 };
for (iData = 0; iData < iDataMax; iData++)
{
Debug.Assert(dwlAccum < s_ulInt32Base);
ulong ulTemp = (ulong)rguiData[iData];
dwlNextAccum = ulTemp * (ulong)uiMultiplier;
dwlAccum += dwlNextAccum;
if (dwlAccum < dwlNextAccum) // Overflow of int64 add
dwlNextAccum = s_ulInt32Base; // how much to add to dwlAccum after div x_dwlBaseUI4
else
dwlNextAccum = 0;
rguiData[iData] = (uint)dwlAccum; // equivalent to mod x_dwlBaseUI4
dwlAccum = (dwlAccum >> 32) + dwlNextAccum; // equivalent to div x_dwlBaseUI4
}
// If any carry,
if (dwlAccum != 0)
{
// Either overflowed
Debug.Assert(dwlAccum < s_ulInt32Base, "dwlAccum < x_dwlBaseUI4", "Integer overflow");
if (iDataMax == s_cNumeMax)
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
// Or extend length by one uint
rguiData[iDataMax] = (uint)dwlAccum;
m_bLen++;
}
if (FGt10_38(rguiData))
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
StoreFromWorkingArray(rguiData);
}
// DivByULong()
//
// Divide numeric value by a ULONG. The result will be returned
// in the dividend *this.
//
// Parameters:
// this - IN Dividend & OUT Result
// ulDivisor - IN Divisor
// Returns: - OUT Remainder
//
internal uint DivByULong(uint iDivisor)
{
ulong dwlDivisor = (ulong)iDivisor;
ulong dwlAccum = 0; //Accumulated sum
uint ulQuotientCur = 0; // Value of the current UI4 of the quotient
bool fAllZero = true; // All of the quotient (so far) has been 0
int iData; //Which UI4 currently on
// Check for zero divisor.
if (dwlDivisor == 0)
throw new XmlException(ResXml.SqlTypes_DivideByZero, (string)null);
// Copy into array, so that we can iterate through the data
uint[] rguiData = new uint[4] { m_data1, m_data2, m_data3, m_data4 };
// Start from the MS UI4 of quotient, divide by divisor, placing result
// in quotient and carrying the remainder.
//DEVNOTE DWORDLONG sufficient accumulator since:
// Accum < Divisor <= 2^32 - 1 at start each loop
// initially,and mod end previous loop
// Accum*2^32 < 2^64 - 2^32
// multiply both side by 2^32 (x_dwlBaseUI4)
// Accum*2^32 + m_rgulData < 2^64
// rglData < 2^32
for (iData = m_bLen; iData > 0; iData--)
{
Debug.Assert(dwlAccum < dwlDivisor);
dwlAccum = (dwlAccum << 32) + (ulong)(rguiData[iData - 1]); // dwlA*x_dwlBaseUI4 + rglData
Debug.Assert((dwlAccum / dwlDivisor) < s_ulInt32Base);
//Update dividend to the quotient.
ulQuotientCur = (uint)(dwlAccum / dwlDivisor);
rguiData[iData - 1] = ulQuotientCur;
//Remainder to be carried to the next lower significant byte.
dwlAccum = dwlAccum % dwlDivisor;
// While current part of quotient still 0, reduce length
fAllZero = fAllZero && (ulQuotientCur == 0);
if (fAllZero)
m_bLen--;
}
StoreFromWorkingArray(rguiData);
// If result is 0, preserve sign but set length to 5
if (fAllZero)
m_bLen = 1;
AssertValid();
// return the remainder
Debug.Assert(dwlAccum < s_ulInt32Base);
return (uint)dwlAccum;
}
//Determine the number of uints needed for a numeric given a precision
//Precision Length
// 0 invalid
// 1-9 1
// 10-19 2
// 20-28 3
// 29-38 4
// The array in Shiloh. Listed here for comparison.
//private static readonly byte[] rgCLenFromPrec = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9,
// 9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17};
private static readonly byte[] s_rgCLenFromPrec = new byte[] {
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
};
private static byte CLenFromPrec(byte bPrec)
{
Debug.Assert(bPrec <= s_maxPrecision && bPrec > 0, "bPrec <= MaxPrecision && bPrec > 0", "Invalid numeric precision");
return s_rgCLenFromPrec[bPrec - 1];
}
private static char ChFromDigit(uint uiDigit)
{
Debug.Assert(uiDigit < 10);
return (char)(uiDigit + '0');
}
public Decimal ToDecimal()
{
if ((int)m_data4 != 0 || m_bScale > 28)
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
return new Decimal((int)m_data1, (int)m_data2, (int)m_data3, !IsPositive, m_bScale);
}
private void TrimTrailingZeros()
{
uint[] rgulNumeric = new uint[4] { m_data1, m_data2, m_data3, m_data4 };
int culLen = m_bLen;
uint ulRem; //Remainder of a division by x_ulBase10, i.e.,least significant digit
// special-case 0
if (culLen == 1 && rgulNumeric[0] == 0)
{
m_bScale = 0;
return;
}
while (m_bScale > 0 && (culLen > 1 || rgulNumeric[0] != 0))
{
MpDiv1(rgulNumeric, ref culLen, 10, out ulRem);
if (ulRem == 0)
{
m_data1 = rgulNumeric[0];
m_data2 = rgulNumeric[1];
m_data3 = rgulNumeric[2];
m_data4 = rgulNumeric[3];
m_bScale--;
}
else
{
break;
}
}
if (m_bLen == 4 && m_data4 == 0)
m_bLen = 3;
if (m_bLen == 3 && m_data3 == 0)
m_bLen = 2;
if (m_bLen == 2 && m_data2 == 0)
m_bLen = 1;
}
public override String ToString()
{
AssertValid();
// Make local copy of data to avoid modifying input.
uint[] rgulNumeric = new uint[4] { m_data1, m_data2, m_data3, m_data4 };
int culLen = m_bLen;
char[] pszTmp = new char[s_NUMERIC_MAX_PRECISION + 1]; //Local Character buffer to hold
//the decimal digits, from the
//lowest significant to highest significant
int iDigits = 0;//Number of significant digits
uint ulRem; //Remainder of a division by x_ulBase10, i.e.,least significant digit
// Build the final numeric string by inserting the sign, reversing
// the order and inserting the decimal number at the correct position
//Retrieve each digit from the lowest significant digit
while (culLen > 1 || rgulNumeric[0] != 0)
{
MpDiv1(rgulNumeric, ref culLen, 10, out ulRem);
//modulo x_ulBase10 is the lowest significant digit
pszTmp[iDigits++] = ChFromDigit(ulRem);
}
// if scale of the number has not been
// reached pad remaining number with zeros.
while (iDigits <= m_bScale)
{
pszTmp[iDigits++] = ChFromDigit(0);
}
bool fPositive = IsPositive;
// Increment the result length if negative (need to add '-')
int uiResultLen = fPositive ? iDigits : iDigits + 1;
// Increment the result length if scale > 0 (need to add '.')
if (m_bScale > 0)
uiResultLen++;
char[] szResult = new char[uiResultLen];
int iCurChar = 0;
if (!fPositive)
szResult[iCurChar++] = '-';
while (iDigits > 0)
{
if (iDigits-- == m_bScale)
szResult[iCurChar++] = '.';
szResult[iCurChar++] = pszTmp[iDigits];
}
AssertValid();
return new String(szResult);
}
// Is this RE numeric valid?
[System.Diagnostics.Conditional("DEBUG")]
private void AssertValid()
{
// Scale,Prec in range
Debug.Assert(m_bScale <= s_NUMERIC_MAX_PRECISION, "m_bScale <= NUMERIC_MAX_PRECISION", "In AssertValid");
Debug.Assert(m_bScale <= m_bPrec, "m_bScale <= m_bPrec", "In AssertValid");
Debug.Assert(m_bScale >= 0, "m_bScale >= 0", "In AssertValid");
Debug.Assert(m_bPrec > 0, "m_bPrec > 0", "In AssertValid");
Debug.Assert(CLenFromPrec(m_bPrec) >= m_bLen, "CLenFromPrec(m_bPrec) >= m_bLen", "In AssertValid");
Debug.Assert(m_bLen <= s_cNumeMax, "m_bLen <= x_cNumeMax", "In AssertValid");
uint[] rglData = new uint[4] { m_data1, m_data2, m_data3, m_data4 };
// highest UI4 is non-0 unless value "zero"
if (rglData[m_bLen - 1] == 0)
{
Debug.Assert(m_bLen == 1, "m_bLen == 1", "In AssertValid");
}
// All UI4s from length to end are 0
for (int iulData = m_bLen; iulData < s_cNumeMax; iulData++)
Debug.Assert(rglData[iulData] == 0, "rglData[iulData] == 0", "In AssertValid");
}
}
internal struct BinXmlSqlMoney
{
private long _data;
public BinXmlSqlMoney(int v) { _data = v; }
public BinXmlSqlMoney(long v) { _data = v; }
public Decimal ToDecimal()
{
bool neg;
ulong v;
if (_data < 0)
{
neg = true;
v = (ulong)unchecked(-_data);
}
else
{
neg = false;
v = (ulong)_data;
}
// SQL Server stores money8 as ticks of 1/10000.
const byte MoneyScale = 4;
return new Decimal(unchecked((int)v), unchecked((int)(v >> 32)), 0, neg, MoneyScale);
}
public override String ToString()
{
Decimal money = ToDecimal();
// Formatting of SqlMoney: At least two digits after decimal point
return money.ToString("#0.00##", CultureInfo.InvariantCulture);
}
}
internal abstract class BinXmlDateTime
{
private const int MaxFractionDigits = 7;
static internal int[] KatmaiTimeScaleMultiplicator = new int[8] {
10000000,
1000000,
100000,
10000,
1000,
100,
10,
1,
};
private static void Write2Dig(StringBuilder sb, int val)
{
Debug.Assert(val >= 0 && val < 100);
sb.Append((char)('0' + (val / 10)));
sb.Append((char)('0' + (val % 10)));
}
private static void Write4DigNeg(StringBuilder sb, int val)
{
Debug.Assert(val > -10000 && val < 10000);
if (val < 0)
{
val = -val;
sb.Append('-');
}
Write2Dig(sb, val / 100);
Write2Dig(sb, val % 100);
}
private static void Write3Dec(StringBuilder sb, int val)
{
Debug.Assert(val >= 0 && val < 1000);
int c3 = val % 10;
val /= 10;
int c2 = val % 10;
val /= 10;
int c1 = val;
sb.Append('.');
sb.Append((char)('0' + c1));
sb.Append((char)('0' + c2));
sb.Append((char)('0' + c3));
}
private static void WriteDate(StringBuilder sb, int yr, int mnth, int day)
{
Write4DigNeg(sb, yr);
sb.Append('-');
Write2Dig(sb, mnth);
sb.Append('-');
Write2Dig(sb, day);
}
private static void WriteTime(StringBuilder sb, int hr, int min, int sec, int ms)
{
Write2Dig(sb, hr);
sb.Append(':');
Write2Dig(sb, min);
sb.Append(':');
Write2Dig(sb, sec);
if (ms != 0)
{
Write3Dec(sb, ms);
}
}
private static void WriteTimeFullPrecision(StringBuilder sb, int hr, int min, int sec, int fraction)
{
Write2Dig(sb, hr);
sb.Append(':');
Write2Dig(sb, min);
sb.Append(':');
Write2Dig(sb, sec);
if (fraction != 0)
{
int fractionDigits = MaxFractionDigits;
while (fraction % 10 == 0)
{
fractionDigits--;
fraction /= 10;
}
char[] charArray = new char[fractionDigits];
while (fractionDigits > 0)
{
fractionDigits--;
charArray[fractionDigits] = (char)(fraction % 10 + '0');
fraction /= 10;
}
sb.Append('.');
sb.Append(charArray);
}
}
private static void WriteTimeZone(StringBuilder sb, TimeSpan zone)
{
bool negTimeZone = true;
if (zone.Ticks < 0)
{
negTimeZone = false;
zone = zone.Negate();
}
WriteTimeZone(sb, negTimeZone, zone.Hours, zone.Minutes);
}
private static void WriteTimeZone(StringBuilder sb, bool negTimeZone, int hr, int min)
{
if (hr == 0 && min == 0)
{
sb.Append('Z');
}
else
{
sb.Append(negTimeZone ? '+' : '-');
Write2Dig(sb, hr);
sb.Append(':');
Write2Dig(sb, min);
}
}
private static void BreakDownXsdDateTime(long val, out int yr, out int mnth, out int day, out int hr, out int min, out int sec, out int ms)
{
if (val < 0)
goto Error;
long date = val / 4; // trim indicator bits
ms = (int)(date % 1000);
date /= 1000;
sec = (int)(date % 60);
date /= 60;
min = (int)(date % 60);
date /= 60;
hr = (int)(date % 24);
date /= 24;
day = (int)(date % 31) + 1;
date /= 31;
mnth = (int)(date % 12) + 1;
date /= 12;
yr = (int)(date - 9999);
if (yr < -9999 || yr > 9999)
goto Error;
return;
Error:
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
}
private static void BreakDownXsdDate(long val, out int yr, out int mnth, out int day, out bool negTimeZone, out int hr, out int min)
{
if (val < 0)
goto Error;
val = val / 4; // trim indicator bits
int totalMin = (int)(val % (29 * 60)) - 60 * 14;
long totalDays = val / (29 * 60);
if (negTimeZone = (totalMin < 0))
totalMin = -totalMin;
min = totalMin % 60;
hr = totalMin / 60;
day = (int)(totalDays % 31) + 1;
totalDays /= 31;
mnth = (int)(totalDays % 12) + 1;
yr = (int)(totalDays / 12) - 9999;
if (yr < -9999 || yr > 9999)
goto Error;
return;
Error:
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
}
private static void BreakDownXsdTime(long val, out int hr, out int min, out int sec, out int ms)
{
if (val < 0)
goto Error;
val = val / 4; // trim indicator bits
ms = (int)(val % 1000);
val /= 1000;
sec = (int)(val % 60);
val /= 60;
min = (int)(val % 60);
hr = (int)(val / 60);
if (0 > hr || hr > 23)
goto Error;
return;
Error:
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
}
public static string XsdDateTimeToString(long val)
{
int yr; int mnth; int day; int hr; int min; int sec; int ms;
BreakDownXsdDateTime(val, out yr, out mnth, out day, out hr, out min, out sec, out ms);
StringBuilder sb = new StringBuilder(20);
WriteDate(sb, yr, mnth, day);
sb.Append('T');
WriteTime(sb, hr, min, sec, ms);
sb.Append('Z');
return sb.ToString();
}
public static DateTime XsdDateTimeToDateTime(long val)
{
int yr; int mnth; int day; int hr; int min; int sec; int ms;
BreakDownXsdDateTime(val, out yr, out mnth, out day, out hr, out min, out sec, out ms);
return new DateTime(yr, mnth, day, hr, min, sec, ms, DateTimeKind.Utc);
}
public static string XsdDateToString(long val)
{
int yr; int mnth; int day; int hr; int min; bool negTimeZ;
BreakDownXsdDate(val, out yr, out mnth, out day, out negTimeZ, out hr, out min);
StringBuilder sb = new StringBuilder(20);
WriteDate(sb, yr, mnth, day);
WriteTimeZone(sb, negTimeZ, hr, min);
return sb.ToString();
}
public static DateTime XsdDateToDateTime(long val)
{
int yr; int mnth; int day; int hr; int min; bool negTimeZ;
BreakDownXsdDate(val, out yr, out mnth, out day, out negTimeZ, out hr, out min);
DateTime d = new DateTime(yr, mnth, day, 0, 0, 0, DateTimeKind.Utc);
// adjust for timezone
int adj = (negTimeZ ? -1 : 1) * ((hr * 60) + min);
return TimeZoneInfo.ConvertTime(d.AddMinutes(adj), TimeZoneInfo.Local);
}
public static string XsdTimeToString(long val)
{
int hr; int min; int sec; int ms;
BreakDownXsdTime(val, out hr, out min, out sec, out ms);
StringBuilder sb = new StringBuilder(16);
WriteTime(sb, hr, min, sec, ms);
sb.Append('Z');
return sb.ToString();
}
public static DateTime XsdTimeToDateTime(long val)
{
int hr; int min; int sec; int ms;
BreakDownXsdTime(val, out hr, out min, out sec, out ms);
return new DateTime(1, 1, 1, hr, min, sec, ms, DateTimeKind.Utc);
}
public static string SqlDateTimeToString(int dateticks, uint timeticks)
{
DateTime dateTime = SqlDateTimeToDateTime(dateticks, timeticks);
string format = (dateTime.Millisecond != 0) ? "yyyy/MM/dd\\THH:mm:ss.ffff" : "yyyy/MM/dd\\THH:mm:ss";
return dateTime.ToString(format, CultureInfo.InvariantCulture);
}
public static DateTime SqlDateTimeToDateTime(int dateticks, uint timeticks)
{
DateTime SQLBaseDate = new DateTime(1900, 1, 1);
//long millisecond = (long)(((ulong)timeticks * 20 + (ulong)3) / (ulong)6);
long millisecond = (long)(timeticks / s_SQLTicksPerMillisecond + 0.5);
return SQLBaseDate.Add(new TimeSpan(dateticks * TimeSpan.TicksPerDay +
millisecond * TimeSpan.TicksPerMillisecond));
}
// Number of (100ns) ticks per time unit
private static readonly double s_SQLTicksPerMillisecond = 0.3;
public static readonly int SQLTicksPerSecond = 300;
public static readonly int SQLTicksPerMinute = SQLTicksPerSecond * 60;
public static readonly int SQLTicksPerHour = SQLTicksPerMinute * 60;
private static readonly int s_SQLTicksPerDay = SQLTicksPerHour * 24;
public static string SqlSmallDateTimeToString(short dateticks, ushort timeticks)
{
DateTime dateTime = SqlSmallDateTimeToDateTime(dateticks, timeticks);
return dateTime.ToString("yyyy/MM/dd\\THH:mm:ss", CultureInfo.InvariantCulture);
}
public static DateTime SqlSmallDateTimeToDateTime(short dateticks, ushort timeticks)
{
return SqlDateTimeToDateTime((int)dateticks, (uint)(timeticks * SQLTicksPerMinute));
}
// Conversions of the Katmai date & time types to DateTime
public static DateTime XsdKatmaiDateToDateTime(byte[] data, int offset)
{
// Katmai SQL type "DATE"
long dateTicks = GetKatmaiDateTicks(data, ref offset);
DateTime dt = new DateTime(dateTicks);
return dt;
}
public static DateTime XsdKatmaiDateTimeToDateTime(byte[] data, int offset)
{
// Katmai SQL type "DATETIME2"
long timeTicks = GetKatmaiTimeTicks(data, ref offset);
long dateTicks = GetKatmaiDateTicks(data, ref offset);
DateTime dt = new DateTime(dateTicks + timeTicks);
return dt;
}
public static DateTime XsdKatmaiTimeToDateTime(byte[] data, int offset)
{
// TIME without zone is stored as DATETIME2
return XsdKatmaiDateTimeToDateTime(data, offset);
}
public static DateTime XsdKatmaiDateOffsetToDateTime(byte[] data, int offset)
{
// read the timezoned value into DateTimeOffset and then convert to local time
return XsdKatmaiDateOffsetToDateTimeOffset(data, offset).LocalDateTime;
}
public static DateTime XsdKatmaiDateTimeOffsetToDateTime(byte[] data, int offset)
{
// read the timezoned value into DateTimeOffset and then convert to local time
return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset).LocalDateTime;
}
public static DateTime XsdKatmaiTimeOffsetToDateTime(byte[] data, int offset)
{
// read the timezoned value into DateTimeOffset and then convert to local time
return XsdKatmaiTimeOffsetToDateTimeOffset(data, offset).LocalDateTime;
}
// Conversions of the Katmai date & time types to DateTimeOffset
public static DateTimeOffset XsdKatmaiDateToDateTimeOffset(byte[] data, int offset)
{
// read the value into DateTime and then convert it to DateTimeOffset, which adds local time zone
return (DateTimeOffset)XsdKatmaiDateToDateTime(data, offset);
}
public static DateTimeOffset XsdKatmaiDateTimeToDateTimeOffset(byte[] data, int offset)
{
// read the value into DateTime and then convert it to DateTimeOffset, which adds local time zone
return (DateTimeOffset)XsdKatmaiDateTimeToDateTime(data, offset);
}
public static DateTimeOffset XsdKatmaiTimeToDateTimeOffset(byte[] data, int offset)
{
// read the value into DateTime and then convert it to DateTimeOffset, which adds local time zone
return (DateTimeOffset)XsdKatmaiTimeToDateTime(data, offset);
}
public static DateTimeOffset XsdKatmaiDateOffsetToDateTimeOffset(byte[] data, int offset)
{
// DATE with zone is stored as DATETIMEOFFSET
return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset);
}
public static DateTimeOffset XsdKatmaiDateTimeOffsetToDateTimeOffset(byte[] data, int offset)
{
// Katmai SQL type "DATETIMEOFFSET"
long timeTicks = GetKatmaiTimeTicks(data, ref offset);
long dateTicks = GetKatmaiDateTicks(data, ref offset);
long zoneTicks = GetKatmaiTimeZoneTicks(data, offset);
// The DATETIMEOFFSET values are serialized in UTC, but DateTimeOffset takes adjusted time -> we need to add zoneTicks
DateTimeOffset dto = new DateTimeOffset(dateTicks + timeTicks + zoneTicks, new TimeSpan(zoneTicks));
return dto;
}
public static DateTimeOffset XsdKatmaiTimeOffsetToDateTimeOffset(byte[] data, int offset)
{
// TIME with zone is stored as DATETIMEOFFSET
return XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset);
}
// Conversions of the Katmai date & time types to string
public static string XsdKatmaiDateToString(byte[] data, int offset)
{
DateTime dt = XsdKatmaiDateToDateTime(data, offset);
StringBuilder sb = new StringBuilder(10);
WriteDate(sb, dt.Year, dt.Month, dt.Day);
return sb.ToString();
}
public static string XsdKatmaiDateTimeToString(byte[] data, int offset)
{
DateTime dt = XsdKatmaiDateTimeToDateTime(data, offset);
StringBuilder sb = new StringBuilder(33);
WriteDate(sb, dt.Year, dt.Month, dt.Day);
sb.Append('T');
WriteTimeFullPrecision(sb, dt.Hour, dt.Minute, dt.Second, GetFractions(dt));
return sb.ToString();
}
public static string XsdKatmaiTimeToString(byte[] data, int offset)
{
DateTime dt = XsdKatmaiTimeToDateTime(data, offset);
StringBuilder sb = new StringBuilder(16);
WriteTimeFullPrecision(sb, dt.Hour, dt.Minute, dt.Second, GetFractions(dt));
return sb.ToString();
}
public static string XsdKatmaiDateOffsetToString(byte[] data, int offset)
{
DateTimeOffset dto = XsdKatmaiDateOffsetToDateTimeOffset(data, offset);
StringBuilder sb = new StringBuilder(16);
WriteDate(sb, dto.Year, dto.Month, dto.Day);
WriteTimeZone(sb, dto.Offset);
return sb.ToString();
}
public static string XsdKatmaiDateTimeOffsetToString(byte[] data, int offset)
{
DateTimeOffset dto = XsdKatmaiDateTimeOffsetToDateTimeOffset(data, offset);
StringBuilder sb = new StringBuilder(39);
WriteDate(sb, dto.Year, dto.Month, dto.Day);
sb.Append('T');
WriteTimeFullPrecision(sb, dto.Hour, dto.Minute, dto.Second, GetFractions(dto));
WriteTimeZone(sb, dto.Offset);
return sb.ToString();
}
public static string XsdKatmaiTimeOffsetToString(byte[] data, int offset)
{
DateTimeOffset dto = XsdKatmaiTimeOffsetToDateTimeOffset(data, offset);
StringBuilder sb = new StringBuilder(22);
WriteTimeFullPrecision(sb, dto.Hour, dto.Minute, dto.Second, GetFractions(dto));
WriteTimeZone(sb, dto.Offset);
return sb.ToString();
}
// Helper methods for the Katmai date & time types
private static long GetKatmaiDateTicks(byte[] data, ref int pos)
{
int p = pos;
pos = p + 3;
return (data[p] | data[p + 1] << 8 | data[p + 2] << 16) * TimeSpan.TicksPerDay;
}
private static long GetKatmaiTimeTicks(byte[] data, ref int pos)
{
int p = pos;
byte scale = data[p];
long timeTicks;
p++;
if (scale <= 2)
{
timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16);
pos = p + 3;
}
else if (scale <= 4)
{
timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16);
timeTicks |= ((long)data[p + 3] << 24);
pos = p + 4;
}
else if (scale <= 7)
{
timeTicks = data[p] | (data[p + 1] << 8) | (data[p + 2] << 16);
timeTicks |= ((long)data[p + 3] << 24) | ((long)data[p + 4] << 32);
pos = p + 5;
}
else
{
throw new XmlException(ResXml.SqlTypes_ArithOverflow, (string)null);
}
return timeTicks * KatmaiTimeScaleMultiplicator[scale];
}
private static long GetKatmaiTimeZoneTicks(byte[] data, int pos)
{
return (short)(data[pos] | data[pos + 1] << 8) * TimeSpan.TicksPerMinute;
}
private static int GetFractions(DateTime dt)
{
return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks);
}
private static int GetFractions(DateTimeOffset dt)
{
return (int)(dt.Ticks - new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second).Ticks);
}
/*
const long SqlDateTicks2Ticks = (long)10000 * 1000 * 60 * 60 * 24;
const long SqlBaseDate = 693595;
public static void DateTime2SqlDateTime(DateTime datetime, out int dateticks, out uint timeticks) {
dateticks = (int)(datetime.Ticks / SqlDateTicks2Ticks) - 693595;
double time = (double)(datetime.Ticks % SqlDateTicks2Ticks);
time = time / 10000; // adjust to ms
time = time * 0.3 + .5; // adjust to sqlticks (and round correctly)
timeticks = (uint)time;
}
public static void DateTime2SqlSmallDateTime(DateTime datetime, out short dateticks, out ushort timeticks) {
dateticks = (short)((int)(datetime.Ticks / SqlDateTicks2Ticks) - 693595);
int time = (int)(datetime.Ticks % SqlDateTicks2Ticks);
timeticks = (ushort)(time / (10000 * 1000 * 60)); // adjust to min
}
public static long DateTime2XsdTime(DateTime datetime) {
// adjust to ms
return (datetime.TimeOfDay.Ticks / 10000) * 4 + 0;
}
public static long DateTime2XsdDateTime(DateTime datetime) {
long t = datetime.TimeOfDay.Ticks / 10000;
t += (datetime.Day-1) * (long)1000*60*60*24;
t += (datetime.Month-1) * (long)1000*60*60*24*31;
int year = datetime.Year;
if (year < -9999 || year > 9999)
throw new XmlException(Res.SqlTypes_ArithOverflow, (string)null);
t += (datetime.Year+9999) * (long)1000*60*60*24*31*12;
return t*4 + 2;
}
public static long DateTime2XsdDate(DateTime datetime) {
// compute local offset
long tzOffset = -TimeZone.CurrentTimeZone.GetUtcOffset(datetime).Ticks / TimeSpan.TicksPerMinute;
tzOffset += 14*60;
// adjust datetime to UTC
datetime = TimeZone.CurrentTimeZone.ToUniversalTime(datetime);
Debug.Assert( tzOffset >= 0 );
int year = datetime.Year;
if (year < -9999 || year > 9999)
throw new XmlException(Res.SqlTypes_ArithOverflow, (string)null);
long t = (datetime.Day - 1)
+ 31*(datetime.Month - 1)
+ 31*12*((long)(year+9999));
t *= (29*60); // adjust in timezone
t += tzOffset;
return t*4+1;
}
* */
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="UnsafeCollabNativeMethods.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net.PeerToPeer.Collaboration
{
using System;
using System.Security.Permissions;
using System.Security.Cryptography.X509Certificates;
using System.Collections;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Text;
using System.Security;
//
// To manage any collaboration memory handle
//
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeCollabData : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeCollabData() : base(true) { }
protected override bool ReleaseHandle()
{
if(!IsInvalid)
UnsafeCollabNativeMethods.PeerFreeData(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
//
// To manage any collaboration enumeration handle
//
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeCollabEnum : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeCollabEnum() : base(true) { }
protected override bool ReleaseHandle()
{
if (!IsInvalid)
UnsafeCollabNativeMethods.PeerEndEnumeration(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
//
// To manage any collaboration invite handle
//
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeCollabInvite : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeCollabInvite() : base(true) { }
protected override bool ReleaseHandle()
{
if (!IsInvalid)
UnsafeCollabNativeMethods.PeerCollabCloseHandle(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
//
// To manage any cert store handle
//
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeCertStore : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeCertStore() : base(true) { }
protected override bool ReleaseHandle()
{
if (!IsInvalid)
UnsafeCollabNativeMethods.CertCloseStore(handle, 0);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
//
// To manage any allocated memory handle
//
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeCollabMemory : SafeHandleZeroOrMinusOneIsInvalid
{
private bool allocated;
internal SafeCollabMemory() : base(true) { }
[SecurityPermissionAttribute(SecurityAction.LinkDemand, UnmanagedCode = true)]
internal SafeCollabMemory(int cb)
: base(true)
{
handle = Marshal.AllocHGlobal(cb);
if (IntPtr.Equals(handle, IntPtr.Zero)){
SetHandleAsInvalid();
throw new PeerToPeerException(SR.GetString(SR.MemoryAllocFailed));
}
allocated = true;
}
protected override bool ReleaseHandle()
{
if (allocated && !IsInvalid)
Marshal.FreeHGlobal(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
//
// To manage any collaboration event handle
//
// <SecurityKernel Critical="True" Ring="0">
// <SatisfiesLinkDemand Name="SafeHandleZeroOrMinusOneIsInvalid" />
// </SecurityKernel>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class SafeCollabEvent : SafeHandleZeroOrMinusOneIsInvalid
{
internal SafeCollabEvent() : base(true) { }
protected override bool ReleaseHandle()
{
UnsafeCollabNativeMethods.PeerCollabUnregisterEvent(handle);
SetHandleAsInvalid(); //Mark it closed - This does not change the value of the handle it self
SetHandle(IntPtr.Zero); //Mark it invalid - Change the value to Zero
return true;
}
}
//
//
// Definitions of structures used for passing data into native collaboration
// functions
//
//
/*
typedef struct peer_presence_info_tag {
PEER_PRESENCE_STATUS status;
PWSTR pwzDescriptiveText;
} PEER_PRESENCE_INFO
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_PRESENCE_INFO
{
internal PeerPresenceStatus status;
internal string descText;
}
//
/*
typedef struct sockaddr_in6 {
ADDRESS_FAMILY sin6_family; // AF_INET6.
USHORT sin6_port; // Transport level port number.
ULONG sin6_flowinfo; // IPv6 flow information.
IN6_ADDR sin6_addr; // IPv6 address.
union {
ULONG sin6_scope_id; // Set of interfaces for a scope.
SCOPE_ID sin6_scope_struct;
};
} SOCKADDR_IN6_LH
*/
[StructLayout(LayoutKind.Sequential)]
internal struct SOCKADDR_IN6
{
internal ushort sin6_family;
internal ushort sin6_port;
internal uint sin6_flowinfo;
internal byte sin6_addr0;
internal byte sin6_addr1;
internal byte sin6_addr2;
internal byte sin6_addr3;
internal byte sin6_addr4;
internal byte sin6_addr5;
internal byte sin6_addr6;
internal byte sin6_addr7;
internal byte sin6_addr8;
internal byte sin6_addr9;
internal byte sin6_addr10;
internal byte sin6_addr11;
internal byte sin6_addr12;
internal byte sin6_addr13;
internal byte sin6_addr14;
internal byte sin6_addr15;
internal uint sin6_scope_id;
}
/*
typedef struct peer_address_tag {
DWORD dwSize;
SOCKADDR_IN6 sin6;
} PEER_ADDRESS
*/
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct PEER_ADDRESS
{
internal uint dwSize;
internal SOCKADDR_IN6 sin6;
}
/*
typedef struct peer_endpoint_tag {
PEER_ADDRESS address;
PWSTR pwzEndpointName;
} PEER_ENDPOINT
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_ENDPOINT
{
internal PEER_ADDRESS peerAddress;
internal IntPtr pwzEndpointName;
}
/*
typedef struct peer_data_tag {
ULONG cbData;
PBYTE pbData;
} PEER_DATA
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_DATA
{
internal UInt32 cbData;
internal IntPtr pbData;
}
// for Guid
/*
typedef struct _GUID {
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[ 8 ];
} GUID;
*/
[StructLayout(LayoutKind.Sequential/*, Pack=1*/)]
internal struct GUID
{
internal uint data1;
internal ushort data2;
internal ushort data3;
internal byte data4;
internal byte data5;
internal byte data6;
internal byte data7;
internal byte data8;
internal byte data9;
internal byte data10;
internal byte data11;
}
/*
typedef struct peer_object_tag {
GUID id;
PEER_DATA data;
DWORD dwPublicationScope;
} PEER_OBJECT
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_OBJECT
{
internal GUID guid;
internal PEER_DATA data;
internal uint dwPublicationScope;
}
/*
typedef struct peer_application_tag {
GUID id;
PEER_DATA data;
PWSTR pwzDescription;
} PEER_APPLICATION
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_APPLICATION
{
internal GUID guid;
internal PEER_DATA data;
internal IntPtr pwzDescription;
}
/*
typedef struct peer_application_registration_info_tag {
PEER_APPLICATION application;
PWSTR pwzApplicationToLaunch;
PWSTR pwzApplicationArguments;
DWORD dwPublicationScope;
} PEER_APPLICATION_REGISTRATION_INFO
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_APPLICATION_REGISTRATION_INFO
{
internal PEER_APPLICATION application;
internal string pwzApplicationToLaunch;
internal string pwzApplicationArguments;
internal uint dwPublicationScope;
}
/*
typedef struct peer_contact_tag
{
PWSTR pwzPeerName;
PWSTR pwzNickName;
PWSTR pwzDisplayName;
PWSTR pwzEmailAddress;
BOOL fWatch;
PEER_WATCH_PERMISSION WatcherPermissions;
PEER_DATA credentials;
} PEER_CONTACT
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_CONTACT
{
internal string pwzPeerName;
internal string pwzNickname;
internal string pwzDisplayName;
internal string pwzEmailAddress;
internal bool fWatch;
internal SubscriptionType WatcherPermissions;
internal PEER_DATA credentials;
}
/*
typedef struct peer_people_near_me_tag {
PWSTR pwzNickName;
PEER_ENDPOINT endpoint;
GUID id;
} PEER_PEOPLE_NEAR_ME
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_PEOPLE_NEAR_ME
{
internal IntPtr pwzNickname;
internal PEER_ENDPOINT endpoint;
internal GUID id;
}
/*
typedef struct peer_invitation_tag {
GUID applicationId;
PEER_DATA applicationData;
PWSTR pwzMessage;
} PEER_INVITATION
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_INVITATION
{
internal GUID applicationId;
internal PEER_DATA applicationData;
internal string pwzMessage;
}
/*
typedef struct peer_invitation_response_tag {
PEER_INVITATION_RESPONSE_TYPE action;
PWSTR pwzMessage;
HRESULT hrExtendedInfo;
} PEER_INVITATION_RESPONSE
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_INVITATION_RESPONSE
{
internal PeerInvitationResponseType action;
internal string pwzMessage;
internal uint hrExtendedInfo;
}
/*
typedef struct peer_app_launch_info_tag {
PPEER_CONTACT pContact;
PPEER_ENDPOINT pEndpoint;
PPEER_INVITATION pInvitation;
} PEER_APP_LAUNCH_INFO
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_APP_LAUNCH_INFO
{
internal IntPtr pContact;
internal IntPtr pEndpoint;
internal IntPtr pInvitation;
}
/*
typedef struct peer_collab_event_registration_tag {
PEER_COLLAB_EVENT_TYPE eventType;
#ifdef MIDL_PASS
[unique]
#endif
GUID * pInstance;
} PEER_COLLAB_EVENT_REGISTRATION
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_COLLAB_EVENT_REGISTRATION
{
internal PeerCollabEventType eventType;
internal IntPtr pInstance;
}
/*
typedef struct peer_event_watchlist_changed_data_tag {
PPEER_CONTACT pContact;
PEER_CHANGE_TYPE changeType;
} PEER_EVENT_WATCHLIST_CHANGED_DATA
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_EVENT_WATCHLIST_CHANGED_DATA
{
internal IntPtr pContact;
internal PeerChangeType changeType;
}
/*
typedef struct peer_event_presence_changed_data_tag {
PPEER_CONTACT pContact;
PPEER_ENDPOINT pEndpoint;
PEER_CHANGE_TYPE changeType;
PPEER_PRESENCE_INFO pPresenceInfo;
} PEER_EVENT_PRESENCE_CHANGED_DATA
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_EVENT_PRESENCE_CHANGED_DATA
{
internal IntPtr pContact;
internal IntPtr pEndPoint;
internal PeerChangeType changeType;
internal IntPtr pPresenceInfo;
}
/*
typedef struct peer_event_application_changed_data_tag {
PPEER_CONTACT pContact;
PPEER_ENDPOINT pEndpoint;
PEER_CHANGE_TYPE changeType;
PPEER_APPLICATION pApplication;
} PEER_EVENT_APPLICATION_CHANGED_DATA
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_EVENT_APPLICATION_CHANGED_DATA
{
internal IntPtr pContact;
internal IntPtr pEndPoint;
internal PeerChangeType changeType;
internal IntPtr pApplication;
}
/*
typedef struct peer_event_object_changed_data_tag {
PPEER_CONTACT pContact;
PPEER_ENDPOINT pEndpoint;
PEER_CHANGE_TYPE changeType;
PPEER_OBJECT pObject;
} PEER_EVENT_OBJECT_CHANGED_DATA
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_EVENT_OBJECT_CHANGED_DATA
{
internal IntPtr pContact;
internal IntPtr pEndPoint;
internal PeerChangeType changeType;
internal IntPtr pObject;
}
/*
typedef struct peer_event_endpoint_changed_data_tag {
PPEER_CONTACT pContact;
PPEER_ENDPOINT pEndpoint;
} PEER_EVENT_ENDPOINT_CHANGED_DATA
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_EVENT_ENDPOINT_CHANGED_DATA
{
internal IntPtr pContact;
internal IntPtr pEndPoint;
}
/*
typedef struct peer_event_people_near_me_changed_data_tag {
PEER_CHANGE_TYPE changeType;
PPEER_PEOPLE_NEAR_ME pPeopleNearMe;
} PEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA, *PPEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA;
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA
{
internal PeerChangeType changeType;
internal IntPtr pPeopleNearMe;
}
/*
typedef struct peer_event_request_status_changed_data_tag {
PPEER_ENDPOINT pEndpoint;
HRESULT hrChange;
} PEER_EVENT_REQUEST_STATUS_CHANGED_DATA, *PPEER_EVENT_REQUEST_STATUS_CHANGED_DATA;
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_EVENT_REQUEST_STATUS_CHANGED_DATA
{
internal IntPtr pEndPoint;
internal int hrChange;
}
/*
typedef struct peer_collab_event_data_tag {
PEER_COLLAB_EVENT_TYPE eventType;
union {
PEER_EVENT_WATCHLIST_CHANGED_DATA watchListChangedData;
PEER_EVENT_PRESENCE_CHANGED_DATA presenceChangedData;
PEER_EVENT_APPLICATION_CHANGED_DATA applicationChangedData;
PEER_EVENT_OBJECT_CHANGED_DATA objectChangedData;
PEER_EVENT_ENDPOINT_CHANGED_DATA endpointChangedData;
PEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA peopleNearMeChangedData;
PEER_EVENT_REQUEST_STATUS_CHANGED_DATA requestStatusChangedData;
};
} PEER_COLLAB_EVENT_DATA, *PPEER_COLLAB_EVENT_DATA;
*/
//
// We have two different structures and one has explicit layout to be able to
// handle the union as shown in the structure above. Two structures are used
// instead of one because of x86 and x64 padding issues.
//
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct PEER_COLLAB_EVENT_DATA
{
internal PeerCollabEventType eventType;
PEER_COLLAB_EVENT_CHANGED_DATA changedData;
internal PEER_EVENT_WATCHLIST_CHANGED_DATA watchListChangedData
{
get{
return changedData.watchListChangedData;
}
}
internal PEER_EVENT_PRESENCE_CHANGED_DATA presenceChangedData
{
get{
return changedData.presenceChangedData;
}
}
internal PEER_EVENT_APPLICATION_CHANGED_DATA applicationChangedData
{
get{
return changedData.applicationChangedData;
}
}
internal PEER_EVENT_OBJECT_CHANGED_DATA objectChangedData
{
get{
return changedData.objectChangedData;
}
}
internal PEER_EVENT_ENDPOINT_CHANGED_DATA endpointChangedData
{
get{
return changedData.endpointChangedData;
}
}
internal PEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA peopleNearMeChangedData
{
get{
return changedData.peopleNearMeChangedData;
}
}
internal PEER_EVENT_REQUEST_STATUS_CHANGED_DATA requestStatusChangedData
{
get{
return changedData.requestStatusChangedData;
}
}
}
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
internal struct PEER_COLLAB_EVENT_CHANGED_DATA
{
[FieldOffset(0)]
internal PEER_EVENT_WATCHLIST_CHANGED_DATA watchListChangedData;
[FieldOffset(0)]
internal PEER_EVENT_PRESENCE_CHANGED_DATA presenceChangedData;
[FieldOffset(0)]
internal PEER_EVENT_APPLICATION_CHANGED_DATA applicationChangedData;
[FieldOffset(0)]
internal PEER_EVENT_OBJECT_CHANGED_DATA objectChangedData;
[FieldOffset(0)]
internal PEER_EVENT_ENDPOINT_CHANGED_DATA endpointChangedData;
[FieldOffset(0)]
internal PEER_EVENT_PEOPLE_NEAR_ME_CHANGED_DATA peopleNearMeChangedData;
[FieldOffset(0)]
internal PEER_EVENT_REQUEST_STATUS_CHANGED_DATA requestStatusChangedData;
}
/// <summary>
/// Stores specific error codes that we use.
/// </summary>
internal static class UnsafeCollabReturnCodes
{
private const UInt32 FACILITY_P2P = 99;
private const UInt32 FACILITY_WIN32 = 7;
internal const int PEER_S_NO_EVENT_DATA = (int)(((int)FACILITY_P2P << 16) | 0x0002);
internal const int PEER_S_SUBSCRIPTION_EXISTS = (int)(((int)FACILITY_P2P << 16) | 0x6000);
internal const int PEER_E_NOT_FOUND = (int)(((int)1 << 31) | ((int)FACILITY_WIN32 << 16) | 1168);
internal const int PEER_E_CONTACT_NOT_FOUND = (int)(((int)1 << 31) | ((int)FACILITY_P2P << 16) | 0x6001);
internal const int PEER_E_ALREADY_EXISTS = (int)(((int)1 << 31) | ((int)FACILITY_WIN32 << 16) | 183);
internal const int PEER_E_TIMEOUT = (int)(((int)1 << 31) | ((int)FACILITY_P2P << 16) | 0x7005);
internal const int ERROR_TIMEOUT = (int)(((int)1 << 31) | ((int)FACILITY_WIN32 << 16) | 0x05B4);
}
/// <summary>
/// This class contains all the collab/windows native functions that are called
/// by Collaboration namespace
/// </summary>
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeCollabNativeMethods
{
private const string P2P = "p2p.dll";
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabStartup(short wVersionRequested);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabSignin(IntPtr hwndParent, PeerScope dwSignInOptions);
[DllImport(P2P, CharSet = CharSet.Unicode)]
public extern static void PeerFreeData(IntPtr dataToFree);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabSignout(PeerScope dwSignInOptions);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetSigninOptions(ref PeerScope dwSignInOptions);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabSetPresenceInfo(ref PEER_PRESENCE_INFO ppi);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetPresenceInfo(IntPtr endpoint, out SafeCollabData pPresenceInfo);
//
// Application registration functions
//
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabRegisterApplication(ref PEER_APPLICATION_REGISTRATION_INFO appRegInfo,
PeerApplicationRegistrationType appRegType);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabUnregisterApplication(ref GUID pApplicationId,
PeerApplicationRegistrationType appRegType);
//
// Object set functions
//
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabSetObject(ref PEER_OBJECT pcObject);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabDeleteObject(ref GUID pObjectId);
//
// Enumeration functions
//
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabEnumObjects( IntPtr pcEndpoint,
IntPtr pObjectId,
out SafeCollabEnum phPeerEnum);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabEnumApplications( IntPtr pcEndpoint,
IntPtr pObjectId,
out SafeCollabEnum phPeerEnum);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabEnumPeopleNearMe(out SafeCollabEnum phPeerEnum);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabEnumEndpoints(ref PEER_CONTACT pcContact,
out SafeCollabEnum phPeerEnum);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabEnumContacts(out SafeCollabEnum phPeerEnum);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerGetItemCount(SafeCollabEnum hPeerEnum, ref UInt32 pCount);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerGetNextItem(SafeCollabEnum hPeerEnum,
ref UInt32 pCount,
out SafeCollabData pppvItems);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerEndEnumeration(IntPtr hPeerEnum);
//
// Misc application functions
//
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetAppLaunchInfo(out SafeCollabData ppLaunchInfo);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetApplicationRegistrationInfo(ref GUID pApplicationId,
PeerApplicationRegistrationType registrationType,
out SafeCollabData ppApplication);
//
// Contact functions
//
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabExportContact(string pwzPeerNAme, ref string ppwzContactData);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabParseContact(string pwzContactData, out SafeCollabData ppContactData);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetContact(string pwzPeerName, out SafeCollabData ppwzContactData);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabQueryContactData(IntPtr pcEndpoint, ref string ppwzContactData);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabAddContact(string pwzContactData, out SafeCollabData ppContact);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabDeleteContact(string pwzPeerName);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabUpdateContact(ref PEER_CONTACT pc);
//
// Endpoint functions
//
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabRefreshEndpointData(IntPtr pcEndpoint);
//
// Event functions
//
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabRegisterEvent(SafeWaitHandle hEvent, UInt32 cEventRegistration,
ref PEER_COLLAB_EVENT_REGISTRATION pEventRegistrations,
out SafeCollabEvent phPeerEvent);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetEventData(SafeCollabEvent hPeerEvent,
out SafeCollabData ppEventData);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabUnregisterEvent(IntPtr handle);
//
private const string CRYPT32 = "crypt32.dll";
//
// Certificate functions
//
[System.Security.SecurityCritical]
[DllImport(CRYPT32, CharSet = CharSet.Auto, SetLastError = true)]
internal extern static SafeCertStore CertOpenStore(IntPtr lpszStoreProvider, uint dwMsgAndCertEncodingType,
IntPtr hCryptProv, uint dwFlags, ref PEER_DATA pvPara);
[System.Security.SecurityCritical]
[DllImport(CRYPT32, CharSet = CharSet.Auto, SetLastError = true)]
internal extern static SafeCertStore CertOpenStore(IntPtr lpszStoreProvider, uint dwMsgAndCertEncodingType,
IntPtr hCryptProv, uint dwFlags, IntPtr pvPara);
[DllImport(CRYPT32, CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.U1)]
internal extern static bool CertCloseStore(IntPtr hCertStore, uint dwFlags);
[System.Security.SecurityCritical]
[DllImport(CRYPT32, CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.U1)]
internal extern static bool CertSaveStore( SafeCertStore hCertStore, uint dwMsgAndCertEncodingType,
uint dwSaveAs, uint dwSaveTo, ref PEER_DATA pvSafeToPara, uint dwFlags);
//
// My Contact functions
//
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetEndpointName(ref string ppwzEndpointName);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabSetEndpointName(string pwzEndpointName);
//
// Invitation functions
//
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabGetInvitationResponse(SafeCollabInvite hInvitation,
out SafeCollabData ppInvitationResponse);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabCancelInvitation(SafeCollabInvite hInvitation);
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabCloseHandle(IntPtr hInvitation);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabInviteContact( ref PEER_CONTACT pcContact,
IntPtr pcEndpoint,
ref PEER_INVITATION pcInvitation,
out SafeCollabData ppResponse);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabAsyncInviteContact(ref PEER_CONTACT pcContact,
IntPtr pcEndpoint,
ref PEER_INVITATION pcInvitation,
SafeWaitHandle hEvent,
out SafeCollabInvite phInvitation);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabInviteEndpoint( IntPtr pcEndpoint,
ref PEER_INVITATION pcInvitation,
out SafeCollabData ppResponse);
[SecurityCritical]
[DllImport(P2P, CharSet = CharSet.Unicode)]
internal extern static int PeerCollabAsyncInviteEndpoint( IntPtr pcEndpoint,
ref PEER_INVITATION pcInvitation,
SafeWaitHandle hEvent,
out SafeCollabInvite phInvitation);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Server.IntegrationTesting.IIS;
using Microsoft.Extensions.Logging;
using Xunit;
namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests
{
public class EventLogHelpers
{
public static void VerifyEventLogEvent(IISDeploymentResult deploymentResult, string expectedRegexMatchString, ILogger logger, bool allowMultiple = false)
{
Assert.True(deploymentResult.HostProcess.HasExited);
var entries = GetEntries(deploymentResult);
try
{
AssertEntry(expectedRegexMatchString, entries, allowMultiple);
}
catch (Exception)
{
foreach (var entry in entries)
{
logger.LogInformation("'{Message}', generated {Generated}, written {Written}", entry.Message, entry.TimeGenerated, entry.TimeWritten);
}
throw;
}
}
public static void VerifyEventLogEvents(IISDeploymentResult deploymentResult, params string[] expectedRegexMatchString)
{
Assert.True(deploymentResult.HostProcess.HasExited);
var entries = GetEntries(deploymentResult).ToList();
foreach (var regexString in expectedRegexMatchString)
{
var matchedEntries = AssertEntry(regexString, entries);
foreach (var matchedEntry in matchedEntries)
{
entries.Remove(matchedEntry);
}
}
Assert.True(0 == entries.Count, $"Some entries were not matched by any regex {FormatEntries(entries)}");
}
public static string OnlyOneAppPerAppPool()
{
if (DeployerSelector.HasNewShim)
{
return "Only one in-process application is allowed per IIS application pool. Please assign the application '(.*)' to a different IIS application pool.";
}
else
{
return "Only one inprocess application is allowed per IIS application pool";
}
}
private static EventLogEntry[] AssertEntry(string regexString, IEnumerable<EventLogEntry> entries, bool allowMultiple = false)
{
var expectedRegex = new Regex(regexString, RegexOptions.Singleline);
var matchedEntries = entries.Where(entry => expectedRegex.IsMatch(entry.Message)).ToArray();
Assert.True(matchedEntries.Length > 0, $"No entries matched by '{regexString}'");
Assert.True(allowMultiple || matchedEntries.Length < 2, $"Multiple entries matched by '{regexString}': {FormatEntries(matchedEntries)}");
return matchedEntries;
}
private static string FormatEntries(IEnumerable<EventLogEntry> entries)
{
return string.Join(",", entries.Select(e => e.Message));
}
private static IEnumerable<EventLogEntry> GetEntries(IISDeploymentResult deploymentResult)
{
var eventLog = new EventLog("Application");
// Eventlog is already sorted based on time of event in ascending time.
// Check results in reverse order.
var processIdString = $"Process Id: {deploymentResult.HostProcess.Id}.";
// Event log messages round down to the nearest second, so subtract 5 seconds to make sure we get event logs
var processStartTime = deploymentResult.HostProcess.StartTime.AddSeconds(-5);
for (var i = eventLog.Entries.Count - 1; i >= 0; i--)
{
var eventLogEntry = eventLog.Entries[i];
if (eventLogEntry.TimeGenerated < processStartTime)
{
// If event logs is older than the process start time, we didn't find a match.
break;
}
if (eventLogEntry.ReplacementStrings == null ||
eventLogEntry.ReplacementStrings.Length < 3)
{
continue;
}
// ReplacementStings == EventData collection in EventLog
// This is unaffected if event providers are not registered correctly
if (eventLogEntry.Source == AncmVersionToMatch(deploymentResult) &&
processIdString == eventLogEntry.ReplacementStrings[1])
{
yield return eventLogEntry;
}
}
}
private static string AncmVersionToMatch(IISDeploymentResult deploymentResult)
{
return "IIS " +
(deploymentResult.DeploymentParameters.ServerType == ServerType.IISExpress ? "Express " : "") +
"AspNetCore Module V2";
}
public static string Started(IISDeploymentResult deploymentResult)
{
if (deploymentResult.DeploymentParameters.HostingModel == HostingModel.InProcess)
{
return InProcessStarted(deploymentResult);
}
else
{
return OutOfProcessStarted(deploymentResult);
}
}
public static string InProcessStarted(IISDeploymentResult deploymentResult)
{
if (DeployerSelector.HasNewHandler)
{
return $"Application '{EscapedContentRoot(deploymentResult)}' started successfully.";
}
else
{
return $"Application '{EscapedContentRoot(deploymentResult)}' started the coreclr in-process successfully";
}
}
public static string OutOfProcessStarted(IISDeploymentResult deploymentResult)
{
return $"Application '/LM/W3SVC/1/ROOT' started process '\\d+' successfully and process '\\d+' is listening on port '\\d+'.";
}
public static string InProcessFailedToStart(IISDeploymentResult deploymentResult, string reason)
{
if (DeployerSelector.HasNewHandler)
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' failed to load coreclr. Exception message:\r\n{reason}";
}
else
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' failed to load clr and managed application. {reason}";
}
}
public static string InProcessShutdown()
{
return "Application 'MACHINE/WEBROOT/APPHOST/.*?' has shutdown.";
}
public static string ShutdownFileChange(IISDeploymentResult deploymentResult)
{
return $"Application '{EscapedContentRoot(deploymentResult)}' was recycled after detecting file change in application directory.";
}
public static string InProcessFailedToStop(IISDeploymentResult deploymentResult, string reason)
{
return "Failed to gracefully shutdown application 'MACHINE/WEBROOT/APPHOST/.*?'.";
}
public static string InProcessThreadException(IISDeploymentResult deploymentResult, string reason)
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' hit unexpected managed exception{reason}";
}
public static string InProcessThreadExit(IISDeploymentResult deploymentResult, string code)
{
if (DeployerSelector.HasNewHandler)
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' has exited from Program.Main with exit code = '{code}'. Please check the stderr logs for more information.";
}
else
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' hit unexpected managed background thread exit, exit code = '{code}'.";
}
}
public static string InProcessThreadExitStdOut(IISDeploymentResult deploymentResult, string code, string output)
{
if (DeployerSelector.HasNewHandler)
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' has exited from Program.Main with exit code = '{code}'. First 30KB characters of captured stdout and stderr logs:\r\n{output}";
}
else
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' hit unexpected managed background thread exit, exit code = '{code}'. Last 4KB characters of captured stdout and stderr logs:\r\n{output}";
}
}
public static string FailedToStartApplication(IISDeploymentResult deploymentResult, string code)
{
return $"Failed to start application '/LM/W3SVC/1/ROOT', ErrorCode '{code}'.";
}
public static string ConfigurationLoadError(IISDeploymentResult deploymentResult, string reason)
{
if (DeployerSelector.HasNewShim)
{
return $"Could not load configuration. Exception message:\r\n{reason}";
}
else
{
return $"Could not load configuration. Exception message: {reason}";
}
}
public static string OutOfProcessFailedToStart(IISDeploymentResult deploymentResult, string output)
{
if (DeployerSelector.HasNewShim)
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' failed to start process with " +
$"commandline '(.*)' with multiple retries. " +
$"Failed to bind to port '(.*)'. First 30KB characters of captured stdout and stderr logs from multiple retries:\r\n{output}";
}
else
{
return $"Application '/LM/W3SVC/1/ROOT' with physical root '{EscapedContentRoot(deploymentResult)}' failed to start process with " +
$"commandline '(.*)' with multiple retries. " +
$"The last try of listening port is '(.*)'. See previous warnings for details.";
}
}
public static string InProcessHostfxrInvalid(IISDeploymentResult deploymentResult)
{
return $"Hostfxr version used does not support 'hostfxr_get_native_search_directories', update the version of hostfxr to a higher version. Path to hostfxr: '(.*)'.";
}
public static string InProcessHostfxrUnableToLoad(IISDeploymentResult deploymentResult)
{
return $"Unable to load '(.*)'. This might be caused by a bitness mismatch between IIS application pool and published application.";
}
public static string InProcessFailedToFindNativeDependencies(IISDeploymentResult deploymentResult)
{
if (DeployerSelector.HasNewShim)
{
return "Unable to locate application dependencies. Ensure that the versions of Microsoft.NetCore.App and Microsoft.AspNetCore.App targeted by the application are installed.";
}
else
{
return "Invoking hostfxr to find the inprocess request handler failed without finding any native dependencies. " +
"This most likely means the app is misconfigured, please check the versions of Microsoft.NetCore.App and Microsoft.AspNetCore.App that " +
"are targeted by the application and are installed on the machine.";
}
}
public static string InProcessFailedToFindRequestHandler(IISDeploymentResult deploymentResult)
{
if (DeployerSelector.HasNewShim)
{
return "Could not find the assembly '(.*)' referenced for the in-process application. Please confirm the Microsoft.AspNetCore.Server.IIS or Microsoft.AspNetCore.App is referenced in your application.";
}
else
{
return "Could not find the assembly '(.*)' referenced for the in-process application. Please confirm the Microsoft.AspNetCore.Server.IIS package is referenced in your application.";
}
}
public static string CouldNotStartStdoutFileRedirection(string file, IISDeploymentResult deploymentResult)
{
return
$"Could not start stdout file redirection to '{Regex.Escape(file)}' with application base '{EscapedContentRoot(deploymentResult)}'.";
}
public static string CouldNotFindHandler()
{
if (DeployerSelector.HasNewShim)
{
return "Could not find 'aspnetcorev2_inprocess.dll'";
}
else
{
return "Could not find the assembly 'aspnetcorev2_inprocess.dll'";
}
}
public static string UnableToStart(IISDeploymentResult deploymentResult, string subError)
{
if (DeployerSelector.HasNewShim)
{
return $@"Application '{Regex.Escape(deploymentResult.ContentRoot)}\\' failed to start. Exception message:\r\n{subError}";
}
else
{
return $@"Application '{Regex.Escape(deploymentResult.ContentRoot)}\\' wasn't able to start. {subError}";
}
}
public static string FrameworkNotFound()
{
if (DeployerSelector.HasNewShim)
{
return "Unable to locate application dependencies. Ensure that the versions of Microsoft.NetCore.App and Microsoft.AspNetCore.App targeted by the application are installed.";
}
else
{
return "The framework 'Microsoft.NETCore.App', version '2.9.9' was not found.";
}
}
private static string EscapedContentRoot(IISDeploymentResult deploymentResult)
{
var contentRoot = deploymentResult.ContentRoot;
if (!contentRoot.EndsWith('\\'))
{
contentRoot += '\\';
}
return Regex.Escape(contentRoot);
}
}
}
| |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.AdManager.v202202;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Reflection;
namespace Google.Api.Ads.AdManager.Util.v202202
{
/// <summary>
/// A utility class for handling PQL objects.
/// </summary>
public class PqlUtilities
{
/// <summary>
/// Gets the underlying value of the Value object. For SetValues, returns
/// a List of underlying values.
/// </summary>
/// <value>The Value object to get the value from.</value>
/// <returns>The underlying value, or List of underlying values from a SetValue.</returns>
public static object GetValue(Value value)
{
if (value is SetValue)
{
PropertyInfo propInfo = value.GetType().GetProperty("values");
if (propInfo != null)
{
Value[] setValues = propInfo.GetValue(value, null) as Value[];
List<object> extractedValues = new List<object>();
foreach (Value setValue in setValues)
{
validateSetValueForSet(GetValue(setValue), extractedValues);
extractedValues.Add(GetValue(setValue));
}
return extractedValues;
}
}
else
{
PropertyInfo propInfo = value.GetType().GetProperty("value");
if (propInfo != null)
{
return propInfo.GetValue(value, null);
}
}
return null;
}
private static void validateSetValueForSet(object entry, IList<object> set)
{
if (entry is IList<object> || entry is SetValue)
{
throw new ArgumentException("Unsupported Value type [nested sets]");
}
if (set.Count > 0)
{
IEnumerator<Object> enumerator = set.GetEnumerator();
enumerator.MoveNext();
Object existingEntry = enumerator.Current;
if (!existingEntry.GetType().IsAssignableFrom(entry.GetType()))
{
throw new ArgumentException(String.Format(
"Unsupported Value type [SetValue with " + "mixed types {0} and {1}]",
existingEntry.GetType(), entry.GetType()));
}
}
}
/// <summary>
/// Gets the result set as list of string arrays.
/// </summary>
/// <param name="resultSet">The result set to convert to a string array list.</param>
/// <returns>A list of string arrays representing the result set.</returns>
public static List<String[]> ResultSetToStringArrayList(ResultSet resultSet)
{
List<string[]> stringArrayList = new List<string[]>();
stringArrayList.Add(GetColumnLabels(resultSet));
if (resultSet.rows != null)
{
foreach (Row row in resultSet.rows)
{
stringArrayList.Add(GetRowStringValues(row));
}
}
return stringArrayList;
}
/// <summary>
/// Gets the result set as a table represenation in the form of:
///
/// <pre>
/// +-------+-------+-------+
/// |column1|column2|column3|
/// +-------+-------+-------+
/// |value1 |value2 |value3 |
/// +-------+-------+-------+
/// |value1 |value2 |value3 |
/// +-------+-------+-------+
/// </pre>
/// </summary>
/// <param name="resultSet">The result set to display as a string</param>
/// <returns>The string represenation of result set as a table.</returns>
public static String ResultSetToString(ResultSet resultSet)
{
StringBuilder resultSetStringBuilder = new StringBuilder();
List<String[]> resultSetStringArrayList = ResultSetToStringArrayList(resultSet);
List<int> maxColumnSizes = GetMaxColumnSizes(resultSetStringArrayList);
string rowTemplate = CreateRowTemplate(maxColumnSizes);
string rowSeparator = CreateRowSeperator(maxColumnSizes);
resultSetStringBuilder.Append(rowSeparator);
for (int i = 0; i < resultSetStringArrayList.Count; i++)
{
resultSetStringBuilder
.AppendFormat(rowTemplate, (object[]) resultSetStringArrayList[i])
.Append(rowSeparator);
}
return resultSetStringBuilder.ToString();
}
/// <summary>
/// Creates the row template given the maximum size for each column.
/// </summary>
/// <param name="maxColumnSizes">The maximum size for each column</param>
/// <returns>The row template to format row data into.</returns>
private static string CreateRowTemplate(List<int> maxColumnSizes)
{
List<String> columnFormatSpecifiers = new List<string>();
int i = 0;
foreach (int maxColumnSize in maxColumnSizes)
{
columnFormatSpecifiers.Add(string.Format("{{{0},{1}}}", i, maxColumnSize));
i++;
}
return new StringBuilder("| ")
.Append(string.Join(" | ", columnFormatSpecifiers.ToArray())).Append(" |\n")
.ToString();
}
/// <summary>
/// Creates the row seperator given the maximum size for each column.
/// </summary>
/// <param name="maxColumnSizes">The maximum size for each column.</param>
/// <returns>The row seperator.</returns>
private static String CreateRowSeperator(List<int> maxColumnSizes)
{
StringBuilder rowSeperator = new StringBuilder("+");
foreach (int maxColumnSize in maxColumnSizes)
{
for (int i = 0; i < maxColumnSize + 2; i++)
{
rowSeperator.Append("-");
}
rowSeperator.Append("+");
}
return rowSeperator.Append("\n").ToString();
}
/// <summary>
/// Gets a list of the maximum size for each column.
/// </summary>
/// <param name="resultSet">The result set to process.</param>
/// <returns>A list of the maximum size for each column.</returns>
private static List<int> GetMaxColumnSizes(List<string[]> resultSet)
{
List<int> maxColumnSizes = new List<int>();
for (int i = 0; i < resultSet[i].Length; i++)
{
int maxColumnSize = -1;
for (int j = 0; j < resultSet.Count; j++)
{
if (resultSet[j][i].Length > maxColumnSize)
{
maxColumnSize = resultSet[j][i].Length;
}
}
maxColumnSizes.Add(maxColumnSize);
}
return maxColumnSizes;
}
/// <summary>
/// Gets the column labels for the result set.
/// </summary>
/// <param name="resultSet">The result set to get the column labels for.
/// </param>
/// <returns>The string array of column labels.</returns>
public static String[] GetColumnLabels(ResultSet resultSet)
{
List<string> columnLabels = new List<string>();
foreach (ColumnType column in resultSet.columnTypes)
{
columnLabels.Add(column.labelName);
}
return columnLabels.ToArray();
}
/// <summary>
/// Gets the row values for a row of the result set in the form of an object
/// array.
/// </summary>
/// <param name="row">The row to get the values for.</param>
/// <returns>The object array of the row values.</returns>
public static object[] GetRowValues(Row row)
{
List<object> rowValues = new List<object>();
foreach (Value value in row.values)
{
rowValues.Add(GetValue(value));
}
return rowValues.ToArray();
}
/// <summary>
/// Gets the row values for a row of the result set in a the form of a string
/// array. <code>null</code> values are interperted as empty strings.
/// </summary>
/// <param name="row">The row to get the values for.</param>
/// <returns>The string array of the row values.</returns>
public static String[] GetRowStringValues(Row row)
{
object[] rowValues = GetRowValues(row);
List<string> rowStringValues = new List<string>();
foreach (object obj in rowValues)
{
rowStringValues.Add(GetTextValue(obj));
}
return rowStringValues.ToArray();
}
/// <summary>
/// Gets the text value of an unwrapped Value object.
/// </summary>
/// <param name="value">The unwrapped Value.</param>
/// <returns>A formatted text representation of the value.</returns>
/// <remarks>DateValue is formatted in yyyy-mm-dd format. DateTimeValue is
/// formatted in yyyy-mm-dd HH:mm:ss Z format.</remarks>
private static string GetTextValue(Object value)
{
if (value == null)
{
return "";
}
if (value is Google.Api.Ads.AdManager.v202202.Date)
{
Google.Api.Ads.AdManager.v202202.Date date =
(Google.Api.Ads.AdManager.v202202.Date) value;
return string.Format("{0:0000}-{1:00}-{2:00}", date.year, date.month, date.day);
}
else if (value is Google.Api.Ads.AdManager.v202202.DateTime)
{
Google.Api.Ads.AdManager.v202202.DateTime dateTime =
(Google.Api.Ads.AdManager.v202202.DateTime) value;
return string.Format("{0:0000}-{1:00}-{2:00}T{3:00}:{4:00}:{5:00} {6}",
dateTime.date.year, dateTime.date.month, dateTime.date.day, dateTime.hour,
dateTime.minute, dateTime.second, dateTime.timeZoneId);
}
else if (value is List<object>)
{
List<string> textValues = (value as List<object>)
.ConvertAll(new Converter<object, string>(GetTextValue))
.ConvertAll(new Converter<string, string>(EscapeCsv));
return String.Join<string>(",", textValues);
}
else
{
// NumberValue, BooleanValue, TextValue
return value.ToString();
}
}
private static string EscapeCsv(string value)
{
value = value.Replace("\"", "\"\"");
if (value.Contains(",") || value.Contains("\""))
{
value = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", value);
}
return value;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests
{
public class CastTests : EnumerableTests
{
[Fact]
public void CastIntToLongThrows()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst = q.Cast<long>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void CastByteToUShortThrows()
{
var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 }
select x;
var rst = q.Cast<ushort>();
Assert.Throws<InvalidCastException>(() => { foreach (var t in rst) ; });
}
[Fact]
public void EmptySource()
{
object[] source = { };
Assert.Empty(source.Cast<int>());
}
[Fact]
public void NullableIntFromAppropriateObjects()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
int?[] expected = { -4, 1, 2, 3, 9, i };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void LongFromNullableIntInObjectsThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, i };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LongFromNullableIntInObjectsIncludingNullThrows()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromAppropriateObjectsIncludingNull()
{
int? i = 10;
object[] source = { -4, 1, 2, 3, 9, null, i };
int?[] expected = { -4, 1, 2, 3, 9, null, i };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowOnUncastableItem()
{
object[] source = { -4, 1, 2, 3, 9, "45" };
int[] expectedBeginning = { -4, 1, 2, 3, 9 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
Assert.Equal(expectedBeginning, cast.Take(5));
Assert.Throws<InvalidCastException>(() => cast.ElementAt(5));
}
[Fact]
public void ThrowCastingIntToDouble()
{
int[] source = new int[] { -4, 1, 2, 9 };
IEnumerable<double> cast = source.Cast<double>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
private static void TestCastThrow<T>(object o)
{
byte? i = 10;
object[] source = { -1, 0, o, i };
IEnumerable<T> cast = source.Cast<T>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowOnHeterogenousSource()
{
TestCastThrow<long?>(null);
TestCastThrow<long>(9L);
}
[Fact]
public void CastToString()
{
object[] source = { "Test1", "4.5", null, "Test2" };
string[] expected = { "Test1", "4.5", null, "Test2" };
Assert.Equal(expected, source.Cast<string>());
}
[Fact]
public void ArrayConversionThrows()
{
Assert.Throws<InvalidCastException>(() => new[] { -4 }.Cast<long>().ToList());
}
[Fact]
public void FirstElementInvalidForCast()
{
object[] source = { "Test", 3, 5, 10 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void LastElementInvalidForCast()
{
object[] source = { -5, 9, 0, 5, 9, "Test" };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void NullableIntFromNullsAndInts()
{
object[] source = { 3, null, 5, -4, 0, null, 9 };
int?[] expected = { 3, null, 5, -4, 0, null, 9 };
Assert.Equal(expected, source.Cast<int?>());
}
[Fact]
public void ThrowCastingIntToLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingIntToNullableLong()
{
int[] source = new int[] { -4, 1, 2, 3, 9 };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9 };
IEnumerable<long> cast = source.Cast<long>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void ThrowCastingNullableIntToNullableLong()
{
int?[] source = new int?[] { -4, 1, 2, 3, 9, null };
IEnumerable<long?> cast = source.Cast<long?>();
Assert.Throws<InvalidCastException>(() => cast.ToList());
}
[Fact]
public void CastingNullToNonnullableIsNullReferenceException()
{
int?[] source = new int?[] { -4, 1, null, 3 };
IEnumerable<int> cast = source.Cast<int>();
Assert.Throws<NullReferenceException>(() => cast.ToList());
}
[Fact]
public void NullSource()
{
Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<object>)null).Cast<string>());
}
[Fact]
public void ForcedToEnumeratorDoesntEnumerate()
{
var iterator = new object[0].Where(i => i != null).Cast<string>();
// Don't insist on this behaviour, but check its correct if it happens
var en = iterator as IEnumerator<string>;
Assert.False(en != null && en.MoveNext());
}
}
}
| |
// Copyright (C) 2012-2015 Luca Piccioni
//
// 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.Diagnostics;
namespace OpenGL.Objects.State
{
/// <summary>
/// Specify how polygons are rasterized.
/// </summary>
[DebuggerDisplay("PolygonOffsetState: Modes={Modes} Factor={Factor} Units={Units}")]
public class PolygonOffsetState : GraphicsState
{
#region Constructors
/// <summary>
///
/// </summary>
public PolygonOffsetState()
{
}
/// <summary>
///
/// </summary>
/// <param name="factor"></param>
/// <param name="units"></param>
public PolygonOffsetState(float factor, float units) :
this(Mode.All, factor, units)
{
}
/// <summary>
///
/// </summary>
/// <param name="modes"></param>
/// <param name="factor"></param>
/// <param name="units"></param>
public PolygonOffsetState(Mode modes, float factor, float units)
{
_Modes = modes;
_Factor = factor;
_Units = units;
}
/// <summary>
/// Construct the current PolygonOffsetState.
/// </summary>
/// <param name='ctx'>
/// Context.
/// </param>
public PolygonOffsetState(GraphicsContext ctx)
{
if (ctx == null)
throw new ArgumentNullException("ctx");
Mode modes = Mode.None;
if (Gl.IsEnabled(EnableCap.PolygonOffsetPoint))
modes |= Mode.Point;
if (Gl.IsEnabled(EnableCap.PolygonOffsetLine))
modes |= Mode.Line;
if (Gl.IsEnabled(EnableCap.PolygonOffsetFill))
modes |= Mode.Fill;
Gl.Get(Gl.POLYGON_OFFSET_FACTOR, out _Factor);
Gl.Get(Gl.POLYGON_OFFSET_UNITS, out _Units);
}
#endregion
#region Information
/// <summary>
/// Modes affected by this state.
/// </summary>
[Flags]
public enum Mode
{
/// <summary>
/// No offset.
/// </summary>
None = 0x00,
/// <summary>
/// Offset applied to rasterized points.
/// </summary>
Point = 0x01,
/// <summary>
/// Offset applied to rasterized lines.
/// </summary>
Line = 0x02,
/// <summary>
/// Offset applied to rasterized polygons.
/// </summary>
Fill = 0x04,
/// <summary>
/// Offset applied to rasterized fragments.
/// </summary>
All = Point | Line | Fill,
}
/// <summary>
/// Modes affected by the polygon offset.
/// </summary>
public Mode Modes { get { return (_Modes); } set { _Modes = value; } }
/// <summary>
/// Modes affected
/// </summary>
private Mode _Modes = Mode.None;
/// <summary>
/// Specify the offset applied to depth of the polygon.
/// </summary>
public float Factor { get { return (_Factor); } set { _Factor = value; } }
/// <summary>
/// Specifies a scale factor that is used to create a variable depth offset for each polygon.
/// </summary>
private float _Factor;
/// <summary>
/// Specify the units of <see cref="Factor"/>.
/// </summary>
public float Units { get { return (_Units); } set { _Units = value; } }
/// <summary>
/// Is multiplied by an implementation-specific value to create a constant depth offset.
/// </summary>
private float _Units;
#endregion
#region Default State
/// <summary>
/// The system default state for PolygonOffsetState.
/// </summary>
public static PolygonOffsetState DefaultState { get { return (new PolygonOffsetState()); } }
#endregion
#region GraphicsState Overrides
/// <summary>
/// The identifier for the blend state.
/// </summary>
public static string StateId = "OpenGL.PolygonOffset";
/// <summary>
/// The identifier of this GraphicsState.
/// </summary>
public override string StateIdentifier { get { return (StateId); } }
/// <summary>
/// Unique index assigned to this GraphicsState.
/// </summary>
public static int StateSetIndex { get { return (_StateIndex); } }
/// <summary>
/// Unique index assigned to this GraphicsState.
/// </summary>
public override int StateIndex { get { return (_StateIndex); } }
/// <summary>
/// The index for this GraphicsState.
/// </summary>
private static int _StateIndex = NextStateIndex();
/// <summary>
/// Set ShaderProgram state.
/// </summary>
/// <param name="ctx">
/// A <see cref="GraphicsContext"/> which has defined the shader program <paramref name="program"/>.
/// </param>
/// <param name="program">
/// The <see cref="ShaderProgram"/> which has the state set.
/// </param>
public override void Apply(GraphicsContext ctx, ShaderProgram program)
{
if (ctx == null)
throw new ArgumentNullException("ctx");
PolygonOffsetState currentState = (PolygonOffsetState)ctx.GetCurrentState(StateIndex);
if (currentState != null)
ApplyStateCore(ctx, program, currentState);
else
ApplyStateCore(ctx, program);
ctx.SetCurrentState(this);
}
private void ApplyStateCore(GraphicsContext ctx, ShaderProgram program)
{
// Enable polygon offset for all primitive
if ((_Modes & Mode.Point) != 0) {
Gl.Enable(EnableCap.PolygonOffsetPoint);
} else {
Gl.Disable(EnableCap.PolygonOffsetPoint);
}
if ((_Modes & Mode.Line) != 0) {
Gl.Enable(EnableCap.PolygonOffsetLine);
} else {
Gl.Disable(EnableCap.PolygonOffsetLine);
}
if ((_Modes & Mode.Fill) != 0) {
Gl.Enable(EnableCap.PolygonOffsetFill);
} else {
Gl.Disable(EnableCap.PolygonOffsetFill);
}
// Set polygon offset
Gl.PolygonOffset(_Factor, _Units);
}
private void ApplyStateCore(GraphicsContext ctx, ShaderProgram program, PolygonOffsetState currentState)
{
if (currentState._Modes != _Modes) {
bool currentMode, thisMode;
currentMode = (currentState._Modes & Mode.Point) != 0;
thisMode = (_Modes & Mode.Point) != 0;
if (currentMode != thisMode) {
if (thisMode)
Gl.Enable(EnableCap.PolygonOffsetPoint);
else
Gl.Disable(EnableCap.PolygonOffsetPoint);
}
currentMode = (currentState._Modes & Mode.Line) != 0;
thisMode = (_Modes & Mode.Line) != 0;
if (currentMode != thisMode) {
if (thisMode)
Gl.Enable(EnableCap.PolygonOffsetLine);
else
Gl.Disable(EnableCap.PolygonOffsetLine);
}
currentMode = (currentState._Modes & Mode.Fill) != 0;
thisMode = (_Modes & Mode.Fill) != 0;
if (currentMode != thisMode) {
if (thisMode)
Gl.Enable(EnableCap.PolygonOffsetFill);
else
Gl.Disable(EnableCap.PolygonOffsetFill);
}
}
// Set polygon offset
if (Math.Abs(currentState._Factor - _Factor) >= Single.Epsilon || Math.Abs(currentState._Units - _Units) >= Single.Epsilon)
Gl.PolygonOffset(_Factor, _Units);
}
/// <summary>
/// Merge this state with another one.
/// </summary>
/// <param name="state">
/// A <see cref="IGraphicsState"/> having the same <see cref="StateIdentifier"/> of this state.
/// </param>
public override void Merge(IGraphicsState state)
{
if (state == null)
throw new ArgumentNullException("state");
PolygonOffsetState otherState = state as PolygonOffsetState;
if (otherState == null)
throw new ArgumentException("not a PolygonOffsetState", "state");
_Modes = otherState._Modes;
_Factor = otherState._Factor;
_Units = otherState._Units;
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">
/// A <see cref="GraphicsState"/> to compare to this GraphicsState.
/// </param>
/// <returns>
/// It returns true if the current object is equal to <paramref name="other"/>.
/// </returns>
/// <remarks>
/// <para>
/// This method test only whether <paramref name="other"/> type equals to this type.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// This exception is thrown if the parameter <paramref name="other"/> is null.
/// </exception>
public override bool Equals(IGraphicsState other)
{
if (base.Equals(other) == false)
return (false);
Debug.Assert(other is PolygonOffsetState);
PolygonOffsetState otherState = (PolygonOffsetState)other;
if (_Modes != otherState._Modes)
return (false);
if (Math.Abs(_Factor - otherState._Factor) >= Single.Epsilon)
return (false);
if (Math.Abs(_Units - otherState._Units) >= Single.Epsilon)
return (false);
return (true);
}
#endregion
}
}
| |
using Discord.Audio;
using Discord.Rest;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
using UserModel = Discord.API.User;
using VoiceStateModel = Discord.API.VoiceState;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based private group channel.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketGroupChannel : SocketChannel, IGroupChannel, ISocketPrivateChannel, ISocketMessageChannel, ISocketAudioChannel
{
private readonly MessageCache _messages;
private readonly ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
private string _iconId;
private ConcurrentDictionary<ulong, SocketGroupUser> _users;
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>();
public new IReadOnlyCollection<SocketGroupUser> Users => _users.ToReadOnlyCollection();
public IReadOnlyCollection<SocketGroupUser> Recipients
=> _users.Select(x => x.Value).Where(x => x.Id != Discord.CurrentUser.Id).ToReadOnlyCollection(() => _users.Count - 1);
internal SocketGroupChannel(DiscordSocketClient discord, ulong id)
: base(discord, id)
{
if (Discord.MessageCacheSize > 0)
_messages = new MessageCache(Discord);
_voiceStates = new ConcurrentDictionary<ulong, SocketVoiceState>(ConcurrentHashSet.DefaultConcurrencyLevel, 5);
_users = new ConcurrentDictionary<ulong, SocketGroupUser>(ConcurrentHashSet.DefaultConcurrencyLevel, 5);
}
internal static SocketGroupChannel Create(DiscordSocketClient discord, ClientState state, Model model)
{
var entity = new SocketGroupChannel(discord, model.Id);
entity.Update(state, model);
return entity;
}
internal override void Update(ClientState state, Model model)
{
if (model.Name.IsSpecified)
Name = model.Name.Value;
if (model.Icon.IsSpecified)
_iconId = model.Icon.Value;
if (model.Recipients.IsSpecified)
UpdateUsers(state, model.Recipients.Value);
}
private void UpdateUsers(ClientState state, UserModel[] models)
{
var users = new ConcurrentDictionary<ulong, SocketGroupUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(models.Length * 1.05));
for (int i = 0; i < models.Length; i++)
users[models[i].Id] = SocketGroupUser.Create(this, state, models[i]);
_users = users;
}
/// <inheritdoc />
public Task LeaveAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
/// <exception cref="NotSupportedException">Voice is not yet supported for group channels.</exception>
public Task<IAudioClient> ConnectAsync()
{
throw new NotSupportedException("Voice is not yet supported for group channels.");
}
//Messages
/// <inheritdoc />
public SocketMessage GetCachedMessage(ulong id)
=> _messages?.Get(id);
/// <summary>
/// Gets a message from this message channel.
/// </summary>
/// <remarks>
/// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessageAsync"/>.
/// Please visit its documentation for more details on this method.
/// </remarks>
/// <param name="id">The snowflake identifier of the message.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents an asynchronous get operation for retrieving the message. The task result contains
/// the retrieved message; <c>null</c> if no message is found with the specified identifier.
/// </returns>
public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null)
{
IMessage msg = _messages?.Get(id);
if (msg == null)
msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false);
return msg;
}
/// <summary>
/// Gets the last N messages from this message channel.
/// </summary>
/// <remarks>
/// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(int, CacheMode, RequestOptions)"/>.
/// Please visit its documentation for more details on this method.
/// </remarks>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options);
/// <summary>
/// Gets a collection of messages in this channel.
/// </summary>
/// <remarks>
/// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(ulong, Direction, int, CacheMode, RequestOptions)"/>.
/// Please visit its documentation for more details on this method.
/// </remarks>
/// <param name="fromMessageId">The ID of the starting message to get the messages from.</param>
/// <param name="dir">The direction of the messages to be gotten from.</param>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options);
/// <summary>
/// Gets a collection of messages in this channel.
/// </summary>
/// <remarks>
/// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(IMessage, Direction, int, CacheMode, RequestOptions)"/>.
/// Please visit its documentation for more details on this method.
/// </remarks>
/// <param name="fromMessage">The starting message to get the messages from.</param>
/// <param name="dir">The direction of the messages to be gotten from.</param>
/// <param name="limit">The numbers of message to be gotten from.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// Paged collection of messages.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options);
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch)
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit);
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit);
/// <inheritdoc />
public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
=> SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit);
/// <inheritdoc />
public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
=> ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
=> ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options);
/// <inheritdoc />
public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false)
=> ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options, isSpoiler);
/// <inheritdoc />
public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false)
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options, isSpoiler);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
internal void AddMessage(SocketMessage msg)
=> _messages?.Add(msg);
internal SocketMessage RemoveMessage(ulong id)
=> _messages?.Remove(id);
//Users
/// <summary>
/// Gets a user from this group.
/// </summary>
/// <param name="id">The snowflake identifier of the user.</param>
/// <returns>
/// A WebSocket-based group user associated with the snowflake identifier.
/// </returns>
public new SocketGroupUser GetUser(ulong id)
{
if (_users.TryGetValue(id, out SocketGroupUser user))
return user;
return null;
}
internal SocketGroupUser GetOrAddUser(UserModel model)
{
if (_users.TryGetValue(model.Id, out SocketGroupUser user))
return user;
else
{
var privateUser = SocketGroupUser.Create(this, Discord.State, model);
privateUser.GlobalUser.AddRef();
_users[privateUser.Id] = privateUser;
return privateUser;
}
}
internal SocketGroupUser RemoveUser(ulong id)
{
if (_users.TryRemove(id, out SocketGroupUser user))
{
user.GlobalUser.RemoveRef(Discord);
return user;
}
return null;
}
//Voice States
internal SocketVoiceState AddOrUpdateVoiceState(ClientState state, VoiceStateModel model)
{
var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel;
var voiceState = SocketVoiceState.Create(voiceChannel, model);
_voiceStates[model.UserId] = voiceState;
return voiceState;
}
internal SocketVoiceState? GetVoiceState(ulong id)
{
if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState))
return voiceState;
return null;
}
internal SocketVoiceState? RemoveVoiceState(ulong id)
{
if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState))
return voiceState;
return null;
}
/// <summary>
/// Returns the name of the group.
/// </summary>
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id}, Group)";
internal new SocketGroupChannel Clone() => MemberwiseClone() as SocketGroupChannel;
//SocketChannel
/// <inheritdoc />
internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
/// <inheritdoc />
internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
//ISocketPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => Recipients;
//IPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<IUser> IPrivateChannel.Recipients => Recipients;
//IMessageChannel
/// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options).ConfigureAwait(false);
else
return GetCachedMessage(id);
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
=> SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
/// <inheritdoc />
async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
=> await GetPinnedMessagesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler)
=> await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler)
=> await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
=> await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
//IAudioChannel
/// <inheritdoc />
/// <exception cref="NotSupportedException">Connecting to a group channel is not supported.</exception>
Task<IAudioClient> IAudioChannel.ConnectAsync(bool selfDeaf, bool selfMute, bool external) { throw new NotSupportedException(); }
Task IAudioChannel.DisconnectAsync() { throw new NotSupportedException(); }
//IChannel
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(id));
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orleans.Runtime
{
// This is the public interface to be used by the consistent ring
public interface IRingRange
{
/// <summary>
/// Check if <paramref name="n"/> is our responsibility to serve
/// </summary>
/// <returns>true if the reminder is in our responsibility range, false otherwise</returns>
bool InRange(uint n);
bool InRange(GrainReference grainReference);
}
// This is the internal interface to be used only by the different range implementations.
internal interface IRingRangeInternal : IRingRange
{
long RangeSize();
double RangePercentage();
string ToFullString();
}
public interface ISingleRange : IRingRange
{
/// <summary>
/// Exclusive
/// </summary>
uint Begin { get; }
/// <summary>
/// Inclusive
/// </summary>
uint End { get; }
}
[Serializable]
internal class SingleRange : IRingRangeInternal, IEquatable<SingleRange>, ISingleRange
{
private readonly uint begin;
private readonly uint end;
/// <summary>
/// Exclusive
/// </summary>
public uint Begin { get { return begin; } }
/// <summary>
/// Inclusive
/// </summary>
public uint End { get { return end; } }
public SingleRange(uint begin, uint end)
{
this.begin = begin;
this.end = end;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
/// <summary>
/// checks if n is element of (Begin, End], while remembering that the ranges are on a ring
/// </summary>
/// <param name="n"></param>
/// <returns>true if n is in (Begin, End], false otherwise</returns>
public bool InRange(uint n)
{
uint num = n;
if (begin < end)
{
return num > begin && num <= end;
}
// Begin > End
return num > begin || num <= end;
}
public long RangeSize()
{
if (begin < end)
{
return end - begin;
}
return RangeFactory.RING_SIZE - (begin - end);
}
public double RangePercentage()
{
return ((double)RangeSize() / (double)RangeFactory.RING_SIZE) * ((double)100.0);
}
public bool Equals(SingleRange other)
{
return other != null && begin == other.begin && end == other.end;
}
public override bool Equals(object obj)
{
return Equals(obj as SingleRange);
}
public override int GetHashCode()
{
return (int)(begin ^ end);
}
public override string ToString()
{
if (begin == 0 && end == 0)
{
return String.Format("<(0 0], Size=x{0,8:X8}, %Ring={1:0.000}%>", RangeSize(), RangePercentage());
}
return String.Format("<(x{0,8:X8} x{1,8:X8}], Size=x{2,8:X8}, %Ring={3:0.000}%>", begin, end, RangeSize(), RangePercentage());
}
public string ToCompactString()
{
return ToString();
}
public string ToFullString()
{
return ToString();
}
}
public static class RangeFactory
{
public const long RING_SIZE = ((long)uint.MaxValue) + 1;
public static IRingRange CreateFullRange()
{
return new SingleRange(0, 0);
}
public static IRingRange CreateRange(uint begin, uint end)
{
return new SingleRange(begin, end);
}
public static IRingRange CreateRange(List<IRingRange> inRanges)
{
return new GeneralMultiRange(inRanges);
}
internal static EquallyDividedMultiRange CreateEquallyDividedMultiRange(IRingRange range, int numSubRanges)
{
return new EquallyDividedMultiRange(range, numSubRanges);
}
public static IEnumerable<ISingleRange> GetSubRanges(IRingRange range)
{
if (range is SingleRange)
{
return new SingleRange[] { (SingleRange)range };
}
else if (range is GeneralMultiRange)
{
return ((GeneralMultiRange)range).Ranges;
}
return null;
}
}
[Serializable]
internal class GeneralMultiRange : IRingRangeInternal
{
private readonly List<SingleRange> ranges;
private readonly long rangeSize;
private readonly double rangePercentage;
internal IEnumerable<SingleRange> Ranges { get { return ranges; } }
internal GeneralMultiRange(IEnumerable<IRingRange> inRanges)
{
ranges = inRanges.Cast<SingleRange>().ToList();
if (ranges.Count == 0)
{
rangeSize = 0;
rangePercentage = 0;
}
else
{
rangeSize = ranges.Sum(r => r.RangeSize());
rangePercentage = ranges.Sum(r => r.RangePercentage());
}
}
public bool InRange(uint n)
{
foreach (IRingRange s in Ranges)
{
if (s.InRange(n)) return true;
}
return false;
}
public bool InRange(GrainReference grainReference)
{
return InRange(grainReference.GetUniformHashCode());
}
public long RangeSize()
{
return rangeSize;
}
public double RangePercentage()
{
return rangePercentage;
}
public override string ToString()
{
return ToCompactString();
}
public string ToCompactString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%>", RangeSize(), RangePercentage());
}
public string ToFullString()
{
if (ranges.Count == 0) return "Empty MultiRange";
if (ranges.Count == 1) return ranges[0].ToString();
return String.Format("<MultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%, {2} Ranges: {3}>", RangeSize(), RangePercentage(), ranges.Count, Utils.EnumerableToString(ranges, r => r.ToFullString()));
}
}
[Serializable]
internal class EquallyDividedMultiRange
{
[Serializable]
private class EquallyDividedSingleRange
{
private readonly List<SingleRange> ranges;
internal EquallyDividedSingleRange(SingleRange singleRange, int numSubRanges)
{
ranges = new List<SingleRange>();
if (numSubRanges == 0) throw new ArgumentException("numSubRanges is 0.", "numSubRanges");
if (numSubRanges == 1)
{
ranges.Add(singleRange);
}
else
{
uint uNumSubRanges = checked((uint)numSubRanges);
uint portion = (uint)(singleRange.RangeSize() / uNumSubRanges);
uint remainder = (uint)(singleRange.RangeSize() - portion * uNumSubRanges);
uint start = singleRange.Begin;
for (uint i = 0; i < uNumSubRanges; i++)
{
// (Begin, End]
uint end = (unchecked(start + portion));
// I want it to overflow on purpose. It will do the right thing.
if (remainder > 0)
{
end++;
remainder--;
}
ranges.Add(new SingleRange(start, end));
start = end; // nextStart
}
}
}
internal SingleRange GetSubRange(int mySubRangeIndex)
{
return ranges[mySubRangeIndex];
}
}
private readonly Dictionary<int, IRingRangeInternal> multiRanges;
private readonly long rangeSize;
private readonly double rangePercentage;
// This class takes a range and devides it into X (x being numSubRanges) equal ranges.
public EquallyDividedMultiRange(IRingRange range, int numSubRanges)
{
multiRanges = new Dictionary<int, IRingRangeInternal>();
if (range is SingleRange)
{
var fullSingleRange = range as SingleRange;
var singleDevided = new EquallyDividedSingleRange(fullSingleRange, numSubRanges);
for (int i = 0; i < numSubRanges; i++)
{
var singleRange = singleDevided.GetSubRange(i);
multiRanges[i] = singleRange;
}
}
else if (range is GeneralMultiRange)
{
var fullMultiRange = range as GeneralMultiRange;
// Take each of the single ranges in the multi range and divide each into equal sub ranges.
// Then go over all those and group them by sub range index.
var allSinglesDevided = new List<EquallyDividedSingleRange>();
foreach (var singleRange in fullMultiRange.Ranges)
{
var singleDevided = new EquallyDividedSingleRange(singleRange, numSubRanges);
allSinglesDevided.Add(singleDevided);
}
for (int i = 0; i < numSubRanges; i++)
{
var singlesForThisIndex = new List<IRingRange>();
foreach (var singleDevided in allSinglesDevided)
{
IRingRange singleRange = singleDevided.GetSubRange(i);
singlesForThisIndex.Add(singleRange);
}
IRingRangeInternal multi = (IRingRangeInternal)RangeFactory.CreateRange(singlesForThisIndex);
multiRanges[i] = multi;
}
}
if (multiRanges.Count == 0)
{
rangeSize = 0;
rangePercentage = 0;
}
else
{
rangeSize = multiRanges.Values.Sum(r => r.RangeSize());
rangePercentage = multiRanges.Values.Sum(r => r.RangePercentage());
}
}
internal IRingRange GetSubRange(int mySubRangeIndex)
{
return multiRanges[mySubRangeIndex];
}
public override string ToString()
{
return ToCompactString();
}
public string ToCompactString()
{
if (multiRanges.Count == 0) return "Empty EquallyDevidedMultiRange";
if (multiRanges.Count == 1) return multiRanges.First().Value.ToString();
return String.Format("<EquallyDevidedMultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%>", rangeSize, rangePercentage);
}
public string ToFullString()
{
if (multiRanges.Count == 0) return "Empty EquallyDevidedMultiRange";
if (multiRanges.Count == 1) return multiRanges.First().Value.ToFullString();
return String.Format("<EquallyDevidedMultiRange: Size=x{0,8:X8}, %Ring={1:0.000}%, {2} Ranges: {3}>", rangeSize, rangePercentage, multiRanges.Count,
Utils.DictionaryToString(multiRanges, r => r.ToFullString()));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Directory;
using Nop.Core.Plugins;
using Nop.Services.Events;
using Nop.Services.Stores;
namespace Nop.Services.Directory
{
/// <summary>
/// Currency service
/// </summary>
public partial class CurrencyService : ICurrencyService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : currency ID
/// </remarks>
private const string CURRENCIES_BY_ID_KEY = "Nop.currency.id-{0}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : show hidden records?
/// </remarks>
private const string CURRENCIES_ALL_KEY = "Nop.currency.all-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string CURRENCIES_PATTERN_KEY = "Nop.currency.";
#endregion
#region Fields
private readonly IRepository<Currency> _currencyRepository;
private readonly IStoreMappingService _storeMappingService;
private readonly ICacheManager _cacheManager;
private readonly CurrencySettings _currencySettings;
private readonly IPluginFinder _pluginFinder;
private readonly IEventPublisher _eventPublisher;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="currencyRepository">Currency repository</param>
/// <param name="storeMappingService">Store mapping service</param>
/// <param name="currencySettings">Currency settings</param>
/// <param name="pluginFinder">Plugin finder</param>
/// <param name="eventPublisher">Event published</param>
public CurrencyService(ICacheManager cacheManager,
IRepository<Currency> currencyRepository,
IStoreMappingService storeMappingService,
CurrencySettings currencySettings,
IPluginFinder pluginFinder,
IEventPublisher eventPublisher)
{
this._cacheManager = cacheManager;
this._currencyRepository = currencyRepository;
this._storeMappingService = storeMappingService;
this._currencySettings = currencySettings;
this._pluginFinder = pluginFinder;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
/// <summary>
/// Gets currency live rates
/// </summary>
/// <param name="exchangeRateCurrencyCode">Exchange rate currency code</param>
/// <returns>Exchange rates</returns>
public virtual IList<ExchangeRate> GetCurrencyLiveRates(string exchangeRateCurrencyCode)
{
var exchangeRateProvider = LoadActiveExchangeRateProvider();
if (exchangeRateProvider == null)
throw new Exception("Active exchange rate provider cannot be loaded");
return exchangeRateProvider.GetCurrencyLiveRates(exchangeRateCurrencyCode);
}
/// <summary>
/// Deletes currency
/// </summary>
/// <param name="currency">Currency</param>
public virtual void DeleteCurrency(Currency currency)
{
if (currency == null)
throw new ArgumentNullException("currency");
_currencyRepository.Delete(currency);
_cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(currency);
}
/// <summary>
/// Gets a currency
/// </summary>
/// <param name="currencyId">Currency identifier</param>
/// <returns>Currency</returns>
public virtual Currency GetCurrencyById(int currencyId)
{
if (currencyId == 0)
return null;
string key = string.Format(CURRENCIES_BY_ID_KEY, currencyId);
return _cacheManager.Get(key, () => _currencyRepository.GetById(currencyId));
}
/// <summary>
/// Gets a currency by code
/// </summary>
/// <param name="currencyCode">Currency code</param>
/// <returns>Currency</returns>
public virtual Currency GetCurrencyByCode(string currencyCode)
{
if (String.IsNullOrEmpty(currencyCode))
return null;
return GetAllCurrencies(true).FirstOrDefault(c => c.CurrencyCode.ToLower() == currencyCode.ToLower());
}
/// <summary>
/// Gets all currencies
/// </summary>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <returns>Currencies</returns>
public virtual IList<Currency> GetAllCurrencies(bool showHidden = false, int storeId = 0)
{
string key = string.Format(CURRENCIES_ALL_KEY, showHidden);
var currencies = _cacheManager.Get(key, () =>
{
var query = _currencyRepository.Table;
if (!showHidden)
query = query.Where(c => c.Published);
query = query.OrderBy(c => c.DisplayOrder);
return query.ToList();
});
//store mapping
if (storeId > 0)
{
currencies = currencies
.Where(c => _storeMappingService.Authorize(c, storeId))
.ToList();
}
return currencies;
}
/// <summary>
/// Inserts a currency
/// </summary>
/// <param name="currency">Currency</param>
public virtual void InsertCurrency(Currency currency)
{
if (currency == null)
throw new ArgumentNullException("currency");
_currencyRepository.Insert(currency);
_cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(currency);
}
/// <summary>
/// Updates the currency
/// </summary>
/// <param name="currency">Currency</param>
public virtual void UpdateCurrency(Currency currency)
{
if (currency == null)
throw new ArgumentNullException("currency");
_currencyRepository.Update(currency);
_cacheManager.RemoveByPattern(CURRENCIES_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(currency);
}
/// <summary>
/// Converts currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="exchangeRate">Currency exchange rate</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertCurrency(decimal amount, decimal exchangeRate)
{
if (amount != decimal.Zero && exchangeRate != decimal.Zero)
return amount * exchangeRate;
return decimal.Zero;
}
/// <summary>
/// Converts currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="sourceCurrencyCode">Source currency code</param>
/// <param name="targetCurrencyCode">Target currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertCurrency(decimal amount, Currency sourceCurrencyCode, Currency targetCurrencyCode)
{
decimal result = amount;
if (sourceCurrencyCode.Id == targetCurrencyCode.Id)
return result;
if (result != decimal.Zero && sourceCurrencyCode.Id != targetCurrencyCode.Id)
{
result = ConvertToPrimaryExchangeRateCurrency(result, sourceCurrencyCode);
result = ConvertFromPrimaryExchangeRateCurrency(result, targetCurrencyCode);
}
return result;
}
/// <summary>
/// Converts to primary exchange rate currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="sourceCurrencyCode">Source currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertToPrimaryExchangeRateCurrency(decimal amount, Currency sourceCurrencyCode)
{
decimal result = amount;
var primaryExchangeRateCurrency = GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);
if (result != decimal.Zero && sourceCurrencyCode.Id != primaryExchangeRateCurrency.Id)
{
decimal exchangeRate = sourceCurrencyCode.Rate;
if (exchangeRate == decimal.Zero)
throw new NopException(string.Format("Exchange rate not found for currency [{0}]", sourceCurrencyCode.Name));
result = result / exchangeRate;
}
return result;
}
/// <summary>
/// Converts from primary exchange rate currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="targetCurrencyCode">Target currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertFromPrimaryExchangeRateCurrency(decimal amount, Currency targetCurrencyCode)
{
decimal result = amount;
var primaryExchangeRateCurrency = GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);
if (result != decimal.Zero && targetCurrencyCode.Id != primaryExchangeRateCurrency.Id)
{
decimal exchangeRate = targetCurrencyCode.Rate;
if (exchangeRate == decimal.Zero)
throw new NopException(string.Format("Exchange rate not found for currency [{0}]", targetCurrencyCode.Name));
result = result * exchangeRate;
}
return result;
}
/// <summary>
/// Converts to primary store currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="sourceCurrencyCode">Source currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertToPrimaryStoreCurrency(decimal amount, Currency sourceCurrencyCode)
{
decimal result = amount;
var primaryStoreCurrency = GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
if (result != decimal.Zero && sourceCurrencyCode.Id != primaryStoreCurrency.Id)
{
decimal exchangeRate = sourceCurrencyCode.Rate;
if (exchangeRate == decimal.Zero)
throw new NopException(string.Format("Exchange rate not found for currency [{0}]", sourceCurrencyCode.Name));
result = result / exchangeRate;
}
return result;
}
/// <summary>
/// Converts from primary store currency
/// </summary>
/// <param name="amount">Amount</param>
/// <param name="targetCurrencyCode">Target currency code</param>
/// <returns>Converted value</returns>
public virtual decimal ConvertFromPrimaryStoreCurrency(decimal amount, Currency targetCurrencyCode)
{
var primaryStoreCurrency = GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
var result = ConvertCurrency(amount, primaryStoreCurrency, targetCurrencyCode);
return result;
}
/// <summary>
/// Load active exchange rate provider
/// </summary>
/// <returns>Active exchange rate provider</returns>
public virtual IExchangeRateProvider LoadActiveExchangeRateProvider()
{
var exchangeRateProvider = LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName);
if (exchangeRateProvider == null)
exchangeRateProvider = LoadAllExchangeRateProviders().FirstOrDefault();
return exchangeRateProvider;
}
/// <summary>
/// Load exchange rate provider by system name
/// </summary>
/// <param name="systemName">System name</param>
/// <returns>Found exchange rate provider</returns>
public virtual IExchangeRateProvider LoadExchangeRateProviderBySystemName(string systemName)
{
var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<IExchangeRateProvider>(systemName);
if (descriptor != null)
return descriptor.Instance<IExchangeRateProvider>();
return null;
}
/// <summary>
/// Load all exchange rate providers
/// </summary>
/// <returns>Exchange rate providers</returns>
public virtual IList<IExchangeRateProvider> LoadAllExchangeRateProviders()
{
var exchangeRateProviders = _pluginFinder.GetPlugins<IExchangeRateProvider>();
return exchangeRateProviders
.OrderBy(tp => tp.PluginDescriptor)
.ToList();
}
#endregion
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cassandra.Serialization;
using NUnit.Framework;
namespace Cassandra.Tests
{
[TestFixture]
public class DataTypeParserTests
{
[Test]
public void ParseDataTypeNameSingleTest()
{
var dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.Int32Type");
Assert.AreEqual(ColumnTypeCode.Int, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.UUIDType");
Assert.AreEqual(ColumnTypeCode.Uuid, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.UTF8Type");
Assert.AreEqual(ColumnTypeCode.Varchar, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.BytesType");
Assert.AreEqual(ColumnTypeCode.Blob, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.FloatType");
Assert.AreEqual(ColumnTypeCode.Float, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.DoubleType");
Assert.AreEqual(ColumnTypeCode.Double, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.BooleanType");
Assert.AreEqual(ColumnTypeCode.Boolean, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.InetAddressType");
Assert.AreEqual(ColumnTypeCode.Inet, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.DateType");
Assert.AreEqual(ColumnTypeCode.Timestamp, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.TimestampType");
Assert.AreEqual(ColumnTypeCode.Timestamp, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.LongType");
Assert.AreEqual(ColumnTypeCode.Bigint, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.DecimalType");
Assert.AreEqual(ColumnTypeCode.Decimal, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.IntegerType");
Assert.AreEqual(ColumnTypeCode.Varint, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.CounterColumnType");
Assert.AreEqual(ColumnTypeCode.Counter, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.TimeUUIDType");
Assert.AreEqual(ColumnTypeCode.Timeuuid, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.AsciiType");
Assert.AreEqual(ColumnTypeCode.Ascii, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.SimpleDateType");
Assert.AreEqual(ColumnTypeCode.Date, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.TimeType");
Assert.AreEqual(ColumnTypeCode.Time, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.ShortType");
Assert.AreEqual(ColumnTypeCode.SmallInt, dataType.TypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.ByteType");
Assert.AreEqual(ColumnTypeCode.TinyInt, dataType.TypeCode);
}
[Test]
public void Parse_DataType_Name_Multiple_Test()
{
var dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)");
Assert.AreEqual(ColumnTypeCode.List, dataType.TypeCode);
Assert.IsInstanceOf<ListColumnInfo>(dataType.TypeInfo);
Assert.AreEqual(ColumnTypeCode.Int, ((ListColumnInfo) dataType.TypeInfo).ValueTypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.UUIDType)");
Assert.AreEqual(ColumnTypeCode.Set, dataType.TypeCode);
Assert.IsInstanceOf<SetColumnInfo>(dataType.TypeInfo);
Assert.AreEqual(ColumnTypeCode.Uuid, ((SetColumnInfo) dataType.TypeInfo).KeyTypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.SetType(org.apache.cassandra.db.marshal.TimeUUIDType)");
Assert.AreEqual(ColumnTypeCode.Set, dataType.TypeCode);
Assert.IsInstanceOf<SetColumnInfo>(dataType.TypeInfo);
Assert.AreEqual(ColumnTypeCode.Timeuuid, ((SetColumnInfo) dataType.TypeInfo).KeyTypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.LongType)");
Assert.AreEqual(ColumnTypeCode.Map, dataType.TypeCode);
Assert.IsInstanceOf<MapColumnInfo>(dataType.TypeInfo);
Assert.AreEqual(ColumnTypeCode.Varchar, ((MapColumnInfo) dataType.TypeInfo).KeyTypeCode);
Assert.AreEqual(ColumnTypeCode.Bigint, ((MapColumnInfo) dataType.TypeInfo).ValueTypeCode);
}
[Test]
public void Parse_DataType_Name_Frozen_Test()
{
var dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.TimeUUIDType))");
Assert.AreEqual(ColumnTypeCode.List, dataType.TypeCode);
Assert.IsInstanceOf<ListColumnInfo>(dataType.TypeInfo);
Assert.AreEqual(ColumnTypeCode.Timeuuid, ((ListColumnInfo) dataType.TypeInfo).ValueTypeCode);
dataType = DataTypeParser.ParseFqTypeName("org.apache.cassandra.db.marshal.MapType(org.apache.cassandra.db.marshal.UTF8Type,org.apache.cassandra.db.marshal.FrozenType(org.apache.cassandra.db.marshal.ListType(org.apache.cassandra.db.marshal.Int32Type)))");
Assert.AreEqual(ColumnTypeCode.Map, dataType.TypeCode);
Assert.IsInstanceOf<MapColumnInfo>(dataType.TypeInfo);
Assert.AreEqual(ColumnTypeCode.Varchar, ((MapColumnInfo) dataType.TypeInfo).KeyTypeCode);
Assert.AreEqual(ColumnTypeCode.List, ((MapColumnInfo) dataType.TypeInfo).ValueTypeCode);
var subType = (ListColumnInfo)(((MapColumnInfo) dataType.TypeInfo).ValueTypeInfo);
Assert.AreEqual(ColumnTypeCode.Int, subType.ValueTypeCode);
}
[Test]
public void Parse_DataType_Name_Udt_Test()
{
var typeText =
"org.apache.cassandra.db.marshal.UserType(" +
"tester,70686f6e65,616c696173:org.apache.cassandra.db.marshal.UTF8Type,6e756d626572:org.apache.cassandra.db.marshal.UTF8Type" +
")";
var dataType = DataTypeParser.ParseFqTypeName(typeText);
Assert.AreEqual(ColumnTypeCode.Udt, dataType.TypeCode);
//Udt name
Assert.AreEqual("phone", dataType.Name);
Assert.IsInstanceOf<UdtColumnInfo>(dataType.TypeInfo);
var subTypes = ((UdtColumnInfo) dataType.TypeInfo).Fields;
Assert.AreEqual(2, subTypes.Count);
Assert.AreEqual("alias", subTypes[0].Name);
Assert.AreEqual(ColumnTypeCode.Varchar, subTypes[0].TypeCode);
Assert.AreEqual("number", subTypes[1].Name);
Assert.AreEqual(ColumnTypeCode.Varchar, subTypes[1].TypeCode);
}
[Test]
public void Parse_DataType_Name_Udt_Nested_Test()
{
var typeText =
"org.apache.cassandra.db.marshal.UserType(" +
"tester," +
"61646472657373," +
"737472656574:org.apache.cassandra.db.marshal.UTF8Type," +
"5a4950:org.apache.cassandra.db.marshal.Int32Type," +
"70686f6e6573:org.apache.cassandra.db.marshal.SetType(" +
"org.apache.cassandra.db.marshal.UserType(" +
"tester," +
"70686f6e65," +
"616c696173:org.apache.cassandra.db.marshal.UTF8Type," +
"6e756d626572:org.apache.cassandra.db.marshal.UTF8Type))" +
")";
var dataType = DataTypeParser.ParseFqTypeName(typeText);
Assert.AreEqual(ColumnTypeCode.Udt, dataType.TypeCode);
Assert.IsInstanceOf<UdtColumnInfo>(dataType.TypeInfo);
Assert.AreEqual("address", dataType.Name);
Assert.AreEqual("tester.address", ((UdtColumnInfo) dataType.TypeInfo).Name);
var subTypes = ((UdtColumnInfo) dataType.TypeInfo).Fields;
Assert.AreEqual(3, subTypes.Count);
Assert.AreEqual("street,ZIP,phones", String.Join(",", subTypes.Select(s => s.Name)));
Assert.AreEqual(ColumnTypeCode.Varchar, subTypes[0].TypeCode);
Assert.AreEqual(ColumnTypeCode.Set, subTypes[2].TypeCode);
//field name
Assert.AreEqual("phones", subTypes[2].Name);
var phonesSubType = (UdtColumnInfo)((SetColumnInfo)subTypes[2].TypeInfo).KeyTypeInfo;
Assert.AreEqual("tester.phone", phonesSubType.Name);
Assert.AreEqual(2, phonesSubType.Fields.Count);
Assert.AreEqual("alias", phonesSubType.Fields[0].Name);
Assert.AreEqual("number", phonesSubType.Fields[1].Name);
}
[Test]
public void ParseTypeName_Should_Parse_Single_Cql_Types()
{
var cqlNames = new Dictionary<string, ColumnTypeCode>
{
{"varchar", ColumnTypeCode.Varchar},
{"text", ColumnTypeCode.Text},
{"ascii", ColumnTypeCode.Ascii},
{"uuid", ColumnTypeCode.Uuid},
{"timeuuid", ColumnTypeCode.Timeuuid},
{"int", ColumnTypeCode.Int},
{"blob", ColumnTypeCode.Blob},
{"float", ColumnTypeCode.Float},
{"double", ColumnTypeCode.Double},
{"boolean", ColumnTypeCode.Boolean},
{"inet", ColumnTypeCode.Inet},
{"date", ColumnTypeCode.Date},
{"time", ColumnTypeCode.Time},
{"smallint", ColumnTypeCode.SmallInt},
{"tinyint", ColumnTypeCode.TinyInt},
{"timestamp", ColumnTypeCode.Timestamp},
{"bigint", ColumnTypeCode.Bigint},
{"decimal", ColumnTypeCode.Decimal},
{"varint", ColumnTypeCode.Varint},
{"counter", ColumnTypeCode.Counter}
};
foreach (var kv in cqlNames)
{
var type = DataTypeParser.ParseTypeName(null, null, kv.Key).Result;
Assert.NotNull(type);
Assert.AreEqual(kv.Value, type.TypeCode);
Assert.Null(type.TypeInfo);
}
}
[Test]
public void ParseTypeName_Should_Parse_Frozen_Cql_Types()
{
var cqlNames = new Dictionary<string, ColumnTypeCode>
{
{"frozen<varchar>", ColumnTypeCode.Varchar},
{"frozen<list<int>>", ColumnTypeCode.List},
{"frozen<map<text,frozen<list<int>>>>", ColumnTypeCode.Map}
};
foreach (var kv in cqlNames)
{
var type = DataTypeParser.ParseTypeName(null, null, kv.Key).Result;
Assert.NotNull(type);
Assert.AreEqual(kv.Value, type.TypeCode);
Assert.AreEqual(true, type.IsFrozen);
}
}
[Test]
public void ParseTypeName_Should_Parse_Collections()
{
{
var type = DataTypeParser.ParseTypeName(null, null, "list<int>").Result;
Assert.NotNull(type);
Assert.AreEqual(ColumnTypeCode.List, type.TypeCode);
var subTypeInfo = (ListColumnInfo)type.TypeInfo;
Assert.AreEqual(ColumnTypeCode.Int, subTypeInfo.ValueTypeCode);
}
{
var type = DataTypeParser.ParseTypeName(null, null, "set<uuid>").Result;
Assert.NotNull(type);
Assert.AreEqual(ColumnTypeCode.Set, type.TypeCode);
var subTypeInfo = (SetColumnInfo)type.TypeInfo;
Assert.AreEqual(ColumnTypeCode.Uuid, subTypeInfo.KeyTypeCode);
}
{
var type = DataTypeParser.ParseTypeName(null, null, "map<text, timeuuid>").Result;
Assert.NotNull(type);
Assert.AreEqual(ColumnTypeCode.Map, type.TypeCode);
var subTypeInfo = (MapColumnInfo)type.TypeInfo;
Assert.AreEqual(ColumnTypeCode.Text, subTypeInfo.KeyTypeCode);
Assert.AreEqual(ColumnTypeCode.Timeuuid, subTypeInfo.ValueTypeCode);
}
{
var type = DataTypeParser.ParseTypeName(null, null, "map<text,frozen<list<int>>>").Result;
Assert.NotNull(type);
Assert.AreEqual(ColumnTypeCode.Map, type.TypeCode);
var subTypeInfo = (MapColumnInfo)type.TypeInfo;
Assert.AreEqual(ColumnTypeCode.Text, subTypeInfo.KeyTypeCode);
Assert.AreEqual(ColumnTypeCode.List, subTypeInfo.ValueTypeCode);
var subListTypeInfo = (ListColumnInfo)subTypeInfo.ValueTypeInfo;
Assert.AreEqual(ColumnTypeCode.Int, subListTypeInfo.ValueTypeCode);
}
}
[Test]
public async Task ParseTypeName_Should_Parse_Custom_Types()
{
var typeNames = new[]
{
"org.apache.cassandra.db.marshal.MyCustomType",
"com.datastax.dse.whatever.TypeName"
};
foreach (var typeName in typeNames)
{
var type = await DataTypeParser.ParseTypeName(null, null, string.Format("'{0}'", typeName)).ConfigureAwait(false);
Assert.AreEqual(ColumnTypeCode.Custom, type.TypeCode);
var info = (CustomColumnInfo)type.TypeInfo;
Assert.AreEqual(typeName, info.CustomTypeName);
}
}
[Test]
public void ParseFqTypeName_Should_Parse_Custom_Types()
{
var typeNames = new[]
{
"org.apache.cassandra.db.marshal.MyCustomType",
"com.datastax.dse.whatever.TypeName"
};
foreach (var typeName in typeNames)
{
var type = DataTypeParser.ParseFqTypeName(typeName);
Assert.AreEqual(ColumnTypeCode.Custom, type.TypeCode);
var info = (CustomColumnInfo)type.TypeInfo;
Assert.AreEqual(typeName, info.CustomTypeName);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.WebUI;
using Vevo.WebUI.Ajax;
using Vevo.WebUI.Products;
public partial class Layouts_CategoryLists_CategoryListDefault : BaseCategoryListControl
{
private string CurrentCategoryName
{
get
{
if ( Request.QueryString[ "CategoryName" ] == null )
return String.Empty;
else
return Request.QueryString[ "CategoryName" ];
}
}
private string CurrentCategoryID
{
get
{
string id = Request.QueryString[ "CategoryID" ];
if ( id != null )
{
return id;
}
else
{
return DataAccessContext.Configurations.GetValue( "RootCategory", new StoreRetriever().GetStore() );
}
}
}
private Category CurrentCategory
{
get
{
return DataAccessContext.CategoryRepository.GetOne( StoreContext.Culture, CurrentCategoryID );
}
}
private string MinPrice
{
get
{
if ( Request.QueryString[ "MinPrice" ] == null )
return String.Empty;
else
return Request.QueryString[ "MinPrice" ];
}
}
private string MaxPrice
{
get
{
if ( Request.QueryString[ "MaxPrice" ] == null )
return String.Empty;
else
return Request.QueryString[ "MaxPrice" ];
}
}
private string ItemPerPage
{
get
{
if ( ViewState[ "ItemPerPage" ] == null )
ViewState[ "ItemPerPage" ] = uxItemsPerPageControl.DefaultValue;
return ( string ) ViewState[ "ItemPerPage" ];
}
set
{
ViewState[ "ItemPerPage" ] = value;
}
}
private bool IsFacetedSearch()
{
string[] allKey = Request.QueryString.AllKeys;
return ( allKey.Length > 1 );
}
private int NoOfCategoryColumn
{
get
{
return DataAccessContext.Configurations.GetIntValue( "NumberOfCategoryColumn" );
}
}
private IList<Category> GetCategoryList( int itemsPerPage, out int totalItems )
{
if ( !String.IsNullOrEmpty( CurrentCategoryName ) )
{
return DataAccessContext.CategoryRepository.GetByParentUrlName(
StoreContext.Culture,
CurrentCategoryName,
"SortOrder",
BoolFilter.ShowTrue,
( uxPagingControl.CurrentPage - 1 ) * itemsPerPage,
( uxPagingControl.CurrentPage * itemsPerPage ) - 1,
out totalItems );
}
else
{
return DataAccessContext.CategoryRepository.GetByParentID(
StoreContext.Culture,
CurrentCategoryID,
"SortOrder",
BoolFilter.ShowTrue,
( uxPagingControl.CurrentPage - 1 ) * itemsPerPage,
( uxPagingControl.CurrentPage * itemsPerPage ) - 1,
out totalItems );
}
}
private string GetCategoryID()
{
string categoryID = Request.QueryString[ "cat" ];
if ( !String.IsNullOrEmpty( categoryID ) )
return categoryID;
else
if ( !String.IsNullOrEmpty( CurrentCategoryName ) )
return DataAccessContext.CategoryRepository.GetOneByUrlName( StoreContext.Culture, CurrentCategoryName ).CategoryID;
else
return CurrentCategoryID;
}
private string GetDepartmentID()
{
string departmentID = "";
if ( !String.IsNullOrEmpty( Request.QueryString[ "dep" ] ) )
{
departmentID = Request.QueryString[ "dep" ];
}
return departmentID;
}
private string GetManufacturerID()
{
string manufacturerID = String.Empty;
if ( !String.IsNullOrEmpty( Request.QueryString[ "manu" ] ) )
{
manufacturerID = Request.QueryString[ "manu" ];
}
return manufacturerID;
}
private void PopulateCategoryControls()
{
uxItemsPerPageControl.SelectValue( ItemPerPage );
int totalItems;
int selectedValue;
selectedValue = Convert.ToInt32( uxItemsPerPageControl.SelectedValue );
uxList.DataSource = GetCategoryList( selectedValue, out totalItems );
uxList.DataBind();
uxPagingControl.NumberOfPages = ( int ) Math.Ceiling( ( double ) totalItems / selectedValue );
}
private void PopulateFacetProductControls()
{
BaseProductListControl productList = ( BaseProductListControl ) uxCatalogControlPanel.FindControl( "uxProductList" );
if ( productList != null ) return;
Category category = new Category();
if ( !String.IsNullOrEmpty( CurrentCategoryName ) )
{
category = DataAccessContext.CategoryRepository.GetOneByUrlName( StoreContext.Culture, CurrentCategoryName );
BaseProductListControl productListControl = new BaseProductListControl();
if ( !String.IsNullOrEmpty( category.ProductListLayoutPath ) )
productListControl = LoadControl( String.Format(
"{0}{1}",
SystemConst.LayoutProductListPath,
category.ProductListLayoutPath ) ) as BaseProductListControl;
else
productListControl = LoadControl( String.Format(
"{0}{1}",
SystemConst.LayoutProductListPath,
DataAccessContext.Configurations.GetValue( "DefaultProductListLayout" ) ) )
as BaseProductListControl;
productListControl.ID = "uxProductList";
productListControl.IsSearchResult = true;
productListControl.UserDefinedParameters = new object[] {
GetCategoryID(),
GetDepartmentID(),
GetManufacturerID(),
MinPrice,
MaxPrice,
GetSpecItemValueList( GetAllSpecKey() )};
productListControl.DataRetriever = new DataAccessCallbacks.ProductListRetriever( GetProductList );
uxCatalogControlPanel.Controls.Add( productListControl );
}
else
uxCatalogControlPanel.Visible = false;
}
private BaseProductListControl GetProductList()
{
return ( BaseProductListControl ) uxCatalogControlPanel.FindControl( "uxProductList" );
}
private void CategoryList_StoreCultureChanged( object sender, CultureEventArgs e )
{
Refresh();
}
private void RegisterStoreEvents()
{
GetStorefrontEvents().StoreCultureChanged +=
new StorefrontEvents.CultureEventHandler( CategoryList_StoreCultureChanged );
}
private ScriptManager GetScriptManager()
{
return AjaxUtilities.GetScriptManager( this );
}
private void AddHistoryPoint()
{
GetScriptManager().AddHistoryPoint( "CatPage", uxPagingControl.CurrentPage.ToString() );
GetScriptManager().AddHistoryPoint( "CatItemPerPage", uxItemsPerPageControl.SelectedValue );
}
protected void uxPagingControl_BubbleEvent( object sender, EventArgs e )
{
AddHistoryPoint();
Refresh();
}
protected void uxItemsPerPageControl_BubbleEvent( object sender, EventArgs e )
{
ItemPerPage = uxItemsPerPageControl.SelectedValue;
uxPagingControl.CurrentPage = 1;
AddHistoryPoint();
Refresh();
}
protected void ScriptManager_Navigate( object sender, HistoryEventArgs e )
{
string args;
if ( !string.IsNullOrEmpty( e.State[ "CatItemPerPage" ] ) )
{
ItemPerPage = e.State[ "CatItemPerPage" ].ToString();
}
else
{
ItemPerPage = uxItemsPerPageControl.DefaultValue;
}
int totalItems;
int selectedValue;
selectedValue = Convert.ToInt32( uxItemsPerPageControl.SelectedValue );
GetCategoryList( selectedValue, out totalItems );
uxPagingControl.NumberOfPages = ( int ) System.Math.Ceiling( ( double ) totalItems / selectedValue );
if ( !string.IsNullOrEmpty( e.State[ "CatPage" ] ) )
{
args = e.State[ "CatPage" ];
uxPagingControl.CurrentPage = int.Parse( args );
}
else
{
uxPagingControl.CurrentPage = 1;
}
Refresh();
}
protected void Page_Load( object sender, EventArgs e )
{
RegisterStoreEvents();
uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_BubbleEvent );
uxItemsPerPageControl.BubbleEvent += new EventHandler( uxItemsPerPageControl_BubbleEvent );
GetScriptManager().Navigate += new EventHandler<HistoryEventArgs>( ScriptManager_Navigate );
AjaxUtilities.ScrollToTop( uxGoToTopLink );
uxList.RepeatColumns = NoOfCategoryColumn;
uxList.RepeatDirection = RepeatDirection.Horizontal;
if ( !IsPostBack )
{
ItemPerPage = CatalogUtilities.CategoryItemsPerPage;
}
Refresh();
}
private IList<string> GetAllSpecKey()
{
string[] allKey = Request.QueryString.AllKeys;
string query = String.Empty;
IList<string> specKeyList = new List<string>();
for ( int i = 0; i < allKey.Length; i++ )
{
if ( !allKey[ i ].ToLower().Equals( "categoryname" ) && !allKey[ i ].ToLower().Equals( "categoryid" ) )
{
if ( allKey[ i ].ToLower().Equals( "minprice" ) ||
allKey[ i ].ToLower().Equals( "maxprice" ) ||
allKey[ i ].ToLower().Equals( "cat" ) ||
allKey[ i ].ToLower().Equals( "dep" ) ||
allKey[ i ].ToLower().Equals( "manu" ) )
{
continue;
}
specKeyList.Add( allKey[ i ] );
}
}
return specKeyList;
}
private IList<SpecificationItemValue> GetSpecItemValueList( IList<string> specKeyList )
{
IList<SpecificationItemValue> specItemValueList = new List<SpecificationItemValue>();
foreach ( string specKey in specKeyList )
{
string specValue = Request.QueryString[ specKey ];
SpecificationItem specItem = DataAccessContext.SpecificationItemRepository.GetOneByName( StoreContext.Culture, specKey );
SpecificationItemValue specItemValue = DataAccessContext.SpecificationItemValueRepository.GetOneBySpecItemIDAndValue( StoreContext.Culture, specItem.SpecificationItemID, specValue );
specItemValueList.Add( specItemValue );
}
return specItemValueList;
}
public static IList<Product> GetProductList(
Culture culture,
string sortBy,
int startIndex,
int endIndex,
object[] userDefined,
out int howManyItems )
{
string categoryID = userDefined[ 0 ].ToString();
string departmentID = userDefined[ 1 ].ToString();
IList<string> list = new List<string>();
IList<string> categoryids = DataAccessContext.CategoryRepository.GetLeafFromCategoryID( categoryID, list );
List<string> categoryCollection = new List<string>();
foreach ( string categoryItem in categoryids )
{
categoryCollection.Add( categoryItem );
}
IList<string> departmentIDs = new List<string>();
if ( !String.IsNullOrEmpty( departmentID ) )
{
IList<string> depList = new List<string>();
departmentIDs = DataAccessContext.DepartmentRepository.GetLeafFromDepartmentID( departmentID, depList );
}
List<string> departmentCollection = new List<string>();
foreach ( string departmentItem in departmentIDs )
{
departmentCollection.Add( departmentItem );
}
return DataAccessContext.ProductRepository.GetFacetResultByCategoryID(
culture,
categoryCollection.ToArray(),
departmentCollection.ToArray(),
userDefined[ 2 ].ToString(),
userDefined[ 3 ].ToString(),
userDefined[ 4 ].ToString(),
( IList<SpecificationItemValue> ) userDefined[ 5 ],
sortBy,
startIndex,
endIndex,
BoolFilter.ShowTrue,
out howManyItems,
new StoreRetriever().GetCurrentStoreID()
);
}
protected void Page_PreRender( object sender, EventArgs e )
{
Refresh();
CatalogUtilities.CategoryItemsPerPage = ItemPerPage;
}
public void Refresh()
{
if ( !IsFacetedSearch() )
{
PopulateCategoryControls();
uxCategoryPageControlDiv.Visible = true;
if ( DataAccessContext.Configurations.GetBoolValue( "CategoryShowProductList", new StoreRetriever().GetStore() ) )
PopulateFacetProductControls();
}
else
{
uxCategoryPageControlDiv.Visible = false;
uxCategoryLinkToTopDiv.Visible = false;
PopulateFacetProductControls();
}
}
}
| |
/**
* (C) Copyright IBM Corp. 2019, 2021.
*
* 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.
*
*/
/**
* IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-153452
*/
using System.Collections.Generic;
using System.Text;
using IBM.Cloud.SDK;
using IBM.Cloud.SDK.Authentication;
using IBM.Cloud.SDK.Connection;
using IBM.Cloud.SDK.Utilities;
using IBM.Watson.CompareComply.V1.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using UnityEngine.Networking;
namespace IBM.Watson.CompareComply.V1
{
[System.Obsolete("On 30 November 2021, Compare and Comply will no longer be available." +
"\nFor more information, see Compare and Comply Deprecation " +
"(https://github.com/watson-developer-cloud/unity-sdk/tree/master#compare-and-comply-deprecation).")]
public partial class CompareComplyService : BaseService
{
private const string defaultServiceName = "compare_comply";
private const string defaultServiceUrl = "https://api.us-south.compare-comply.watson.cloud.ibm.com";
#region Version
private string version;
/// <summary>
/// Gets and sets the version of the service.
/// Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current
/// version is `2018-10-15`.
/// </summary>
public string Version
{
get { return version; }
set { version = value; }
}
#endregion
#region DisableSslVerification
private bool disableSslVerification = false;
/// <summary>
/// Gets and sets the option to disable ssl verification
/// </summary>
public bool DisableSslVerification
{
get { return disableSslVerification; }
set { disableSslVerification = value; }
}
#endregion
/// <summary>
/// CompareComplyService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-10-15`.</param>
public CompareComplyService(string version) : this(version, defaultServiceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(defaultServiceName)) {}
/// <summary>
/// CompareComplyService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-10-15`.</param>
/// <param name="authenticator">The service authenticator.</param>
public CompareComplyService(string version, Authenticator authenticator) : this(version, defaultServiceName, authenticator) {}
/// <summary>
/// CompareComplyService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-10-15`.</param>
/// <param name="serviceName">The service name to be used when configuring the client instance</param>
public CompareComplyService(string version, string serviceName) : this(version, serviceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceName)) {}
/// <summary>
/// CompareComplyService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-10-15`.</param>
/// <param name="serviceName">The service name to be used when configuring the client instance</param>
/// <param name="authenticator">The service authenticator.</param>
public CompareComplyService(string version, string serviceName, Authenticator authenticator) : base(authenticator, serviceName)
{
Authenticator = authenticator;
if (string.IsNullOrEmpty(version))
{
throw new ArgumentNullException("`version` is required");
}
else
{
Version = version;
}
if (string.IsNullOrEmpty(GetServiceUrl()))
{
SetServiceUrl(defaultServiceUrl);
}
}
/// <summary>
/// Convert document to HTML.
///
/// Converts a document to HTML.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="file">The document to convert.</param>
/// <param name="fileContentType">The content type of file. (optional)</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="HTMLReturn" />HTMLReturn</returns>
public bool ConvertToHtml(Callback<HTMLReturn> callback, System.IO.MemoryStream file, string fileContentType = null, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ConvertToHtml`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (file == null)
throw new ArgumentNullException("`file` is required for `ConvertToHtml`");
RequestObject<HTMLReturn> req = new RequestObject<HTMLReturn>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "ConvertToHtml"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Forms = new Dictionary<string, RESTConnector.Form>();
if (file != null)
{
req.Forms["file"] = new RESTConnector.Form(file, "filename", fileContentType);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnConvertToHtmlResponse;
Connector.URL = GetServiceUrl() + "/v1/html_conversion";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnConvertToHtmlResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<HTMLReturn> response = new DetailedResponse<HTMLReturn>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<HTMLReturn>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnConvertToHtmlResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<HTMLReturn>)req).Callback != null)
((RequestObject<HTMLReturn>)req).Callback(response, resp.Error);
}
/// <summary>
/// Classify the elements of a document.
///
/// Analyzes the structural and semantic elements of a document.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="file">The document to classify.</param>
/// <param name="fileContentType">The content type of file. (optional)</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="ClassifyReturn" />ClassifyReturn</returns>
public bool ClassifyElements(Callback<ClassifyReturn> callback, System.IO.MemoryStream file, string fileContentType = null, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ClassifyElements`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (file == null)
throw new ArgumentNullException("`file` is required for `ClassifyElements`");
RequestObject<ClassifyReturn> req = new RequestObject<ClassifyReturn>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "ClassifyElements"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Forms = new Dictionary<string, RESTConnector.Form>();
if (file != null)
{
req.Forms["file"] = new RESTConnector.Form(file, "filename", fileContentType);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnClassifyElementsResponse;
Connector.URL = GetServiceUrl() + "/v1/element_classification";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnClassifyElementsResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<ClassifyReturn> response = new DetailedResponse<ClassifyReturn>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<ClassifyReturn>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnClassifyElementsResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<ClassifyReturn>)req).Callback != null)
((RequestObject<ClassifyReturn>)req).Callback(response, resp.Error);
}
/// <summary>
/// Extract a document's tables.
///
/// Analyzes the tables in a document.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="file">The document on which to run table extraction.</param>
/// <param name="fileContentType">The content type of file. (optional)</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="TableReturn" />TableReturn</returns>
public bool ExtractTables(Callback<TableReturn> callback, System.IO.MemoryStream file, string fileContentType = null, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ExtractTables`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (file == null)
throw new ArgumentNullException("`file` is required for `ExtractTables`");
RequestObject<TableReturn> req = new RequestObject<TableReturn>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "ExtractTables"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Forms = new Dictionary<string, RESTConnector.Form>();
if (file != null)
{
req.Forms["file"] = new RESTConnector.Form(file, "filename", fileContentType);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnExtractTablesResponse;
Connector.URL = GetServiceUrl() + "/v1/tables";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnExtractTablesResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<TableReturn> response = new DetailedResponse<TableReturn>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<TableReturn>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnExtractTablesResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<TableReturn>)req).Callback != null)
((RequestObject<TableReturn>)req).Callback(response, resp.Error);
}
/// <summary>
/// Compare two documents.
///
/// Compares two input documents. Documents must be in the same format.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="file1">The first document to compare.</param>
/// <param name="file2">The second document to compare.</param>
/// <param name="file1ContentType">The content type of file1. (optional)</param>
/// <param name="file2ContentType">The content type of file2. (optional)</param>
/// <param name="file1Label">A text label for the first document. (optional, default to file_1)</param>
/// <param name="file2Label">A text label for the second document. (optional, default to file_2)</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="CompareReturn" />CompareReturn</returns>
public bool CompareDocuments(Callback<CompareReturn> callback, System.IO.MemoryStream file1, System.IO.MemoryStream file2, string file1ContentType = null, string file2ContentType = null, string file1Label = null, string file2Label = null, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `CompareDocuments`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (file1 == null)
throw new ArgumentNullException("`file1` is required for `CompareDocuments`");
if (file2 == null)
throw new ArgumentNullException("`file2` is required for `CompareDocuments`");
RequestObject<CompareReturn> req = new RequestObject<CompareReturn>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "CompareDocuments"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Forms = new Dictionary<string, RESTConnector.Form>();
if (file1 != null)
{
req.Forms["file_1"] = new RESTConnector.Form(file1, "filename", file1ContentType);
}
if (file2 != null)
{
req.Forms["file_2"] = new RESTConnector.Form(file2, "filename", file2ContentType);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(file1Label))
{
req.Parameters["file_1_label"] = file1Label;
}
if (!string.IsNullOrEmpty(file2Label))
{
req.Parameters["file_2_label"] = file2Label;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnCompareDocumentsResponse;
Connector.URL = GetServiceUrl() + "/v1/comparison";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnCompareDocumentsResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<CompareReturn> response = new DetailedResponse<CompareReturn>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<CompareReturn>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnCompareDocumentsResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<CompareReturn>)req).Callback != null)
((RequestObject<CompareReturn>)req).Callback(response, resp.Error);
}
/// <summary>
/// Add feedback.
///
/// Adds feedback in the form of _labels_ from a subject-matter expert (SME) to a governing document.
/// **Important:** Feedback is not immediately incorporated into the training model, nor is it guaranteed to be
/// incorporated at a later date. Instead, submitted feedback is used to suggest future updates to the training
/// model.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="feedbackData">Feedback data for submission.</param>
/// <param name="userId">An optional string identifying the user. (optional)</param>
/// <param name="comment">An optional comment on or description of the feedback. (optional)</param>
/// <returns><see cref="FeedbackReturn" />FeedbackReturn</returns>
public bool AddFeedback(Callback<FeedbackReturn> callback, FeedbackDataInput feedbackData, string userId = null, string comment = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `AddFeedback`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (feedbackData == null)
throw new ArgumentNullException("`feedbackData` is required for `AddFeedback`");
RequestObject<FeedbackReturn> req = new RequestObject<FeedbackReturn>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "AddFeedback"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.Headers["Content-Type"] = "application/json";
req.Headers["Accept"] = "application/json";
JObject bodyObject = new JObject();
if (feedbackData != null)
bodyObject["feedback_data"] = JToken.FromObject(feedbackData);
if (!string.IsNullOrEmpty(userId))
bodyObject["user_id"] = userId;
if (!string.IsNullOrEmpty(comment))
bodyObject["comment"] = comment;
req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));
req.OnResponse = OnAddFeedbackResponse;
Connector.URL = GetServiceUrl() + "/v1/feedback";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnAddFeedbackResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<FeedbackReturn> response = new DetailedResponse<FeedbackReturn>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<FeedbackReturn>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnAddFeedbackResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<FeedbackReturn>)req).Callback != null)
((RequestObject<FeedbackReturn>)req).Callback(response, resp.Error);
}
/// <summary>
/// List the feedback in a document.
///
/// Lists the feedback in a document.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="feedbackType">An optional string that filters the output to include only feedback with the
/// specified feedback type. The only permitted value is `element_classification`. (optional)</param>
/// <param name="documentTitle">An optional string that filters the output to include only feedback from the
/// document with the specified `document_title`. (optional)</param>
/// <param name="modelId">An optional string that filters the output to include only feedback with the specified
/// `model_id`. The only permitted value is `contracts`. (optional)</param>
/// <param name="modelVersion">An optional string that filters the output to include only feedback with the
/// specified `model_version`. (optional)</param>
/// <param name="categoryRemoved">An optional string in the form of a comma-separated list of categories. If it
/// is specified, the service filters the output to include only feedback that has at least one category from
/// the list removed. (optional)</param>
/// <param name="categoryAdded">An optional string in the form of a comma-separated list of categories. If this
/// is specified, the service filters the output to include only feedback that has at least one category from
/// the list added. (optional)</param>
/// <param name="categoryNotChanged">An optional string in the form of a comma-separated list of categories. If
/// this is specified, the service filters the output to include only feedback that has at least one category
/// from the list unchanged. (optional)</param>
/// <param name="typeRemoved">An optional string of comma-separated `nature`:`party` pairs. If this is
/// specified, the service filters the output to include only feedback that has at least one `nature`:`party`
/// pair from the list removed. (optional)</param>
/// <param name="typeAdded">An optional string of comma-separated `nature`:`party` pairs. If this is specified,
/// the service filters the output to include only feedback that has at least one `nature`:`party` pair from the
/// list removed. (optional)</param>
/// <param name="typeNotChanged">An optional string of comma-separated `nature`:`party` pairs. If this is
/// specified, the service filters the output to include only feedback that has at least one `nature`:`party`
/// pair from the list unchanged. (optional)</param>
/// <param name="pageLimit">An optional integer specifying the number of documents that you want the service to
/// return. (optional)</param>
/// <param name="cursor">An optional string that returns the set of documents after the previous set. Use this
/// parameter with the `page_limit` parameter. (optional)</param>
/// <param name="sort">An optional comma-separated list of fields in the document to sort on. You can optionally
/// specify the sort direction by prefixing the value of the field with `-` for descending order or `+` for
/// ascending order (the default). Currently permitted sorting fields are `created`, `user_id`, and
/// `document_title`. (optional)</param>
/// <param name="includeTotal">An optional boolean value. If specified as `true`, the `pagination` object in the
/// output includes a value called `total` that gives the total count of feedback created. (optional)</param>
/// <returns><see cref="FeedbackList" />FeedbackList</returns>
public bool ListFeedback(Callback<FeedbackList> callback, string feedbackType = null, string documentTitle = null, string modelId = null, string modelVersion = null, string categoryRemoved = null, string categoryAdded = null, string categoryNotChanged = null, string typeRemoved = null, string typeAdded = null, string typeNotChanged = null, long? pageLimit = null, string cursor = null, string sort = null, bool? includeTotal = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListFeedback`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
RequestObject<FeedbackList> req = new RequestObject<FeedbackList>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "ListFeedback"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(feedbackType))
{
req.Parameters["feedback_type"] = feedbackType;
}
if (!string.IsNullOrEmpty(documentTitle))
{
req.Parameters["document_title"] = documentTitle;
}
if (!string.IsNullOrEmpty(modelId))
{
req.Parameters["model_id"] = modelId;
}
if (!string.IsNullOrEmpty(modelVersion))
{
req.Parameters["model_version"] = modelVersion;
}
if (!string.IsNullOrEmpty(categoryRemoved))
{
req.Parameters["category_removed"] = categoryRemoved;
}
if (!string.IsNullOrEmpty(categoryAdded))
{
req.Parameters["category_added"] = categoryAdded;
}
if (!string.IsNullOrEmpty(categoryNotChanged))
{
req.Parameters["category_not_changed"] = categoryNotChanged;
}
if (!string.IsNullOrEmpty(typeRemoved))
{
req.Parameters["type_removed"] = typeRemoved;
}
if (!string.IsNullOrEmpty(typeAdded))
{
req.Parameters["type_added"] = typeAdded;
}
if (!string.IsNullOrEmpty(typeNotChanged))
{
req.Parameters["type_not_changed"] = typeNotChanged;
}
if (pageLimit != null)
{
req.Parameters["page_limit"] = pageLimit;
}
if (!string.IsNullOrEmpty(cursor))
{
req.Parameters["cursor"] = cursor;
}
if (!string.IsNullOrEmpty(sort))
{
req.Parameters["sort"] = sort;
}
if (includeTotal != null)
{
req.Parameters["include_total"] = (bool)includeTotal ? "true" : "false";
}
req.OnResponse = OnListFeedbackResponse;
Connector.URL = GetServiceUrl() + "/v1/feedback";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListFeedbackResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<FeedbackList> response = new DetailedResponse<FeedbackList>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<FeedbackList>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnListFeedbackResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<FeedbackList>)req).Callback != null)
((RequestObject<FeedbackList>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get a specified feedback entry.
///
/// Gets a feedback entry with a specified `feedback_id`.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="feedbackId">A string that specifies the feedback entry to be included in the output.</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="GetFeedback" />GetFeedback</returns>
public bool GetFeedback(Callback<GetFeedback> callback, string feedbackId, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetFeedback`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(feedbackId))
throw new ArgumentNullException("`feedbackId` is required for `GetFeedback`");
RequestObject<GetFeedback> req = new RequestObject<GetFeedback>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "GetFeedback"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnGetFeedbackResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/feedback/{0}", feedbackId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetFeedbackResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<GetFeedback> response = new DetailedResponse<GetFeedback>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<GetFeedback>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnGetFeedbackResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<GetFeedback>)req).Callback != null)
((RequestObject<GetFeedback>)req).Callback(response, resp.Error);
}
/// <summary>
/// Delete a specified feedback entry.
///
/// Deletes a feedback entry with a specified `feedback_id`.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="feedbackId">A string that specifies the feedback entry to be deleted from the document.</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="FeedbackDeleted" />FeedbackDeleted</returns>
public bool DeleteFeedback(Callback<FeedbackDeleted> callback, string feedbackId, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `DeleteFeedback`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(feedbackId))
throw new ArgumentNullException("`feedbackId` is required for `DeleteFeedback`");
RequestObject<FeedbackDeleted> req = new RequestObject<FeedbackDeleted>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbDELETE,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "DeleteFeedback"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnDeleteFeedbackResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/feedback/{0}", feedbackId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnDeleteFeedbackResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<FeedbackDeleted> response = new DetailedResponse<FeedbackDeleted>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<FeedbackDeleted>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnDeleteFeedbackResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<FeedbackDeleted>)req).Callback != null)
((RequestObject<FeedbackDeleted>)req).Callback(response, resp.Error);
}
/// <summary>
/// Submit a batch-processing request.
///
/// Run Compare and Comply methods over a collection of input documents.
///
/// **Important:** Batch processing requires the use of the [IBM Cloud Object Storage
/// service](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-about#about-ibm-cloud-object-storage).
/// The use of IBM Cloud Object Storage with Compare and Comply is discussed at [Using batch
/// processing](https://cloud.ibm.com/docs/compare-comply?topic=compare-comply-batching#before-you-batch).
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="function">The Compare and Comply method to run across the submitted input documents.</param>
/// <param name="inputCredentialsFile">A JSON file containing the input Cloud Object Storage credentials. At a
/// minimum, the credentials must enable `READ` permissions on the bucket defined by the `input_bucket_name`
/// parameter.</param>
/// <param name="inputBucketLocation">The geographical location of the Cloud Object Storage input bucket as
/// listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or
/// `ap-geo`.</param>
/// <param name="inputBucketName">The name of the Cloud Object Storage input bucket.</param>
/// <param name="outputCredentialsFile">A JSON file that lists the Cloud Object Storage output credentials. At a
/// minimum, the credentials must enable `READ` and `WRITE` permissions on the bucket defined by the
/// `output_bucket_name` parameter.</param>
/// <param name="outputBucketLocation">The geographical location of the Cloud Object Storage output bucket as
/// listed on the **Endpoint** tab of your Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or
/// `ap-geo`.</param>
/// <param name="outputBucketName">The name of the Cloud Object Storage output bucket.</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="BatchStatus" />BatchStatus</returns>
public bool CreateBatch(Callback<BatchStatus> callback, string function, System.IO.MemoryStream inputCredentialsFile, string inputBucketLocation, string inputBucketName, System.IO.MemoryStream outputCredentialsFile, string outputBucketLocation, string outputBucketName, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `CreateBatch`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(function))
throw new ArgumentNullException("`function` is required for `CreateBatch`");
if (inputCredentialsFile == null)
throw new ArgumentNullException("`inputCredentialsFile` is required for `CreateBatch`");
if (string.IsNullOrEmpty(inputBucketLocation))
throw new ArgumentNullException("`inputBucketLocation` is required for `CreateBatch`");
if (string.IsNullOrEmpty(inputBucketName))
throw new ArgumentNullException("`inputBucketName` is required for `CreateBatch`");
if (outputCredentialsFile == null)
throw new ArgumentNullException("`outputCredentialsFile` is required for `CreateBatch`");
if (string.IsNullOrEmpty(outputBucketLocation))
throw new ArgumentNullException("`outputBucketLocation` is required for `CreateBatch`");
if (string.IsNullOrEmpty(outputBucketName))
throw new ArgumentNullException("`outputBucketName` is required for `CreateBatch`");
RequestObject<BatchStatus> req = new RequestObject<BatchStatus>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "CreateBatch"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Forms = new Dictionary<string, RESTConnector.Form>();
if (inputCredentialsFile != null)
{
req.Forms["input_credentials_file"] = new RESTConnector.Form(inputCredentialsFile, "filename", "application/json");
}
if (!string.IsNullOrEmpty(inputBucketLocation))
{
req.Forms["input_bucket_location"] = new RESTConnector.Form(inputBucketLocation);
}
if (!string.IsNullOrEmpty(inputBucketName))
{
req.Forms["input_bucket_name"] = new RESTConnector.Form(inputBucketName);
}
if (outputCredentialsFile != null)
{
req.Forms["output_credentials_file"] = new RESTConnector.Form(outputCredentialsFile, "filename", "application/json");
}
if (!string.IsNullOrEmpty(outputBucketLocation))
{
req.Forms["output_bucket_location"] = new RESTConnector.Form(outputBucketLocation);
}
if (!string.IsNullOrEmpty(outputBucketName))
{
req.Forms["output_bucket_name"] = new RESTConnector.Form(outputBucketName);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(function))
{
req.Parameters["function"] = function;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnCreateBatchResponse;
Connector.URL = GetServiceUrl() + "/v1/batches";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnCreateBatchResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<BatchStatus> response = new DetailedResponse<BatchStatus>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<BatchStatus>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnCreateBatchResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<BatchStatus>)req).Callback != null)
((RequestObject<BatchStatus>)req).Callback(response, resp.Error);
}
/// <summary>
/// List submitted batch-processing jobs.
///
/// Lists batch-processing jobs submitted by users.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <returns><see cref="Batches" />Batches</returns>
public bool ListBatches(Callback<Batches> callback)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListBatches`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
RequestObject<Batches> req = new RequestObject<Batches>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "ListBatches"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnListBatchesResponse;
Connector.URL = GetServiceUrl() + "/v1/batches";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListBatchesResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<Batches> response = new DetailedResponse<Batches>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<Batches>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnListBatchesResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<Batches>)req).Callback != null)
((RequestObject<Batches>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get information about a specific batch-processing job.
///
/// Gets information about a batch-processing job with a specified ID.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="batchId">The ID of the batch-processing job whose information you want to retrieve.</param>
/// <returns><see cref="BatchStatus" />BatchStatus</returns>
public bool GetBatch(Callback<BatchStatus> callback, string batchId)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetBatch`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(batchId))
throw new ArgumentNullException("`batchId` is required for `GetBatch`");
RequestObject<BatchStatus> req = new RequestObject<BatchStatus>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "GetBatch"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnGetBatchResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/batches/{0}", batchId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetBatchResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<BatchStatus> response = new DetailedResponse<BatchStatus>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<BatchStatus>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnGetBatchResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<BatchStatus>)req).Callback != null)
((RequestObject<BatchStatus>)req).Callback(response, resp.Error);
}
/// <summary>
/// Update a pending or active batch-processing job.
///
/// Updates a pending or active batch-processing job. You can rescan the input bucket to check for new documents
/// or cancel a job.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="batchId">The ID of the batch-processing job you want to update.</param>
/// <param name="action">The action you want to perform on the specified batch-processing job.</param>
/// <param name="model">The analysis model to be used by the service. For the **Element classification** and
/// **Compare two documents** methods, the default is `contracts`. For the **Extract tables** method, the
/// default is `tables`. These defaults apply to the standalone methods as well as to the methods' use in
/// batch-processing requests. (optional)</param>
/// <returns><see cref="BatchStatus" />BatchStatus</returns>
public bool UpdateBatch(Callback<BatchStatus> callback, string batchId, string action, string model = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `UpdateBatch`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(batchId))
throw new ArgumentNullException("`batchId` is required for `UpdateBatch`");
if (string.IsNullOrEmpty(action))
throw new ArgumentNullException("`action` is required for `UpdateBatch`");
RequestObject<BatchStatus> req = new RequestObject<BatchStatus>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPUT,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("compare-comply", "V1", "UpdateBatch"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(action))
{
req.Parameters["action"] = action;
}
if (!string.IsNullOrEmpty(model))
{
req.Parameters["model"] = model;
}
req.OnResponse = OnUpdateBatchResponse;
Connector.URL = GetServiceUrl() + string.Format("/v1/batches/{0}", batchId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnUpdateBatchResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<BatchStatus> response = new DetailedResponse<BatchStatus>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<BatchStatus>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("CompareComplyService.OnUpdateBatchResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<BatchStatus>)req).Callback != null)
((RequestObject<BatchStatus>)req).Callback(response, resp.Error);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using Validation;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable unordered hash set implementation.
/// </summary>
/// <typeparam name="T">The type of elements in the set.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableHashSetDebuggerProxy<>))]
public sealed partial class ImmutableHashSet<T> : IImmutableSet<T>, IHashKeyCollection<T>, IReadOnlyCollection<T>, ICollection<T>, ISet<T>, ICollection, IStrongEnumerable<T, ImmutableHashSet<T>.Enumerator>
{
/// <summary>
/// An empty immutable hash set with the default comparer for <typeparamref name="T"/>.
/// </summary>
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(SortedInt32KeyNode<HashBucket>.EmptyNode, EqualityComparer<T>.Default, 0);
/// <summary>
/// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen.
/// </summary>
private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = (kv) => kv.Value.Freeze();
/// <summary>
/// The equality comparer used to hash the elements in the collection.
/// </summary>
private readonly IEqualityComparer<T> _equalityComparer;
/// <summary>
/// The number of elements in this collection.
/// </summary>
private readonly int _count;
/// <summary>
/// The sorted dictionary that this hash set wraps. The key is the hash code and the value is the bucket of all items that hashed to it.
/// </summary>
private readonly SortedInt32KeyNode<HashBucket> _root;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet<T>"/> class.
/// </summary>
/// <param name="equalityComparer">The equality comparer.</param>
internal ImmutableHashSet(IEqualityComparer<T> equalityComparer)
: this(SortedInt32KeyNode<HashBucket>.EmptyNode, equalityComparer, 0)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableHashSet<T>"/> class.
/// </summary>
/// <param name="root">The sorted set that this set wraps.</param>
/// <param name="equalityComparer">The equality comparer used by this instance.</param>
/// <param name="count">The number of elements in this collection.</param>
private ImmutableHashSet(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count)
{
Requires.NotNull(root, "root");
Requires.NotNull(equalityComparer, "equalityComparer");
root.Freeze(s_FreezeBucketAction);
_root = root;
_count = count;
_equalityComparer = equalityComparer;
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
public ImmutableHashSet<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>().IsEmpty);
return this.IsEmpty ? this : ImmutableHashSet<T>.Empty.WithComparer(_equalityComparer);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
public bool IsEmpty
{
get { return this.Count == 0; }
}
#region IHashKeyCollection<T> Properties
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
public IEqualityComparer<T> KeyComparer
{
get { return _equalityComparer; }
}
#endregion
#region IImmutableSet<T> Properties
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Clear()
{
return this.Clear();
}
#endregion
#region ICollection Properties
/// <summary>
/// See ICollection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// See the ICollection interface.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get
{
// This is immutable, so it is always thread-safe.
return true;
}
}
#endregion
/// <summary>
/// Gets the root node (for testing purposes).
/// </summary>
internal IBinaryTree Root
{
get { return _root; }
}
/// <summary>
/// Gets a data structure that captures the current state of this map, as an input into a query or mutating function.
/// </summary>
private MutationInput Origin
{
get { return new MutationInput(this); }
}
#region Public methods
/// <summary>
/// Creates a collection with the same contents as this collection that
/// can be efficiently mutated across multiple operations using standard
/// mutable interfaces.
/// </summary>
/// <remarks>
/// This is an O(1) operation and results in only a single (small) memory allocation.
/// The mutable collection that is returned is *not* thread-safe.
/// </remarks>
[Pure]
public Builder ToBuilder()
{
// We must not cache the instance created here and return it to various callers.
// Those who request a mutable collection must get references to the collection
// that version independently of each other.
return new Builder(this);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> Add(T item)
{
Requires.NotNullAllowStructs(item, "item");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
var result = Add(item, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
public ImmutableHashSet<T> Remove(T item)
{
Requires.NotNullAllowStructs(item, "item");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
var result = Remove(item, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// Searches the set for a given value and returns the equal value it finds, if any.
/// </summary>
/// <param name="equalValue">The value to search for.</param>
/// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param>
/// <returns>A value indicating whether the search was successful.</returns>
/// <remarks>
/// This can be useful when you want to reuse a previously stored reference instead of
/// a newly constructed one (so that more sharing of references can occur) or to look up
/// a value that has more complete data than the value you currently have, although their
/// comparer functions indicate they are equal.
/// </remarks>
[Pure]
public bool TryGetValue(T equalValue, out T actualValue)
{
Requires.NotNullAllowStructs(equalValue, "value");
int hashCode = _equalityComparer.GetHashCode(equalValue);
HashBucket bucket;
if (_root.TryGetValue(hashCode, out bucket))
{
return bucket.TryExchange(equalValue, _equalityComparer, out actualValue);
}
actualValue = equalValue;
return false;
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> Union(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
return this.Union(other, avoidWithComparer: false);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> Intersect(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
var result = Intersect(other, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
public ImmutableHashSet<T> Except(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
var result = Except(other, _equalityComparer, _root);
return result.Finalize(this);
}
/// <summary>
/// Produces a set that contains elements either in this set or a given sequence, but not both.
/// </summary>
/// <param name="other">The other sequence of items.</param>
/// <returns>The new set.</returns>
[Pure]
public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
Contract.Ensures(Contract.Result<IImmutableSet<T>>() != null);
var result = SymmetricExcept(other, this.Origin);
return result.Finalize(this);
}
/// <summary>
/// Checks whether a given sequence of items entirely describe the contents of this set.
/// </summary>
/// <param name="other">The sequence of items to check against this set.</param>
/// <returns>A value indicating whether the sets are equal.</returns>
[Pure]
public bool SetEquals(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
if (object.ReferenceEquals(this, other))
{
return true;
}
return SetEquals(other, this.Origin);
}
/// <summary>
/// Determines whether the current set is a property (strict) subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct subset of other; otherwise, false.</returns>
[Pure]
public bool IsProperSubsetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsProperSubsetOf(other, this.Origin);
}
/// <summary>
/// Determines whether the current set is a correct superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a correct superset of other; otherwise, false.</returns>
[Pure]
public bool IsProperSupersetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsProperSupersetOf(other, this.Origin);
}
/// <summary>
/// Determines whether a set is a subset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of other; otherwise, false.</returns>
[Pure]
public bool IsSubsetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsSubsetOf(other, this.Origin);
}
/// <summary>
/// Determines whether the current set is a superset of a specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
[Pure]
public bool IsSupersetOf(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return IsSupersetOf(other, this.Origin);
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and other share at least one common element; otherwise, false.</returns>
[Pure]
public bool Overlaps(IEnumerable<T> other)
{
Requires.NotNull(other, "other");
return Overlaps(other, this.Origin);
}
#endregion
#region IImmutableSet<T> Methods
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Add(T item)
{
return this.Add(item);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Remove(T item)
{
return this.Remove(item);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other)
{
return this.Union(other);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other)
{
return this.Intersect(other);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other)
{
return this.Except(other);
}
/// <summary>
/// Produces a set that contains elements either in this set or a given sequence, but not both.
/// </summary>
/// <param name="other">The other sequence of items.</param>
/// <returns>The new set.</returns>
[ExcludeFromCodeCoverage]
IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other)
{
return this.SymmetricExcept(other);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
public bool Contains(T item)
{
Requires.NotNullAllowStructs(item, "item");
return Contains(item, this.Origin);
}
/// <summary>
/// See the <see cref="IImmutableSet<T>"/> interface.
/// </summary>
[Pure]
public ImmutableHashSet<T> WithComparer(IEqualityComparer<T> equalityComparer)
{
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
if (equalityComparer == null)
{
equalityComparer = EqualityComparer<T>.Default;
}
if (equalityComparer == _equalityComparer)
{
return this;
}
else
{
var result = new ImmutableHashSet<T>(equalityComparer);
result = result.Union(this, avoidWithComparer: true);
return result;
}
}
#endregion
#region ISet<T> Members
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
bool ISet<T>.Add(T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.ExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.IntersectWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.SymmetricExceptWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
/// <summary>
/// See <see cref="ISet{T}"/>
/// </summary>
void ISet<T>.UnionWith(IEnumerable<T> other)
{
throw new NotSupportedException();
}
#endregion
#region ICollection<T> members
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
foreach (T item in this)
{
array[arrayIndex++] = item;
}
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
/// <summary>
/// See the <see cref="ICollection{T}"/> interface.
/// </summary>
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
/// <summary>
/// See the <see cref="IList{T}"/> interface.
/// </summary>
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
#endregion
#region ICollection Methods
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
void ICollection.CopyTo(Array array, int arrayIndex)
{
Requires.NotNull(array, "array");
Requires.Range(arrayIndex >= 0, "arrayIndex");
Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex");
if (_count == 0)
{
return;
}
int[] indices = new int[1]; // SetValue takes a params array; lifting out the implicit allocation from the loop
foreach (T item in this)
{
indices[0] = arrayIndex++;
array.SetValue(item, indices);
}
}
#endregion
#region IEnumerable<T> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator(_root);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Static query and manipulator methods
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (!Contains(item, origin))
{
return false;
}
}
return true;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Add(T item, MutationInput origin)
{
Requires.NotNullAllowStructs(item, "item");
OperationResult result;
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket = origin.Root.GetValueOrDefault(hashCode);
var newBucket = bucket.Add(item, origin.EqualityComparer, out result);
if (result == OperationResult.NoChangeRequired)
{
return new MutationResult(origin.Root, 0);
}
var newRoot = UpdateRoot(origin.Root, hashCode, newBucket);
Debug.Assert(result == OperationResult.SizeChanged);
return new MutationResult(newRoot, 1 /*result == OperationResult.SizeChanged ? 1 : 0*/);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Remove(T item, MutationInput origin)
{
Requires.NotNullAllowStructs(item, "item");
var result = OperationResult.NoChangeRequired;
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket;
var newRoot = origin.Root;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
var newBucket = bucket.Remove(item, origin.EqualityComparer, out result);
if (result == OperationResult.NoChangeRequired)
{
return new MutationResult(origin.Root, 0);
}
newRoot = UpdateRoot(origin.Root, hashCode, newBucket);
}
return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool Contains(T item, MutationInput origin)
{
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket;
if (origin.Root.TryGetValue(hashCode, out bucket))
{
return bucket.Contains(item, origin.EqualityComparer);
}
return false;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Union(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
int count = 0;
var newRoot = origin.Root;
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
int hashCode = origin.EqualityComparer.GetHashCode(item);
HashBucket bucket = newRoot.GetValueOrDefault(hashCode);
OperationResult result;
var newBucket = bucket.Add(item, origin.EqualityComparer, out result);
if (result == OperationResult.SizeChanged)
{
newRoot = UpdateRoot(newRoot, hashCode, newBucket);
count++;
}
}
return new MutationResult(newRoot, count);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool Overlaps(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return false;
}
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (Contains(item, origin))
{
return true;
}
}
return false;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool SetEquals(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
if (origin.Count != otherSet.Count)
{
return false;
}
int matches = 0;
foreach (T item in otherSet)
{
if (!Contains(item, origin))
{
return false;
}
matches++;
}
return matches == origin.Count;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, HashBucket newBucket)
{
bool mutated;
if (newBucket.IsEmpty)
{
return root.Remove(hashCode, out mutated);
}
else
{
bool replacedExistingValue;
return root.SetItem(hashCode, newBucket, EqualityComparer<HashBucket>.Default, out replacedExistingValue, out mutated);
}
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
var newSet = SortedInt32KeyNode<HashBucket>.EmptyNode;
int count = 0;
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
if (Contains(item, origin))
{
var result = Add(item, new MutationInput(newSet, origin.EqualityComparer, count));
newSet = result.Root;
count += result.Count;
}
}
return new MutationResult(newSet, count, CountType.FinalValue);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, SortedInt32KeyNode<HashBucket> root)
{
Requires.NotNull(other, "other");
Requires.NotNull(equalityComparer, "equalityComparer");
Requires.NotNull(root, "root");
int count = 0;
var newRoot = root;
foreach (var item in other.GetEnumerableDisposable<T, Enumerator>())
{
int hashCode = equalityComparer.GetHashCode(item);
HashBucket bucket;
if (newRoot.TryGetValue(hashCode, out bucket))
{
OperationResult result;
HashBucket newBucket = bucket.Remove(item, equalityComparer, out result);
if (result == OperationResult.SizeChanged)
{
count--;
newRoot = UpdateRoot(newRoot, hashCode, newBucket);
}
}
}
return new MutationResult(newRoot, count);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
[Pure]
private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
var otherAsSet = Empty.Union(other);
int count = 0;
var result = SortedInt32KeyNode<HashBucket>.EmptyNode;
foreach (T item in new NodeEnumerable(origin.Root))
{
if (!otherAsSet.Contains(item))
{
var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count));
result = mutationResult.Root;
count += mutationResult.Count;
}
}
foreach (T item in otherAsSet)
{
if (!Contains(item, origin))
{
var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count));
result = mutationResult.Root;
count += mutationResult.Count;
}
}
return new MutationResult(result, count, CountType.FinalValue);
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return other.Any();
}
// To determine whether everything we have is also in another sequence,
// we enumerate the sequence and "tag" whether it's in this collection,
// then consider whether every element in this collection was tagged.
// Since this collection is immutable we cannot directly tag. So instead
// we simply count how many "hits" we have and ensure it's equal to the
// size of this collection. Of course for this to work we need to ensure
// the uniqueness of items in the given sequence, so we create a set based
// on the sequence first.
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
if (origin.Count >= otherSet.Count)
{
return false;
}
int matches = 0;
bool extraFound = false;
foreach (T item in otherSet)
{
if (Contains(item, origin))
{
matches++;
}
else
{
extraFound = true;
}
if (matches == origin.Count && extraFound)
{
return true;
}
}
return false;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return false;
}
int matchCount = 0;
foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
{
matchCount++;
if (!Contains(item, origin))
{
return false;
}
}
return origin.Count > matchCount;
}
/// <summary>
/// Performs the set operation on a given data structure.
/// </summary>
private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin)
{
Requires.NotNull(other, "other");
if (origin.Root.IsEmpty)
{
return true;
}
// To determine whether everything we have is also in another sequence,
// we enumerate the sequence and "tag" whether it's in this collection,
// then consider whether every element in this collection was tagged.
// Since this collection is immutable we cannot directly tag. So instead
// we simply count how many "hits" we have and ensure it's equal to the
// size of this collection. Of course for this to work we need to ensure
// the uniqueness of items in the given sequence, so we create a set based
// on the sequence first.
var otherSet = new HashSet<T>(other, origin.EqualityComparer);
int matches = 0;
foreach (T item in otherSet)
{
if (Contains(item, origin))
{
matches++;
}
}
return matches == origin.Count;
}
#endregion
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="equalityComparer">The equality comparer.</param>
/// <param name="count">The number of elements in the data structure.</param>
/// <returns>The immutable collection.</returns>
private static ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count)
{
Requires.NotNull(root, "root");
Requires.NotNull(equalityComparer, "equalityComparer");
Requires.Range(count >= 0, "count");
return new ImmutableHashSet<T>(root, equalityComparer, count);
}
/// <summary>
/// Wraps the specified data structure with an immutable collection wrapper.
/// </summary>
/// <param name="root">The root of the data structure.</param>
/// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param>
/// <returns>The immutable collection.</returns>
private ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot)
{
return (root != _root) ? new ImmutableHashSet<T>(root, _equalityComparer, adjustedCountIfDifferentRoot) : this;
}
/// <summary>
/// Bulk adds entries to the set.
/// </summary>
/// <param name="items">The entries to add.</param>
/// <param name="avoidWithComparer"><c>true</c> when being called from ToHashSet to avoid StackOverflow.</param>
[Pure]
private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer)
{
Requires.NotNull(items, "items");
Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null);
// Some optimizations may apply if we're an empty set.
if (this.IsEmpty && !avoidWithComparer)
{
// If the items being added actually come from an ImmutableHashSet<T>,
// reuse that instance if possible.
var other = items as ImmutableHashSet<T>;
if (other != null)
{
return other.WithComparer(this.KeyComparer);
}
}
var result = Union(items, this.Origin);
return result.Finalize(this);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using CoreFXTestLibrary;
using System;
namespace System.Threading.Tasks.Test.Unit
{
public sealed class ParallelForeachPartitioner
{
[Fact]
public static void ParallelForeachPartitioner0()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ChunkSize = -1,
PartitionerType = PartitionerType.IListBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void ParallelForeachPartitioner1()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ChunkSize = 10,
PartitionerType = PartitionerType.IEnumerableOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner2()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ChunkSize = 1,
PartitionerType = PartitionerType.ArrayBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner3()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ChunkSize = 3,
PartitionerType = PartitionerType.RangePartitioner,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner4()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 10,
ChunkSize = 97,
PartitionerType = PartitionerType.RangePartitioner,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner5()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ChunkSize = -1,
PartitionerType = PartitionerType.ArrayBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner6()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ChunkSize = -1,
PartitionerType = PartitionerType.RangePartitioner,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner7()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ChunkSize = 10,
PartitionerType = PartitionerType.IListBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner8()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ChunkSize = 1,
PartitionerType = PartitionerType.IEnumerableOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner9()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ChunkSize = 3,
PartitionerType = PartitionerType.IEnumerableOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void ParallelForeachPartitioner10()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 1,
ChunkSize = 97,
PartitionerType = PartitionerType.IEnumerableOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner11()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ChunkSize = -1,
PartitionerType = PartitionerType.IEnumerableOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner12()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ChunkSize = 10,
PartitionerType = PartitionerType.ArrayBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner13()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ChunkSize = 1,
PartitionerType = PartitionerType.RangePartitioner,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner14()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ChunkSize = 3,
PartitionerType = PartitionerType.IListBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner15()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 2,
ChunkSize = 97,
PartitionerType = PartitionerType.IListBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner16()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 97,
ChunkSize = -1,
PartitionerType = PartitionerType.IEnumerableOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.None,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner17()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 97,
ChunkSize = 10,
PartitionerType = PartitionerType.RangePartitioner,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.None,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner18()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 97,
ChunkSize = 1,
PartitionerType = PartitionerType.IListBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.None,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner19()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 97,
ChunkSize = 3,
PartitionerType = PartitionerType.ArrayBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelForeachPartitioner20()
{
TestParameters parameters = new TestParameters(API.Foreach, StartIndexBase.Zero)
{
Count = 97,
ChunkSize = 97,
PartitionerType = PartitionerType.ArrayBalancedOOB,
ParallelForeachDataSourceType = DataSourceType.Partitioner,
ParallelOption = WithParallelOption.WithDOP,
LocalOption = ActionWithLocal.HasFinally,
StateOption = ActionWithState.Stop,
};
ParallelForTest test = new ParallelForTest(parameters);
test.RealRun();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Entities.DynamicQuery;
using Signum.Entities.MachineLearning;
using Signum.Entities.UserAssets;
using Signum.Utilities;
using Signum.Utilities.Reflection;
namespace Signum.Engine.MachineLearning.TensorFlow;
public interface ITensorFlowEncoding
{
string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token);
List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column);
object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options);
void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset); //Span<T>
}
public class NoneTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
var nn = (NeuralNetworkSettingsEntity)predictor.AlgorithmSettings;
if (!ReflectionTools.IsNumber(token.Token.Type) && token.Token.Type.UnNullify() != typeof(bool))
return PredictorMessage._0IsRequiredFor1.NiceToString(DefaultColumnEncodings.OneHot.NiceToString(), token.Token.NiceTypeName);
if (usage == PredictorColumnUsage.Output && (nn.PredictionType == PredictionType.Classification || nn.PredictionType == PredictionType.MultiClassification))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), nn.PredictionType.NiceToString());
return null;
}
public List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
return new List<PredictorCodification> { new PredictorCodification(column) };
}
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
var c = codifications.SingleEx();
inputValues[offset + c.Index] = Convert.ToSingle(value);
}
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
var c = codifications.SingleEx();
return ReflectionTools.ChangeType(outputValues[c.Index], column.Token.Type);
}
}
public class OneHotTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
var nn = (NeuralNetworkSettingsEntity)predictor.AlgorithmSettings;
if (ReflectionTools.IsDecimalNumber(token.Token.Type))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), predictor.Algorithm.NiceToString());
if (usage == PredictorColumnUsage.Output && (nn.PredictionType == PredictionType.Regression || nn.PredictionType == PredictionType.MultiRegression))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), nn.PredictionType.NiceToString());
return null;
}
public List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
return rc.Values.Cast<object>().NotNull().Distinct().Select(v => new PredictorCodification(column) { IsValue = v }).ToList();
}
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
var dic = GetCodificationDictionary(column, codifications);
if (value != null && dic.TryGetValue(value, out int index))
inputValues[offset + index] = 1;
}
public virtual Dictionary<object, int> GetCodificationDictionary(PredictorColumnBase column, List<PredictorCodification> codifications)
{
if (column.ColumnModel != null)
return (Dictionary<object, int>)column.ColumnModel;
column.ColumnModel = codifications.ToDictionary(a => a.IsValue!, a => a.Index);
return (Dictionary<object, int>)column.ColumnModel;
}
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
var cods = options?.FilteredCodifications ?? codifications;
if (options?.AlternativeCount == null)
{
var max = float.MinValue;
PredictorCodification? best = null;
foreach (var c in cods)
{
if (max < outputValues[c.Index])
{
best = c;
max = outputValues[c.Index];
}
}
return best?.IsValue;
}
else
{
//Softmax
var sum = cods.Sum(cod => Math.Exp(outputValues[cod.Index]));
return cods.OrderByDescending(c => outputValues[c.Index]).Take(options.AlternativeCount.Value).Select(c => new AlternativePrediction(
probability: (float)(Math.Exp(outputValues[c.Index]) / sum),
value: c.IsValue
)).ToList();
}
}
}
public abstract class BaseNormalizeTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
if (!ReflectionTools.IsDecimalNumber(token.Token.Type) && !ReflectionTools.IsNumber(token.Token.Type))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), predictor.Algorithm.NiceToString());
return null;
}
public List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
var values = rc.Values.Cast<object>().NotNull().Select(a => Convert.ToSingle(a)).ToList();
return new List<PredictorCodification>
{
new PredictorCodification(column)
{
Average = values.Count == 0 ? 0 : values.Average(),
StdDev = values.Count == 0 ? 1 : values.StdDev(),
Min = values.Count == 0 ? 0 : values.Min(),
Max = values.Count == 0 ? 1 : values.Max(),
}
};
}
public abstract float EncodeSingleValue(object? valueDefault, PredictorCodification c);
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
PredictorCodification c = codifications.SingleEx();
inputValues[offset + c.Index] = EncodeSingleValue(value, c);
}
public abstract object? DecodeSingleValue(float value, PredictorCodification c);
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
PredictorCodification cod = codifications.SingleEx();
float value = outputValues[cod.Index];
return DecodeSingleValue(value, cod);
}
}
public class NormalizeZScoreTFEncoding : BaseNormalizeTFEncoding
{
public override float EncodeSingleValue(object? value, PredictorCodification c)
{
return (Convert.ToSingle(value) - c.Average!.Value) / c.StdDev!.Value;
}
public override object? DecodeSingleValue(float value, PredictorCodification c)
{
var newValue = c.Average! + (c.StdDev! * value);
return ReflectionTools.ChangeType(newValue, c.Column.Token.Type);
}
}
public class NormalizeMinMaxTFEncoding : BaseNormalizeTFEncoding
{
public override float EncodeSingleValue(object? value, PredictorCodification c)
{
return (Convert.ToSingle(value) - c.Min!.Value) / (c.Max!.Value - c.Min!.Value);
}
public override object? DecodeSingleValue(float value, PredictorCodification c)
{
var newValue = c.Min!.Value + ((c.Max!.Value - c.Min.Value) * value);
return ReflectionTools.ChangeType(newValue, c.Column.Token.Type);
}
}
class NormalizeLogTFEncoding : BaseNormalizeTFEncoding
{
public float MinLog = -5;
public override float EncodeSingleValue(object? value, PredictorCodification c)
{
var dValue = Convert.ToDouble(value);
return (dValue <= 0 ? MinLog : Math.Max(MinLog, (float)Math.Log(dValue)));
}
public override object? DecodeSingleValue(float value, PredictorCodification c)
{
var newValue = (float)Math.Exp((double)value);
return ReflectionTools.ChangeType(newValue, c.Column.Token.Type);
}
}
public class SplitWordsTFEncoding : ITensorFlowEncoding
{
public string? ValidateEncodingProperty(PredictorEntity predictor, PredictorSubQueryEntity? subQuery, PredictorColumnEncodingSymbol encoding, PredictorColumnUsage usage, QueryTokenEmbedded token)
{
var nn = (NeuralNetworkSettingsEntity)predictor.AlgorithmSettings;
if (token.Token.Type != typeof(string))
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), predictor.Algorithm.NiceToString());
if (usage == PredictorColumnUsage.Output)
return PredictorMessage._0NotSuportedFor1.NiceToString(encoding.NiceToString(), usage.NiceToString());
return null;
}
public virtual List<PredictorCodification> GenerateCodifications(ResultColumn rc, PredictorColumnBase column)
{
var distinctStrings = rc.Values.Cast<string>().NotNull().Distinct();
var allWords = distinctStrings.SelectMany(str => SplitWords(str)).Distinct(StringComparer.CurrentCultureIgnoreCase).ToList();
return allWords.Select(v => new PredictorCodification(column) { IsValue = v }).ToList();
}
public char[] separators = new[] { '.', ',', ' ', '-', '(', ')', '/', '\\', ';', ':' };
public virtual string[] SplitWords(string str)
{
return str.SplitNoEmpty(separators);
}
public void EncodeValue(object? value, PredictorColumnBase column, List<PredictorCodification> codifications, float[] inputValues, int offset)
{
var words = SplitWords((string)value! ?? "");
var dic = GetCodificationDictionary(column, codifications);
foreach (var w in words)
{
if (dic.TryGetValue(w, out int index))
inputValues[index + offset] = 1;
}
}
public int MaxDecodedWords = 5;
public float MinDecodedWordValue = 0.1f;
public object? DecodeValue(PredictorColumnBase column, List<PredictorCodification> codifications, float[] outputValues, PredictionOptions options)
{
var bestCodifications = codifications
.Where(c => outputValues[c.Index] > MinDecodedWordValue)
.OrderByDescending(a => outputValues[a.Index])
.Take(MaxDecodedWords)
.ToList();
return bestCodifications.ToString(a => a.IsValue!.ToString(), ", ");
}
public virtual Dictionary<string, int> GetCodificationDictionary(PredictorColumnBase column, List<PredictorCodification> codifications)
{
if (column.ColumnModel != null)
return (Dictionary<string, int>)column.ColumnModel;
column.ColumnModel = codifications.ToDictionaryEx(a => (string)a.IsValue!, a => a.Index, StringComparer.CurrentCultureIgnoreCase);
return (Dictionary<string, int>)column.ColumnModel;
}
}
| |
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.Collections;
using System.Collections.Generic;
namespace HtmlAgilityPack
{
/// <summary>
/// Represents a list of mixed code fragments.
/// </summary>
public class MixedCodeDocumentFragmentList : IEnumerable
{
#region Fields
private MixedCodeDocument _doc;
private IList<MixedCodeDocumentFragment> _items = new List<MixedCodeDocumentFragment>();
#endregion
#region Constructors
internal MixedCodeDocumentFragmentList(MixedCodeDocument doc)
{
_doc = doc;
}
#endregion
#region Properties
///<summary>
/// Gets the Document
///</summary>
public MixedCodeDocument Doc
{
get { return _doc; }
}
/// <summary>
/// Gets the number of fragments contained in the list.
/// </summary>
public int Count
{
get { return _items.Count; }
}
/// <summary>
/// Gets a fragment from the list using its index.
/// </summary>
public MixedCodeDocumentFragment this[int index]
{
get { return _items[index] as MixedCodeDocumentFragment; }
}
#endregion
#region IEnumerable Members
/// <summary>
/// Gets an enumerator that can iterate through the fragment list.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Public Methods
/// <summary>
/// Appends a fragment to the list of fragments.
/// </summary>
/// <param name="newFragment">The fragment to append. May not be null.</param>
public void Append(MixedCodeDocumentFragment newFragment)
{
if (newFragment == null)
{
throw new ArgumentNullException("newFragment");
}
_items.Add(newFragment);
}
/// <summary>
/// Gets an enumerator that can iterate through the fragment list.
/// </summary>
public MixedCodeDocumentFragmentEnumerator GetEnumerator()
{
return new MixedCodeDocumentFragmentEnumerator(_items);
}
/// <summary>
/// Prepends a fragment to the list of fragments.
/// </summary>
/// <param name="newFragment">The fragment to append. May not be null.</param>
public void Prepend(MixedCodeDocumentFragment newFragment)
{
if (newFragment == null)
{
throw new ArgumentNullException("newFragment");
}
_items.Insert(0, newFragment);
}
/// <summary>
/// Remove a fragment from the list of fragments. If this fragment was not in the list, an exception will be raised.
/// </summary>
/// <param name="fragment">The fragment to remove. May not be null.</param>
public void Remove(MixedCodeDocumentFragment fragment)
{
if (fragment == null)
{
throw new ArgumentNullException("fragment");
}
int index = GetFragmentIndex(fragment);
if (index == -1)
{
throw new IndexOutOfRangeException();
}
RemoveAt(index);
}
/// <summary>
/// Remove all fragments from the list.
/// </summary>
public void RemoveAll()
{
_items.Clear();
}
/// <summary>
/// Remove a fragment from the list of fragments, using its index in the list.
/// </summary>
/// <param name="index">The index of the fragment to remove.</param>
public void RemoveAt(int index)
{
//MixedCodeDocumentFragment frag = (MixedCodeDocumentFragment) _items[index];
_items.RemoveAt(index);
}
#endregion
#region Internal Methods
internal void Clear()
{
_items.Clear();
}
internal int GetFragmentIndex(MixedCodeDocumentFragment fragment)
{
if (fragment == null)
{
throw new ArgumentNullException("fragment");
}
for (int i = 0; i < _items.Count; i++)
{
if ((_items[i]) == fragment)
{
return i;
}
}
return -1;
}
#endregion
#region Nested type: MixedCodeDocumentFragmentEnumerator
/// <summary>
/// Represents a fragment enumerator.
/// </summary>
public class MixedCodeDocumentFragmentEnumerator : IEnumerator
{
#region Fields
private int _index;
private IList<MixedCodeDocumentFragment> _items;
#endregion
#region Constructors
internal MixedCodeDocumentFragmentEnumerator(IList<MixedCodeDocumentFragment> items)
{
_items = items;
_index = -1;
}
#endregion
#region Properties
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public MixedCodeDocumentFragment Current
{
get { return (MixedCodeDocumentFragment) (_items[_index]); }
}
#endregion
#region IEnumerator Members
/// <summary>
/// Gets the current element in the collection.
/// </summary>
object IEnumerator.Current
{
get { return (Current); }
}
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.</returns>
public bool MoveNext()
{
_index++;
return (_index < _items.Count);
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
public void Reset()
{
_index = -1;
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Log2Console.Log;
using Log2Console.Settings;
namespace Log2Console.Receiver
{
/// <summary>
/// This receiver watch a given file, like a 'tail' program, with one log event by line.
/// Ideally the log events should use the log4j XML Schema layout.
/// </summary>
[Serializable]
[DisplayName("CSV Log File")]
public class CsvFileReceiver : BaseReceiver
{
[NonSerialized]
private FileSystemWatcher _fileWatcher;
[NonSerialized]
private StreamReader _fileReader;
[NonSerialized]
private string _filename;
private string _fileToWatch = String.Empty;
private bool _showFromBeginning;
private string _loggerName;
[Category("Configuration")]
[DisplayName("File to Watch")]
public string FileToWatch
{
get { return _fileToWatch; }
set
{
if (String.Compare(_fileToWatch, value, true) == 0)
return;
_fileToWatch = value;
Restart();
}
}
[Category("Configuration")]
[DisplayName("Show from Beginning")]
[Description("Show file contents from the beginning (not just newly appended lines)")]
[DefaultValue(false)]
public bool ShowFromBeginning
{
get { return _showFromBeginning; }
set { _showFromBeginning = value; }
}
private FieldType[] _fieldList = new[]
{
new FieldType(LogMessageField.SequenceNr, "sequence"),
new FieldType(LogMessageField.TimeStamp, "time"),
new FieldType(LogMessageField.Level, "level"),
new FieldType(LogMessageField.ThreadName, "thread"),
new FieldType(LogMessageField.CallSiteClass, "class"),
new FieldType(LogMessageField.CallSiteMethod, "method"),
new FieldType(LogMessageField.Message, "message"),
new FieldType(LogMessageField.Exception, "exception"),
new FieldType(LogMessageField.SourceFileName, "file")
};
[Category("Configuration")]
[DisplayName("Field List")]
[Description("Defines the type of each field")]
public FieldType[] FieldList
{
get { return _fieldList; }
set { _fieldList = value; }
}
[Category("Configuration")]
[DisplayName("Read Header From File")]
[Description("Read the Header or First List of the CSV File to Automatically determine the Field Types")]
[DefaultValue(false)]
public bool ReadHeaderFromFile { get; set; }
private string _dateTimeFormat = "yyyy/MM/dd HH:mm:ss.fff";
[Category("Configuration")]
[DisplayName("Time Format")]
[Description("Specifies the DateTime Format used to Parse the DateTime Field")]
[DefaultValue("yyyy/MM/dd HH:mm:ss.fff")]
public string DateTimeFormat
{
get { return _dateTimeFormat; }
set { _dateTimeFormat = value; }
}
private string _quoteChar = "\"";
[Category("Configuration")]
[DisplayName("Quote Char")]
[Description("If a field includes the delimiter, the whole field will be enclosed with a quote")]
[DefaultValue("\"")]
public string QuoteChar
{
get { return _quoteChar; }
set { _quoteChar = value; }
}
private string _delimiter = ",";
[Category("Configuration")]
[DisplayName("Delimiter ")]
[Description("The character used to delimit each field")]
[DefaultValue(",")]
public string Delimiter
{
get { return _delimiter; }
set { _delimiter = value; }
}
[Category("Behavior")]
[DisplayName("Logger Name")]
[Description("Append the given Name to the Logger Name. If left empty, the filename will be used.")]
public string LoggerName
{
get { return _loggerName; }
set
{
_loggerName = value;
ComputeFullLoggerName();
}
}
#region IReceiver Members
[Browsable(false)]
public override string SampleClientConfig
{
get
{
return
@"<target name=""CsvLog""
xsi:type=""File""
fileName=""${basedir}/Logs/log.csv""
archiveFileName=""${basedir}/Logs/Archives/log_{#}_${date:format=yyyy-MM-d_HH}.txt""
archiveEvery=""Hour""
archiveNumbering=""Sequence""
maxArchiveFiles=""30000""
concurrentWrites=""true""
keepFileOpen=""false""
>
<layout xsi:type=""CSVLayout"">
<column name =""sequence"" layout =""${counter}"" />
<column name=""time"" layout=""${date:format=yyyy/MM/dd HH\:mm\:ss.fff}"" />
<column name=""level"" layout=""${level}""/>
<column name=""thread"" layout=""${threadid}""/>
<column name=""class"" layout =""${callsite:className=true:methodName=false:fileName=false:includeSourcePath=false}"" />
<column name=""method"" layout =""${callsite:className=false:methodName=true:fileName=false:includeSourcePath=false}"" />
<column name=""message"" layout=""${message}"" />
<column name=""exception"" layout=""${exception:format=Message,Type,StackTrace}"" />
<column name=""file"" layout =""${callsite:className=false:methodName=false:fileName=true:includeSourcePath=true}"" />
</layout>
</target>";
}
}
public override void Initialize()
{
if (String.IsNullOrEmpty(_fileToWatch))
return;
_fileReader =
new StreamReader(new FileStream(_fileToWatch, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
string path = Path.GetDirectoryName(_fileToWatch);
_filename = Path.GetFileName(_fileToWatch);
_fileWatcher = new FileSystemWatcher(path, _filename)
{NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size};
_fileWatcher.Changed += OnFileChanged;
_fileWatcher.EnableRaisingEvents = true;
ComputeFullLoggerName();
if (ReadHeaderFromFile)
AutoConfigureHeader();
if (!_showFromBeginning)
{
_fileReader.BaseStream.Seek(0, SeekOrigin.End);
_fileReader.DiscardBufferedData();
}
}
private void AutoConfigureHeader()
{
var line = _fileReader. ReadLine();
var fields = line.Split(new[] { Delimiter }, StringSplitOptions.None);
bool headerValid = false;
try
{
var fieldList = new FieldType[fields.Length];
for (int index = 0; index < fields.Length; index++)
{
var field = fields[index];
if (UserSettings.Instance.CsvHeaderFieldTypes.ContainsKey(field))
{
fieldList[index] = UserSettings.Instance.CsvHeaderFieldTypes[field];
//Note: This is a very basic check for a valid header. If any field is detected, the header
//is considered valid. This could be made more thorough.
headerValid = true;
}
else
fieldList[index] = new FieldType(LogMessageField.Properties, field, field);
}
if (headerValid)
{
_fieldList = fieldList;
}
else
{
MessageBox.Show("Could not Parse the Header: " + line, "Error Parsing CSV Header");
}
}
catch(Exception ex)
{
MessageBox.Show(string.Format("Could not Parse the Header: {0}\n\rError: {1}", line, ex),
"Error Parsing CSV Header");
}
}
public override void Terminate()
{
if (_fileWatcher != null)
{
_fileWatcher.EnableRaisingEvents = false;
_fileWatcher.Changed -= OnFileChanged;
_fileWatcher = null;
}
if (_fileReader != null)
_fileReader.Close();
_fileReader = null;
}
public override void Attach(ILogMessageNotifiable notifiable)
{
base.Attach(notifiable);
if (_showFromBeginning)
ReadFile();
}
#endregion
private void Restart()
{
Terminate();
Initialize();
}
private void ComputeFullLoggerName()
{
DisplayName = String.IsNullOrEmpty(_loggerName)
? String.Empty
: String.Format("Log File [{0}]", _loggerName);
}
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
return;
ReadFile();
}
private void ReadFile()
{
if ((_fileReader == null))
return;
if (_fileReader.BaseStream.Position > _fileReader.BaseStream.Length)
{
_fileReader.BaseStream.Seek(0, SeekOrigin.Begin);
_fileReader.DiscardBufferedData();
}
// Get last added lines
var logMsgs = new List<LogMessage>();
List<string> fields;
while ((fields = ReadLogEntry()) != null)
{
var logMsg = new LogMessage {ThreadName = string.Empty};
if (fields.Count == FieldList.Length)
{
ParseFields(ref logMsg, fields);
logMsgs.Add(logMsg);
}
}
// Notify the UI with the set of messages
Notifiable.Notify(logMsgs.ToArray());
}
private void ParseFields(ref LogMessage logMsg, List<string> fields)
{
for (int i = 0; i < FieldList.Length; i++)
{
var fieldType = _fieldList[i];
string fieldValue = fields[i];
try
{
switch (fieldType.Field)
{
case LogMessageField.SequenceNr:
logMsg.SequenceNr = ulong.Parse(fieldValue);
break;
case LogMessageField.LoggerName:
logMsg.LoggerName = fieldValue;
break;
case LogMessageField.RootLoggerName:
logMsg.RootLoggerName = fieldValue;
break;
case LogMessageField.Level:
logMsg.Level = LogLevels.Instance[(LogLevel) Enum.Parse(typeof (LogLevel), fieldValue)];
//if (logMsg.Level == null)
// throw new NullReferenceException("Cannot parse string: " + fieldValue);
break;
case LogMessageField.Message:
logMsg.Message = fieldValue;
break;
case LogMessageField.ThreadName:
logMsg.ThreadName = fieldValue;
break;
case LogMessageField.TimeStamp:
DateTime time;
DateTime.TryParseExact(fieldValue, DateTimeFormat, null, DateTimeStyles.None, out time);
logMsg.TimeStamp = time;
break;
case LogMessageField.Exception:
logMsg.ExceptionString = fieldValue;
break;
case LogMessageField.CallSiteClass:
logMsg.CallSiteClass = fieldValue;
logMsg.LoggerName = logMsg.CallSiteClass;
break;
case LogMessageField.CallSiteMethod:
logMsg.CallSiteMethod = fieldValue;
break;
case LogMessageField.SourceFileName:
fieldValue = fieldValue.Trim("()".ToCharArray());
//Detect the Line Nr
var fileNameFields = fieldValue.Split(new[] {":"}, StringSplitOptions.None);
if (fileNameFields.Length == 3)
{
uint line;
var lineNrString = fileNameFields[2];
if (uint.TryParse(lineNrString, out line))
logMsg.SourceFileLineNr = line;
var fileName = fieldValue.Substring(0, fieldValue.Length - lineNrString.Length - 1);
logMsg.SourceFileName = fileName;
}
else
logMsg.SourceFileName = fieldValue;
break;
case LogMessageField.SourceFileLineNr:
logMsg.SourceFileLineNr = uint.Parse(fieldValue);
break;
case LogMessageField.Properties:
logMsg.Properties.Add(fieldType.Property, fieldValue);
break;
}
}
catch (Exception ex)
{
var sb = new StringBuilder();
foreach (var field in fields)
{
sb.Append(field);
sb.Append(Delimiter);
}
logMsg = new LogMessage
{
SequenceNr = 0,
LoggerName = "Log2Console",
RootLoggerName = "Log2Console",
Level = LogLevels.Instance[LogLevel.Error],
Message = "Error Parsing Log Entry Line: " + sb,
ThreadName = string.Empty,
TimeStamp = DateTime.Now,
ExceptionString = ex.Message + ex.StackTrace,
CallSiteClass = string.Empty,
CallSiteMethod = string.Empty,
SourceFileName = string.Empty,
SourceFileLineNr = 0,
};
return;
}
}
}
private List<string> ReadLogEntry()
{
var finalFields = new List<string>();
bool quoteDetected = false;
StringBuilder quoteString = null;
do
{
//If there is a log entry, that spans multiple lines, it will be surrounded by the Quote Character.
if(quoteDetected)
{
quoteString.AppendLine();
}
var line = _fileReader.ReadLine();
if (line == null)
return null;
if (string.IsNullOrEmpty(line)) //Skip blank lines
continue;
var fields = line.Split(new[] {Delimiter}, StringSplitOptions.None);
foreach (var nextField in fields)
{
//First check for Quote Char in fields
if(!quoteDetected)
{
//See if there is a start quote
if ((nextField.Length > 0) && (nextField.Substring(0,1).Equals(QuoteChar)))
{
quoteString = new StringBuilder();
if ((nextField.Length > 1))
{
var fieldWithoutQuote = nextField.Substring(1, nextField.Length - 1);
quoteString.Append(fieldWithoutQuote);
quoteDetected = true;
}
}
//If not, simply add the field
else
{
finalFields.Add(nextField);
}
}
//Keep on concatenating the string until the end quote is detected
else
{
//See if the last character is a quote
if((nextField.Length > 0) && (nextField.Substring(nextField.Length-1,1).Equals(QuoteChar)))
{
var fieldWithoutQuote = nextField.Substring(0, nextField.Length - 1);
quoteString.Append(fieldWithoutQuote);
quoteDetected = false;
finalFields.Add(quoteString.ToString());
}
//No quote is detected, keep on adding the next field
else
{
quoteString.Append(nextField);
quoteString.Append(Delimiter); //Since this is enclosed in the Quote Char's it is part of a string field, and not valid delimiter
}
}
}
//If this is a normal log entry, without any quotes, then check that the correct amount of fields is detected
if(!quoteDetected && (finalFields.Count != FieldList.Length))
return null;
} while (finalFields.Count < FieldList.Length); //If this is a multi line log, keep on reading the following lines
return finalFields;
}
}
}
| |
// 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>
/// RouteFilterRulesOperations operations.
/// </summary>
internal partial class RouteFilterRulesOperations : IServiceOperations<NetworkManagementClient>, IRouteFilterRulesOperations
{
/// <summary>
/// Initializes a new instance of the RouteFilterRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RouteFilterRulesOperations(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 rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </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 routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<RouteFilterRule>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-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("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_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<RouteFilterRule>();
_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<RouteFilterRule>(_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 route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule 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<RouteFilterRule>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilterRule> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule 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<RouteFilterRule>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<RouteFilterRule> _response = await BeginUpdateWithHttpMessagesAsync(resourceGroupName, routeFilterName, ruleName, routeFilterRuleParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all RouteFilterRules in a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </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<RouteFilterRule>>> ListByRouteFilterWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-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("routeFilterName", routeFilterName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByRouteFilter", 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/routeFilters/{routeFilterName}/routeFilterRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_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<RouteFilterRule>>();
_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<RouteFilterRule>>(_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 rule from a route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="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 routeFilterName, string ruleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-09-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("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
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/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_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 != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
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 route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the create or update route filter rule 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<RouteFilterRule>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, RouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (routeFilterRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters");
}
if (routeFilterRuleParameters != null)
{
routeFilterRuleParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (routeFilterRuleParameters == null)
{
routeFilterRuleParameters = new RouteFilterRule();
}
string apiVersion = "2017-09-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("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters);
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/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_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(routeFilterRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, 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 != 200 && (int)_statusCode != 201)
{
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<RouteFilterRule>();
_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<RouteFilterRule>(_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<RouteFilterRule>(_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>
/// Updates a route in the specified route filter.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeFilterName'>
/// The name of the route filter.
/// </param>
/// <param name='ruleName'>
/// The name of the route filter rule.
/// </param>
/// <param name='routeFilterRuleParameters'>
/// Parameters supplied to the update route filter rule 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<RouteFilterRule>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string ruleName, PatchRouteFilterRule routeFilterRuleParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeFilterName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterName");
}
if (ruleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ruleName");
}
if (routeFilterRuleParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeFilterRuleParameters");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (routeFilterRuleParameters == null)
{
routeFilterRuleParameters = new PatchRouteFilterRule();
}
string apiVersion = "2017-09-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("routeFilterName", routeFilterName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("routeFilterRuleParameters", routeFilterRuleParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", 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/routeFilters/{routeFilterName}/routeFilterRules/{ruleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeFilterName}", System.Uri.EscapeDataString(routeFilterName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_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("PATCH");
_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(routeFilterRuleParameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(routeFilterRuleParameters, 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 != 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<RouteFilterRule>();
_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<RouteFilterRule>(_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 RouteFilterRules in a route filter.
/// </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<RouteFilterRule>>> ListByRouteFilterNextWithHttpMessagesAsync(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, "ListByRouteFilterNext", 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<RouteFilterRule>>();
_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<RouteFilterRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Controls.UnitTests
{
public class TextBoxTests
{
[Fact]
public void Opening_Context_Menu_Does_not_Lose_Selection()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
ContextMenu = new TestContextMenu()
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot() { Child = sp };
target1.SelectionStart = 0;
target1.SelectionEnd = 3;
target1.Focus();
Assert.False(target2.IsFocused);
Assert.True(target1.IsFocused);
target2.Focus();
Assert.Equal("123", target1.SelectedText);
}
}
[Fact]
public void DefaultBindingMode_Should_Be_TwoWay()
{
Assert.Equal(
BindingMode.TwoWay,
TextBox.TextProperty.GetMetadata(typeof(TextBox)).DefaultBindingMode);
}
[Fact]
public void CaretIndex_Can_Moved_To_Position_After_The_End_Of_Text_With_Arrow_Key()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
target.CaretIndex = 3;
RaiseKeyEvent(target, Key.Right, 0);
Assert.Equal(4, target.CaretIndex);
}
}
[Fact]
public void Press_Ctrl_A_Select_All_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
Assert.Equal(0, target.SelectionStart);
Assert.Equal(4, target.SelectionEnd);
}
}
[Fact]
public void Press_Ctrl_A_Select_All_Null_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate()
};
RaiseKeyEvent(target, Key.A, KeyModifiers.Control);
Assert.Equal(0, target.SelectionStart);
Assert.Equal(0, target.SelectionEnd);
}
}
[Fact]
public void Press_Ctrl_Z_Will_Not_Modify_Text()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
RaiseKeyEvent(target, Key.Z, KeyModifiers.Control);
Assert.Equal("1234", target.Text);
}
}
[Fact]
public void Typing_Beginning_With_0_Should_Not_Modify_Text_When_Bound_To_Int()
{
using (UnitTestApplication.Start(Services))
{
var source = new Class1();
var target = new TextBox
{
DataContext = source,
Template = CreateTemplate(),
};
target.ApplyTemplate();
target.Bind(TextBox.TextProperty, new Binding(nameof(Class1.Foo), BindingMode.TwoWay));
Assert.Equal("0", target.Text);
target.CaretIndex = 1;
target.RaiseEvent(new TextInputEventArgs
{
RoutedEvent = InputElement.TextInputEvent,
Text = "2",
});
Assert.Equal("02", target.Text);
}
}
[Fact]
public void Control_Backspace_Should_Remove_The_Word_Before_The_Caret_If_There_Is_No_Selection()
{
using (UnitTestApplication.Start(Services))
{
TextBox textBox = new TextBox
{
Text = "First Second Third Fourth",
CaretIndex = 5
};
// (First| Second Third Fourth)
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" Second Third Fourth", textBox.Text);
// ( Second |Third Fourth)
textBox.CaretIndex = 8;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" Third Fourth", textBox.Text);
// ( Thi|rd Fourth)
textBox.CaretIndex = 4;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" rd Fourth", textBox.Text);
// ( rd F[ou]rth)
textBox.SelectionStart = 5;
textBox.SelectionEnd = 7;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal(" rd Frth", textBox.Text);
// ( |rd Frth)
textBox.CaretIndex = 1;
RaiseKeyEvent(textBox, Key.Back, KeyModifiers.Control);
Assert.Equal("rd Frth", textBox.Text);
}
}
[Fact]
public void Control_Delete_Should_Remove_The_Word_After_The_Caret_If_There_Is_No_Selection()
{
using (UnitTestApplication.Start(Services))
{
TextBox textBox = new TextBox
{
Text = "First Second Third Fourth",
CaretIndex = 19
};
// (First Second Third |Fourth)
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Second Third ", textBox.Text);
// (First Second |Third )
textBox.CaretIndex = 13;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Second ", textBox.Text);
// (First Sec|ond )
textBox.CaretIndex = 9;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("First Sec", textBox.Text);
// (Fi[rs]t Sec )
textBox.SelectionStart = 2;
textBox.SelectionEnd = 4;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("Fit Sec", textBox.Text);
// (Fit Sec| )
textBox.Text += " ";
textBox.CaretIndex = 7;
RaiseKeyEvent(textBox, Key.Delete, KeyModifiers.Control);
Assert.Equal("Fit Sec", textBox.Text);
}
}
[Fact]
public void Setting_SelectionStart_To_SelectionEnd_Sets_CaretPosition_To_SelectionStart()
{
using (UnitTestApplication.Start(Services))
{
var textBox = new TextBox
{
Text = "0123456789"
};
textBox.SelectionStart = 2;
textBox.SelectionEnd = 2;
Assert.Equal(2, textBox.CaretIndex);
}
}
[Fact]
public void Setting_Text_Updates_CaretPosition()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Text = "Initial Text",
CaretIndex = 11
};
var invoked = false;
target.GetObservable(TextBox.TextProperty).Skip(1).Subscribe(_ =>
{
// Caret index should be set before Text changed notification, as we don't want
// to notify with an invalid CaretIndex.
Assert.Equal(7, target.CaretIndex);
invoked = true;
});
target.Text = "Changed";
Assert.True(invoked);
}
}
[Fact]
public void Press_Enter_Does_Not_Accept_Return()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = false,
Text = "1234"
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal("1234", target.Text);
}
}
[Fact]
public void Press_Enter_Add_Default_Newline()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = true
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal(Environment.NewLine, target.Text);
}
}
[Fact]
public void Press_Enter_Add_Custom_Newline()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
AcceptsReturn = true,
NewLine = "Test"
};
RaiseKeyEvent(target, Key.Enter, 0);
Assert.Equal("Test", target.Text);
}
}
[Theory]
[InlineData(new object[] { false, TextWrapping.NoWrap, ScrollBarVisibility.Hidden })]
[InlineData(new object[] { false, TextWrapping.Wrap, ScrollBarVisibility.Hidden })]
[InlineData(new object[] { true, TextWrapping.NoWrap, ScrollBarVisibility.Auto })]
[InlineData(new object[] { true, TextWrapping.Wrap, ScrollBarVisibility.Disabled })]
public void Has_Correct_Horizontal_ScrollBar_Visibility(
bool acceptsReturn,
TextWrapping wrapping,
ScrollBarVisibility expected)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
AcceptsReturn = acceptsReturn,
TextWrapping = wrapping,
};
Assert.Equal(expected, ScrollViewer.GetHorizontalScrollBarVisibility(target));
}
}
[Fact]
public void SelectionEnd_Doesnt_Cause_Exception()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 0;
target.SelectionEnd = 9;
target.Text = "123";
RaiseTextEvent(target, "456");
Assert.True(true);
}
}
[Fact]
public void SelectionStart_Doesnt_Cause_Exception()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 8;
target.SelectionEnd = 9;
target.Text = "123";
RaiseTextEvent(target, "456");
Assert.True(true);
}
}
[Fact]
public void SelectionStartEnd_Are_Valid_AterTextChange()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
target.SelectionStart = 8;
target.SelectionEnd = 9;
target.Text = "123";
Assert.True(target.SelectionStart <= "123".Length);
Assert.True(target.SelectionEnd <= "123".Length);
}
}
[Fact]
public void SelectedText_Changes_OnSelectionChange()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789"
};
Assert.True(target.SelectedText == "");
target.SelectionStart = 2;
target.SelectionEnd = 4;
Assert.True(target.SelectedText == "23");
}
}
[Fact]
public void SelectedText_EditsText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectedText = "AA";
Assert.True(target.Text == "AA0123");
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = "BB";
Assert.True(target.Text == "ABB123");
}
}
[Fact]
public void SelectedText_CanClearText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = "";
Assert.True(target.Text == "03");
}
}
[Fact]
public void SelectedText_NullClearsText()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123"
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
target.SelectedText = null;
Assert.True(target.Text == "03");
}
}
[Fact]
public void CoerceCaretIndex_Doesnt_Cause_Exception_with_malformed_line_ending()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123456789\r"
};
target.CaretIndex = 11;
Assert.True(true);
}
}
[Fact]
public void TextBox_GotFocus_And_LostFocus_Work_Properly()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
var gfcount = 0;
var lfcount = 0;
target1.GotFocus += (s, e) => gfcount++;
target2.LostFocus += (s, e) => lfcount++;
target2.Focus();
Assert.False(target1.IsFocused);
Assert.True(target2.IsFocused);
target1.Focus();
Assert.False(target2.IsFocused);
Assert.True(target1.IsFocused);
Assert.Equal(1, gfcount);
Assert.Equal(1, lfcount);
}
}
[Fact]
public void TextBox_CaretIndex_Persists_When_Focus_Lost()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234"
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
target2.Focus();
target2.CaretIndex = 2;
Assert.False(target1.IsFocused);
Assert.True(target2.IsFocused);
target1.Focus();
Assert.Equal(2, target2.CaretIndex);
}
}
[Fact]
public void TextBox_Reveal_Password_Reset_When_Lost_Focus()
{
using (UnitTestApplication.Start(FocusServices))
{
var target1 = new TextBox
{
Template = CreateTemplate(),
Text = "1234",
PasswordChar = '*'
};
var target2 = new TextBox
{
Template = CreateTemplate(),
Text = "5678"
};
var sp = new StackPanel();
sp.Children.Add(target1);
sp.Children.Add(target2);
target1.ApplyTemplate();
target2.ApplyTemplate();
var root = new TestRoot { Child = sp };
target1.Focus();
target1.RevealPassword = true;
target2.Focus();
Assert.False(target1.RevealPassword);
}
}
[Fact]
public void Setting_Bound_Text_To_Null_Works()
{
using (UnitTestApplication.Start(Services))
{
var source = new Class1 { Bar = "bar" };
var target = new TextBox { DataContext = source };
target.Bind(TextBox.TextProperty, new Binding("Bar"));
Assert.Equal("bar", target.Text);
source.Bar = null;
Assert.Null(target.Text);
}
}
[Fact]
public void Text_Box_MaxLength_Work_Properly()
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "abc",
MaxLength = 3,
};
RaiseKeyEvent(target, Key.D, KeyModifiers.None);
Assert.Equal("abc", target.Text);
}
}
[Theory]
[InlineData(Key.X, KeyModifiers.Control)]
[InlineData(Key.Back, KeyModifiers.None)]
[InlineData(Key.Delete, KeyModifiers.None)]
[InlineData(Key.Tab, KeyModifiers.None)]
[InlineData(Key.Enter, KeyModifiers.None)]
public void Keys_Allow_Undo(Key key, KeyModifiers modifiers)
{
using (UnitTestApplication.Start(Services))
{
var target = new TextBox
{
Template = CreateTemplate(),
Text = "0123",
AcceptsReturn = true,
AcceptsTab = true
};
target.SelectionStart = 1;
target.SelectionEnd = 3;
AvaloniaLocator.CurrentMutable
.Bind<Input.Platform.IClipboard>().ToSingleton<ClipboardStub>();
RaiseKeyEvent(target, key, modifiers);
RaiseKeyEvent(target, Key.Z, KeyModifiers.Control); // undo
Assert.True(target.Text == "0123");
}
}
private static TestServices FocusServices => TestServices.MockThreadingInterface.With(
focusManager: new FocusManager(),
keyboardDevice: () => new KeyboardDevice(),
keyboardNavigation: new KeyboardNavigationHandler(),
inputManager: new InputManager(),
standardCursorFactory: Mock.Of<IStandardCursorFactory>());
private static TestServices Services => TestServices.MockThreadingInterface.With(
standardCursorFactory: Mock.Of<IStandardCursorFactory>());
private IControlTemplate CreateTemplate()
{
return new FuncControlTemplate<TextBox>((control, scope) =>
new TextPresenter
{
Name = "PART_TextPresenter",
[!!TextPresenter.TextProperty] = new Binding
{
Path = "Text",
Mode = BindingMode.TwoWay,
Priority = BindingPriority.TemplatedParent,
RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent),
},
}.RegisterInNameScope(scope));
}
private void RaiseKeyEvent(TextBox textBox, Key key, KeyModifiers inputModifiers)
{
textBox.RaiseEvent(new KeyEventArgs
{
RoutedEvent = InputElement.KeyDownEvent,
KeyModifiers = inputModifiers,
Key = key
});
}
private void RaiseTextEvent(TextBox textBox, string text)
{
textBox.RaiseEvent(new TextInputEventArgs
{
RoutedEvent = InputElement.TextInputEvent,
Text = text
});
}
private class Class1 : NotifyingBase
{
private int _foo;
private string _bar;
public int Foo
{
get { return _foo; }
set { _foo = value; RaisePropertyChanged(); }
}
public string Bar
{
get { return _bar; }
set { _bar = value; RaisePropertyChanged(); }
}
}
private class ClipboardStub : IClipboard // in order to get tests working that use the clipboard
{
public Task<string> GetTextAsync() => Task.FromResult("");
public Task SetTextAsync(string text) => Task.CompletedTask;
public Task ClearAsync() => Task.CompletedTask;
public Task SetDataObjectAsync(IDataObject data) => Task.CompletedTask;
public Task<string[]> GetFormatsAsync() => Task.FromResult(Array.Empty<string>());
public Task<object> GetDataAsync(string format) => Task.FromResult((object)null);
}
private class TestContextMenu : ContextMenu
{
public TestContextMenu()
{
IsOpen = true;
}
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !MONO && !NETSTANDARD
namespace NLog.UnitTests.Targets.Wrappers
{
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Xunit;
public class ImpersonatingTargetWrapperTests : NLogTestBase, IDisposable
{
private const string NLogTestUser = "NLogTestUser";
private const string NLogTestUserPassword = "BC@57acasd123";
private string Localhost = Environment.MachineName;
public ImpersonatingTargetWrapperTests()
{
CreateUserIfNotPresent();
}
[Fact]
public void ImpersonatingWrapperTest()
{
var wrapped = new MyTarget()
{
ExpectedUser = Environment.MachineName + "\\" + NLogTestUser,
};
var wrapper = new ImpersonatingTargetWrapper()
{
UserName = NLogTestUser,
Password = NLogTestUserPassword,
Domain = Environment.MachineName,
WrappedTarget = wrapped,
};
// wrapped.Initialize(null);
wrapper.Initialize(null);
var exceptions = new List<Exception>();
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Single(exceptions);
wrapper.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(4, exceptions.Count);
wrapper.Flush(exceptions.Add);
Assert.Equal(5, exceptions.Count);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
wrapper.Close();
}
[Fact]
public void RevertToSelfTest()
{
var wrapped = new MyTarget()
{
ExpectedUser = Environment.UserDomainName + "\\" + Environment.UserName,
};
WindowsIdentity originalIdentity = WindowsIdentity.GetCurrent();
try
{
var id = CreateWindowsIdentity(NLogTestUser, Environment.MachineName, NLogTestUserPassword, SecurityLogOnType.Interactive, LogOnProviderType.Default, SecurityImpersonationLevel.Identification);
id.Impersonate();
WindowsIdentity changedIdentity = WindowsIdentity.GetCurrent();
Assert.Contains(NLogTestUser.ToLowerInvariant(), changedIdentity.Name.ToLowerInvariant(), StringComparison.InvariantCulture);
var wrapper = new ImpersonatingTargetWrapper()
{
WrappedTarget = wrapped,
RevertToSelf = true,
};
// wrapped.Initialize(null);
wrapper.Initialize(null);
var exceptions = new List<Exception>();
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Single(exceptions);
wrapper.WriteAsyncLogEvents(
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
Assert.Equal(4, exceptions.Count);
wrapper.Flush(exceptions.Add);
Assert.Equal(5, exceptions.Count);
foreach (var ex in exceptions)
{
Assert.Null(ex);
}
wrapper.Close();
}
finally
{
// revert to self
NativeMethods.RevertToSelf();
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
Assert.Equal(originalIdentity.Name.ToLowerInvariant(), currentIdentity.Name.ToLowerInvariant());
}
}
[Fact]
public void ImpersonatingWrapperNegativeTest()
{
var wrapped = new MyTarget()
{
ExpectedUser = NLogTestUser,
};
LogManager.ThrowExceptions = true;
var wrapper = new ImpersonatingTargetWrapper()
{
UserName = NLogTestUser,
Password = Guid.NewGuid().ToString("N"), // wrong password
Domain = Environment.MachineName,
WrappedTarget = wrapped,
};
Assert.Throws<COMException>(() =>
{
wrapper.Initialize(null);
});
wrapper.Close(); // will not fail because Initialize() failed
}
[Fact]
public void ImpersonatingWrapperNegativeTest2()
{
var wrapped = new MyTarget()
{
ExpectedUser = NLogTestUser,
};
LogManager.ThrowExceptions = true;
var wrapper = new ImpersonatingTargetWrapper()
{
UserName = NLogTestUser,
Password = NLogTestUserPassword,
Domain = Environment.MachineName,
ImpersonationLevel = (SecurityImpersonationLevel)1234,
WrappedTarget = wrapped,
};
Assert.Throws<COMException>(() =>
{
wrapper.Initialize(null);
});
wrapper.Close(); // will not fail because Initialize() failed
}
private WindowsIdentity CreateWindowsIdentity(string username, string domain, string password, SecurityLogOnType logonType, LogOnProviderType logonProviderType, SecurityImpersonationLevel impersonationLevel)
{
// initialize tokens
var existingTokenHandle = IntPtr.Zero;
var duplicateTokenHandle = IntPtr.Zero;
if (!NativeMethods.LogonUser(
username,
domain,
password,
(int)logonType,
(int)logonProviderType,
out existingTokenHandle))
{
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
if (!NativeMethods.DuplicateToken(existingTokenHandle, (int)impersonationLevel, out duplicateTokenHandle))
{
NativeMethods.CloseHandle(existingTokenHandle);
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
// create new identity using new primary token
return new WindowsIdentity(duplicateTokenHandle);
}
private static class NativeMethods
{
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
// closes open handles returned by LogonUser
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(IntPtr handle);
// creates duplicate token handle
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DuplicateToken(IntPtr existingTokenHandle, int impersonationLevel, out IntPtr duplicateTokenHandle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RevertToSelf();
}
public class MyTarget : Target
{
public MyTarget()
{
Events = new List<LogEventInfo>();
}
public MyTarget(string name) : this()
{
Name = name;
}
public List<LogEventInfo> Events { get; set; }
public string ExpectedUser { get; set; }
protected override void InitializeTarget()
{
base.InitializeTarget();
AssertExpectedUser();
}
protected override void CloseTarget()
{
base.CloseTarget();
AssertExpectedUser();
}
protected override void Write(LogEventInfo logEvent)
{
AssertExpectedUser();
Events.Add(logEvent);
}
protected override void Write(IList<AsyncLogEventInfo> logEvents)
{
AssertExpectedUser();
base.Write(logEvents);
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
AssertExpectedUser();
base.FlushAsync(asyncContinuation);
}
private void AssertExpectedUser()
{
if (ExpectedUser != null)
{
var windowsIdentity = WindowsIdentity.GetCurrent();
Assert.True(windowsIdentity.IsAuthenticated);
Assert.Equal(Environment.MachineName + "\\" + ExpectedUser, windowsIdentity.Name);
}
}
}
private void CreateUserIfNotPresent()
{
using (var context = new PrincipalContext(ContextType.Machine, Localhost))
{
if (UserPrincipal.FindByIdentity(context, IdentityType.Name, NLogTestUser) != null)
return;
var user = new UserPrincipal(context);
user.SetPassword(NLogTestUserPassword);
user.Name = NLogTestUser;
user.Save();
var group = GroupPrincipal.FindByIdentity(context, "Users");
group.Members.Add(user);
group.Save();
}
}
public void Dispose()
{
DeleteUser();
}
private void DeleteUser()
{
using (var context = new PrincipalContext(ContextType.Machine, Localhost))
using (var up = UserPrincipal.FindByIdentity(context, IdentityType.Name, NLogTestUser))
{
if (up != null)
up.Delete();
}
}
}
}
#endif
| |
/* ========================================================================
* PROJECT: UART
* ========================================================================
* Portions of this work are built on top of VRPN which was developed by
* Russell Taylor
* University of North Carolina
* http://www.cs.unc.edu/Research/vrpn/
*
* We acknowledge the CISMM project at the University of North Carolina at Chapel Hill, supported by NIH/NCRR
* and NIH/NIBIB award #2P41EB002025, for their ongoing * support and maintenance of VRPN.
*
* Portions of this work are also built on top of the VideoWrapper,
* a BSD licensed video access library for MacOSX and Windows.
* VideoWrapper is available at SourceForge via
* http://sourceforge.net/projects/videowrapper/
*
* Copyright of VideoWrapper is
* (C) 2003-2010 Georgia Tech Research Corportation
*
* Copyright of the new and derived portions of this work
* (C) 2010 Georgia Tech Research Corporation
*
* This software released under the Boost Software License 1.0 (BSL1.0), so as to be
* compatible with the VRPN software distribution:
*
* Permission is hereby granted, free of charge, to any person or organization obtaining a copy
* of the software and accompanying documentation covered by this license (the "Software") to use,
* reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative
* works of the Software, and to permit third-parties to whom the Software is furnished to do so,
* all subject to the following:
*
* The copyright notices in the Software and this entire statement, including the above license grant,
* this restriction and the following disclaimer, must be included in all copies of the Software, in
* whole or in part, and all derivative works of the Software, unless such copies or derivative works
* are solely in the form of machine-executable object code generated by a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT.
* IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR
* OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* For further information regarding UART, please contact
* Blair MacIntyre
* <blair@cc.gatech.edu>
* Georgia Tech, School of Interactive Computing
* 85 5th Street NW
* Atlanta, GA 30308
*
* For further information regarding VRPN, please contact
* Russell M. Taylor II
* <taylor@cs.unc.edu>
* University of North Carolina,
* CB #3175, Sitterson Hall,
* Chapel Hill, NC 27599-3175
*
* ========================================================================
** @author Alex Hill (ahill@gatech.edu)
*
* ========================================================================
*
* VRPNTrackerCalibrate.cs
*
* usage: Add this script to any VRPNTracker to calibrate its transform
*
* inputs:
*
* Notes:
*
* ========================================================================*/
using UnityEngine;
using System;
public class VRPNTrackerCalibrate : MonoBehaviour {
private enum Action_Type { None, FieldOfView, Rotate, XYAxis, XZAxis };
private Action_Type state;
private string label_text1 =
"\tSelect\tSave\t\tReset\tGain+\tGain-\n" +
"\t8\t\t\t9\t\t\t0\t\t\t-\t\t\t+\n" +
"\tI\t\t\tO\t\t\tP\t\t\t[\t\t\t";
private int index;
private int last_global_index = 0;
public static int global_index = 0;
public static int global_count = 0;
private Vector3 sensorPosition;
private Quaternion sensorRotation;
private Vector3 trackerPosition;
private Quaternion trackerRotation;
public static float fieldOfView;
private Transform plane;
private int gain = 1;
private VRPNTracker tracker;
private string[] state_string;
private bool savedDebug;
private VRPNTracker.Transform_Type savedApply;
void Start () {
index = global_count;
global_count++;
global_index = global_count;
state_string = new string[4];
state_string[0] = "fov";
state_string[1] = "rotate";
state_string[2] = "xy";
state_string[3] = "xz";
tracker = (VRPNTracker)GetComponent(typeof(VRPNTracker));
sensorPosition = tracker.SensorOffset.localPosition;
sensorRotation = tracker.SensorOffset.localRotation;
if (Camera.main == null)
Debug.Log("No camera found");
else
{
fieldOfView = Camera.main.fieldOfView;
Component planeRender = GetComponentInChildren(typeof(Renderer));
if (planeRender != null)
plane = planeRender.gameObject.transform;
}
if (tracker == null)
Debug.Log("No tracker found");
else
{
savedApply = tracker.ApplyTracking;
savedDebug = tracker.ShowDebug;
}
}
void Update () {
//avoid capturing key events twice
if (global_index != last_global_index)
{
last_global_index = global_index;
return;
}
if (index == global_index || (index == global_count-1 && global_index == global_count))
{
//Select Tracker
if (Input.GetKeyDown(KeyCode.Alpha8))
{
global_index++;
if (global_index > global_count)
global_index = 0;
tracker.ApplyTracking = savedApply;
tracker.ShowDebug = savedDebug;
}
}
if (index == global_index && tracker != null)
{
Action_Type priorState = state;
//Save to prefab
if (Input.GetKeyDown(KeyCode.Alpha9))
{
sensorPosition = tracker.SensorOffset.localPosition;
sensorRotation = tracker.SensorOffset.localRotation;
if (Camera.main != null)
fieldOfView = Camera.main.fieldOfView;
}
else if (Input.GetKeyDown(KeyCode.Alpha0))
{
tracker.SensorOffset.localPosition = sensorPosition;
tracker.SensorOffset.localRotation = sensorRotation;
if (Camera.main != null)
Camera.main.fieldOfView = fieldOfView;
}
else if (Input.GetKeyDown(KeyCode.Minus))
{
gain -= 1;
if (gain <= 0)
gain = 1;
}
else if (Input.GetKeyDown(KeyCode.Equals))
{
gain += 1;
}
else if (Input.GetKeyDown(KeyCode.I))
{
if (state == Action_Type.FieldOfView)
state = Action_Type.None;
else
state = Action_Type.FieldOfView;
}
else if (Input.GetKeyDown(KeyCode.O))
{
if (state == Action_Type.Rotate)
state = Action_Type.None;
else
state = Action_Type.Rotate;
}
else if (Input.GetKeyDown(KeyCode.P))
{
if (state == Action_Type.XYAxis)
state = Action_Type.None;
else
state = Action_Type.XYAxis;
}
else if (Input.GetKeyDown(KeyCode.LeftBracket))
{
if (state == Action_Type.XZAxis)
state = Action_Type.None;
else
state = Action_Type.XZAxis;
}
if (priorState == Action_Type.None && (int)state > 0)
{
savedApply = tracker.ApplyTracking;
savedDebug = tracker.ShowDebug;
if (tracker.TrackerType == VRPNManager.Tracker_Types.vrpn_Tracker_MotionNode)
tracker.ApplyTracking = VRPNTracker.Transform_Type.None;
trackerPosition = tracker.GetPosition();
trackerRotation = tracker.GetRotation();
tracker.ShowDebug = true;
}
else if (state != priorState)
{
tracker.ApplyTracking = savedApply;
tracker.ShowDebug = savedDebug;
}
if (state == Action_Type.FieldOfView)
{
float fov = Camera.main.fieldOfView;
fov += gain*0.01f*Input.GetAxis("Mouse X");
if (Camera.main != null)
{
Camera.main.fieldOfView = fov;
if (plane != null)
{
Vector3 pos = plane.localPosition;
pos.z = (float)(5.0*plane.localScale.z/Math.Tan(Math.PI*(double)fov/360.0f));
plane.localPosition = pos;
}
}
}
else if (state == Action_Type.Rotate)
{
if (tracker.TrackerType == VRPNManager.Tracker_Types.vrpn_Tracker_MotionNode)
{
tracker.SensorOffset.localRotation = Quaternion.Inverse(trackerRotation)*tracker.GetRotation();
tracker.SensorOffset.localRotation *= sensorRotation;
}
else
{
Vector3 right = tracker.SensorOffset.localRotation * Vector3.right;
Vector3 up = tracker.SensorOffset.localRotation * Vector3.up;
Quaternion mouseXRotation = Quaternion.AngleAxis(-gain*0.01f*Input.GetAxis("Mouse X"),up);
Quaternion mouseYRotation = Quaternion.AngleAxis(-gain*0.01f*Input.GetAxis("Mouse Y"),right);
tracker.SensorOffset.localRotation *= mouseXRotation * mouseYRotation;
}
}
else if (state == Action_Type.XYAxis)
{
if (tracker.TrackerType == VRPNManager.Tracker_Types.vrpn_Tracker_MotionNode)
{
Vector3 pos = tracker.SensorOffset.localPosition;
pos.x += gain*0.01f*Input.GetAxis("Mouse X");
pos.y += gain*0.01f*Input.GetAxis("Mouse Y");
tracker.SensorOffset.localPosition = pos;
}
else
tracker.SensorOffset.localPosition = tracker.GetPosition() - trackerPosition;
}
else if (state == Action_Type.XZAxis)
{
if (tracker.TrackerType == VRPNManager.Tracker_Types.vrpn_Tracker_MotionNode)
{
Vector3 pos = tracker.SensorOffset.localPosition;
pos.x += gain*0.01f*Input.GetAxis("Mouse X");
pos.z += gain*0.01f*Input.GetAxis("Mouse Y");
tracker.SensorOffset.localPosition = pos;
}
else
tracker.SensorOffset.localPosition = tracker.GetPosition() - trackerPosition;
}
}
}
void OnGUI () {
if (index == global_index) {
for (int i=0; i<4; i++)
{
if ((int)state == i+1)
state_string[i] = state_string[i].ToUpper();
else
state_string[i] = state_string[i].ToLower();
}
GUI.skin.box.alignment = TextAnchor.LowerLeft;
string debug_text = "Tracker: " + gameObject.name + " SensorOffset: " +
tracker.SensorOffset.gameObject.name + "\n" + label_text1 +
gain.ToString() + "\n" +
"\t" + state_string[0] + "\t\t" + state_string[1] +
"\t" + state_string[2] + "\t\t" + state_string[3] + "\n";
GUI.Box(new Rect(Screen.width/2-150, Screen.height-100, 350, 90), debug_text);
if (state == Action_Type.FieldOfView)
{
int debug_xoffset = VRPNTracker.num_trackers*210;
if (VRPNManager.debug_flag)
debug_xoffset += 405;
string debug_text2;
if (Camera.main != null)
{
debug_text2 = Camera.main.name +
System.String.Format("\nFOV[{0:F2}]\n", Camera.main.fieldOfView);
if (plane != null)
debug_text2 += System.String.Format("PLANE[{0:F2}]", plane.localPosition.z);
}
else
debug_text2 = Camera.main.name + "\nNo Camera Found\n";
GUI.skin.box.alignment = TextAnchor.LowerLeft;
GUI.Box(new Rect(debug_xoffset + 10, 10, 200, 45), debug_text2);
}
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 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.Diagnostics;
using FarseerPhysics.Common;
using FarseerPhysics.Common.ConvexHull;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// Represents a simple non-selfintersecting convex polygon.
/// Create a convex hull from the given array of points.
/// </summary>
public class PolygonShape : Shape
{
/// <summary>
/// Create a convex hull from the given array of local points.
/// The number of vertices must be in the range [3, Settings.MaxPolygonVertices].
/// Warning: the points may be re-ordered, even if they form a convex polygon
/// Warning: collinear points are handled but not removed. Collinear points may lead to poor stacking behavior.
/// </summary>
public Vertices vertices
{
get { return _vertices; }
set { setVerticesNoCopy( new Vertices( value ) ); }
}
public Vertices normals { get { return _normals; } }
public override int childCount { get { return 1; } }
Vertices _vertices;
Vertices _normals;
/// <summary>
/// Initializes a new instance of the <see cref="PolygonShape"/> class.
/// </summary>
/// <param name="vertices">The vertices.</param>
/// <param name="density">The density.</param>
public PolygonShape( Vertices vertices, float density ) : base( density )
{
shapeType = ShapeType.Polygon;
_radius = Settings.polygonRadius;
this.vertices = vertices;
}
/// <summary>
/// Create a new PolygonShape with the specified density.
/// </summary>
/// <param name="density">The density.</param>
public PolygonShape( float density ) : base( density )
{
Debug.Assert( density >= 0f );
shapeType = ShapeType.Polygon;
_radius = Settings.polygonRadius;
_vertices = new Vertices( Settings.maxPolygonVertices );
_normals = new Vertices( Settings.maxPolygonVertices );
}
internal PolygonShape() : base( 0 )
{
shapeType = ShapeType.Polygon;
_radius = Settings.polygonRadius;
_vertices = new Vertices( Settings.maxPolygonVertices );
_normals = new Vertices( Settings.maxPolygonVertices );
}
/// <summary>
/// sets the vertices without copying over the data from verts to the local List.
/// </summary>
/// <param name="verts">Verts.</param>
public void setVerticesNoCopy( Vertices verts )
{
Debug.Assert( verts.Count >= 3 && verts.Count <= Settings.maxPolygonVertices );
_vertices = verts;
if( Settings.useConvexHullPolygons )
{
// FPE note: This check is required as the GiftWrap algorithm early exits on triangles
// So instead of giftwrapping a triangle, we just force it to be clock wise.
if( _vertices.Count <= 3 )
_vertices.forceCounterClockWise();
else
_vertices = GiftWrap.getConvexHull( _vertices );
}
if( _normals == null )
_normals = new Vertices( _vertices.Count );
else
_normals.Clear();
// Compute normals. Ensure the edges have non-zero length.
for( var i = 0; i < _vertices.Count; ++i )
{
var next = i + 1 < _vertices.Count ? i + 1 : 0;
var edge = _vertices[next] - _vertices[i];
Debug.Assert( edge.LengthSquared() > Settings.epsilon * Settings.epsilon );
// FPE optimization: Normals.Add(MathHelper.Cross(edge, 1.0f));
var temp = new Vector2( edge.Y, -edge.X );
Nez.Vector2Ext.normalize( ref temp );
_normals.Add( temp );
}
// Compute the polygon mass data
computeProperties();
}
protected override void computeProperties()
{
// Polygon mass, centroid, and inertia.
// Let rho be the polygon density in mass per unit area.
// Then:
// mass = rho * int(dA)
// centroid.X = (1/mass) * rho * int(x * dA)
// centroid.Y = (1/mass) * rho * int(y * dA)
// I = rho * int((x*x + y*y) * dA)
//
// We can compute these integrals by summing all the integrals
// for each triangle of the polygon. To evaluate the integral
// for a single triangle, we make a change of variables to
// the (u,v) coordinates of the triangle:
// x = x0 + e1x * u + e2x * v
// y = y0 + e1y * u + e2y * v
// where 0 <= u && 0 <= v && u + v <= 1.
//
// We integrate u from [0,1-v] and then v from [0,1].
// We also need to use the Jacobian of the transformation:
// D = cross(e1, e2)
//
// Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
//
// The rest of the derivation is handled by computer algebra.
Debug.Assert( vertices.Count >= 3 );
//FPE optimization: Early exit as polygons with 0 density does not have any properties.
if( _density <= 0 )
return;
//FPE optimization: Consolidated the calculate centroid and mass code to a single method.
var center = Vector2.Zero;
var area = 0.0f;
var I = 0.0f;
// pRef is the reference point for forming triangles.
// It's location doesn't change the result (except for rounding error).
var s = Vector2.Zero;
// This code would put the reference point inside the polygon.
for( int i = 0; i < vertices.Count; ++i )
s += vertices[i];
s *= 1.0f / vertices.Count;
const float k_inv3 = 1.0f / 3.0f;
for( int i = 0; i < vertices.Count; ++i )
{
// Triangle vertices.
Vector2 e1 = vertices[i] - s;
Vector2 e2 = i + 1 < vertices.Count ? vertices[i + 1] - s : vertices[0] - s;
var D = MathUtils.cross( e1, e2 );
var triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * ( e1 + e2 );
float ex1 = e1.X, ey1 = e1.Y;
float ex2 = e2.X, ey2 = e2.Y;
var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
I += ( 0.25f * k_inv3 * D ) * ( intx2 + inty2 );
}
//The area is too small for the engine to handle.
Debug.Assert( area > Settings.epsilon );
// We save the area
massData.area = area;
// Total mass
massData.mass = _density * area;
// Center of mass
center *= 1.0f / area;
massData.centroid = center + s;
// Inertia tensor relative to the local origin (point s).
massData.inertia = _density * I;
// Shift to center of mass then to original body origin.
massData.inertia += massData.mass * ( Vector2.Dot( massData.centroid, massData.centroid ) - Vector2.Dot( center, center ) );
}
public override bool testPoint( ref Transform transform, ref Vector2 point )
{
Vector2 pLocal = MathUtils.mulT( transform.q, point - transform.p );
for( int i = 0; i < vertices.Count; ++i )
{
float dot = Vector2.Dot( normals[i], pLocal - vertices[i] );
if( dot > 0.0f )
{
return false;
}
}
return true;
}
public override bool rayCast( out RayCastOutput output, ref RayCastInput input, ref Transform transform, int childIndex )
{
output = new RayCastOutput();
// Put the ray into the polygon's frame of reference.
Vector2 p1 = MathUtils.mulT( transform.q, input.point1 - transform.p );
Vector2 p2 = MathUtils.mulT( transform.q, input.point2 - transform.p );
Vector2 d = p2 - p1;
float lower = 0.0f, upper = input.maxFraction;
int index = -1;
for( int i = 0; i < vertices.Count; ++i )
{
// p = p1 + a * d
// dot(normal, p - v) = 0
// dot(normal, p1 - v) + a * dot(normal, d) = 0
float numerator = Vector2.Dot( normals[i], vertices[i] - p1 );
float denominator = Vector2.Dot( normals[i], d );
if( denominator == 0.0f )
{
if( numerator < 0.0f )
{
return false;
}
}
else
{
// Note: we want this predicate without division:
// lower < numerator / denominator, where denominator < 0
// Since denominator < 0, we have to flip the inequality:
// lower < numerator / denominator <==> denominator * lower > numerator.
if( denominator < 0.0f && numerator < lower * denominator )
{
// Increase lower.
// The segment enters this half-space.
lower = numerator / denominator;
index = i;
}
else if( denominator > 0.0f && numerator < upper * denominator )
{
// Decrease upper.
// The segment exits this half-space.
upper = numerator / denominator;
}
}
// The use of epsilon here causes the assert on lower to trip
// in some cases. Apparently the use of epsilon was to make edge
// shapes work, but now those are handled separately.
//if (upper < lower - b2_epsilon)
if( upper < lower )
{
return false;
}
}
Debug.Assert( 0.0f <= lower && lower <= input.maxFraction );
if( index >= 0 )
{
output.fraction = lower;
output.normal = MathUtils.mul( transform.q, normals[index] );
return true;
}
return false;
}
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public override void computeAABB( out AABB aabb, ref Transform transform, int childIndex )
{
var lower = MathUtils.mul( ref transform, vertices[0] );
var upper = lower;
for( int i = 1; i < vertices.Count; ++i )
{
var v = MathUtils.mul( ref transform, vertices[i] );
lower = Vector2.Min( lower, v );
upper = Vector2.Max( upper, v );
}
var r = new Vector2( radius, radius );
aabb.lowerBound = lower - r;
aabb.upperBound = upper + r;
}
public override float computeSubmergedArea( ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc )
{
sc = Vector2.Zero;
//Transform plane into shape co-ordinates
var normalL = MathUtils.mulT( xf.q, normal );
float offsetL = offset - Vector2.Dot( normal, xf.p );
float[] depths = new float[Settings.maxPolygonVertices];
int diveCount = 0;
int intoIndex = -1;
int outoIndex = -1;
bool lastSubmerged = false;
int i;
for( i = 0; i < vertices.Count; i++ )
{
depths[i] = Vector2.Dot( normalL, vertices[i] ) - offsetL;
bool isSubmerged = depths[i] < -Settings.epsilon;
if( i > 0 )
{
if( isSubmerged )
{
if( !lastSubmerged )
{
intoIndex = i - 1;
diveCount++;
}
}
else
{
if( lastSubmerged )
{
outoIndex = i - 1;
diveCount++;
}
}
}
lastSubmerged = isSubmerged;
}
switch( diveCount )
{
case 0:
if( lastSubmerged )
{
//Completely submerged
sc = MathUtils.mul( ref xf, massData.centroid );
return massData.mass / density;
}
//Completely dry
return 0;
case 1:
if( intoIndex == -1 )
{
intoIndex = vertices.Count - 1;
}
else
{
outoIndex = vertices.Count - 1;
}
break;
}
int intoIndex2 = ( intoIndex + 1 ) % vertices.Count;
int outoIndex2 = ( outoIndex + 1 ) % vertices.Count;
float intoLambda = ( 0 - depths[intoIndex] ) / ( depths[intoIndex2] - depths[intoIndex] );
float outoLambda = ( 0 - depths[outoIndex] ) / ( depths[outoIndex2] - depths[outoIndex] );
Vector2 intoVec = new Vector2( vertices[intoIndex].X * ( 1 - intoLambda ) + vertices[intoIndex2].X * intoLambda, vertices[intoIndex].Y * ( 1 - intoLambda ) + vertices[intoIndex2].Y * intoLambda );
Vector2 outoVec = new Vector2( vertices[outoIndex].X * ( 1 - outoLambda ) + vertices[outoIndex2].X * outoLambda, vertices[outoIndex].Y * ( 1 - outoLambda ) + vertices[outoIndex2].Y * outoLambda );
//Initialize accumulator
float area = 0;
Vector2 center = new Vector2( 0, 0 );
Vector2 p2 = vertices[intoIndex2];
const float k_inv3 = 1.0f / 3.0f;
//An awkward loop from intoIndex2+1 to outIndex2
i = intoIndex2;
while( i != outoIndex2 )
{
i = ( i + 1 ) % vertices.Count;
Vector2 p3;
if( i == outoIndex2 )
p3 = outoVec;
else
p3 = vertices[i];
//Add the triangle formed by intoVec,p2,p3
{
Vector2 e1 = p2 - intoVec;
Vector2 e2 = p3 - intoVec;
float D = MathUtils.cross( e1, e2 );
float triangleArea = 0.5f * D;
area += triangleArea;
// Area weighted centroid
center += triangleArea * k_inv3 * ( intoVec + p2 + p3 );
}
p2 = p3;
}
//Normalize and transform centroid
center *= 1.0f / area;
sc = MathUtils.mul( ref xf, center );
return area;
}
public bool CompareTo( PolygonShape shape )
{
if( vertices.Count != shape.vertices.Count )
return false;
for( int i = 0; i < vertices.Count; i++ )
{
if( vertices[i] != shape.vertices[i] )
return false;
}
return ( radius == shape.radius && massData == shape.massData );
}
public override Shape clone()
{
var clone = new PolygonShape();
clone.shapeType = shapeType;
clone._radius = _radius;
clone._density = _density;
clone._vertices = new Vertices( _vertices );
clone._normals = new Vertices( _normals );
clone.massData = massData;
return clone;
}
}
}
| |
// 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.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public abstract partial class HttpClientTest : HttpClientTestBase
{
[Fact]
public void Dispose_MultipleTimes_Success()
{
HttpClient client = CreateHttpClient();
client.Dispose();
client.Dispose();
}
[Fact]
public void DefaultRequestHeaders_Idempotent()
{
using (HttpClient client = CreateHttpClient())
{
Assert.NotNull(client.DefaultRequestHeaders);
Assert.Same(client.DefaultRequestHeaders, client.DefaultRequestHeaders);
}
}
[Fact]
public void BaseAddress_Roundtrip_Equal()
{
using (HttpClient client = CreateHttpClient())
{
Assert.Null(client.BaseAddress);
Uri uri = new Uri(CreateFakeUri());
client.BaseAddress = uri;
Assert.Equal(uri, client.BaseAddress);
client.BaseAddress = null;
Assert.Null(client.BaseAddress);
}
}
[Fact]
public void BaseAddress_InvalidUri_Throws()
{
using (HttpClient client = CreateHttpClient())
{
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("ftp://onlyhttpsupported"));
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("/onlyabsolutesupported", UriKind.Relative));
}
}
[Fact]
public void Timeout_Roundtrip_Equal()
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, client.Timeout);
client.Timeout = TimeSpan.FromSeconds(1);
Assert.Equal(TimeSpan.FromSeconds(1), client.Timeout);
}
}
[Fact]
public void Timeout_OutOfRange_Throws()
{
using (HttpClient client = CreateHttpClient())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(-2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(int.MaxValue));
}
}
[Fact]
public void MaxResponseContentBufferSize_Roundtrip_Equal()
{
using (HttpClient client = CreateHttpClient())
{
client.MaxResponseContentBufferSize = 1;
Assert.Equal(1, client.MaxResponseContentBufferSize);
client.MaxResponseContentBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, client.MaxResponseContentBufferSize);
}
}
[Fact]
public void MaxResponseContentBufferSize_OutOfRange_Throws()
{
using (HttpClient client = CreateHttpClient())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = -1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 0);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 1 + (long)int.MaxValue);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "no exception throw on netfx")]
[Theory]
[InlineData(1, 2, true)]
[InlineData(1, 127, true)]
[InlineData(254, 255, true)]
[InlineData(10, 256, true)]
[InlineData(1, 440, true)]
[InlineData(2, 1, false)]
[InlineData(2, 2, false)]
[InlineData(1000, 1000, false)]
public async Task MaxResponseContentBufferSize_ThrowsIfTooSmallForContent(int maxSize, int contentLength, bool exceptionExpected)
{
using (HttpClient client = CreateHttpClient())
{
client.MaxResponseContentBufferSize = maxSize;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<string> getTask = client.GetStringAsync(url);
Task serverTask = server.AcceptConnectionSendResponseAndCloseAsync(content: new string('s', contentLength));
Task bothTasks = TestHelper.WhenAllCompletedOrAnyFailed(getTask, serverTask);
if (exceptionExpected)
{
await Assert.ThrowsAsync<HttpRequestException>(() => bothTasks);
}
else
{
await bothTasks;
}
});
}
}
[Fact]
public async Task Properties_CantChangeAfterOperation_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
(await client.GetAsync(CreateFakeUri())).Dispose();
Assert.Throws<InvalidOperationException>(() => client.BaseAddress = null);
Assert.Throws<InvalidOperationException>(() => client.Timeout = TimeSpan.FromSeconds(1));
Assert.Throws<InvalidOperationException>(() => client.MaxResponseContentBufferSize = 1);
}
}
[Theory]
[InlineData(null)]
[InlineData("/something.html")]
public void GetAsync_NoBaseAddress_InvalidUri_ThrowsException(string uri)
{
using (HttpClient client = CreateHttpClient())
{
Assert.Throws<InvalidOperationException>(() => { client.GetAsync(uri == null ? null : new Uri(uri, UriKind.RelativeOrAbsolute)); });
}
}
[Theory]
[InlineData(null)]
[InlineData("/")]
public async Task GetAsync_BaseAddress_ValidUri_Success(string uri)
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
client.BaseAddress = new Uri(CreateFakeUri());
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetContentAsync_ErrorStatusCode_ExpectedExceptionThrown(bool withResponseContent)
{
using (var client = new HttpClient(new CustomResponseHandler(
(r,c) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = withResponseContent ? new ByteArrayContent(new byte[1]) : null
}))))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetByteArrayAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponse_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponseContent_ReturnsDefaultValue()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage() { Content = null }))))
{
Assert.Same(string.Empty, await client.GetStringAsync(CreateFakeUri()));
if (PlatformDetection.IsFullFramework)
{
Assert.Equal(Array.Empty<byte>(), await client.GetByteArrayAsync(CreateFakeUri()));
}
else
{
Assert.Same(Array.Empty<byte>(), await client.GetByteArrayAsync(CreateFakeUri()));
}
Assert.Same(Stream.Null, await client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Synchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => { throw e; }) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Asynchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => Task.FromException(e)) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetAsync_InvalidUrl_ExpectedExceptionThrown()
{
using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Canceled_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
var content = new ByteArrayContent(new byte[1]);
var cts = new CancellationTokenSource();
Task t1 = client.GetAsync(CreateFakeUri(), cts.Token);
Task t2 = client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, cts.Token);
Task t3 = client.PostAsync(CreateFakeUri(), content, cts.Token);
Task t4 = client.PutAsync(CreateFakeUri(), content, cts.Token);
Task t5 = client.DeleteAsync(CreateFakeUri(), cts.Token);
cts.Cancel();
await Assert.ThrowsAsync<TaskCanceledException>(() => t1);
await Assert.ThrowsAsync<TaskCanceledException>(() => t2);
await Assert.ThrowsAsync<TaskCanceledException>(() => t3);
await Assert.ThrowsAsync<TaskCanceledException>(() => t4);
await Assert.ThrowsAsync<TaskCanceledException>(() => t5);
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Success()
{
Action<HttpResponseMessage> verify = message => { using (message) Assert.Equal(HttpStatusCode.OK, message.StatusCode); };
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
verify(await client.GetAsync(CreateFakeUri()));
verify(await client.GetAsync(CreateFakeUri(), CancellationToken.None));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, CancellationToken.None));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.DeleteAsync(CreateFakeUri()));
verify(await client.DeleteAsync(CreateFakeUri(), CancellationToken.None));
}
}
[Fact]
public void GetAsync_CustomException_Synchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => { throw e; })))
{
FormatException thrown = Assert.Throws<FormatException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Same(e, thrown);
}
}
[Fact]
public async Task GetAsync_CustomException_Asynchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromException<HttpResponseMessage>(e))))
{
FormatException thrown = await Assert.ThrowsAsync<FormatException>(() => client.GetAsync(CreateFakeUri()));
Assert.Same(e, thrown);
}
}
[Fact]
public void SendAsync_NullRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
AssertExtensions.Throws<ArgumentNullException>("request", () => { client.SendAsync(null); });
}
}
[Fact]
public async Task SendAsync_DuplicateRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()))
{
(await client.SendAsync(request)).Dispose();
Assert.Throws<InvalidOperationException>(() => { client.SendAsync(request); });
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework disposes request content after send")]
public async Task SendAsync_RequestContentNotDisposed()
{
var content = new ByteArrayContent(new byte[1]);
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()) { Content = content })
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
await client.SendAsync(request);
await content.ReadAsStringAsync(); // no exception
}
}
[Fact]
public void Dispose_UseAfterDispose_Throws()
{
HttpClient client = CreateHttpClient();
client.Dispose();
Assert.Throws<ObjectDisposedException>(() => client.BaseAddress = null);
Assert.Throws<ObjectDisposedException>(() => client.CancelPendingRequests());
Assert.Throws<ObjectDisposedException>(() => { client.DeleteAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetByteArrayAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStreamAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStringAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.SendAsync(new HttpRequestMessage(HttpMethod.Get, CreateFakeUri())); });
Assert.Throws<ObjectDisposedException>(() => { client.Timeout = TimeSpan.FromSeconds(1); });
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CancelAllPending_AllPendingOperationsCanceled(bool withInfiniteTimeout)
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
if (withInfiniteTimeout)
{
client.Timeout = Timeout.InfiniteTimeSpan;
}
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
client.CancelPendingRequests();
Assert.All(tasks, task => Assert.Throws<TaskCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
public void Timeout_TooShort_AllPendingOperationsCanceled()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
client.Timeout = TimeSpan.FromMilliseconds(1);
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
Assert.All(tasks, task => Assert.Throws<TaskCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
public async Task SendAsync_UserAgent_CorrectlyWritten()
{
string userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.18 Safari/537.36";
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using (var client = CreateHttpClient())
{
var message = new HttpRequestMessage(HttpMethod.Get, uri);
message.Headers.TryAddWithoutValidation("User-Agent", userAgent);
(await client.SendAsync(message).ConfigureAwait(false)).Dispose();
}
}, server => server.AcceptConnectionAsync(async connection =>
{
List<string> headers = await connection.ReadRequestHeaderAndSendResponseAsync();
Assert.Contains($"User-Agent: {userAgent}", headers);
}));
}
[Fact]
[OuterLoop("One second delay in getting server's response")]
public async Task Timeout_SetTo30AndGetResponseFromLoopbackQuickly_Success()
{
using (HttpClient client = CreateHttpClient())
{
client.Timeout = TimeSpan.FromSeconds(30);
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task getTask = client.GetStringAsync(url);
await Task.Delay(TimeSpan.FromSeconds(.5));
await TestHelper.WhenAllCompletedOrAnyFailed(
getTask,
server.AcceptConnectionSendResponseAndCloseAsync());
});
}
}
private static string CreateFakeUri() => $"http://{Guid.NewGuid().ToString("N")}";
private static async Task<T> WhenCanceled<T>(CancellationToken cancellationToken)
{
await Task.Delay(-1, cancellationToken).ConfigureAwait(false);
return default(T);
}
private sealed class CustomResponseHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _func;
public CustomResponseHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> func) { _func = func; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _func(request, cancellationToken);
}
}
private sealed class CustomContent : HttpContent
{
private readonly Func<Stream, Task> _func;
public CustomContent(Func<Stream, Task> func) { _func = func; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _func(stream);
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MemberRelationshipService.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.ComponentModel.Design.Serialization {
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Security.Permissions;
/// <devdoc>
/// A member relationship service is used by a serializer to announce that one
/// property is related to a property on another object. Consider a code
/// based serialization scheme where code is of the following form:
///
/// object1.Property1 = object2.Property2
///
/// Upon interpretation of this code, Property1 on object1 will be
/// set to the return value of object2.Property2. But the relationship
/// between these two objects is lost. Serialization schemes that
/// wish to maintain this relationship may install a MemberRelationshipService
/// into the serialization manager. When an object is deserialized
/// this serivce will be notified of these relationships. It is up to the service
/// to act on these notifications if it wishes. During serialization, the
/// service is also consulted. If a relationship exists the same
/// relationship is maintained by the serializer.
/// </devdoc>
[HostProtection(SharedState = true)]
public abstract class MemberRelationshipService
{
private Dictionary<RelationshipEntry,RelationshipEntry> _relationships = new Dictionary<RelationshipEntry,RelationshipEntry>();
/// <devdoc>
/// Returns the the current relationship associated with the source, or MemberRelationship.Empty if
/// there is no relationship. Also sets a relationship between two objects. Empty
/// can also be passed as the property value, in which case the relationship will
/// be cleared.
/// </devdoc>
[SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")]
public MemberRelationship this[MemberRelationship source] {
get {
if (source.Owner == null) throw new ArgumentNullException("Owner");
if (source.Member== null) throw new ArgumentNullException("Member");
return GetRelationship(source);
}
set {
if (source.Owner == null) throw new ArgumentNullException("Owner");
if (source.Member == null) throw new ArgumentNullException("Member");
SetRelationship(source, value);
}
}
/// <devdoc>
/// Returns the the current relationship associated with the source, or null if
/// there is no relationship. Also sets a relationship between two objects. Null
/// can be passed as the property value, in which case the relationship will
/// be cleared.
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1023:IndexersShouldNotBeMultidimensional")]
public MemberRelationship this[object sourceOwner, MemberDescriptor sourceMember] {
get {
if (sourceOwner == null) throw new ArgumentNullException("sourceOwner");
if (sourceMember == null) throw new ArgumentNullException("sourceMember");
return GetRelationship(new MemberRelationship(sourceOwner, sourceMember));
}
set {
if (sourceOwner == null) throw new ArgumentNullException("sourceOwner");
if (sourceMember == null) throw new ArgumentNullException("sourceMember");
SetRelationship(new MemberRelationship(sourceOwner, sourceMember), value);
}
}
/// <devdoc>
/// This is the implementation API for returning relationships. The default implementation stores the
/// relationship in a table. Relationships are stored weakly, so they do not keep an object alive.
/// </devdoc>
protected virtual MemberRelationship GetRelationship(MemberRelationship source) {
RelationshipEntry retVal;
if (_relationships != null && _relationships.TryGetValue(new RelationshipEntry(source), out retVal) && retVal.Owner.IsAlive) {
return new MemberRelationship(retVal.Owner.Target, retVal.Member);
}
return MemberRelationship.Empty;
}
/// <devdoc>
/// This is the implementation API for returning relationships. The default implementation stores the
/// relationship in a table. Relationships are stored weakly, so they do not keep an object alive. Empty can be
/// passed in for relationship to remove the relationship.
/// </devdoc>
protected virtual void SetRelationship(MemberRelationship source, MemberRelationship relationship) {
if (!relationship.IsEmpty && !SupportsRelationship(source, relationship)) {
string sourceName = TypeDescriptor.GetComponentName(source.Owner);
string relName = TypeDescriptor.GetComponentName(relationship.Owner);
if (sourceName == null) {
sourceName = source.Owner.ToString();
}
if (relName == null) {
relName = relationship.Owner.ToString();
}
throw new ArgumentException(SR.GetString(SR.MemberRelationshipService_RelationshipNotSupported, sourceName, source.Member.Name, relName, relationship.Member.Name));
}
if (_relationships == null) {
_relationships = new Dictionary<RelationshipEntry,RelationshipEntry>();
}
_relationships[new RelationshipEntry(source)] = new RelationshipEntry(relationship);
}
/// <devdoc>
/// Returns true if the provided relatinoship is supported.
/// </devdoc>
public abstract bool SupportsRelationship(MemberRelationship source, MemberRelationship relationship);
/// <devdoc>
/// Used as storage in our relationship table
/// </devdoc>
private struct RelationshipEntry {
internal WeakReference Owner;
internal MemberDescriptor Member;
private int hashCode;
internal RelationshipEntry(MemberRelationship rel) {
Owner = new WeakReference(rel.Owner);
Member = rel.Member;
hashCode = rel.Owner == null ? 0 : rel.Owner.GetHashCode();
}
public override bool Equals(object o) {
if (o is RelationshipEntry) {
RelationshipEntry e = (RelationshipEntry)o;
return this == e;
}
return false;
}
public static bool operator==(RelationshipEntry re1, RelationshipEntry re2){
object owner1 = (re1.Owner.IsAlive ? re1.Owner.Target : null);
object owner2 = (re2.Owner.IsAlive ? re2.Owner.Target : null);
return owner1 == owner2 && re1.Member.Equals(re2.Member);
}
public static bool operator!=(RelationshipEntry re1, RelationshipEntry re2){
return !(re1 == re2);
}
public override int GetHashCode() {
return hashCode;
}
}
}
/// <devdoc>
/// This class represents a single relationship between an object and a member.
/// </devdoc>
public struct MemberRelationship {
private object _owner;
private MemberDescriptor _member;
public static readonly MemberRelationship Empty = new MemberRelationship();
/// <devdoc>
/// Creates a new member relationship.
/// </devdoc>
public MemberRelationship(object owner, MemberDescriptor member) {
if (owner == null) throw new ArgumentNullException("owner");
if (member == null) throw new ArgumentNullException("member");
_owner = owner;
_member = member;
}
/// <devdoc>
/// Returns true if this relationship is empty.
/// </devdoc>
public bool IsEmpty {
get {
return _owner == null;
}
}
/// <devdoc>
/// The member in this relationship.
/// </devdoc>
public MemberDescriptor Member {
get {
return _member;
}
}
/// <devdoc>
/// The object owning the member.
/// </devdoc>
public object Owner {
get {
return _owner;
}
}
/// <devdoc>
/// Infrastructure support to make this a first class struct
/// </devdoc>
public override bool Equals(object obj) {
if (!(obj is MemberRelationship))
return false;
MemberRelationship rel = (MemberRelationship)obj;
return rel.Owner == Owner && rel.Member == Member;
}
/// <devdoc>
/// Infrastructure support to make this a first class struct
/// </devdoc>
public override int GetHashCode() {
if (_owner == null) return base.GetHashCode();
return _owner.GetHashCode() ^ _member.GetHashCode();
}
/// <devdoc>
/// Infrastructure support to make this a first class struct
/// </devdoc>
public static bool operator ==(MemberRelationship left, MemberRelationship right) {
return left.Owner == right.Owner && left.Member == right.Member;
}
/// <devdoc>
/// Infrastructure support to make this a first class struct
/// </devdoc>
public static bool operator !=(MemberRelationship left, MemberRelationship right) {
return !(left == right);
}
}
}
| |
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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 NSubstitute;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using IBM.Cloud.SDK.Core.Http;
using IBM.Cloud.SDK.Core.Http.Exceptions;
using IBM.Cloud.SDK.Core.Authentication.NoAuth;
using IBM.Watson.CompareComply.v1.Model;
using IBM.Cloud.SDK.Core.Model;
namespace IBM.Watson.CompareComply.v1.UnitTests
{
[TestClass]
public class CompareComplyServiceUnitTests
{
#region Constructor
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void Constructor_HttpClient_Null()
{
CompareComplyService service = new CompareComplyService(httpClient: null);
}
[TestMethod]
public void ConstructorHttpClient()
{
CompareComplyService service = new CompareComplyService(new IBMHttpClient());
Assert.IsNotNull(service);
}
[TestMethod]
public void ConstructorExternalConfig()
{
var apikey = System.Environment.GetEnvironmentVariable("COMPARE_COMPLY_APIKEY");
System.Environment.SetEnvironmentVariable("COMPARE_COMPLY_APIKEY", "apikey");
CompareComplyService service = Substitute.For<CompareComplyService>("versionDate");
Assert.IsNotNull(service);
System.Environment.SetEnvironmentVariable("COMPARE_COMPLY_APIKEY", apikey);
}
[TestMethod]
public void Constructor()
{
CompareComplyService service = new CompareComplyService(new IBMHttpClient());
Assert.IsNotNull(service);
}
[TestMethod]
public void ConstructorAuthenticator()
{
CompareComplyService service = new CompareComplyService("versionDate", new NoAuthAuthenticator());
Assert.IsNotNull(service);
}
[TestMethod, ExpectedException(typeof(ArgumentNullException))]
public void ConstructorNoVersion()
{
CompareComplyService service = new CompareComplyService(null, new NoAuthAuthenticator());
}
[TestMethod]
public void ConstructorNoUrl()
{
var apikey = System.Environment.GetEnvironmentVariable("COMPARE_COMPLY_APIKEY");
System.Environment.SetEnvironmentVariable("COMPARE_COMPLY_APIKEY", "apikey");
var url = System.Environment.GetEnvironmentVariable("COMPARE_COMPLY_URL");
System.Environment.SetEnvironmentVariable("COMPARE_COMPLY_URL", null);
CompareComplyService service = Substitute.For<CompareComplyService>("versionDate");
Assert.IsTrue(service.ServiceUrl == "https://api.us-south.compare-comply.watson.cloud.ibm.com");
System.Environment.SetEnvironmentVariable("COMPARE_COMPLY_URL", url);
}
#endregion
[TestMethod]
public void ConvertToHtml_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var file = new MemoryStream();
var fileContentType = "fileContentType";
var model = "model";
var result = service.ConvertToHtml(file: file, fileContentType: fileContentType, model: model);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void ClassifyElements_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var file = new MemoryStream();
var fileContentType = "fileContentType";
var model = "model";
var result = service.ClassifyElements(file: file, fileContentType: fileContentType, model: model);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void ExtractTables_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var file = new MemoryStream();
var fileContentType = "fileContentType";
var model = "model";
var result = service.ExtractTables(file: file, fileContentType: fileContentType, model: model);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void CompareDocuments_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var file1 = new MemoryStream();
var file2 = new MemoryStream();
var file1ContentType = "file1ContentType";
var file2ContentType = "file2ContentType";
var file1Label = "file1Label";
var file2Label = "file2Label";
var model = "model";
var result = service.CompareDocuments(file1: file1, file2: file2, file1ContentType: file1ContentType, file2ContentType: file2ContentType, file1Label: file1Label, file2Label: file2Label, model: model);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void AddFeedback_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var feedbackData = new FeedbackDataInput();
var userId = "userId";
var comment = "comment";
var result = service.AddFeedback(feedbackData: feedbackData, userId: userId, comment: comment);
JObject bodyObject = new JObject();
if (feedbackData != null)
{
bodyObject["feedback_data"] = JToken.FromObject(feedbackData);
}
if (!string.IsNullOrEmpty(userId))
{
bodyObject["user_id"] = JToken.FromObject(userId);
}
if (!string.IsNullOrEmpty(comment))
{
bodyObject["comment"] = JToken.FromObject(comment);
}
var json = JsonConvert.SerializeObject(bodyObject);
request.Received().WithArgument("version", versionDate);
request.Received().WithBodyContent(Arg.Is<StringContent>(x => x.ReadAsStringAsync().Result.Equals(json)));
}
[TestMethod]
public void ListFeedback_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var feedbackType = "feedbackType";
DateTime? before = DateTime.MaxValue;
DateTime? after = DateTime.MaxValue;
var documentTitle = "documentTitle";
var modelId = "modelId";
var modelVersion = "modelVersion";
var categoryRemoved = "categoryRemoved";
var categoryAdded = "categoryAdded";
var categoryNotChanged = "categoryNotChanged";
var typeRemoved = "typeRemoved";
var typeAdded = "typeAdded";
var typeNotChanged = "typeNotChanged";
long? pageLimit = 1;
var cursor = "cursor";
var sort = "sort";
var includeTotal = false;
var result = service.ListFeedback(feedbackType: feedbackType, documentTitle: documentTitle, modelId: modelId, modelVersion: modelVersion, categoryRemoved: categoryRemoved, categoryAdded: categoryAdded, categoryNotChanged: categoryNotChanged, typeRemoved: typeRemoved, typeAdded: typeAdded, typeNotChanged: typeNotChanged, pageLimit: pageLimit, cursor: cursor, sort: sort, includeTotal: includeTotal);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetFeedback_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var feedbackId = "feedbackId";
var model = "model";
var result = service.GetFeedback(feedbackId: feedbackId, model: model);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/feedback/{feedbackId}");
}
[TestMethod]
public void DeleteFeedback_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.DeleteAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var feedbackId = "feedbackId";
var model = "model";
var result = service.DeleteFeedback(feedbackId: feedbackId, model: model);
request.Received().WithArgument("version", versionDate);
client.Received().DeleteAsync($"{service.ServiceUrl}/v1/feedback/{feedbackId}");
}
[TestMethod]
public void CreateBatch_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PostAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var function = "function";
var inputCredentialsFile = new MemoryStream();
var inputBucketLocation = "inputBucketLocation";
var inputBucketName = "inputBucketName";
var outputCredentialsFile = new MemoryStream();
var outputBucketLocation = "outputBucketLocation";
var outputBucketName = "outputBucketName";
var model = "model";
var result = service.CreateBatch(function: function, inputCredentialsFile: inputCredentialsFile, inputBucketLocation: inputBucketLocation, inputBucketName: inputBucketName, outputCredentialsFile: outputCredentialsFile, outputBucketLocation: outputBucketLocation, outputBucketName: outputBucketName, model: model);
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void ListBatches_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var result = service.ListBatches();
request.Received().WithArgument("version", versionDate);
}
[TestMethod]
public void GetBatch_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.GetAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var batchId = "batchId";
var result = service.GetBatch(batchId: batchId);
request.Received().WithArgument("version", versionDate);
client.Received().GetAsync($"{service.ServiceUrl}/v1/batches/{batchId}");
}
[TestMethod]
public void UpdateBatch_Success()
{
IClient client = Substitute.For<IClient>();
IRequest request = Substitute.For<IRequest>();
client.PutAsync(Arg.Any<string>())
.Returns(request);
CompareComplyService service = new CompareComplyService(client);
var versionDate = "versionDate";
service.Version = versionDate;
var batchId = "batchId";
var action = "action";
var model = "model";
var result = service.UpdateBatch(batchId: batchId, action: action, model: model);
request.Received().WithArgument("version", versionDate);
client.Received().PutAsync($"{service.ServiceUrl}/v1/batches/{batchId}");
}
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Loader;
using System.Reflection;
using System.Collections.Generic;
using Microsoft.TeamFoundation.DistributedTask.Logging;
using System.Net.Http.Headers;
namespace Microsoft.VisualStudio.Services.Agent.Tests
{
public sealed class TestHostContext : IHostContext, IDisposable
{
private readonly ConcurrentDictionary<Type, ConcurrentQueue<object>> _serviceInstances = new ConcurrentDictionary<Type, ConcurrentQueue<object>>();
private readonly ConcurrentDictionary<Type, object> _serviceSingletons = new ConcurrentDictionary<Type, object>();
private readonly ITraceManager _traceManager;
private readonly Terminal _term;
private readonly SecretMasker _secretMasker;
private CancellationTokenSource _agentShutdownTokenSource = new CancellationTokenSource();
private string _suiteName;
private string _testName;
private Tracing _trace;
private AssemblyLoadContext _loadContext;
private string _tempDirectoryRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("D"));
private StartupType _startupType;
public event EventHandler Unloading;
public CancellationToken AgentShutdownToken => _agentShutdownTokenSource.Token;
public ShutdownReason AgentShutdownReason { get; private set; }
public ISecretMasker SecretMasker => _secretMasker;
public TestHostContext(object testClass, [CallerMemberName] string testName = "")
{
ArgUtil.NotNull(testClass, nameof(testClass));
ArgUtil.NotNullOrEmpty(testName, nameof(testName));
_loadContext = AssemblyLoadContext.GetLoadContext(typeof(TestHostContext).GetTypeInfo().Assembly);
_loadContext.Unloading += LoadContext_Unloading;
_testName = testName;
// Trim the test assembly's root namespace from the test class's full name.
_suiteName = testClass.GetType().FullName.Substring(
startIndex: typeof(Tests.TestHostContext).FullName.LastIndexOf(nameof(TestHostContext)));
_suiteName = _suiteName.Replace(".", "_");
// Setup the trace manager.
TraceFileName = Path.Combine(
Path.Combine(TestUtil.GetSrcPath(), "Test", "TestLogs"),
$"trace_{_suiteName}_{_testName}.log");
if (File.Exists(TraceFileName))
{
File.Delete(TraceFileName);
}
var traceListener = new HostTraceListener(TraceFileName);
_secretMasker = new SecretMasker();
_secretMasker.AddValueEncoder(ValueEncoders.JsonStringEscape);
_secretMasker.AddValueEncoder(ValueEncoders.UriDataEscape);
_traceManager = new TraceManager(traceListener, _secretMasker);
_trace = GetTrace(nameof(TestHostContext));
// inject a terminal in silent mode so all console output
// goes to the test trace file
_term = new Terminal();
_term.Silent = true;
SetSingleton<ITerminal>(_term);
EnqueueInstance<ITerminal>(_term);
#if !OS_WINDOWS
string eulaFile = Path.Combine(GetDirectory(WellKnownDirectory.Externals), Constants.Path.TeeDirectory, "license.html");
Directory.CreateDirectory(GetDirectory(WellKnownDirectory.Externals));
Directory.CreateDirectory(Path.Combine(GetDirectory(WellKnownDirectory.Externals), Constants.Path.TeeDirectory));
File.WriteAllText(eulaFile, "testeulafile");
#endif
}
public CultureInfo DefaultCulture { get; private set; }
public RunMode RunMode { get; set; }
public string TraceFileName { get; private set; }
public StartupType StartupType
{
get
{
return _startupType;
}
set
{
_startupType = value;
}
}
public ProductInfoHeaderValue UserAgent => new ProductInfoHeaderValue("L0Test", "0.0");
public async Task Delay(TimeSpan delay, CancellationToken token)
{
await Task.Delay(TimeSpan.Zero);
}
public T CreateService<T>() where T : class, IAgentService
{
_trace.Verbose($"Create service: '{typeof(T).Name}'");
// Dequeue a registered instance.
object service;
ConcurrentQueue<object> queue;
if (!_serviceInstances.TryGetValue(typeof(T), out queue) ||
!queue.TryDequeue(out service))
{
throw new Exception($"Unable to dequeue a registered instance for type '{typeof(T).FullName}'.");
}
var s = service as T;
s.Initialize(this);
return s;
}
public T GetService<T>() where T : class, IAgentService
{
_trace.Verbose($"Get service: '{typeof(T).Name}'");
// Get the registered singleton instance.
object service;
if (!_serviceSingletons.TryGetValue(typeof(T), out service))
{
throw new Exception($"Singleton instance not registered for type '{typeof(T).FullName}'.");
}
T s = service as T;
s.Initialize(this);
return s;
}
public void EnqueueInstance<T>(T instance) where T : class, IAgentService
{
// Enqueue a service instance to be returned by CreateService.
if (object.ReferenceEquals(instance, null))
{
throw new ArgumentNullException(nameof(instance));
}
ConcurrentQueue<object> queue = _serviceInstances.GetOrAdd(
key: typeof(T),
valueFactory: x => new ConcurrentQueue<object>());
queue.Enqueue(instance);
}
public void SetDefaultCulture(string name)
{
DefaultCulture = new CultureInfo(name);
}
public void SetSingleton<T>(T singleton) where T : class, IAgentService
{
// Set the singleton instance to be returned by GetService.
if (object.ReferenceEquals(singleton, null))
{
throw new ArgumentNullException(nameof(singleton));
}
_serviceSingletons[typeof(T)] = singleton;
}
public string GetDirectory(WellKnownDirectory directory)
{
string path;
switch (directory)
{
case WellKnownDirectory.Bin:
path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
break;
case WellKnownDirectory.Diag:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
Constants.Path.DiagDirectory);
break;
case WellKnownDirectory.Externals:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
Constants.Path.ExternalsDirectory);
break;
case WellKnownDirectory.LegacyPSHost:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Externals),
Constants.Path.LegacyPSHostDirectory);
break;
case WellKnownDirectory.Root:
path = new DirectoryInfo(GetDirectory(WellKnownDirectory.Bin)).Parent.FullName;
break;
case WellKnownDirectory.ServerOM:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Externals),
Constants.Path.ServerOMDirectory);
break;
case WellKnownDirectory.Tee:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Externals),
Constants.Path.TeeDirectory);
break;
case WellKnownDirectory.Temp:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.TempDirectory);
break;
case WellKnownDirectory.Tasks:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.TasksDirectory);
break;
case WellKnownDirectory.Tools:
path = Environment.GetEnvironmentVariable("AGENT_TOOLSDIRECTORY") ?? Environment.GetEnvironmentVariable(Constants.Variables.Agent.ToolsDirectory);
if (string.IsNullOrEmpty(path))
{
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.ToolDirectory);
}
break;
case WellKnownDirectory.Update:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Work),
Constants.Path.UpdateDirectory);
break;
case WellKnownDirectory.Work:
path = Path.Combine(
_tempDirectoryRoot,
WellKnownDirectory.Work.ToString());
break;
default:
throw new NotSupportedException($"Unexpected well known directory: '{directory}'");
}
_trace.Info($"Well known directory '{directory}': '{path}'");
return path;
}
public string GetConfigFile(WellKnownConfigFile configFile)
{
string path;
switch (configFile)
{
case WellKnownConfigFile.Agent:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".agent");
break;
case WellKnownConfigFile.Credentials:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credentials");
break;
case WellKnownConfigFile.RSACredentials:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credentials_rsaparams");
break;
case WellKnownConfigFile.Service:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".service");
break;
case WellKnownConfigFile.CredentialStore:
#if OS_OSX
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credential_store.keychain");
#else
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".credential_store");
#endif
break;
case WellKnownConfigFile.Certificates:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".certificates");
break;
case WellKnownConfigFile.Proxy:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".proxy");
break;
case WellKnownConfigFile.ProxyCredentials:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".proxycredentials");
break;
case WellKnownConfigFile.ProxyBypass:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".proxybypass");
break;
case WellKnownConfigFile.Autologon:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".autologon");
break;
case WellKnownConfigFile.Options:
path = Path.Combine(
GetDirectory(WellKnownDirectory.Root),
".options");
break;
default:
throw new NotSupportedException($"Unexpected well known config file: '{configFile}'");
}
_trace.Info($"Well known config file '{configFile}': '{path}'");
return path;
}
// simple convenience factory so each suite/test gets a different trace file per run
public Tracing GetTrace()
{
Tracing trace = GetTrace($"{_suiteName}_{_testName}");
trace.Info($"Starting {_testName}");
return trace;
}
public Tracing GetTrace(string name)
{
return _traceManager[name];
}
public void ShutdownAgent(ShutdownReason reason)
{
ArgUtil.NotNull(reason, nameof(reason));
AgentShutdownReason = reason;
_agentShutdownTokenSource.Cancel();
}
public void WritePerfCounter(string counter)
{
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_loadContext != null)
{
_loadContext.Unloading -= LoadContext_Unloading;
_loadContext = null;
}
_traceManager?.Dispose();
try
{
Directory.Delete(_tempDirectoryRoot);
}
catch (Exception)
{
// eat exception on dispose
}
}
}
private void LoadContext_Unloading(AssemblyLoadContext obj)
{
if (Unloading != null)
{
Unloading(this, null);
}
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using System;
using Microsoft.Boogie;
using Microsoft.Basetypes;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Numerics;
using System.Linq;
namespace Symbooglix
{
public class SimpleExprBuilder : IExprBuilder
{
FunctionCallBuilder FCB;
private readonly bool _Immutable;
public bool Immutable
{
get { return _Immutable; }
}
public SimpleExprBuilder(bool immutable)
{
FCB = new FunctionCallBuilder();
_Immutable = immutable;
}
private FunctionCall CreateBVBuiltIn(string Name, string Builtin, Microsoft.Boogie.Type returnType, IList<Microsoft.Boogie.Type> argTypes)
{
// Skip the cache as we implement a cache elsewhere for bv operators
var funcCall = FCB.CreateUninterpretedFunctionCall(Name, returnType, argTypes);
funcCall.Func.AddAttribute("bvbuiltin", new string[] { Builtin });
return funcCall;
}
private FunctionCall CreateBuiltIn(string name, string builtin, Microsoft.Boogie.Type returnType, IList<Microsoft.Boogie.Type> argTypes)
{
// Skip the cache as we implement a cache elsewhere for bv operators
var funcCall = FCB.CreateUninterpretedFunctionCall(name, returnType, argTypes);
funcCall.Func.AddAttribute("builtin", new string[] { builtin });
return funcCall;
}
private NAryExpr GetNAry(IAppliable fun, List<Expr> args)
{
return new NAryExpr(Token.NoToken, fun, args, Immutable);
}
public LiteralExpr ConstantInt(int value)
{
return new LiteralExpr(Token.NoToken, BigNum.FromInt(value), Immutable);
}
public LiteralExpr ConstantInt(BigInteger decimalValue)
{
return new LiteralExpr(Token.NoToken, BigNum.FromBigInt(decimalValue), Immutable);
}
public LiteralExpr ConstantReal(string value)
{
return new LiteralExpr(Token.NoToken, BigDec.FromString(value), Immutable);
}
public LiteralExpr ConstantReal(Microsoft.Basetypes.BigDec value)
{
return new LiteralExpr(Token.NoToken, value, Immutable);
}
public LiteralExpr ConstantBool(bool value)
{
return new LiteralExpr(Token.NoToken, value, Immutable);
}
public LiteralExpr ConstantBV(int decimalValue, int bitWidth)
{
return ConstantBV(new BigInteger(decimalValue), bitWidth);
}
public LiteralExpr True
{
get
{
return ConstantBool(true);
}
}
public LiteralExpr False
{
get
{
return ConstantBool(false);
}
}
public Expr Identifier(Variable v)
{
return new IdentifierExpr(Token.NoToken, v, Immutable);
}
public LiteralExpr ConstantBV(BigInteger decimalValue, int bitWidth)
{
var twoToPowerOfBits = BigInteger.Pow(2, bitWidth);
if (decimalValue.Sign < 0)
{
// Convert the decimal value into two's complement representation
//
// The rule is basically this:
//
// decimal_rep_for_bits = (2^m - |x|) mod (2^m)
if (bitWidth <=1)
throw new ArgumentException("Decimal value cannot be represented in the requested number of bits");
var abs = BigInteger.Abs(decimalValue);
if (abs > BigInteger.Pow(2, bitWidth -1))
throw new ArgumentException("Decimal value cannot be represented in the requested number of bits");
var result = ( twoToPowerOfBits - abs );
Debug.Assert(result > 0);
return new LiteralExpr(Token.NoToken, BigNum.FromBigInt(result), bitWidth, Immutable);
}
else
{
if (bitWidth < 1)
throw new ArgumentException("Bitwidth must be >= 1");
// Positive or zero
if (decimalValue >= twoToPowerOfBits)
throw new ArgumentException("Decimal value cannot be represented in the requested number of bits");
return new LiteralExpr(Token.NoToken, BigNum.FromBigInt(decimalValue), bitWidth, Immutable);
}
}
private ConcurrentDictionary<string, FunctionCall> CachedFunctions = new ConcurrentDictionary<string, FunctionCall>();
private Expr GetBinaryBVFunction(Microsoft.Boogie.Type returnType, string NameWithoutSizeSuffx, string builtin, Expr lhs, Expr rhs)
{
if (!lhs.Type.IsBv)
{
throw new ExprTypeCheckException("lhs must be bitvector");
}
if (!rhs.Type.IsBv)
{
throw new ExprTypeCheckException("rhs must be bitvector");
}
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("bitwidth mistmatch");
}
int bits = lhs.Type.BvBits;
Debug.Assert(bits == rhs.Type.BvBits);
var functionName = NameWithoutSizeSuffx + bits.ToString();
FunctionCall builtinFunctionCall = null;
try
{
builtinFunctionCall = CachedFunctions[functionName];
}
catch(KeyNotFoundException)
{
// Cache miss, build the FunctionCall
builtinFunctionCall = CreateBVBuiltIn(functionName,
builtin, returnType, new List<Microsoft.Boogie.Type>()
{
BasicType.GetBvType(bits),
BasicType.GetBvType(bits)
});
CachedFunctions[functionName] = builtinFunctionCall;
}
var result = GetNAry(builtinFunctionCall, new List<Expr>() { lhs, rhs });
return result;
}
public Expr BVSLT(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVSLT", "bvslt", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVSLE (Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVSLE", "bvsle", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVSGT(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVSGT", "bvsgt", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVSGE(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVSGE", "bvsge", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVULT(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVULT", "bvult", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVULE(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVULE", "bvule", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVUGT(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVUGT", "bvugt", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVUGE(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(BasicType.Bool, "BVUGE", "bvuge", lhs, rhs);
result.Type = Microsoft.Boogie.Type.Bool;
return result;
}
public Expr BVOR(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVOR", "bvor", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVAND(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVAND", "bvand", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVXOR(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVXOR", "bvxor", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVSHL(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVSHL", "bvshl", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVLSHR(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVLSHR", "bvlshr", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVASHR(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVASHR", "bvashr", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVADD(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVADD", "bvadd", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVSUB(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVSUB", "bvsub", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVMUL(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVMUL", "bvmul", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVUDIV(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVUDIV", "bvudiv", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVSDIV(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVSDIV", "bvsdiv", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVUREM(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVUREM", "bvurem", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVSREM(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVSREM", "bvsrem", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr BVSMOD(Expr lhs, Expr rhs)
{
var result = GetBinaryBVFunction(lhs.Type, "BVSMOD", "bvsmod", lhs, rhs);
result.Type = lhs.Type;
return result;
}
public Expr GetUnaryBVFunction(Microsoft.Boogie.Type returnType, string NameWithoutSizeSuffx, string builtin, Expr operand, bool getSuffixFromReturnType = false)
{
if (!operand.Type.IsBv)
{
throw new ExprTypeCheckException("operand must be BvType");
}
int bits = operand.Type.BvBits;
string suffixString = null;
if (getSuffixFromReturnType)
{
if (!returnType.IsBv)
throw new ArgumentException("expected return type to be BvType");
suffixString = returnType.BvBits.ToString();
}
else
{
suffixString = bits.ToString();
}
var functionName = NameWithoutSizeSuffx + suffixString;
FunctionCall builtinFunctionCall = null;
try
{
builtinFunctionCall = CachedFunctions[functionName];
}
catch (KeyNotFoundException)
{
// Cache miss, build the FunctionCall
builtinFunctionCall = CreateBVBuiltIn(functionName,
builtin, returnType, new List<Microsoft.Boogie.Type>()
{
BasicType.GetBvType(bits)
});
CachedFunctions[functionName] = builtinFunctionCall;
}
var result = GetNAry(builtinFunctionCall, new List<Expr>() { operand});
return result;
}
public Expr BVNEG(Expr operand)
{
var result = GetUnaryBVFunction(operand.Type, "BVNEG", "bvneg", operand);
result.Type = operand.Type;
return result;
}
public Expr BVNOT(Expr operand)
{
var result = GetUnaryBVFunction(operand.Type, "BVNOT", "bvnot", operand);
result.Type = operand.Type;
return result;
}
public Expr BVSEXT(Expr operand, int newWidth)
{
if (!operand.Type.IsBv)
{
throw new ExprTypeCheckException("operand must be BvType");
}
int originalWidth = operand.Type.BvBits;
if (newWidth < originalWidth)
{
throw new ArgumentException("newWidth must be greater than the operand's bit width");
}
var functionNameWithoutSuffix = string.Format("BV{0}_SEXT", originalWidth);
var builtinName = string.Format("sign_extend {0}", ( newWidth - originalWidth ));
var newType = BasicType.GetBvType(newWidth);
var result = GetUnaryBVFunction(newType, functionNameWithoutSuffix, builtinName, operand, /*getSuffixFromReturnType=*/ true);
result.Type = newType;
return result;
}
public Expr BVZEXT(Expr operand, int newWidth)
{
if (!operand.Type.IsBv)
{
throw new ExprTypeCheckException("operand must be BvType");
}
int originalWidth = operand.Type.BvBits;
if (newWidth < originalWidth)
{
throw new ArgumentException("newWidth must be greater than the operand's bit width");
}
var functionNameWithoutSuffix = string.Format("BV{0}_ZEXT", originalWidth);
var builtinName = string.Format("zero_extend {0}", ( newWidth - originalWidth ));
var newType = BasicType.GetBvType(newWidth);
var result = GetUnaryBVFunction(newType, functionNameWithoutSuffix, builtinName, operand, /*getSuffixFromReturnType=*/ true);
result.Type = newType;
return result;
}
public Expr BVCONCAT(Expr MSB, Expr LSB)
{
if (!MSB.Type.IsBv)
{
throw new ExprTypeCheckException("MSB must be BvType");
}
if (!LSB.Type.IsBv)
{
throw new ExprTypeCheckException("MSB must be BvType");
}
var result = new BvConcatExpr(Token.NoToken, MSB, LSB, Immutable);
result.Type = result.ShallowType;
return result;
}
public Expr BVEXTRACT(Expr operand, int end, int start)
{
if (!operand.Type.IsBv)
{
throw new ExprTypeCheckException("operand must be BvType");
}
if (end <= start)
{
throw new ArgumentException("end must be > start");
}
if (start < 0)
{
throw new ArgumentException("start must be >= 0");
}
if (end > operand.Type.BvBits)
{
throw new ArgumentException("end must be <= the bit width of the operand");
}
var result = new BvExtractExpr(Token.NoToken, operand, end, start, Immutable);
result.Type = result.ShallowType;
return result;
}
private ConcurrentDictionary<BinaryOperator.Opcode, BinaryOperator> BinaryOperatorCache = new ConcurrentDictionary<BinaryOperator.Opcode, BinaryOperator>();
private IAppliable GetBinaryFunction(BinaryOperator.Opcode oc)
{
BinaryOperator function = null;
try
{
function = BinaryOperatorCache[oc];
}
catch (KeyNotFoundException)
{
function = new BinaryOperator(Token.NoToken, oc);
BinaryOperatorCache[oc] = function;
}
return function;
}
public Expr NotEq(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs type must be the same");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Neq), new List<Expr> { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr Eq(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs type must be the same");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Eq), new List<Expr> { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr Iff(Expr lhs, Expr rhs)
{
if (!lhs.Type.IsBool)
{
throw new ExprTypeCheckException("lhs must be bool");
}
if (!rhs.Type.IsBool)
{
throw new ExprTypeCheckException("rhs must be bool");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Iff), new List<Expr> { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr Imp(Expr lhs, Expr rhs)
{
if (!lhs.Type.IsBool)
{
throw new ExprTypeCheckException("lhs must be bool");
}
if (!rhs.Type.IsBool)
{
throw new ExprTypeCheckException("rhs must be bool");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Imp), new List<Expr> { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr And(Expr lhs, Expr rhs)
{
if (!lhs.Type.IsBool)
{
throw new ExprTypeCheckException("lhs must be bool");
}
if (!rhs.Type.IsBool)
{
throw new ExprTypeCheckException("rhs must be bool");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.And), new List<Expr> { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr Or(Expr lhs, Expr rhs)
{
if (!lhs.Type.IsBool)
{
throw new ExprTypeCheckException("lhs must be bool");
}
if (!rhs.Type.IsBool)
{
throw new ExprTypeCheckException("rhs must be bool");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Or), new List<Expr> { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
private Microsoft.Boogie.IfThenElse IfThenElseCached = new Microsoft.Boogie.IfThenElse(Token.NoToken);
public Expr IfThenElse(Expr condition, Expr thenExpr, Expr elseExpr)
{
if (!condition.Type.IsBool)
{
throw new ExprTypeCheckException("Condition must be bool");
}
if (!thenExpr.Type.Equals(elseExpr.Type))
{
throw new ExprTypeCheckException("thenExpr and elseExpr types must match");
}
var result = GetNAry(IfThenElseCached, new List<Expr> { condition, thenExpr, elseExpr });
result.Type = thenExpr.Type;
return result;
}
private ConcurrentDictionary<UnaryOperator.Opcode, UnaryOperator> UnaryOperatorCache = new ConcurrentDictionary<UnaryOperator.Opcode, UnaryOperator>();
private IAppliable GetUnaryFunction(UnaryOperator.Opcode op)
{
UnaryOperator function = null;
try
{
function = UnaryOperatorCache[op];
}
catch (KeyNotFoundException)
{
function = new UnaryOperator(Token.NoToken, op);
UnaryOperatorCache[op] = function;
}
return function;
}
public Expr Not(Expr e)
{
if (!e.Type.IsBool)
{
throw new ExprTypeCheckException("expr must be bool");
}
var result = GetNAry(GetUnaryFunction(UnaryOperator.Opcode.Not), new List<Expr> { e });
result.Type = BasicType.Bool;
return result;
}
public Expr UFC(FunctionCall func, params Expr[] args)
{
if (args.Length != func.Func.InParams.Count)
{
throw new ExprTypeCheckException("Wrong number of arguments for supplied FunctionCall");
}
// Check type matches
for (int index=0; index < args.Length; ++index)
{
if (!( args[index].Type.Equals(func.Func.InParams[index].TypedIdent.Type) ))
{
throw new ExprTypeCheckException("Type mismatch between supplied FunctionCall and argument at index " + index.ToString());
}
}
var result = GetNAry(func, new List<Expr>(args));
result.Type = func.Func.OutParams[0].TypedIdent.Type;
return result;
}
public Expr Add(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of real or int type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Add), new List<Expr>() { lhs, rhs });
result.Type = lhs.Type;
return result;
}
public Expr Sub(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of real or int type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Sub), new List<Expr>() { lhs, rhs });
result.Type = lhs.Type;
return result;
}
public Expr Mul(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of real or int type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Mul), new List<Expr>() { lhs, rhs });
result.Type = lhs.Type;
return result;
}
public Expr Div(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt)
{
throw new ExprTypeCheckException("lhs and rhs must both be of int type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Div), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Int;
return result;
}
public Expr RealDiv(Expr lhs, Expr rhs)
{
// Boogie's Type checker seems to allow operands of mixed types. I really don't like this.
// I'd much rather enforce that args being of type (int, int) or (real, real).
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must be of real or int type");
}
if (!rhs.Type.IsInt && !rhs.Type.IsReal)
{
throw new ExprTypeCheckException("rhs and rhs must be of real or int type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.RealDiv), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Real;
return result;
}
public Expr Mod(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt)
{
throw new ExprTypeCheckException("lhs and rhs must both be of int type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Mod), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Int;
return result;
}
// This is a Z3 extension and isn't a core operator in Boogie's Expr language
public Expr Rem(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt)
{
throw new ExprTypeCheckException("lhs and rhs must both be of int type");
}
// Try to get from cache
FunctionCall function = null;
try
{
function = CachedFunctions["rem"];
}
catch (KeyNotFoundException)
{
function = CreateBuiltIn("rem", "rem", BasicType.Int, new List<Microsoft.Boogie.Type>() {BasicType.Int, BasicType.Int});
CachedFunctions["rem"] = function;
}
var result = GetNAry(function, new List<Expr>() { lhs, rhs });
result.Type = BasicType.Int;
return result;
}
public Expr Pow(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of real type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Pow), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Real;
return result;
}
public Expr Neg(Expr operand)
{
if (!operand.Type.IsInt && !operand.Type.IsReal)
{
throw new ExprTypeCheckException("operand must be real or int");
}
var result = GetNAry(GetUnaryFunction(UnaryOperator.Opcode.Neg), new List<Expr>() { operand });
result.Type = operand.Type;
return result;
}
public Expr Lt(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of int type or real type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Lt), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr Le(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of int type or real type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Le), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr Gt(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of int type or real type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Gt), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
public Expr Ge(Expr lhs, Expr rhs)
{
if (!lhs.Type.Equals(rhs.Type))
{
throw new ExprTypeCheckException("lhs and rhs must be the same type");
}
if (!lhs.Type.IsInt && !lhs.Type.IsReal)
{
throw new ExprTypeCheckException("lhs and rhs must both be of int type or real type");
}
var result = GetNAry(GetBinaryFunction(BinaryOperator.Opcode.Ge), new List<Expr>() { lhs, rhs });
result.Type = BasicType.Bool;
return result;
}
private ConcurrentDictionary<ArithmeticCoercion.CoercionType, ArithmeticCoercion> ArithmeticCoercionCache = new ConcurrentDictionary<ArithmeticCoercion.CoercionType, ArithmeticCoercion>();
public Expr ArithmeticCoercion(ArithmeticCoercion.CoercionType coercionType, Expr operand)
{
Microsoft.Boogie.Type resultType = null;
switch (coercionType)
{
case Microsoft.Boogie.ArithmeticCoercion.CoercionType.ToInt:
if (!operand.Type.IsReal)
throw new ExprTypeCheckException("When coercising to int operand must be a real");
resultType = BasicType.Int;
break;
case Microsoft.Boogie.ArithmeticCoercion.CoercionType.ToReal:
if (!operand.Type.IsInt)
throw new ExprTypeCheckException("When coercising to real operand must be an int");
resultType = BasicType.Real;
break;
default:
throw new ArgumentException("coercionType not supported");
}
// Use Cache
ArithmeticCoercion coercionFun = null;
try
{
coercionFun = ArithmeticCoercionCache[coercionType];
}
catch (KeyNotFoundException)
{
coercionFun = new ArithmeticCoercion(Token.NoToken, coercionType);
ArithmeticCoercionCache[coercionType] = coercionFun;
}
var result = GetNAry(coercionFun, new List<Expr>() { operand });
result.Type = resultType;
return result;
}
private ConcurrentDictionary<int, MapSelect> MapSelectCache = new ConcurrentDictionary<int, Microsoft.Boogie.MapSelect>();
public Expr MapSelect(Expr map, params Expr[] indices)
{
if (!map.Type.IsMap)
{
throw new ExprTypeCheckException("map must be of map type");
}
if (indices.Length < 1)
{
throw new ArgumentException("Must pass at least one index");
}
if (map.Type.AsMap.MapArity != indices.Length)
{
throw new ArgumentException("the number of arguments does not match the map arity");
}
// Use Cache
MapSelect ms = null;
try
{
ms = MapSelectCache[indices.Length];
}
catch (KeyNotFoundException)
{
ms = new MapSelect(Token.NoToken, indices.Length);
MapSelectCache[indices.Length] = ms;
}
var argList = new List<Expr>() { map };
for (int index = 0; index < indices.Length; ++index)
{
argList.Add(indices[index]);
}
// Type check each argument
foreach (var typePair in map.Type.AsMap.Arguments.Zip(indices.Select( i => i.ShallowType)))
{
if (!typePair.Item1.Equals(typePair.Item2))
{
throw new ExprTypeCheckException("Map argument type mismatch. " + typePair.Item1.ToString() + " != " + typePair.Item2.ToString());
}
}
var result = GetNAry(ms, argList);
result.Type = map.Type.AsMap.Result;
return result;
}
private ConcurrentDictionary<int, MapStore> MapStoreCache = new ConcurrentDictionary<int, MapStore>();
public Expr MapStore(Expr map, Expr value, params Expr[] indices)
{
if (!map.Type.IsMap)
{
throw new ExprTypeCheckException("map must be of map type");
}
if (indices.Length < 1)
{
throw new ArgumentException("Must pass at least one index");
}
if (map.Type.AsMap.MapArity != indices.Length)
{
throw new ArgumentException("the number of arguments does not match the map arity");
}
if (!map.Type.AsMap.Result.Equals(value.Type))
{
throw new ExprTypeCheckException("value (" + value.Type.ToString() + ") must match map's result type (" + map.Type.AsMap.Result.ToString() + ")");
}
// Use Cache
MapStore ms = null;
try
{
ms = MapStoreCache[indices.Length];
}
catch (KeyNotFoundException)
{
ms = new MapStore(Token.NoToken, indices.Length);
MapStoreCache[indices.Length] = ms;
}
// Type check each argument
foreach (var typePair in map.Type.AsMap.Arguments.Zip(indices.Select( i => i.ShallowType)))
{
if (!typePair.Item1.Equals(typePair.Item2))
{
throw new ExprTypeCheckException("Map argument type mismatch. " + typePair.Item1.ToString() + " != " + typePair.Item2.ToString());
}
}
// Build the argument list
var argList = new List<Expr>() { map }; // First argument is map to add store to
for (int index = 0; index < indices.Length; ++index)
{
argList.Add(indices[index]);
}
// Now add the last argument which is the value to store
argList.Add(value);
var result = GetNAry(ms, argList);
result.Type = map.Type;
return result;
}
public Expr Old(Expr operand)
{
var result = new OldExpr(Token.NoToken, operand, Immutable);
result.Type = operand.Type;
return result;
}
public Expr ForAll(IList<Variable> freeVars, Expr body, Trigger triggers=null)
{
if (!body.Type.IsBool)
{
throw new ExprTypeCheckException("body must be of type bool");
}
if (freeVars.Count < 1)
{
throw new ArgumentException("ForAllExpr must have at least one free variable");
}
TypeCheckTriggers(freeVars, body, triggers);
// Should we check the free variables are actually used? This could be quite expensive to do!
var result = new ForallExpr(Token.NoToken, new List<Variable>(freeVars), triggers, body, Immutable);
result.Type = BasicType.Bool;
return result;
}
public Expr Exists(IList<Variable> freeVars, Expr body, Trigger triggers=null)
{
if (!body.Type.IsBool)
{
throw new ExprTypeCheckException("body must be of type bool");
}
if (freeVars.Count < 1)
{
throw new ArgumentException("ExistsExpr must have at least one free variable");
}
TypeCheckTriggers(freeVars, body, triggers);
// Should we check the free variables are actually used? This could be quite expensive to do!
var result = new ExistsExpr(Token.NoToken, new List<Variable>(freeVars), triggers, body, Immutable);
result.Type = BasicType.Bool;
return result;
}
private void TypeCheckTriggers(IList<Variable> freeVars, Expr body, Trigger triggers)
{
// TODO:
}
public Expr Distinct(IList<Expr> exprs)
{
if (exprs.Count < 1)
throw new ArgumentException("Distinct must have at least two arguments");
// Check the types
var firstType = exprs[0].Type;
if (firstType == null)
throw new ExprTypeCheckException("First argument cannot have a null Type");
for (int index = 1; index < exprs.Count; ++index)
{
if (!firstType.Equals(exprs[index].Type))
throw new ExprTypeCheckException(String.Format("The first argument and expr type at index (zero indexded) {0} do not match", index));
}
var distinctOp = new DistinctOperator(Token.NoToken, exprs.Count);
var result = new NAryExpr(Token.NoToken, distinctOp, exprs, Immutable);
result.Type = BasicType.Bool;
return result;
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NLog.Targets;
using Xunit;
using Xunit.Extensions;
public class ColoredConsoleTargetTests : NLogTestBase
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WordHighlightingTextTest(bool compileRegex)
{
var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" };
target.WordHighlightingRules.Add(
new ConsoleWordHighlightingRule
{
ForegroundColor = ConsoleOutputColor.Red,
Text = "at",
CompileRegex = compileRegex
});
AssertOutput(target, "The Cat Sat At The Bar.",
new string[] { "The C", "at", " S", "at", " At The Bar." });
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WordHighlightingTextIgnoreCase(bool compileRegex)
{
var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" };
target.WordHighlightingRules.Add(
new ConsoleWordHighlightingRule
{
ForegroundColor = ConsoleOutputColor.Red,
Text = "at",
IgnoreCase = true,
CompileRegex = compileRegex
});
AssertOutput(target, "The Cat Sat At The Bar.",
new string[] { "The C", "at", " S", "at", " ", "At", " The Bar." });
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WordHighlightingTextWholeWords(bool compileRegex)
{
var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" };
target.WordHighlightingRules.Add(
new ConsoleWordHighlightingRule
{
ForegroundColor = ConsoleOutputColor.Red,
Text = "at",
WholeWords = true,
CompileRegex = compileRegex
});
AssertOutput(target, "The cat sat at the bar.",
new string[] { "The cat sat ", "at", " the bar." });
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void WordHighlightingRegex(bool compileRegex)
{
var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" };
target.WordHighlightingRules.Add(
new ConsoleWordHighlightingRule
{
ForegroundColor = ConsoleOutputColor.Red,
Regex = "\\wat",
CompileRegex = compileRegex
});
AssertOutput(target, "The cat sat at the bar.",
new string[] { "The ", "cat", " ", "sat", " at the bar." });
}
/// <summary>
/// With or wihout CompileRegex, CompileRegex is never null, even if not used when CompileRegex=false. (needed for backwardscomp)
/// </summary>
/// <param name="compileRegex"></param>
[Theory]
[InlineData(true)]
[InlineData(false)]
public void CompiledRegexPropertyNotNull(bool compileRegex)
{
var rule = new ConsoleWordHighlightingRule
{
ForegroundColor = ConsoleOutputColor.Red,
Regex = "\\wat",
CompileRegex = compileRegex
};
Assert.NotNull(rule.CompiledRegex);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void DonRemoveIfRegexIsEmpty(bool compileRegex)
{
var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" };
target.WordHighlightingRules.Add(
new ConsoleWordHighlightingRule
{
ForegroundColor = ConsoleOutputColor.Red,
Text = null,
IgnoreCase = true,
CompileRegex = compileRegex
});
AssertOutput(target, "The Cat Sat At The Bar.",
new string[] { "The Cat Sat At The Bar." });
}
#if !NET3_5 && !MONO
[Fact]
public void ColoredConsoleRaceCondtionIgnoreTest()
{
var configXml = @"
<nlog throwExceptions='true'>
<targets>
<target name='console' type='coloredConsole' layout='${message}' />
<target name='console2' type='coloredConsole' layout='${message}' />
<target name='console3' type='coloredConsole' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='console,console2,console3' />
</rules>
</nlog>";
ConsoleTargetTests.ConsoleRaceCondtionIgnoreInnerTest(configXml);
}
#endif
private static void AssertOutput(Target target, string message, string[] expectedParts)
{
var consoleOutWriter = new PartsWriter();
TextWriter oldConsoleOutWriter = Console.Out;
Console.SetOut(consoleOutWriter);
try
{
var exceptions = new List<Exception>();
target.Initialize(null);
target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger", message).WithContinuation(exceptions.Add));
target.Close();
Assert.Single(exceptions);
Assert.True(exceptions.TrueForAll(e => e == null));
}
finally
{
Console.SetOut(oldConsoleOutWriter);
}
var expected = Enumerable.Repeat("Logger " + expectedParts[0], 1).Concat(expectedParts.Skip(1));
Assert.Equal(expected, consoleOutWriter.Values);
}
private class PartsWriter : StringWriter
{
public PartsWriter()
{
Values = new List<string>();
}
public List<string> Values { get; private set; }
public override void Write(string value)
{
Values.Add(value);
}
}
}
}
| |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Testing
{
using System.Linq;
using NUnit.Framework;
using MassTransit.Testing;
using Shouldly;
[TestFixture, Explicit]
public class Using_the_handler_test_factory
{
IHandlerTest<A> _test;
[SetUp]
public void Setup()
{
_test = TestFactory.ForHandler<A>()
.New(x =>
{
x.Send(new A());
x.Send(new B());
});
_test.Execute();
}
[TearDown]
public void Teardown()
{
_test.Dispose();
_test = null;
}
[Test]
public void Should_have_received_a_message_of_type_a()
{
_test.Received.Select<A>().Any().ShouldBe(true);
}
[Test]
public void Should_have_skipped_a_message_of_type_b()
{
_test.Skipped.Select<B>().Any().ShouldBe(true);
}
[Test]
public void Should_not_have_skipped_a_message_of_type_a()
{
_test.Skipped.Select<A>().Any().ShouldBe(false);
}
[Test]
public void Should_have_sent_a_message_of_type_a()
{
_test.Sent.Select<A>().Any().ShouldBe(true);
}
[Test]
public void Should_have_sent_a_message_of_type_b()
{
_test.Sent.Select<B>().Any().ShouldBe(true);
}
[Test]
public void Should_support_a_simple_handler()
{
_test.Handler.Received.Select().Any().ShouldBe(true);
}
class A
{
}
class B
{
}
}
[TestFixture, Explicit]
public class Using_the_handler_on_a_remote_bus
{
IHandlerTest<A> _test;
[SetUp]
public void Setup()
{
_test = TestFactory.ForHandler<A>()
.New(x =>
{
x.Send(new A());
x.Send(new B());
});
_test.Execute();
}
[TearDown]
public void Teardown()
{
_test.Dispose();
_test = null;
}
[Test]
public void Should_have_received_a_message_of_type_a()
{
_test.Received.Select<A>().Any().ShouldBe(true);
}
[Test]
public void Should_have_skipped_a_message_of_type_b()
{
_test.Skipped.Select<B>().Any().ShouldBe(true);
}
[Test]
public void Should_not_have_skipped_a_message_of_type_a()
{
_test.Skipped.Select<A>().Any().ShouldBe(false);
}
[Test]
public void Should_have_sent_a_message_of_type_a()
{
_test.Sent.Select<A>().Any().ShouldBe(true);
}
[Test]
public void Should_have_sent_a_message_of_type_b()
{
_test.Sent.Select<B>().Any().ShouldBe(true);
}
[Test]
public void Should_support_a_simple_handler()
{
_test.Handler.Received.Select().Any().ShouldBe(true);
}
class A
{
}
class B
{
}
}
[TestFixture, Explicit]
public class Publishing_to_a_handler_test
{
IHandlerTest<A> _test;
[SetUp]
public void Setup()
{
_test = TestFactory.ForHandler<A>()
.New(x =>
{
x.Publish(new A());
x.Publish(new B());
});
_test.Execute();
}
[TearDown]
public void Teardown()
{
_test.Dispose();
_test = null;
}
[Test]
public void Should_have_received_a_message_of_type_a()
{
_test.Received.Select<A>().Any().ShouldBe(true);
}
[Test]
public void Should_have_published_a_message_of_type_b()
{
_test.Published.Select<B>().Any().ShouldBe(true);
}
[Test]
public void Should_have_published_a_message_of_type_ib()
{
_test.Published.Select<IB>().Any().ShouldBe(true);
}
[Test]
public void Should_not_have_skipped_a_message_of_type_a()
{
_test.Skipped.Select<A>().Any().ShouldBe(false);
}
[Test]
public void Should_have_sent_a_message_of_type_a()
{
_test.Sent.Select<A>().Any().ShouldBe(true);
}
[Test]
public void Should_not_have_sent_a_message_of_type_b()
{
_test.Sent.Select<B>().Any().ShouldBe(false);
}
[Test]
public void Should_support_a_simple_handler()
{
_test.Handler.Received.Select().Any().ShouldBe(true);
}
class A
{
}
class B :
IB
{
}
interface IB
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Graphics.cs
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com) (stubbed out)
// Alexandre Pigolkine(pigolkine@gmx.de)
// Jordi Mas i Hernandez (jordi@ximian.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2003 Ximian, Inc. (http://www.ximian.com)
// Copyright (C) 2004-2006 Novell, Inc. (http://www.novell.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.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Drawing.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public sealed partial class Graphics : MarshalByRefObject, IDisposable, IDeviceContext
{
internal IMacContext maccontext;
private bool disposed = false;
private static float defDpiX = 0;
private static float defDpiY = 0;
internal Graphics(IntPtr nativeGraphics) => NativeGraphics = nativeGraphics;
~Graphics()
{
Dispose();
}
internal static float systemDpiX
{
get
{
if (defDpiX == 0)
{
Bitmap bmp = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bmp);
defDpiX = g.DpiX;
defDpiY = g.DpiY;
}
return defDpiX;
}
}
internal static float systemDpiY
{
get
{
if (defDpiY == 0)
{
Bitmap bmp = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bmp);
defDpiX = g.DpiX;
defDpiY = g.DpiY;
}
return defDpiY;
}
}
public void AddMetafileComment(byte[] data)
{
throw new NotImplementedException();
}
public GraphicsContainer BeginContainer()
{
int state;
int status = Gdip.GdipBeginContainer2(new HandleRef(this, NativeGraphics), out state);
Gdip.CheckStatus(status);
return new GraphicsContainer(state);
}
public GraphicsContainer BeginContainer(Rectangle dstrect, Rectangle srcrect, GraphicsUnit unit)
{
int state;
int status = Gdip.GdipBeginContainerI(new HandleRef(this, NativeGraphics), ref dstrect, ref srcrect, unit, out state);
Gdip.CheckStatus(status);
return new GraphicsContainer(state);
}
public GraphicsContainer BeginContainer(RectangleF dstrect, RectangleF srcrect, GraphicsUnit unit)
{
int state;
int status = Gdip.GdipBeginContainer(new HandleRef(this, NativeGraphics), ref dstrect, ref srcrect, unit, out state);
Gdip.CheckStatus(status);
return new GraphicsContainer(state);
}
public void CopyFromScreen(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
{
if (!Enum.IsDefined(typeof(CopyPixelOperation), copyPixelOperation))
throw new InvalidEnumArgumentException(string.Format("Enum argument value '{0}' is not valid for CopyPixelOperation", copyPixelOperation));
if (Gdip.UseX11Drawable)
{
CopyFromScreenX11(sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
}
else
{
throw new PlatformNotSupportedException();
}
}
private void CopyFromScreenX11(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
{
IntPtr window, image, defvisual, vPtr;
int AllPlanes = ~0, nitems = 0, pixel;
if (copyPixelOperation != CopyPixelOperation.SourceCopy)
throw new NotImplementedException("Operation not implemented under X11");
if (Gdip.Display == IntPtr.Zero)
{
Gdip.Display = LibX11Functions.XOpenDisplay(IntPtr.Zero);
}
window = LibX11Functions.XRootWindow(Gdip.Display, 0);
defvisual = LibX11Functions.XDefaultVisual(Gdip.Display, 0);
XVisualInfo visual = new XVisualInfo();
/* Get XVisualInfo for this visual */
visual.visualid = LibX11Functions.XVisualIDFromVisual(defvisual);
vPtr = LibX11Functions.XGetVisualInfo(Gdip.Display, 0x1 /* VisualIDMask */, ref visual, ref nitems);
visual = (XVisualInfo)Marshal.PtrToStructure(vPtr, typeof(XVisualInfo));
image = LibX11Functions.XGetImage(Gdip.Display, window, sourceX, sourceY, blockRegionSize.Width,
blockRegionSize.Height, AllPlanes, 2 /* ZPixmap*/);
if (image == IntPtr.Zero)
{
string s = string.Format("XGetImage returned NULL when asked to for a {0}x{1} region block",
blockRegionSize.Width, blockRegionSize.Height);
throw new InvalidOperationException(s);
}
Bitmap bmp = new Bitmap(blockRegionSize.Width, blockRegionSize.Height);
int red, blue, green;
int red_mask = (int)visual.red_mask;
int blue_mask = (int)visual.blue_mask;
int green_mask = (int)visual.green_mask;
for (int y = 0; y < blockRegionSize.Height; y++)
{
for (int x = 0; x < blockRegionSize.Width; x++)
{
pixel = LibX11Functions.XGetPixel(image, x, y);
switch (visual.depth)
{
case 16: /* 16bbp pixel transformation */
red = (int)((pixel & red_mask) >> 8) & 0xff;
green = (int)(((pixel & green_mask) >> 3)) & 0xff;
blue = (int)((pixel & blue_mask) << 3) & 0xff;
break;
case 24:
case 32:
red = (int)((pixel & red_mask) >> 16) & 0xff;
green = (int)(((pixel & green_mask) >> 8)) & 0xff;
blue = (int)((pixel & blue_mask)) & 0xff;
break;
default:
string text = string.Format("{0}bbp depth not supported.", visual.depth);
throw new NotImplementedException(text);
}
bmp.SetPixel(x, y, Color.FromArgb(255, red, green, blue));
}
}
DrawImage(bmp, destinationX, destinationY);
bmp.Dispose();
LibX11Functions.XDestroyImage(image);
LibX11Functions.XFree(vPtr);
}
public void Dispose()
{
int status;
if (!disposed)
{
if (_nativeHdc != IntPtr.Zero) // avoid a handle leak.
{
ReleaseHdc();
}
if (!Gdip.UseX11Drawable)
{
Flush();
if (maccontext != null)
maccontext.Release();
}
status = Gdip.GdipDeleteGraphics(new HandleRef(this, NativeGraphics));
NativeGraphics = IntPtr.Zero;
Gdip.CheckStatus(status);
disposed = true;
}
GC.SuppressFinalize(this);
}
public void DrawBeziers(Pen pen, Point[] points)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
if (points == null)
throw new ArgumentNullException(nameof(points));
int length = points.Length;
int status;
if (length < 4)
return;
for (int i = 0; i < length - 1; i += 3)
{
Point p1 = points[i];
Point p2 = points[i + 1];
Point p3 = points[i + 2];
Point p4 = points[i + 3];
status = Gdip.GdipDrawBezier(
new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
p1.X, p1.Y, p2.X, p2.Y,
p3.X, p3.Y, p4.X, p4.Y);
Gdip.CheckStatus(status);
}
}
public void DrawBeziers(Pen pen, PointF[] points)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
if (points == null)
throw new ArgumentNullException(nameof(points));
int length = points.Length;
int status;
if (length < 4)
return;
for (int i = 0; i < length - 1; i += 3)
{
PointF p1 = points[i];
PointF p2 = points[i + 1];
PointF p3 = points[i + 2];
PointF p4 = points[i + 3];
status = Gdip.GdipDrawBezier(
new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
p1.X, p1.Y, p2.X, p2.Y,
p3.X, p3.Y, p4.X, p4.Y);
Gdip.CheckStatus(status);
}
}
public void DrawIcon(Icon icon, Rectangle targetRect)
{
if (icon == null)
throw new ArgumentNullException(nameof(icon));
DrawImage(icon.GetInternalBitmap(), targetRect);
}
public void DrawIcon(Icon icon, int x, int y)
{
if (icon == null)
throw new ArgumentNullException(nameof(icon));
DrawImage(icon.GetInternalBitmap(), x, y);
}
public void DrawIconUnstretched(Icon icon, Rectangle targetRect)
{
if (icon == null)
throw new ArgumentNullException(nameof(icon));
DrawImageUnscaled(icon.GetInternalBitmap(), targetRect);
}
public void DrawLine(Pen pen, float x1, float y1, float x2, float y2)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
if (!float.IsNaN(x1) && !float.IsNaN(y1) &&
!float.IsNaN(x2) && !float.IsNaN(y2))
{
int status = Gdip.GdipDrawLine(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2);
Gdip.CheckStatus(status);
}
}
public void EndContainer(GraphicsContainer container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
int status = Gdip.GdipEndContainer(new HandleRef(this, NativeGraphics), container.nativeGraphicsContainer);
Gdip.CheckStatus(status);
}
public void EnumerateMetafile(Metafile metafile, RectangleF destRect, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, Point destPoint, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, PointF destPoint, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, Point[] destPoints, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, Rectangle destRect, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, Point[] destPoints, Rectangle srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, Rectangle destRect, Rectangle srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, Point destPoint, Rectangle srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, RectangleF destRect, RectangleF srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints, RectangleF srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void EnumerateMetafile(Metafile metafile, PointF destPoint, RectangleF srcRect, GraphicsUnit unit, EnumerateMetafileProc callback, IntPtr callbackData, ImageAttributes imageAttr)
{
throw new NotImplementedException();
}
public void FillPath(Brush brush, GraphicsPath path)
{
if (brush == null)
throw new ArgumentNullException(nameof(brush));
if (path == null)
throw new ArgumentNullException(nameof(path));
int status = Gdip.GdipFillPath(NativeGraphics, brush.NativeBrush, path._nativePath);
Gdip.CheckStatus(status);
}
public void FillRegion(Brush brush, Region region)
{
if (brush == null)
throw new ArgumentNullException(nameof(brush));
if (region == null)
throw new ArgumentNullException(nameof(region));
int status = (int)Gdip.GdipFillRegion(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), new HandleRef(region, region.NativeRegion));
Gdip.CheckStatus(status);
}
private void FlushCore() => maccontext?.Synchronize();
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Graphics FromHdc(IntPtr hdc)
{
IntPtr graphics;
int status = Gdip.GdipCreateFromHDC(hdc, out graphics);
Gdip.CheckStatus(status);
return new Graphics(graphics);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Graphics FromHdc(IntPtr hdc, IntPtr hdevice)
{
throw new NotImplementedException();
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Graphics FromHdcInternal(IntPtr hdc)
{
Gdip.Display = hdc;
return null;
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Graphics FromHwnd(IntPtr hwnd)
{
IntPtr graphics;
if (!Gdip.UseX11Drawable)
{
CarbonContext context = MacSupport.GetCGContextForView(hwnd);
Gdip.GdipCreateFromContext_macosx(context.ctx, context.width, context.height, out graphics);
Graphics g = new Graphics(graphics);
g.maccontext = context;
return g;
}
else
{
if (Gdip.Display == IntPtr.Zero)
{
Gdip.Display = LibX11Functions.XOpenDisplay(IntPtr.Zero);
if (Gdip.Display == IntPtr.Zero)
throw new NotSupportedException("Could not open display (X-Server required. Check your DISPLAY environment variable)");
}
if (hwnd == IntPtr.Zero)
{
hwnd = LibX11Functions.XRootWindow(Gdip.Display, LibX11Functions.XDefaultScreen(Gdip.Display));
}
return FromXDrawable(hwnd, Gdip.Display);
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Graphics FromHwndInternal(IntPtr hwnd)
{
return FromHwnd(hwnd);
}
public static Graphics FromImage(Image image)
{
IntPtr graphics;
if (image == null)
throw new ArgumentNullException(nameof(image));
if ((image.PixelFormat & PixelFormat.Indexed) != 0)
throw new ArgumentException("Cannot create Graphics from an indexed bitmap.", nameof(image));
int status = Gdip.GdipGetImageGraphicsContext(image.nativeImage, out graphics);
Gdip.CheckStatus(status);
Graphics result = new Graphics(graphics);
Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
Gdip.GdipSetVisibleClip_linux(result.NativeGraphics, ref rect);
return result;
}
internal static Graphics FromXDrawable(IntPtr drawable, IntPtr display)
{
IntPtr graphics;
int s = Gdip.GdipCreateFromXDrawable_linux(drawable, display, out graphics);
Gdip.CheckStatus(s);
return new Graphics(graphics);
}
public static IntPtr GetHalftonePalette()
{
throw new NotImplementedException();
}
public Color GetNearestColor(Color color)
{
int argb;
int status = Gdip.GdipGetNearestColor(NativeGraphics, out argb);
Gdip.CheckStatus(status);
return Color.FromArgb(argb);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void ReleaseHdcInternal(IntPtr hdc)
{
int status = Gdip.InvalidParameter;
if (hdc == _nativeHdc)
{
status = Gdip.GdipReleaseDC(new HandleRef(this, NativeGraphics), new HandleRef(this, _nativeHdc));
_nativeHdc = IntPtr.Zero;
}
Gdip.CheckStatus(status);
}
public void Restore(GraphicsState gstate)
{
// the possible NRE thrown by gstate.nativeState match MS behaviour
int status = Gdip.GdipRestoreGraphics(NativeGraphics, (uint)gstate.nativeState);
Gdip.CheckStatus(status);
}
public GraphicsState Save()
{
int status = Gdip.GdipSaveGraphics(new HandleRef(this, NativeGraphics), out int state);
Gdip.CheckStatus(status);
return new GraphicsState((int)state);
}
public RectangleF VisibleClipBounds
{
get
{
int status = Gdip.GdipGetVisibleClipBounds(new HandleRef(this, NativeGraphics), out RectangleF rect);
Gdip.CheckStatus(status);
return rect;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
public object GetContextInfo()
{
// only known source of information @ http://blogs.wdevs.com/jdunlap/Default.aspx
throw new NotImplementedException();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.libc.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.libc.MaxName; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and
// has varying degrees of support on different systems.
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
const int bufferSize = FileStream.DefaultBufferSize;
const bool useAsync = false;
using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync))
using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
src.CopyTo(dst);
}
// Now copy over relevant read/write/execute permissions from the source to the destination
Interop.libcoreclr.fileinfo fileinfo;
while (Interop.CheckIo(Interop.libcoreclr.GetFileInformationFromPath(sourceFullPath, out fileinfo), sourceFullPath)) ;
int newMode = fileinfo.mode & (int)Interop.libc.Permissions.Mask;
while (Interop.CheckIo(Interop.libc.chmod(destFullPath, newMode), destFullPath)) ;
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
// The desired behavior for Move(source, dest) is to not overwrite the destination file
// if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,
// a check is added before rename is called. Note that this is a race condition. Possible
// better solutions would be to use link/unlink or platform specific functions instead of
// rename(source, dest). Regardless of the implementation, an IOException should be thrown if
// 'dest' refers to a file that already exists.
if (File.Exists(destFullPath))
throw new IOException(SR.GetResourceString(SR.IO_AlreadyExists_Name, destFullPath));
while (Interop.libc.rename(sourceFullPath, destFullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
if (errno == Interop.Errors.EINTR) // interrupted; try again
{
continue;
}
else if (errno == Interop.Errors.EXDEV) // link fails across devices / mount points
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
break;
}
//else if (errno == Interop.Errors.ENOENT && (!Directory.Exists(Path.GetDirectoryName(sourceFullPath)) || !Directory.Exists(Path.GetDirectoryName(destFullPath)))) // The parent directory for either source or dest can't be found
else if (errno == Interop.Errors.ENOENT && !Directory.Exists(Path.GetDirectoryName(destFullPath))) // The parent directory of destFile can't be found
{
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
throw Interop.GetExceptionForIoErrno(errno, destFullPath, isDirectory: true);
}
else
{
throw Interop.GetExceptionForIoErrno(errno);
}
}
}
public override void DeleteFile(string fullPath)
{
while (Interop.libc.unlink(fullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
if (errno == Interop.Errors.EINTR) // interrupted; try again
{
continue;
}
else if (errno == Interop.Errors.ENOENT) // already doesn't exist; nop
{
break;
}
else
{
if (errno == Interop.Errors.EISDIR)
errno = Interop.Errors.EACCES;
throw Interop.GetExceptionForIoErrno(errno, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Errors.ENOENT, fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
int firstError = 0;
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
int errno = 0;
while ((result = Interop.libc.mkdir(name, (int)Interop.libc.Permissions.S_IRWXU)) < 0 && (errno = Marshal.GetLastWin32Error()) == Interop.Errors.EINTR) ;
if (result < 0 && firstError == 0)
{
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errno != Interop.Errors.EEXIST)
{
firstError = errno;
}
else if (FileExists(name) || (!DirectoryExists(name, out errno) && errno == Interop.Errors.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errno;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
while (Interop.libc.rename(sourceFullPath, destFullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
switch (errno)
{
case Interop.Errors.EINTR: // interrupted; try again
continue;
case Interop.Errors.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errno);
default:
throw Interop.GetExceptionForIoErrno(errno, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
if (!DirectoryExists(fullPath))
{
throw Interop.GetExceptionForIoErrno(Interop.Errors.ENOENT, fullPath, isDirectory: true);
}
RemoveDirectoryInternal(fullPath, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
if (DirectoryExists(item))
{
RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
while (Interop.libc.rmdir(fullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
switch (errno)
{
case Interop.Errors.EINTR: // interrupted; try again
continue;
case Interop.Errors.EACCES:
case Interop.Errors.EPERM:
case Interop.Errors.EROFS:
case Interop.Errors.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // match Win32 exception
case Interop.Errors.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errno, fullPath, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
int errno;
return DirectoryExists(fullPath, out errno);
}
private static bool DirectoryExists(string fullPath, out int errno)
{
return FileExists(fullPath, Interop.libcoreclr.FileTypes.S_IFDIR, out errno);
}
public override bool FileExists(string fullPath)
{
int errno;
return FileExists(fullPath, Interop.libcoreclr.FileTypes.S_IFREG, out errno);
}
private static bool FileExists(string fullPath, int fileType, out int errno)
{
Interop.libcoreclr.fileinfo fileinfo;
while (true)
{
errno = 0;
int result = Interop.libcoreclr.GetFileInformationFromPath(fullPath, out fileinfo);
if (result < 0)
{
errno = Marshal.GetLastWin32Error();
if (errno == Interop.Errors.EINTR)
{
continue;
}
return false;
}
return (fileinfo.mode & Interop.libcoreclr.FileTypes.S_IFMT) == fileType;
}
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, new UnixFileSystemObject(path, isDir)));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, new UnixFileSystemObject(path, isDir)));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, new UnixFileSystemObject(path, isDir)) :
(FileSystemInfo)new FileInfo(path, new UnixFileSystemObject(path, isDir)));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Interop.libc.SafeDirHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
IntPtr curEntry;
while ((curEntry = Interop.libc.readdir(dirHandle)) != IntPtr.Zero) // no validation needed for readdir
{
string name = Interop.libc.GetDirEntName(curEntry);
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory,
// e.g. a FIFO will be classified as a file.
bool isDir;
switch (Interop.libc.GetDirEntType(curEntry))
{
case Interop.libc.DType.DT_DIR:
// We know it's a directory.
isDir = true;
break;
case Interop.libc.DType.DT_LNK:
case Interop.libc.DType.DT_UNKNOWN:
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g.symlink to a file, broken symlink, etc.), we'll just treat it as a file.
int errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, name), out errnoIgnored);
break;
default:
// Otherwise, treat it as a file. This includes regular files,
// FIFOs, etc.
isDir = false;
break;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(name))
{
if (_includeDirectories &&
Interop.libc.fnmatch(_searchPattern, name, Interop.libc.FnmatchFlags.None) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, name), /*isDirectory*/true);
}
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
toExplore.Push(new PathPair(Path.Combine(dirPath.UserPath, name), Path.Combine(dirPath.FullPath, name)));
}
}
}
else if (_includeFiles &&
Interop.libc.fnmatch(_searchPattern, name, Interop.libc.FnmatchFlags.None) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, name), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Interop.libc.SafeDirHandle OpenDirectory(string fullPath)
{
Interop.libc.SafeDirHandle handle = Interop.libc.opendir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Marshal.GetLastWin32Error(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.libc.getcwd();
}
public override void SetCurrentDirectory(string fullPath)
{
while (Interop.CheckIo(Interop.libc.chdir(fullPath), fullPath)) ;
}
public override FileAttributes GetAttributes(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new UnixFileSystemObject(fullPath, false).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return new UnixFileSystemObject(fullPath, asDirectory);
}
}
}
| |
using GitVersion.Helpers;
using GitVersion.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using YamlDotNet.Serialization;
using static GitVersion.Extensions.ObjectExtensions;
namespace GitVersion.OutputVariables
{
public class VersionVariables : IEnumerable<KeyValuePair<string, string>>
{
public VersionVariables(string major,
string minor,
string patch,
string buildMetaData,
string buildMetaDataPadded,
string fullBuildMetaData,
string branchName,
string escapedBranchName,
string sha,
string shortSha,
string majorMinorPatch,
string semVer,
string legacySemVer,
string legacySemVerPadded,
string fullSemVer,
string assemblySemVer,
string assemblySemFileVer,
string preReleaseTag,
string preReleaseTagWithDash,
string preReleaseLabel,
string preReleaseLabelWithDash,
string preReleaseNumber,
string weightedPreReleaseNumber,
string informationalVersion,
string commitDate,
string nugetVersion,
string nugetVersionV2,
string nugetPreReleaseTag,
string nugetPreReleaseTagV2,
string versionSourceSha,
string commitsSinceVersionSource,
string commitsSinceVersionSourcePadded,
string uncommittedChanges)
{
Major = major;
Minor = minor;
Patch = patch;
BuildMetaData = buildMetaData;
BuildMetaDataPadded = buildMetaDataPadded;
FullBuildMetaData = fullBuildMetaData;
BranchName = branchName;
EscapedBranchName = escapedBranchName;
Sha = sha;
ShortSha = shortSha;
MajorMinorPatch = majorMinorPatch;
SemVer = semVer;
LegacySemVer = legacySemVer;
LegacySemVerPadded = legacySemVerPadded;
FullSemVer = fullSemVer;
AssemblySemVer = assemblySemVer;
AssemblySemFileVer = assemblySemFileVer;
PreReleaseTag = preReleaseTag;
PreReleaseTagWithDash = preReleaseTagWithDash;
PreReleaseLabel = preReleaseLabel;
PreReleaseLabelWithDash = preReleaseLabelWithDash;
PreReleaseNumber = preReleaseNumber;
WeightedPreReleaseNumber = weightedPreReleaseNumber;
InformationalVersion = informationalVersion;
CommitDate = commitDate;
NuGetVersion = nugetVersion;
NuGetVersionV2 = nugetVersionV2;
NuGetPreReleaseTag = nugetPreReleaseTag;
NuGetPreReleaseTagV2 = nugetPreReleaseTagV2;
VersionSourceSha = versionSourceSha;
CommitsSinceVersionSource = commitsSinceVersionSource;
CommitsSinceVersionSourcePadded = commitsSinceVersionSourcePadded;
UncommittedChanges = uncommittedChanges;
}
public string Major { get; }
public string Minor { get; }
public string Patch { get; }
public string PreReleaseTag { get; }
public string PreReleaseTagWithDash { get; }
public string PreReleaseLabel { get; }
public string PreReleaseLabelWithDash { get; }
public string PreReleaseNumber { get; }
public string WeightedPreReleaseNumber { get; }
public string BuildMetaData { get; }
public string BuildMetaDataPadded { get; }
public string FullBuildMetaData { get; }
public string MajorMinorPatch { get; }
public string SemVer { get; }
public string LegacySemVer { get; }
public string LegacySemVerPadded { get; }
public string AssemblySemVer { get; }
public string AssemblySemFileVer { get; }
public string FullSemVer { get; }
public string InformationalVersion { get; }
public string BranchName { get; }
public string EscapedBranchName { get; }
public string Sha { get; }
public string ShortSha { get; }
public string NuGetVersionV2 { get; }
public string NuGetVersion { get; }
public string NuGetPreReleaseTagV2 { get; }
public string NuGetPreReleaseTag { get; }
public string VersionSourceSha { get; }
public string CommitsSinceVersionSource { get; }
public string CommitsSinceVersionSourcePadded { get; }
public string UncommittedChanges { get; }
public string CommitDate { get; set; }
[ReflectionIgnore]
public static IEnumerable<string> AvailableVariables
{
get
{
return typeof(VersionVariables)
.GetProperties()
.Where(p => !p.GetCustomAttributes(typeof(ReflectionIgnoreAttribute), false).Any())
.Select(p => p.Name)
.OrderBy(a => a, StringComparer.Ordinal);
}
}
[ReflectionIgnore]
public string FileName { get; set; }
[ReflectionIgnore]
public string this[string variable] => typeof(VersionVariables).GetProperty(variable)?.GetValue(this, null) as string;
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return this.GetProperties().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public static VersionVariables FromDictionary(IEnumerable<KeyValuePair<string, string>> properties)
{
var type = typeof(VersionVariables);
var constructors = type.GetConstructors();
var ctor = constructors.Single();
var ctorArgs = ctor.GetParameters()
.Select(p => properties.Single(v => string.Equals(v.Key, p.Name, StringComparison.InvariantCultureIgnoreCase)).Value)
.Cast<object>()
.ToArray();
return (VersionVariables)Activator.CreateInstance(type, ctorArgs);
}
public static VersionVariables FromJson(string json)
{
var serializeOptions = JsonSerializerOptions();
var variablePairs = JsonSerializer.Deserialize<Dictionary<string, string>>(json, serializeOptions);
return FromDictionary(variablePairs);
}
public static VersionVariables FromFile(string filePath, IFileSystem fileSystem, ILog log)
{
try
{
if (log == null)
{
return FromFileInternal(filePath, fileSystem);
}
var retryAction = new RetryAction<IOException, VersionVariables>();
return retryAction.Execute(() => FromFileInternal(filePath, fileSystem));
}
catch (AggregateException ex)
{
var lastException = ex.InnerExceptions?.LastOrDefault() ?? ex.InnerException;
if (lastException != null)
{
throw lastException;
}
throw;
}
}
private static VersionVariables FromFileInternal(string filePath, IFileSystem fileSystem)
{
using var stream = fileSystem.OpenRead(filePath);
using var reader = new StreamReader(stream);
var dictionary = new Deserializer().Deserialize<Dictionary<string, string>>(reader);
var versionVariables = FromDictionary(dictionary);
versionVariables.FileName = filePath;
return versionVariables;
}
public bool TryGetValue(string variable, out string variableValue)
{
if (ContainsKey(variable))
{
variableValue = this[variable];
return true;
}
variableValue = null;
return false;
}
private static bool ContainsKey(string variable)
{
return typeof(VersionVariables).GetProperty(variable) != null;
}
public override string ToString()
{
var variablesType = typeof(VersionVariablesJsonModel);
var variables = new VersionVariablesJsonModel();
foreach (KeyValuePair<string, string> property in this.GetProperties())
{
variablesType.GetProperty(property.Key).SetValue(variables, property.Value);
}
var serializeOptions = JsonSerializerOptions();
return JsonSerializer.Serialize(variables, serializeOptions);
}
private static JsonSerializerOptions JsonSerializerOptions()
{
var serializeOptions = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
Converters = { new VersionVariablesJsonStringConverter() }
};
return serializeOptions;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using DotVVM.Framework.Compilation.Parser.Dothtml.Parser;
using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer;
using DotVVM.Framework.Controls;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace DotVVM.Framework.Tools.SeleniumGenerator.Generators
{
public abstract class SeleniumGenerator<TControl> : ISeleniumGenerator where TControl : DotvvmControl
{
/// <summary>
/// Gets a list of properties that can be used to determine the control name.
/// </summary>
public abstract DotvvmProperty[] NameProperties { get; }
/// <summary>
/// Gets a value indicating whether the content of the control can be used to generate the control name.
/// </summary>
public abstract bool CanUseControlContentForName { get; }
/// <summary>
/// Gets a list of declarations emitted by the control.
/// </summary>
public void AddDeclarations(HelperDefinition helper, SeleniumGeneratorContext context)
{
// determine the name
var uniqueName = DetermineName(context);
// make the name unique
if (context.UsedNames.Contains(uniqueName))
{
var index = 1;
while (context.UsedNames.Contains(uniqueName + index))
{
index++;
}
uniqueName = uniqueName + index;
}
context.UsedNames.Add(uniqueName);
context.UniqueName = uniqueName;
// determine the selector
var selector = TryGetNameFromProperty(context.Control, UITests.NameProperty);
if (selector == null)
{
selector = uniqueName;
AddUITestNameProperty(helper, context, uniqueName);
}
context.Selector = selector;
AddDeclarationsCore(helper, context);
}
public virtual bool CanAddDeclarations(HelperDefinition helperDefinition, SeleniumGeneratorContext context)
{
return true;
}
private void AddUITestNameProperty(HelperDefinition helper, SeleniumGeneratorContext context, string uniqueName)
{
// find end of the tag
var token = context.Control.DothtmlNode.Tokens.First(t => t.Type == DothtmlTokenType.CloseTag || t.Type == DothtmlTokenType.Slash);
helper.MarkupFileModifications.Add(new MarkupFileInsertText()
{
Text = " UITests.Name=\"" + uniqueName + "\"",
Position = token.StartPosition
});
}
protected virtual string DetermineName(SeleniumGeneratorContext context)
{
// get the name from the UITest.Name property
var uniqueName = TryGetNameFromProperty(context.Control, UITests.NameProperty);
// if not found, use the name properties to determine the name
if (uniqueName == null)
{
foreach (var nameProperty in NameProperties)
{
uniqueName = TryGetNameFromProperty(context.Control, nameProperty);
if (uniqueName != null)
{
break;
}
}
}
// if not found, try to use the content of the control to determine the name
if (uniqueName == null && CanUseControlContentForName)
{
uniqueName = GetTextFromContent(context.Control.Content);
}
// if not found, use control name
if (uniqueName == null)
{
uniqueName = typeof(TControl).Name;
}
return uniqueName;
}
protected string TryGetNameFromProperty(ResolvedControl control, DotvvmProperty property)
{
IAbstractPropertySetter setter;
if (control.TryGetProperty(property, out setter))
{
if (setter is ResolvedPropertyValue)
{
return RemoveNonIdentifierCharacters(((ResolvedPropertyValue) setter).Value?.ToString());
}
else if (setter is ResolvedPropertyBinding)
{
var binding = ((ResolvedPropertyBinding) setter).Binding;
return RemoveNonIdentifierCharacters(binding.Value);
}
}
return null;
}
private string RemoveNonIdentifierCharacters(string value)
{
var sb = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
if (char.IsLetterOrDigit(value[i]) || value[i] == '_')
{
sb.Append(value[i]);
}
}
if (sb.Length == 0)
{
return null;
}
else if (char.IsDigit(sb[0]))
{
sb.Insert(0, '_');
}
return sb.ToString();
}
private string GetTextFromContent(IEnumerable<ResolvedControl> controls)
{
var sb = new StringBuilder();
foreach (var control in controls)
{
if (control.Metadata.Type == typeof(Literal))
{
sb.Append(TryGetNameFromProperty(control, Literal.TextProperty));
}
else if (control.Metadata.Type == typeof(HtmlGenericControl))
{
sb.Append(TryGetNameFromProperty(control, HtmlGenericControl.InnerTextProperty));
}
}
// ensure the text is not too long
var text = RemoveNonIdentifierCharacters(sb.ToString());
if (text?.Length > 20)
{
text = text.Substring(0, 20);
}
return text;
}
private static TypeSyntax ParseTypeName(string typeName, params string[] genericTypeNames)
{
if (genericTypeNames.Length == 0)
{
return SyntaxFactory.ParseTypeName(typeName);
}
else
{
return SyntaxFactory.GenericName(typeName)
.WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(
genericTypeNames.Select(n => SyntaxFactory.ParseTypeName(n)))
));
}
}
protected MemberDeclarationSyntax GeneratePropertyForProxy(SeleniumGeneratorContext context, string typeName, params string[] genericTypeNames)
{
return SyntaxFactory.PropertyDeclaration(
ParseTypeName(typeName, genericTypeNames),
context.UniqueName
)
.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.AddAccessorListAccessors(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
);
}
protected StatementSyntax GenerateInitializerForProxy(SeleniumGeneratorContext context, string propertyName, string typeName, params string[] genericTypeNames)
{
return SyntaxFactory.ExpressionStatement(
SyntaxFactory.AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
SyntaxFactory.IdentifierName(propertyName),
SyntaxFactory.ObjectCreationExpression(ParseTypeName(typeName, genericTypeNames))
.WithArgumentList(
SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new[]
{
SyntaxFactory.Argument(SyntaxFactory.ThisExpression()),
SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(context.Selector)))
}))
)
)
);
}
protected abstract void AddDeclarationsCore(HelperDefinition helper, SeleniumGeneratorContext context);
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Sce.Atf;
using Sce.Sled.Shared.Document;
using Sce.Sled.Shared.Services;
namespace Sce.Sled
{
public partial class SledModifiedFilesForm : Form
{
public SledModifiedFilesForm()
{
InitializeComponent();
}
public new void Show()
{
Show(null);
}
public new void Show(IWin32Window owner)
{
// TODO: Enable this code once we figure out
// TODO: why SLED gets stuck minimized...
// TODO: StateMachine Editor uses the same code
// TODO: but doesn't have the stuck-minimized issue.
//if (owner != null)
//{
// var ownerForm = FromHandle(owner.Handle) as Form;
// if ((ownerForm != null) && (ownerForm.WindowState == FormWindowState.Minimized))
// WindowState = FormWindowState.Minimized;
//}
if (!Visible)
base.Show(owner);
else
Activate();
}
public void AddFile(ISledDocument sd)
{
lock (m_lock)
{
if (m_lstFiles.Contains(sd))
return;
// Add to collection
m_lstFiles.Add(sd);
// Add to list box
m_lstBoxFiles.Items.Add(new SledModifiedFilesFormItem(sd));
// Select first item added
if (m_lstBoxFiles.Items.Count == 1)
m_lstBoxFiles.SelectedIndex = 0;
}
}
public int Count
{
get
{
lock (m_lock)
{
return m_lstFiles.Count;
}
}
}
public event EventHandler<SledFileWatcherServiceEventArgs> ReloadFileEvent;
public event EventHandler<SledFileWatcherServiceEventArgs> IgnoreFileEvent;
#region Form Events
private void SledModifiedFilesFormFormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
BtnIgnoreAllClick(sender, EventArgs.Empty);
}
private void BtnReloadClick(object sender, EventArgs e)
{
lock (m_lock)
{
if (m_lstBoxFiles.SelectedItem == null)
return;
var iIndex = m_lstBoxFiles.SelectedIndex;
var item = (SledModifiedFilesFormItem)m_lstBoxFiles.SelectedItem;
ReloadFile(item);
RemoveFile(item);
SelectNext(iIndex);
if (m_lstBoxFiles.Items.Count <= 0)
Hide();
}
}
private void BtnIgnoreClick(object sender, EventArgs e)
{
lock (m_lock)
{
if (m_lstBoxFiles.SelectedItem == null)
return;
var iIndex = m_lstBoxFiles.SelectedIndex;
var item = (SledModifiedFilesFormItem)m_lstBoxFiles.SelectedItem;
IgnoreFile(item);
RemoveFile(item);
SelectNext(iIndex);
if (m_lstBoxFiles.Items.Count <= 0)
Hide();
}
}
private void BtnReloadAllClick(object sender, EventArgs e)
{
lock (m_lock)
{
while (m_lstBoxFiles.Items.Count > 0)
{
var item = (SledModifiedFilesFormItem)m_lstBoxFiles.Items[0];
ReloadFile(item);
RemoveFile(item);
}
Hide();
}
}
private void BtnIgnoreAllClick(object sender, EventArgs e)
{
lock (m_lock)
{
while (m_lstBoxFiles.Items.Count > 0)
{
var item = (SledModifiedFilesFormItem)m_lstBoxFiles.Items[0];
IgnoreFile(item);
RemoveFile(item);
}
Hide();
}
}
#endregion
private void ReloadFile(SledModifiedFilesFormItem item)
{
lock (m_lock)
{
ReloadFileEvent.Raise(this, new SledFileWatcherServiceEventArgs(item.SledDocument));
}
}
private void IgnoreFile(SledModifiedFilesFormItem item)
{
lock (m_lock)
{
IgnoreFileEvent.Raise(this, new SledFileWatcherServiceEventArgs(item.SledDocument));
}
}
private void RemoveFile(SledModifiedFilesFormItem item)
{
lock (m_lock)
{
m_lstFiles.Remove(item.SledDocument);
m_lstBoxFiles.Items.Remove(item);
}
}
private void SelectNext(int iIndex)
{
if (m_lstBoxFiles.Items.Count <= 0)
return;
if (m_lstBoxFiles.Items.Count <= iIndex)
iIndex--;
m_lstBoxFiles.SelectedIndex = iIndex;
}
#region Private Class SledModifiedFilesFormItem
private class SledModifiedFilesFormItem
{
public SledModifiedFilesFormItem(ISledDocument sd)
{
m_sledDocument = sd;
}
public ISledDocument SledDocument
{
get { return m_sledDocument; }
}
public override string ToString()
{
return m_sledDocument.Uri.LocalPath;
}
private readonly ISledDocument m_sledDocument;
}
#endregion
private volatile object m_lock =
new object();
private readonly IList<ISledDocument> m_lstFiles =
new List<ISledDocument>();
}
}
| |
using UnityEngine;
namespace Pathfinding {
//Mem - 4+1+4+1+[4]+[4]+1+1+4+4+4+4+4+ 12+12+12+12+12+12+4+4+4+4+4+1+1+(4)+4+4+4+4+4+4+4 ? 166 bytes
/** Basic path, finds the shortest path from A to B.
* \ingroup paths
* This is the most basic path object it will try to find the shortest path from A to B.\n
* Many other path types inherit from this type.
* \see Seeker.StartPath
*/
public class ABPath : Path {
/** Defines if start and end nodes will have their connection costs recalculated for this path.
* These connection costs will be more accurate and based on the exact start point and target point,
* however it should not be used when connection costs are not the default ones (all build in graph generators currently generate default connection costs).
* \see Int3.costMagnitude
* \since Added in 3.0.8.3
* \bug Does not do anything in 3.2 and up due to incompabilities with multithreading. Will be enabled again in later versions.
*/
public bool recalcStartEndCosts = true;
/** Start node of the path */
public GraphNode startNode;
/** End node of the path */
public GraphNode endNode;
/** Hints can be set to enable faster Get Nearest Node queries. Only applies to some graph types */
public GraphNode startHint;
/** Hints can be set to enable faster Get Nearest Node queries. Only applies to some graph types */
public GraphNode endHint;
/** Start Point exactly as in the path request */
public Vector3 originalStartPoint;
/** End Point exactly as in the path request */
public Vector3 originalEndPoint;
/** Start point of the path.
* This is the closest point on the #startNode to #originalStartPoint
*/
public Vector3 startPoint;
/** End point of the path.
* This is the closest point on the #endNode to #originalEndPoint
*/
public Vector3 endPoint;
/** Determines if a search for an end node should be done.
* Set by different path types.
* \since Added in 3.0.8.3
*/
protected virtual bool hasEndPoint {
get {
return true;
}
}
public Int3 startIntPoint; /**< Start point in integer coordinates */
/** Calculate partial path if the target node cannot be reached.
* If the target node cannot be reached, the node which was closest (given by heuristic) will be chosen as target node
* and a partial path will be returned.
* This only works if a heuristic is used (which is the default).
* If a partial path is found, CompleteState is set to Partial.
* \note It is not required by other path types to respect this setting
*
* \warning This feature is currently a work in progress and may not work in the current version
*/
public bool calculatePartial;
/** Current best target for the partial path.
* This is the node with the lowest H score.
* \warning This feature is currently a work in progress and may not work in the current version
*/
protected PathNode partialBestTarget;
/** Saved original costs for the end node. \see ResetCosts */
protected int[] endNodeCosts;
/** @{ @name Constructors */
/** Default constructor.
* Do not use this. Instead use the static Construct method which can handle path pooling.
*/
public ABPath () {}
/** Construct a path with a start and end point.
* The delegate will be called when the path has been calculated.
* Do not confuse it with the Seeker callback as they are sent at different times.
* If you are using a Seeker to start the path you can set \a callback to null.
*
* \returns The constructed path object
*/
public static ABPath Construct (Vector3 start, Vector3 end, OnPathDelegate callback = null) {
var p = PathPool.GetPath<ABPath>();
p.Setup(start, end, callback);
return p;
}
protected void Setup (Vector3 start, Vector3 end, OnPathDelegate callbackDelegate) {
callback = callbackDelegate;
UpdateStartEnd(start, end);
}
/** @} */
/** Sets the start and end points.
* Sets #originalStartPoint, #originalEndPoint, #startPoint, #endPoint, #startIntPoint and #hTarget (to \a end ) */
protected void UpdateStartEnd (Vector3 start, Vector3 end) {
originalStartPoint = start;
originalEndPoint = end;
startPoint = start;
endPoint = end;
startIntPoint = (Int3)start;
hTarget = (Int3)end;
}
public override uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
if (startNode != null && endNode != null) {
if (a == startNode) {
return (uint)((startIntPoint - (b == endNode ? hTarget : b.position)).costMagnitude * (currentCost*1.0/(a.position-b.position).costMagnitude));
}
if (b == startNode) {
return (uint)((startIntPoint - (a == endNode ? hTarget : a.position)).costMagnitude * (currentCost*1.0/(a.position-b.position).costMagnitude));
}
if (a == endNode) {
return (uint)((hTarget - b.position).costMagnitude * (currentCost*1.0/(a.position-b.position).costMagnitude));
}
if (b == endNode) {
return (uint)((hTarget - a.position).costMagnitude * (currentCost*1.0/(a.position-b.position).costMagnitude));
}
} else {
// endNode is null, startNode should never be null for an ABPath
if (a == startNode) {
return (uint)((startIntPoint - b.position).costMagnitude * (currentCost*1.0/(a.position-b.position).costMagnitude));
}
if (b == startNode) {
return (uint)((startIntPoint - a.position).costMagnitude * (currentCost*1.0/(a.position-b.position).costMagnitude));
}
}
return currentCost;
}
/** Reset all values to their default values.
* All inheriting path types must implement this function, resetting ALL their variables to enable recycling of paths.
* Call this base function in inheriting types with base.Reset ();
*/
public override void Reset () {
base.Reset();
startNode = null;
endNode = null;
startHint = null;
endHint = null;
originalStartPoint = Vector3.zero;
originalEndPoint = Vector3.zero;
startPoint = Vector3.zero;
endPoint = Vector3.zero;
calculatePartial = false;
partialBestTarget = null;
startIntPoint = new Int3();
hTarget = new Int3();
endNodeCosts = null;
}
/** Prepares the path. Searches for start and end nodes and does some simple checking if a path is at all possible */
public override void Prepare () {
AstarProfiler.StartProfile("Get Nearest");
//Initialize the NNConstraint
nnConstraint.tags = enabledTags;
NNInfo startNNInfo = AstarPath.active.GetNearest(startPoint, nnConstraint, startHint);
//Tell the NNConstraint which node was found as the start node if it is a PathNNConstraint and not a normal NNConstraint
var pathNNConstraint = nnConstraint as PathNNConstraint;
if (pathNNConstraint != null) {
pathNNConstraint.SetStart(startNNInfo.node);
}
startPoint = startNNInfo.clampedPosition;
startIntPoint = (Int3)startPoint;
startNode = startNNInfo.node;
//If it is declared that this path type has an end point
//Some path types might want to use most of the ABPath code, but will not have an explicit end point at this stage
if (hasEndPoint) {
NNInfo endNNInfo = AstarPath.active.GetNearest(endPoint, nnConstraint, endHint);
endPoint = endNNInfo.clampedPosition;
// Note, other methods assume hTarget is (Int3)endPoint
hTarget = (Int3)endPoint;
endNode = endNNInfo.node;
hTargetNode = endNode;
}
AstarProfiler.EndProfile();
#if ASTARDEBUG
if (startNode != null)
Debug.DrawLine((Vector3)startNode.position, startPoint, Color.blue);
if (endNode != null)
Debug.DrawLine((Vector3)endNode.position, endPoint, Color.blue);
#endif
if (startNode == null && (hasEndPoint && endNode == null)) {
Error();
LogError("Couldn't find close nodes to the start point or the end point");
return;
}
if (startNode == null) {
Error();
LogError("Couldn't find a close node to the start point");
return;
}
if (endNode == null && hasEndPoint) {
Error();
LogError("Couldn't find a close node to the end point");
return;
}
if (!startNode.Walkable) {
#if ASTARDEBUG
Debug.DrawRay(startPoint, Vector3.up, Color.red);
Debug.DrawLine(startPoint, (Vector3)startNode.position, Color.red);
#endif
Error();
LogError("The node closest to the start point is not walkable");
return;
}
if (hasEndPoint && !endNode.Walkable) {
Error();
LogError("The node closest to the end point is not walkable");
return;
}
if (hasEndPoint && startNode.Area != endNode.Area) {
Error();
LogError("There is no valid path to the target (start area: "+startNode.Area+", target area: "+endNode.Area+")");
return;
}
}
/** Checks if the start node is the target and complete the path if that is the case.
* This is necessary so that subclasses (e.g XPath) can override this behaviour.
*
* If the start node is a valid target point, this method should set CompleteState to Complete
* and trace the path.
*/
protected virtual void CompletePathIfStartIsValidTarget () {
if (hasEndPoint && startNode == endNode) {
Trace(pathHandler.GetPathNode(startNode));
CompleteState = PathCompleteState.Complete;
}
}
public override void Initialize () {
// Mark nodes to enable special connection costs for start and end nodes
// See GetConnectionSpecialCost
if (startNode != null) pathHandler.GetPathNode(startNode).flag2 = true;
if (endNode != null) pathHandler.GetPathNode(endNode).flag2 = true;
// Zero out the properties on the start node
PathNode startRNode = pathHandler.GetPathNode(startNode);
startRNode.node = startNode;
startRNode.pathID = pathHandler.PathID;
startRNode.parent = null;
startRNode.cost = 0;
startRNode.G = GetTraversalCost(startNode);
startRNode.H = CalculateHScore(startNode);
// Check if the start node is the target and complete the path if that is the case
CompletePathIfStartIsValidTarget();
if (CompleteState == PathCompleteState.Complete) return;
// Open the start node and puts its neighbours in the open list
startNode.Open(this, startRNode, pathHandler);
searchedNodes++;
partialBestTarget = startRNode;
// Any nodes left to search?
if (pathHandler.HeapEmpty()) {
if (calculatePartial) {
CompleteState = PathCompleteState.Partial;
Trace(partialBestTarget);
} else {
Error();
LogError("No open points, the start node didn't open any nodes");
return;
}
}
// Pop the first node off the open list
currentR = pathHandler.PopNode();
}
public override void Cleanup () {
if (startNode != null) pathHandler.GetPathNode(startNode).flag2 = false;
if (endNode != null) pathHandler.GetPathNode(endNode).flag2 = false;
}
/** Calculates the path until completed or until the time has passed \a targetTick.
* Usually a check is only done every 500 nodes if the time has passed \a targetTick.
* Time/Ticks are got from System.DateTime.UtcNow.Ticks.
*
* Basic outline of what the function does for the standard path (Pathfinding.ABPath).
* \code
* while the end has not been found and no error has ocurred
* check if we have reached the end
* if so, exit and return the path
*
* open the current node, i.e loop through its neighbours, mark them as visited and put them on a heap
*
* check if there are still nodes left to process (or have we searched the whole graph)
* if there are none, flag error and exit
*
* pop the next node of the heap and set it as current
*
* check if the function has exceeded the time limit
* if so, return and wait for the function to get called again
* \endcode
*/
public override void CalculateStep (long targetTick) {
int counter = 0;
// Continue to search while there hasn't ocurred an error and the end hasn't been found
while (CompleteState == PathCompleteState.NotCalculated) {
searchedNodes++;
// Close the current node, if the current node is the target node then the path is finished
if (currentR.node == endNode) {
CompleteState = PathCompleteState.Complete;
break;
}
if (currentR.H < partialBestTarget.H) {
partialBestTarget = currentR;
}
AstarProfiler.StartFastProfile(4);
// Loop through all walkable neighbours of the node and add them to the open list.
currentR.node.Open(this, currentR, pathHandler);
AstarProfiler.EndFastProfile(4);
// Any nodes left to search?
if (pathHandler.HeapEmpty()) {
Error();
LogError("Searched whole area but could not find target");
return;
}
// Select the node with the lowest F score and remove it from the open list
AstarProfiler.StartFastProfile(7);
currentR = pathHandler.PopNode();
AstarProfiler.EndFastProfile(7);
// Check for time every 500 nodes, roughly every 0.5 ms usually
if (counter > 500) {
// Have we exceded the maxFrameTime, if so we should wait one frame before continuing the search since we don't want the game to lag
if (System.DateTime.UtcNow.Ticks >= targetTick) {
// Return instead of yield'ing, a separate function handles the yield (CalculatePaths)
return;
}
counter = 0;
if (searchedNodes > 1000000) {
throw new System.Exception("Probable infinite loop. Over 1,000,000 nodes searched");
}
}
counter++;
}
AstarProfiler.StartProfile("Trace");
if (CompleteState == PathCompleteState.Complete) {
Trace(currentR);
} else if (calculatePartial && partialBestTarget != null) {
CompleteState = PathCompleteState.Partial;
Trace(partialBestTarget);
}
AstarProfiler.EndProfile();
}
/** Resets End Node Costs. Costs are updated on the end node at the start of the search to better reflect the end point passed to the path, the previous ones are saved in #endNodeCosts and are reset in this function which is called after the path search is complete */
public void ResetCosts (Path p) {
#if FALSE
if (!hasEndPoint) return;
endNode.ResetCosts(endNodeCosts);
#endif
}
/* String builder used for all debug logging */
//public static System.Text.StringBuilder debugStringBuilder = new System.Text.StringBuilder ();
/** Returns a debug string for this path.
*/
public override string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
var text = new System.Text.StringBuilder();
DebugStringPrefix(logMode, text);
if (!error && logMode == PathLog.Heavy) {
text.Append("\nSearch Iterations "+searchIterations);
if (hasEndPoint && endNode != null) {
PathNode nodeR = pathHandler.GetPathNode(endNode);
text.Append("\nEnd Node\n G: ");
text.Append(nodeR.G);
text.Append("\n H: ");
text.Append(nodeR.H);
text.Append("\n F: ");
text.Append(nodeR.F);
text.Append("\n Point: ");
text.Append(((Vector3)endPoint).ToString());
text.Append("\n Graph: ");
text.Append(endNode.GraphIndex);
}
text.Append("\nStart Node");
text.Append("\n Point: ");
text.Append(((Vector3)startPoint).ToString());
text.Append("\n Graph: ");
if (startNode != null) text.Append(startNode.GraphIndex);
else text.Append("< null startNode >");
}
DebugStringSuffix(logMode, text);
return text.ToString();
}
//Movement stuff
/** Returns in which direction to move from a point on the path.
* A simple and quite slow (well, compared to more optimized algorithms) algorithm first finds the closest path segment (from #vectorPath) and then returns
* the direction to the next point from there. The direction is not normalized.
* \returns Direction to move from a \a point, returns Vector3.zero if #vectorPath is null or has a length of 0 */
public Vector3 GetMovementVector (Vector3 point) {
if (vectorPath == null || vectorPath.Count == 0) {
return Vector3.zero;
}
if (vectorPath.Count == 1) {
return vectorPath[0]-point;
}
float minDist = float.PositiveInfinity;//Mathf.Infinity;
int minSegment = 0;
for (int i = 0; i < vectorPath.Count-1; i++) {
Vector3 closest = VectorMath.ClosestPointOnSegment(vectorPath[i], vectorPath[i+1], point);
float dist = (closest-point).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
minSegment = i;
}
}
return vectorPath[minSegment+1]-point;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace Microsoft.Win32.SafeHandles {
/// <summary>
/// Base class for NCrypt handles which need to support being pseudo-duplicated. This class is not for
/// external use (instead applications should consume the concrete subclasses of this class).
/// </summary>
/// <remarks>
/// Since NCrypt handles do not have a native DuplicateHandle type call, we need to do manual
/// reference counting in managed code whenever we hand out an extra reference to one of these handles.
/// This class wraps up the logic to correctly duplicate and free these handles to simluate a native
/// duplication.
///
/// Each open handle object can be thought of as being in one of three states:
/// 1. Owner - created via the marshaler, traditional style safe handle. Notably, only one owner
/// handle exists for a given native handle.
/// 2. Duplicate - points at a handle in the Holder state. Releasing a handle in the duplicate state
/// results only in decrementing the reference count of the holder, not in a release
/// of the native handle.
/// 3. Holder - holds onto a native handle and is referenced by handles in the duplicate state.
/// When all duplicate handles are closed, the holder handle releases the native
/// handle. A holder handle will never be finalized, since this results in a ----
/// between the finalizers of the duplicate handles and the holder handle. Instead,
/// it relies upon all of the duplicate handles to be finalized and decriment the
/// ref count to zero. Instances of a holder handle should never be referenced by
/// anything but a duplicate handle.
/// </remarks>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode = true)]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public abstract class SafeNCryptHandle : SafeHandleZeroOrMinusOneIsInvalid {
private enum OwnershipState {
/// <summary>
/// The safe handle owns the native handle outright. This must be value 0, as this is the
/// state the marshaler will place the handle in when marshaling back a SafeHandle
/// </summary>
Owner = 0,
/// <summary>
/// The safe handle does not own the native handle, but points to a Holder which does
/// </summary>
Duplicate,
/// <summary>
/// The safe handle owns the native handle, but shares it with other Duplicate handles
/// </summary>
Holder
}
private OwnershipState m_ownershipState;
/// <summary>
/// If the handle is a Duplicate, this points at the safe handle which actually owns the native handle.
/// </summary>
private SafeNCryptHandle m_holder;
protected SafeNCryptHandle() : base(true) {
return;
}
/// <summary>
/// Wrapper for the m_holder field which ensures that we're in a consistent state
/// </summary>
private SafeNCryptHandle Holder {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {
Contract.Requires((m_ownershipState == OwnershipState.Duplicate && m_holder != null) ||
(m_ownershipState != OwnershipState.Duplicate && m_holder == null));
Contract.Requires(m_holder == null || m_holder.m_ownershipState == OwnershipState.Holder);
return m_holder;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
set {
Contract.Ensures(m_holder.m_ownershipState == OwnershipState.Holder);
Contract.Ensures(m_ownershipState == OwnershipState.Duplicate);
#if DEBUG
Contract.Ensures(IsValidOpenState);
Contract.Assert(value.IsValidOpenState);
#endif
Contract.Assert(m_ownershipState != OwnershipState.Duplicate);
Contract.Assert(value.m_ownershipState == OwnershipState.Holder);
m_holder = value;
m_ownershipState = OwnershipState.Duplicate;
}
}
#if DEBUG
/// <summary>
/// Ensure the state of the handle is consistent for an open handle
/// </summary>
private bool IsValidOpenState {
[Pure]
get {
switch (m_ownershipState) {
// Owner handles do not have a holder
case OwnershipState.Owner:
return Holder == null && !IsInvalid && !IsClosed;
// Duplicate handles have valid open holders with the same raw handle value
case OwnershipState.Duplicate:
bool acquiredHolder = false;
RuntimeHelpers.PrepareConstrainedRegions();
try {
IntPtr holderRawHandle = IntPtr.Zero;
if (Holder != null) {
Holder.DangerousAddRef(ref acquiredHolder);
holderRawHandle = Holder.DangerousGetHandle();
}
bool holderValid = Holder != null &&
!Holder.IsInvalid &&
!Holder.IsClosed &&
holderRawHandle != IntPtr.Zero &&
holderRawHandle == handle;
return holderValid && !IsInvalid && !IsClosed;
}
finally {
if (acquiredHolder) {
Holder.DangerousRelease();
}
}
// Holder handles do not have a holder
case OwnershipState.Holder:
return Holder == null && !IsInvalid && !IsClosed;
// Unknown ownership state
default:
return false;
}
}
}
#endif
/// <summary>
/// Duplicate a handle
/// </summary>
/// <remarks>
/// #NCryptHandleDuplicationAlgorithm
///
/// Duplicating a handle performs different operations depending upon the state of the handle:
///
/// * Owner - Allocate two new handles, a holder and a duplicate.
/// - Suppress finalization on the holder
/// - Transition into the duplicate state
/// - Use the new holder as the holder for both this handle and the duplicate
/// - Increment the reference count on the holder
///
/// * Duplicate - Allocate a duplicate handle
/// - Increment the reference count of our holder
/// - Assign the duplicate's holder to be our holder
///
/// * Holder - Specifically disallowed. Holders should only ever be referenced by duplicates,
/// so duplication will occur on the duplicate rather than the holder handle.
/// </remarks>
internal T Duplicate<T>() where T : SafeNCryptHandle, new() {
// Spec#: Consider adding a model variable for ownership state?
Contract.Ensures(Contract.Result<T>() != null);
Contract.Ensures(m_ownershipState == OwnershipState.Duplicate);
Contract.Ensures(Contract.Result<T>().m_ownershipState == OwnershipState.Duplicate);
#if DEBUG
// Spec#: Consider a debug-only? model variable for IsValidOpenState?
Contract.Ensures(Contract.Result<T>().IsValidOpenState);
Contract.Ensures(IsValidOpenState);
Contract.Assert(IsValidOpenState);
#endif
Contract.Assert(m_ownershipState != OwnershipState.Holder);
Contract.Assert(typeof(T) == this.GetType());
if (m_ownershipState == OwnershipState.Owner) {
return DuplicateOwnerHandle<T>();
}
else {
// If we're not an owner handle, and we're being duplicated then we must be a duplicate handle.
return DuplicateDuplicatedHandle<T>();
}
}
/// <summary>
/// Duplicate a safe handle which is already duplicated.
///
/// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for
/// details about the algorithm.
/// </summary>
private T DuplicateDuplicatedHandle<T>() where T : SafeNCryptHandle, new() {
Contract.Ensures(m_ownershipState == OwnershipState.Duplicate);
Contract.Ensures(Contract.Result<T>() != null &&
Contract.Result<T>().m_ownershipState == OwnershipState.Duplicate);
#if DEBUG
Contract.Ensures(IsValidOpenState);
Contract.Ensures(Contract.Result<T>().IsValidOpenState);
Contract.Assert(IsValidOpenState);
#endif
Contract.Assert(m_ownershipState == OwnershipState.Duplicate);
Contract.Assert(typeof(T) == this.GetType());
bool addedRef = false;
T duplicate = new T();
// We need to do this operation in a CER, since we need to make sure that if the AddRef occurs
// that the duplicated handle will always point back to the Holder, otherwise the Holder will leak
// since it will never have its ref count reduced to zero.
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally {
Holder.DangerousAddRef(ref addedRef);
duplicate.SetHandle(Holder.DangerousGetHandle());
duplicate.Holder = Holder; // Transitions to OwnershipState.Duplicate
}
return duplicate;
}
/// <summary>
/// Duplicate a safe handle which is currently the exclusive owner of a native handle
///
/// See code:Microsoft.Win32.SafeHandles.SafeNCryptHandle#NCryptHandleDuplicationAlgorithm for
/// details about the algorithm.
/// </summary>
private T DuplicateOwnerHandle<T>() where T : SafeNCryptHandle, new() {
Contract.Ensures(m_ownershipState == OwnershipState.Duplicate);
Contract.Ensures(Contract.Result<T>() != null &&
Contract.Result<T>().m_ownershipState == OwnershipState.Duplicate);
#if DEBUG
Contract.Ensures(IsValidOpenState);
Contract.Ensures(Contract.Result<T>().IsValidOpenState);
Contract.Assert(IsValidOpenState);
#endif
Contract.Assert(m_ownershipState == OwnershipState.Owner);
Contract.Assert(typeof(T) == this.GetType());
bool addRef = false;
T holder = new T();
T duplicate = new T();
// We need to do this operation in a CER in order to ensure that everybody's state stays consistent
// with the current view of the world. If the state of the various handles gets out of [....], then
// we'll end up leaking since reference counts will not be set up properly.
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally {
// Setup a holder safe handle to ref count the native handle
holder.m_ownershipState = OwnershipState.Holder;
holder.SetHandle(DangerousGetHandle());
GC.SuppressFinalize(holder);
// Transition into the duplicate state, referencing the holder. The initial reference count
// on the holder will refer to the original handle so there is no need to AddRef here.
Holder = holder; // Transitions to OwnershipState.Duplicate
// The duplicate handle will also reference the holder
holder.DangerousAddRef(ref addRef);
duplicate.SetHandle(holder.DangerousGetHandle());
duplicate.Holder = holder; // Transitions to OwnershipState.Duplicate
}
return duplicate;
}
/// <summary>
/// Release the handle
/// </summary>
/// <remarks>
/// Similar to duplication, releasing a handle performs different operations based upon the state
/// of the handle.
///
/// * Owner - Simply call the release P/Invoke method
/// * Duplicate - Decrement the reference count of the current holder
/// * Holder - Call the release P/Invoke. Note that ReleaseHandle on a holder implies a reference
/// count of zero.
/// </remarks>
protected override bool ReleaseHandle() {
if (m_ownershipState == OwnershipState.Duplicate) {
Holder.DangerousRelease();
return true;
}
else {
return ReleaseNativeHandle();
}
}
/// <summary>
/// Perform the actual release P/Invoke
/// </summary>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected abstract bool ReleaseNativeHandle();
}
/// <summary>
/// Safe handle representing an NCRYPT_KEY_HANDLE
/// </summary>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class SafeNCryptKeyHandle : SafeNCryptHandle {
[DllImport("ncrypt.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
private static extern int NCryptFreeObject(IntPtr hObject);
internal SafeNCryptKeyHandle Duplicate() {
return Duplicate<SafeNCryptKeyHandle>();
}
protected override bool ReleaseNativeHandle() {
return NCryptFreeObject(handle) == 0;
}
}
/// <summary>
/// Safe handle representing an NCRYPT_PROV_HANDLE
/// </summary>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class SafeNCryptProviderHandle : SafeNCryptHandle {
[DllImport("ncrypt.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
private static extern int NCryptFreeObject(IntPtr hObject);
internal SafeNCryptProviderHandle Duplicate() {
return Duplicate<SafeNCryptProviderHandle>();
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal void SetHandleValue(IntPtr newHandleValue) {
Contract.Requires(newHandleValue != IntPtr.Zero);
Contract.Requires(!IsClosed);
Contract.Ensures(!IsInvalid);
Contract.Assert(handle == IntPtr.Zero);
SetHandle(newHandleValue);
}
protected override bool ReleaseNativeHandle() {
return NCryptFreeObject(handle) == 0;
}
}
/// <summary>
/// Safe handle representing an NCRYPT_SECRET_HANDLE
/// </summary>
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[System.Security.SecurityCritical(System.Security.SecurityCriticalScope.Everything)]
#pragma warning restore 618
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class SafeNCryptSecretHandle : SafeNCryptHandle {
[DllImport("ncrypt.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
private static extern int NCryptFreeObject(IntPtr hObject);
protected override bool ReleaseNativeHandle() {
return NCryptFreeObject(handle) == 0;
}
}
}
| |
using J2N.Text;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Codecs
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReader = Lucene.Net.Index.AtomicReader;
using IBits = Lucene.Net.Util.IBits;
using BytesRef = Lucene.Net.Util.BytesRef;
using DataInput = Lucene.Net.Store.DataInput;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using Fields = Lucene.Net.Index.Fields;
using MergeState = Lucene.Net.Index.MergeState;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
/// <summary>
/// Codec API for writing term vectors:
/// <para/>
/// <list type="number">
/// <item><description>For every document, <see cref="StartDocument(int)"/> is called,
/// informing the <see cref="Codec"/> how many fields will be written.</description></item>
/// <item><description><see cref="StartField(FieldInfo, int, bool, bool, bool)"/> is called for
/// each field in the document, informing the codec how many terms
/// will be written for that field, and whether or not positions,
/// offsets, or payloads are enabled.</description></item>
/// <item><description>Within each field, <see cref="StartTerm(BytesRef, int)"/> is called
/// for each term.</description></item>
/// <item><description>If offsets and/or positions are enabled, then
/// <see cref="AddPosition(int, int, int, BytesRef)"/> will be called for each term
/// occurrence.</description></item>
/// <item><description>After all documents have been written, <see cref="Finish(FieldInfos, int)"/>
/// is called for verification/sanity-checks.</description></item>
/// <item><description>Finally the writer is disposed (<see cref="Dispose(bool)"/>)</description></item>
/// </list>
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class TermVectorsWriter : IDisposable
{
/// <summary>
/// Sole constructor. (For invocation by subclass
/// constructors, typically implicit.)
/// </summary>
protected internal TermVectorsWriter()
{
}
/// <summary>
/// Called before writing the term vectors of the document.
/// <see cref="StartField(FieldInfo, int, bool, bool, bool)"/> will
/// be called <paramref name="numVectorFields"/> times. Note that if term
/// vectors are enabled, this is called even if the document
/// has no vector fields, in this case <paramref name="numVectorFields"/>
/// will be zero.
/// </summary>
public abstract void StartDocument(int numVectorFields);
/// <summary>
/// Called after a doc and all its fields have been added. </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public virtual void FinishDocument()
{
}
/// <summary>
/// Called before writing the terms of the field.
/// <see cref="StartTerm(BytesRef, int)"/> will be called <paramref name="numTerms"/> times.
/// </summary>
public abstract void StartField(FieldInfo info, int numTerms, bool positions, bool offsets, bool payloads);
/// <summary>
/// Called after a field and all its terms have been added. </summary>
public virtual void FinishField()
{
}
/// <summary>
/// Adds a <paramref name="term"/> and its term frequency <paramref name="freq"/>.
/// If this field has positions and/or offsets enabled, then
/// <see cref="AddPosition(int, int, int, BytesRef)"/> will be called
/// <paramref name="freq"/> times respectively.
/// </summary>
public abstract void StartTerm(BytesRef term, int freq);
/// <summary>
/// Called after a term and all its positions have been added. </summary>
public virtual void FinishTerm()
{
}
/// <summary>
/// Adds a term <paramref name="position"/> and offsets. </summary>
public abstract void AddPosition(int position, int startOffset, int endOffset, BytesRef payload);
/// <summary>
/// Aborts writing entirely, implementation should remove
/// any partially-written files, etc.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public abstract void Abort();
/// <summary>
/// Called before <see cref="Dispose(bool)"/>, passing in the number
/// of documents that were written. Note that this is
/// intentionally redundant (equivalent to the number of
/// calls to <see cref="StartDocument(int)"/>, but a <see cref="Codec"/> should
/// check that this is the case to detect the bug described
/// in LUCENE-1282.
/// </summary>
public abstract void Finish(FieldInfos fis, int numDocs);
/// <summary>
/// Called by <see cref="Index.IndexWriter"/> when writing new segments.
/// <para/>
/// This is an expert API that allows the codec to consume
/// positions and offsets directly from the indexer.
/// <para/>
/// The default implementation calls <see cref="AddPosition(int, int, int, BytesRef)"/>,
/// but subclasses can override this if they want to efficiently write
/// all the positions, then all the offsets, for example.
/// <para/>
/// NOTE: this API is extremely expert and subject to change or removal!!!
/// <para/>
/// @lucene.internal
/// </summary>
// TODO: we should probably nuke this and make a more efficient 4.x format
// PreFlex-RW could then be slow and buffer (its only used in tests...)
public virtual void AddProx(int numProx, DataInput positions, DataInput offsets)
{
int position = 0;
int lastOffset = 0;
BytesRef payload = null;
for (int i = 0; i < numProx; i++)
{
int startOffset;
int endOffset;
BytesRef thisPayload;
if (positions == null)
{
position = -1;
thisPayload = null;
}
else
{
int code = positions.ReadVInt32();
position += (int)((uint)code >> 1);
if ((code & 1) != 0)
{
// this position has a payload
int payloadLength = positions.ReadVInt32();
if (payload == null)
{
payload = new BytesRef();
payload.Bytes = new byte[payloadLength];
}
else if (payload.Bytes.Length < payloadLength)
{
payload.Grow(payloadLength);
}
positions.ReadBytes(payload.Bytes, 0, payloadLength);
payload.Length = payloadLength;
thisPayload = payload;
}
else
{
thisPayload = null;
}
}
if (offsets == null)
{
startOffset = endOffset = -1;
}
else
{
startOffset = lastOffset + offsets.ReadVInt32();
endOffset = startOffset + offsets.ReadVInt32();
lastOffset = endOffset;
}
AddPosition(position, startOffset, endOffset, thisPayload);
}
}
/// <summary>
/// Merges in the term vectors from the readers in
/// <paramref name="mergeState"/>. The default implementation skips
/// over deleted documents, and uses <see cref="StartDocument(int)"/>,
/// <see cref="StartField(FieldInfo, int, bool, bool, bool)"/>,
/// <see cref="StartTerm(BytesRef, int)"/>, <see cref="AddPosition(int, int, int, BytesRef)"/>,
/// and <see cref="Finish(FieldInfos, int)"/>,
/// returning the number of documents that were written.
/// Implementations can override this method for more sophisticated
/// merging (bulk-byte copying, etc).
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public virtual int Merge(MergeState mergeState)
{
int docCount = 0;
for (int i = 0; i < mergeState.Readers.Count; i++)
{
AtomicReader reader = mergeState.Readers[i];
int maxDoc = reader.MaxDoc;
IBits liveDocs = reader.LiveDocs;
for (int docID = 0; docID < maxDoc; docID++)
{
if (liveDocs != null && !liveDocs.Get(docID))
{
// skip deleted docs
continue;
}
// NOTE: it's very important to first assign to vectors then pass it to
// termVectorsWriter.addAllDocVectors; see LUCENE-1282
Fields vectors = reader.GetTermVectors(docID);
AddAllDocVectors(vectors, mergeState);
docCount++;
mergeState.CheckAbort.Work(300);
}
}
Finish(mergeState.FieldInfos, docCount);
return docCount;
}
/// <summary>
/// Safe (but, slowish) default method to write every
/// vector field in the document.
/// </summary>
protected void AddAllDocVectors(Fields vectors, MergeState mergeState)
{
if (vectors == null)
{
StartDocument(0);
FinishDocument();
return;
}
int numFields = vectors.Count;
if (numFields == -1)
{
// count manually! TODO: Maybe enforce that Fields.size() returns something valid?
numFields = 0;
//for (IEnumerator<string> it = vectors.Iterator(); it.hasNext();)
foreach (string it in vectors)
{
numFields++;
}
}
StartDocument(numFields);
string lastFieldName = null;
TermsEnum termsEnum = null;
DocsAndPositionsEnum docsAndPositionsEnum = null;
int fieldCount = 0;
foreach (string fieldName in vectors)
{
fieldCount++;
FieldInfo fieldInfo = mergeState.FieldInfos.FieldInfo(fieldName);
Debug.Assert(lastFieldName == null || fieldName.CompareToOrdinal(lastFieldName) > 0, "lastFieldName=" + lastFieldName + " fieldName=" + fieldName);
lastFieldName = fieldName;
Terms terms = vectors.GetTerms(fieldName);
if (terms == null)
{
// FieldsEnum shouldn't lie...
continue;
}
bool hasPositions = terms.HasPositions;
bool hasOffsets = terms.HasOffsets;
bool hasPayloads = terms.HasPayloads;
Debug.Assert(!hasPayloads || hasPositions);
int numTerms = (int)terms.Count;
if (numTerms == -1)
{
// count manually. It is stupid, but needed, as Terms.size() is not a mandatory statistics function
numTerms = 0;
termsEnum = terms.GetIterator(termsEnum);
while (termsEnum.Next() != null)
{
numTerms++;
}
}
StartField(fieldInfo, numTerms, hasPositions, hasOffsets, hasPayloads);
termsEnum = terms.GetIterator(termsEnum);
int termCount = 0;
while (termsEnum.Next() != null)
{
termCount++;
int freq = (int)termsEnum.TotalTermFreq;
StartTerm(termsEnum.Term, freq);
if (hasPositions || hasOffsets)
{
docsAndPositionsEnum = termsEnum.DocsAndPositions(null, docsAndPositionsEnum);
Debug.Assert(docsAndPositionsEnum != null);
int docID = docsAndPositionsEnum.NextDoc();
Debug.Assert(docID != DocIdSetIterator.NO_MORE_DOCS);
Debug.Assert(docsAndPositionsEnum.Freq == freq);
for (int posUpto = 0; posUpto < freq; posUpto++)
{
int pos = docsAndPositionsEnum.NextPosition();
int startOffset = docsAndPositionsEnum.StartOffset;
int endOffset = docsAndPositionsEnum.EndOffset;
BytesRef payload = docsAndPositionsEnum.GetPayload();
Debug.Assert(!hasPositions || pos >= 0);
AddPosition(pos, startOffset, endOffset, payload);
}
}
FinishTerm();
}
Debug.Assert(termCount == numTerms);
FinishField();
}
Debug.Assert(fieldCount == numFields);
FinishDocument();
}
/// <summary>
/// Return the <see cref="T:IComparer{BytesRef}"/> used to sort terms
/// before feeding to this API.
/// </summary>
public abstract IComparer<BytesRef> Comparer { get; }
/// <summary>
/// Disposes all resources used by this object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Implementations must override and should dispose all resources used by this instance.
/// </summary>
protected abstract void Dispose(bool disposing);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Alluvial.Fluent;
using trace = System.Diagnostics.Trace;
namespace Alluvial
{
/// <summary>
/// Methods for working with streams.
/// </summary>
public static class Stream
{
/// <summary>
/// Creates a stream based on an enumerable sequence.
/// </summary>
public static IStream<TData, TData> AsStream<TData>(
this IEnumerable<TData> source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return Create(query => source.SkipWhile(x => query.Cursor.HasReached(x))
.Take(query.BatchSize ?? StreamBatch.MaxSize),
advanceCursor: (q, b) =>
{
var last = b.LastOrDefault();
if (last != null)
{
q.Cursor.AdvanceTo(last);
}
},
newCursor: () => Cursor.New<TData>(), source: source);
}
/// <summary>
/// Creates a stream based on an enumerable sequence.
/// </summary>
public static IStream<TData, TCursor> AsStream<TData, TCursor>(
this IEnumerable<TData> source,
Func<TData, TCursor> cursorPosition,
string id = null)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (cursorPosition == null)
{
throw new ArgumentNullException(nameof(cursorPosition));
}
return Create(query: query => source.SkipWhile(x =>
query.Cursor.HasReached(cursorPosition(x)))
.Take(query.BatchSize ?? StreamBatch.MaxSize),
id: id,
advanceCursor: (q, b) =>
{
var last = b.LastOrDefault();
if (last != null)
{
q.Cursor.AdvanceTo(cursorPosition(last));
}
},
newCursor: () => Cursor.New<TCursor>(), source: source);
}
/// <summary>
/// Creates a stream based on an enumerable sequence, whose cursor is an integer.
/// </summary>
public static IStream<TData, int> AsSequentialStream<TData>(
this IEnumerable<TData> source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return Create(query => source.Skip(query.Cursor.Position)
.Take(query.BatchSize ?? StreamBatch.MaxSize),
$"{typeof (TData)}({source.GetHashCode()})", newCursor: () => Cursor.New<int>());
}
/// <summary>
/// Creates a stream based on a queryable data source.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <param name="query">The query.</param>
/// <param name="advanceCursor">A delegate that advances the cursor after a batch is pulled from the stream.</param>
/// <param name="newCursor">A delegate that returns a new cursor.</param>
public static IStream<TData, TCursor> Create<TData, TCursor>(
Func<IStreamQuery<TCursor>, Task<IEnumerable<TData>>> query,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor = null,
Func<ICursor<TCursor>> newCursor = null) =>
Create(null,
query,
advanceCursor,
newCursor);
/// <summary>
/// Creates a stream based on a queryable data source.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <param name="id">The stream identifier.</param>
/// <param name="query">The query.</param>
/// <param name="advanceCursor">A delegate that advances the cursor after a batch is pulled from the stream.</param>
/// <param name="newCursor">A delegate that returns a new cursor.</param>
/// <returns></returns>
public static IStream<TData, TCursor> Create<TData, TCursor>(
string id,
Func<IStreamQuery<TCursor>, Task<IEnumerable<TData>>> query,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor = null,
Func<ICursor<TCursor>> newCursor = null) =>
new AnonymousStream<TData, TCursor>(
id,
async q =>
{
var cursor = q.Cursor.Clone();
var data = await query(q);
return data as IStreamBatch<TData> ?? StreamBatch.Create(data, cursor);
},
advanceCursor,
newCursor);
/// <summary>
/// Creates a stream based on a queryable data source.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <param name="query">The query.</param>
/// <param name="advanceCursor">A delegate that advances the cursor after a batch is pulled from the stream.</param>
/// <param name="id">The stream identifier.</param>
/// <param name="newCursor">A delegate that returns a new cursor.</param>
public static IStream<TData, TCursor> Create<TData, TCursor>(
Func<IStreamQuery<TCursor>, IEnumerable<TData>> query,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor = null,
string id = null,
Func<ICursor<TCursor>> newCursor = null) =>
Create(query,
id,
advanceCursor,
newCursor);
/// <summary>
/// Creates a stream based on a queryable data source where the stream data and cursor are of the same type.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <param name="query">The query.</param>
/// <param name="advanceCursor">A delegate that advances the cursor after a batch is pulled from the stream.</param>
/// <param name="id">The stream identifier.</param>
/// <param name="newCursor">A delegate that returns a new cursor.</param>
public static IStream<TData, TData> Create<TData>(
Func<IStreamQuery<TData>, IEnumerable<TData>> query,
string id = null,
Action<IStreamQuery<TData>, IStreamBatch<TData>> advanceCursor = null,
Func<ICursor<TData>> newCursor = null)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
return Create<TData, TData>(
id: id,
query: query,
advanceCursor: advanceCursor ?? ((q, batch) =>
{
var last = batch.LastOrDefault();
if (last != null)
{
q.Cursor.AdvanceTo(last);
}
}),
newCursor: newCursor);
}
private static IStream<TData, TCursor> Create<TData, TCursor>(
Func<IStreamQuery<TCursor>, IEnumerable<TData>> query,
string id = null,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor = null,
Func<ICursor<TCursor>> newCursor = null,
IEnumerable<TData> source = null)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
return new AnonymousStream<TData, TCursor>(
id,
q => StreamBatch.Create(query(q), q.Cursor).CompletedTask(),
advanceCursor,
newCursor,
source);
}
/// <summary>
/// Creates a stream builder.
/// </summary>
public static StreamBuilder<TData> Of<TData>(
string streamId = null) =>
new StreamBuilder<TData>(streamId);
/// <summary>
/// Maps data from a stream into a new form.
/// </summary>
public static IStream<TTo, TCursor> Map<TFrom, TTo, TCursor>(
this IStream<TFrom, TCursor> source,
Func<IEnumerable<TFrom>, IEnumerable<TTo>> map,
string id = null)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (map == null)
{
throw new ArgumentNullException(nameof(map));
}
return Create<TTo, TCursor>(
id: id ?? $"{source.Id}->Map(d:{typeof (TTo).ReadableName()})",
query: async q =>
{
var query = source.CreateQuery(q.Cursor, q.BatchSize);
var sourceBatch = await source.Fetch(query);
var mappedItems = map(sourceBatch);
var mappedCursor = Cursor.New<TCursor>(sourceBatch.StartsAtCursorPosition);
var mappedBatch = StreamBatch.Create(mappedItems, mappedCursor);
return mappedBatch;
},
advanceCursor: (query, batch) =>
{
// don't advance the cursor in the map operation, since sourceStream.Fetch will already have done it
},
newCursor: source.NewCursor);
}
/// <summary>
/// Maps data from a stream into a new form.
/// </summary>
public static IPartitionedStream<TTo, TCursor, TPartition> Map<TFrom, TTo, TCursor, TPartition>(
this IPartitionedStream<TFrom, TCursor, TPartition> source,
Func<IEnumerable<TFrom>, IEnumerable<TTo>> map,
string id = null)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
return new AnonymousPartitionedStream<TTo, TCursor, TPartition>(
id: id ?? $"{source.Id}->Map(d:{typeof (TTo).ReadableName()})",
getStream: async partition =>
{
var stream = await source.GetStream(partition);
return stream.Map(map);
});
}
/// <summary>
/// Splits a stream into many streams that can be independently caught up.
/// </summary>
/// <typeparam name="TUpstream">The type of the upstream stream.</typeparam>
/// <typeparam name="TDownstream">The type of the downstream streams.</typeparam>
/// <typeparam name="TUpstreamCursor">The type of the upstream cursor.</typeparam>
/// <param name="upstream">The upstream stream.</param>
/// <param name="queryDownstream">The downstream query.</param>
/// <returns></returns>
public static IStream<TDownstream, TUpstreamCursor> IntoMany<TUpstream, TDownstream, TUpstreamCursor>(
this IStream<TUpstream, TUpstreamCursor> upstream,
QueryDownstreamAsync<TUpstream, TDownstream, TUpstreamCursor> queryDownstream)
{
if (upstream == null)
{
throw new ArgumentNullException(nameof(upstream));
}
return Create(
id: $"{upstream.Id}->IntoMany(d:{typeof (TDownstream).ReadableName()})",
query: async upstreamQuery =>
{
var upstreamBatch = await upstream.Fetch(
upstream.CreateQuery(upstreamQuery.Cursor,
upstreamQuery.BatchSize));
var streams = upstreamBatch.Select(
async x =>
{
TUpstreamCursor startingCursor = upstreamBatch.StartsAtCursorPosition;
return await queryDownstream(x,
startingCursor,
upstreamQuery.Cursor.Position);
});
return await streams.AwaitAll();
},
advanceCursor: (query, batch) =>
{
// we're passing the cursor through to the upstream query, so we don't want downstream queries to overwrite it
},
newCursor: upstream.NewCursor);
}
/// <summary>
/// Splits a partitioned stream into many streams that can be independently caught up.
/// </summary>
/// <typeparam name="TUpstream">The type of the upstream, partitioned stream.</typeparam>
/// <typeparam name="TDownstream">The type of the downstream streams.</typeparam>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <typeparam name="TUpstreamCursor">The type of the partitionedStream cursor.</typeparam>
/// <param name="partitionedStream">The partitioned stream.</param>
/// <param name="queryDownstream">The query downstream.</param>
/// <returns></returns>
public static IPartitionedStream<TDownstream, TUpstreamCursor, TPartition> IntoMany<TUpstream, TDownstream, TUpstreamCursor, TPartition>(
this IPartitionedStream<TUpstream, TUpstreamCursor, TPartition> partitionedStream,
QueryDownstreamAsync<TUpstream, TDownstream, TUpstreamCursor, TPartition> queryDownstream)
{
if (partitionedStream == null)
{
throw new ArgumentNullException(nameof(partitionedStream));
}
if (queryDownstream == null)
{
throw new ArgumentNullException(nameof(queryDownstream));
}
return Partitioned<TDownstream, TUpstreamCursor, TPartition>(
id: $"{partitionedStream.Id}->IntoMany(d:{typeof (TDownstream).ReadableName()})",
query: async (upstreamQuery, partition) =>
{
var upstreamStream = await partitionedStream.GetStream(partition);
var upstreamBatch = await upstreamStream.Fetch(
upstreamStream.CreateQuery(upstreamQuery.Cursor,
upstreamQuery.BatchSize));
var streams = upstreamBatch.Select(
async x =>
{
TUpstreamCursor startingCursor = upstreamBatch.StartsAtCursorPosition;
return await queryDownstream(x,
startingCursor,
upstreamQuery.Cursor.Position,
partition);
});
return await streams.AwaitAll();
},
advanceCursor: (query, batch) =>
{
// we're passing the cursor through to the upstream query, so we don't want downstream queries to overwrite it
});
}
/// <summary>
/// Splits a stream into many streams that can be independently caught up.
/// </summary>
/// <typeparam name="TUpstream">The type of the upstream stream.</typeparam>
/// <typeparam name="TDownstream">The type of the downstream streams.</typeparam>
/// <typeparam name="TUpstreamCursor">The type of the upstream cursor.</typeparam>
/// <param name="upstream">The upstream stream.</param>
/// <param name="queryDownstream">The downstream query.</param>
/// <returns></returns>
public static IStream<TDownstream, TUpstreamCursor> IntoMany<TUpstream, TDownstream, TUpstreamCursor>(
this IStream<TUpstream, TUpstreamCursor> upstream,
QueryDownstream<TUpstream, TDownstream, TUpstreamCursor> queryDownstream) =>
upstream.IntoMany(
new QueryDownstreamAsync<TUpstream, TDownstream, TUpstreamCursor>(
(upstreamItem, fromCursor, toCursor) =>
queryDownstream(upstreamItem,
fromCursor,
toCursor).CompletedTask()));
/// <summary>
/// Splits a partitioned stream into many streams that can be independently caught up.
/// </summary>
/// <typeparam name="TUpstream">The type of the upstream, partitioned stream.</typeparam>
/// <typeparam name="TDownstream">The type of the downstream streams.</typeparam>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <typeparam name="TUpstreamCursor">The type of the partitionedStream cursor.</typeparam>
/// <param name="partitionedStream">The partitioned stream.</param>
/// <param name="queryDownstream">The query downstream.</param>
/// <returns></returns>
public static IPartitionedStream<TDownstream, TUpstreamCursor, TPartition> IntoMany<TUpstream, TDownstream, TUpstreamCursor, TPartition>(
this IPartitionedStream<TUpstream, TUpstreamCursor, TPartition> partitionedStream,
QueryDownstream<TUpstream, TDownstream, TUpstreamCursor, TPartition> queryDownstream) =>
partitionedStream
.IntoMany(
new QueryDownstreamAsync<TUpstream, TDownstream, TUpstreamCursor, TPartition>(
(upstreamItem, fromCursor, toCursor, partition) =>
queryDownstream(upstreamItem,
fromCursor,
toCursor,
partition).CompletedTask()));
/// <summary>
/// Aggregates a single batch of data from a stream using the specified aggregator and projection.
/// </summary>
/// <typeparam name="TProjection">The type of the projection.</typeparam>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="aggregator">The aggregator.</param>
/// <param name="projection">The projection.</param>
/// <returns>The updated state of the projection.</returns>
/// <remarks>This method can be used to create on-demand projections. It does not do any projection persistence.</remarks>
public static async Task<TProjection> Aggregate<TProjection, TData, TCursor>(
this IStream<TData, TCursor> stream,
IStreamAggregator<TProjection, TData> aggregator,
TProjection projection = null)
where TProjection : class
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (aggregator == null)
{
throw new ArgumentNullException(nameof(aggregator));
}
var cursor = (projection as ICursor<TCursor>) ??
stream.NewCursor();
var query = stream.CreateQuery(cursor);
var data = await query.NextBatch();
if (data.Any())
{
projection = await aggregator.Aggregate(projection, data);
}
return projection;
}
/// <summary>
/// Creates a partitioned stream.
/// </summary>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <param name="query">The query.</param>
/// <param name="id">The base identifier for the partitioned stream.</param>
/// <param name="advanceCursor">A delegate that advances the cursor after a batch is pulled from the stream.</param>
/// <param name="newCursor">A delegate that returns a new cursor.</param>
public static IPartitionedStream<TData, TCursor, TPartition> Partitioned<TData, TCursor, TPartition>(
Func<IStreamQuery<TCursor>, IStreamQueryPartition<TPartition>, Task<IEnumerable<TData>>> query,
string id = null,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor = null,
Func<ICursor<TCursor>> newCursor = null)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
return new AnonymousPartitionedStream<TData, TCursor, TPartition>(
id: id,
fetch: async (q, partition) =>
{
q.BatchSize = q.BatchSize ?? StreamBatch.MaxSize;
var batch = await query(q, partition);
return StreamBatch.Create(batch, q.Cursor);
},
advanceCursor: advanceCursor,
newCursor: newCursor);
}
/// <summary>
/// Creates a partitioned stream, partitioned by query ranges.
/// </summary>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <param name="query">The query.</param>
/// <param name="id">The base identifier for the partitioned stream.</param>
/// <param name="advanceCursor">A delegate that advances the cursor after a batch is pulled from the stream.</param>
/// <param name="newCursor">A delegate that returns a new cursor.</param>
public static IPartitionedStream<TData, TCursor, TPartition> PartitionedByRange<TData, TCursor, TPartition>(
Func<IStreamQuery<TCursor>, IStreamQueryRangePartition<TPartition>, Task<IEnumerable<TData>>> query,
string id = null,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor = null,
Func<ICursor<TCursor>> newCursor = null)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
return new AnonymousPartitionedStream<TData, TCursor, TPartition>(
id: id,
fetch: async (q, partition) =>
{
q.BatchSize = q.BatchSize ?? StreamBatch.MaxSize;
var batch = await query(q, (IStreamQueryRangePartition<TPartition>) partition);
return StreamBatch.Create(batch, q.Cursor);
},
advanceCursor: advanceCursor,
newCursor: newCursor);
}
/// <summary>
/// Creates a partitioned stream.
/// </summary>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <typeparam name="TCursor">The type of the cursor.</typeparam>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <param name="query">The query.</param>
/// <param name="id">The base identifier for the partitioned stream.</param>
/// <param name="advanceCursor">A delegate that advances the cursor after a batch is pulled from the stream.</param>
/// <param name="newCursor">A delegate that returns a new cursor.</param>
public static IPartitionedStream<TData, TCursor, TPartition> PartitionedByValue<TData, TCursor, TPartition>(
Func<IStreamQuery<TCursor>, IStreamQueryValuePartition<TPartition>, Task<IEnumerable<TData>>> query,
string id = null,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> advanceCursor = null,
Func<ICursor<TCursor>> newCursor = null)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
return new AnonymousPartitionedStream<TData, TCursor, TPartition>(
id: id,
fetch: async (q, partition) =>
{
q.BatchSize = q.BatchSize ?? StreamBatch.MaxSize;
var batch = await query(q, (IStreamQueryValuePartition<TPartition>) partition);
return StreamBatch.Create(batch, q.Cursor);
},
advanceCursor: advanceCursor,
newCursor: newCursor);
}
/// <summary>
/// Traces queries sent and and data received on a stream.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TCursor">The type of the stream's cursor.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="onSendQuery">Specifies how to trace information about queries sent to the stream.</param>
/// <param name="onResults">Specifies how to trace data received from the stream.</param>
public static IStream<TData, TCursor> Trace<TData, TCursor>(
this IStream<TData, TCursor> stream,
Action<IStreamQuery<TCursor>> onSendQuery = null,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> onResults = null)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
onSendQuery = onSendQuery ??
(q => trace.WriteLine(
$"[Query] stream {stream.Id} @ cursor {q.Cursor.Position}"));
onResults = onResults ??
((q, streamBatch) =>
{
trace.WriteLine(
$" [Fetched] stream {stream.Id} batch of {streamBatch.Count}, now @ cursor {q.Cursor.Position}");
});
return Create<TData, TCursor>(
id: stream.Id,
query: async q =>
{
onSendQuery(q);
var streamBatch = await stream.Fetch(q);
onResults(q, streamBatch);
return streamBatch;
},
advanceCursor: (q, b) => { },
newCursor: stream.NewCursor);
}
/// <summary>
/// Traces queries sent and and data received on a partitioned stream.
/// </summary>
/// <typeparam name="TData">The type of the stream's data.</typeparam>
/// <typeparam name="TCursor">The type of the stream's cursor.</typeparam>
/// <typeparam name="TPartition">The type of the partition.</typeparam>
/// <param name="stream">The stream.</param>
/// <param name="onSendQuery">Specifies how to trace information about queries sent to the stream.</param>
/// <param name="onResults">Specifies how to trace data received from the stream.</param>
public static IPartitionedStream<TData, TCursor, TPartition> Trace<TData, TCursor, TPartition>(
this IPartitionedStream<TData, TCursor, TPartition> stream,
Action<IStreamQuery<TCursor>> onSendQuery = null,
Action<IStreamQuery<TCursor>, IStreamBatch<TData>> onResults = null)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
return new AnonymousPartitionedStream<TData, TCursor, TPartition>(
stream.Id,
async p => (await stream.GetStream(p)).Trace(onSendQuery, onResults));
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Reflection;
using Dbg = System.Management.Automation.Diagnostics;
//
// Now define the set of commands for manipulating modules.
//
namespace Microsoft.PowerShell.Commands
{
#region Remove-Module
/// <summary>
/// Implements a cmdlet that gets the list of loaded modules...
/// </summary>
[Cmdlet(VerbsCommon.Remove, "Module", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096802")]
public sealed class RemoveModuleCommand : ModuleCmdletBase
{
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "name", ValueFromPipeline = true, Position = 0)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Name
{
get { return _name; }
set { _name = value; }
}
private string[] _name = Array.Empty<string>();
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "FullyQualifiedName", ValueFromPipeline = true, Position = 0)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public ModuleSpecification[] FullyQualifiedName { get; set; }
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = "ModuleInfo", ValueFromPipeline = true, Position = 0)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public PSModuleInfo[] ModuleInfo
{
get { return _moduleInfo; }
set { _moduleInfo = value; }
}
private PSModuleInfo[] _moduleInfo = Array.Empty<PSModuleInfo>();
/// <summary>
/// If provided, this parameter will allow readonly modules to be removed.
/// </summary>
[Parameter]
public SwitchParameter Force
{
get { return BaseForce; }
set { BaseForce = value; }
}
private int _numberRemoved = 0; // Maintains a count of the number of modules removed...
/// <summary>
/// Remove the specified modules. Modules can be specified either through a ModuleInfo or a name.
/// </summary>
protected override void ProcessRecord()
{
// This dictionary has the list of modules to be removed.
// Key - Module specified as a parameter to Remove-Module
// Values - List of all modules that need to be removed for this key (includes all nested modules of this module)
Dictionary<PSModuleInfo, List<PSModuleInfo>> modulesToRemove = new Dictionary<PSModuleInfo, List<PSModuleInfo>>();
foreach (var m in Context.Modules.GetModules(_name, false))
{
modulesToRemove.Add(m, new List<PSModuleInfo> { m });
}
if (FullyQualifiedName != null)
{
// TODO:
// Paths in the module name may fail here because
// they the wrong directory separator or are relative.
// Fix with the code below:
// FullyQualifiedName = FullyQualifiedName.Select(ms => ms.WithNormalizedName(Context, SessionState.Path.CurrentLocation.Path)).ToArray();
foreach (var m in Context.Modules.GetModules(FullyQualifiedName, false))
{
modulesToRemove.Add(m, new List<PSModuleInfo> { m });
}
}
foreach (var m in _moduleInfo)
{
modulesToRemove.Add(m, new List<PSModuleInfo> { m });
}
// Add any of the child modules of a manifests to the list of modules to remove...
Dictionary<PSModuleInfo, List<PSModuleInfo>> nestedModules = new Dictionary<PSModuleInfo, List<PSModuleInfo>>();
foreach (var entry in modulesToRemove)
{
var module = entry.Key;
if (module.NestedModules != null && module.NestedModules.Count > 0)
{
List<PSModuleInfo> nestedModulesWithNoCircularReference = new List<PSModuleInfo>();
GetAllNestedModules(module, ref nestedModulesWithNoCircularReference);
nestedModules.Add(module, nestedModulesWithNoCircularReference);
}
}
// dont add duplicates to our original modulesToRemove list..so that the
// evaluation loop below will not duplicate in case of WriteError and WriteWarning.
// A global list of modules to be removed is maintained for this purpose
HashSet<PSModuleInfo> globalListOfModules = new HashSet<PSModuleInfo>(new PSModuleInfoComparer());
if (nestedModules.Count > 0)
{
foreach (var entry in nestedModules)
{
List<PSModuleInfo> values = null;
if (modulesToRemove.TryGetValue(entry.Key, out values))
{
foreach (var module in entry.Value)
{
if (!globalListOfModules.Contains(module))
{
values.Add(module);
globalListOfModules.Add(module);
}
}
}
}
}
// Check the list of modules to remove and exclude those that cannot or should not be removed
Dictionary<PSModuleInfo, List<PSModuleInfo>> actualModulesToRemove = new Dictionary<PSModuleInfo, List<PSModuleInfo>>();
// We want to remove the modules starting from the nested modules
// If we start from the parent module, the nested modules do not get removed and are left orphaned in the parent modules's sessionstate.
foreach (var entry in modulesToRemove)
{
List<PSModuleInfo> moduleList = new List<PSModuleInfo>();
for (int i = entry.Value.Count - 1; i >= 0; i--)
{
PSModuleInfo module = entry.Value[i];
// See if the module is constant...
if (module.AccessMode == ModuleAccessMode.Constant)
{
string message = StringUtil.Format(Modules.ModuleIsConstant, module.Name);
InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsConstant",
ErrorCategory.PermissionDenied, module);
WriteError(er);
continue;
}
// See if the module is readonly...
if (module.AccessMode == ModuleAccessMode.ReadOnly && !BaseForce)
{
string message = StringUtil.Format(Modules.ModuleIsReadOnly, module.Name);
if (InitialSessionState.IsConstantEngineModule(module.Name))
{
WriteWarning(message);
}
else
{
InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsReadOnly",
ErrorCategory.PermissionDenied, module);
WriteError(er);
}
continue;
}
if (!ShouldProcess(StringUtil.Format(Modules.ConfirmRemoveModule, module.Name, module.Path)))
{
continue;
}
// If this module provides the current session drive, then we cannot remove it.
// Abort this command since we don't want to do a partial removal of a module manifest.
if (ModuleProvidesCurrentSessionDrive(module))
{
if (InitialSessionState.IsEngineModule(module.Name))
{
if (!BaseForce)
{
string message = StringUtil.Format(Modules.CoreModuleCannotBeRemoved, module.Name);
this.WriteWarning(message);
}
continue;
}
// Specify the overall module name if there is only one.
// Otherwise specify the particular module name.
string moduleName = (_name.Length == 1) ? _name[0] : module.Name;
PSInvalidOperationException invalidOperation =
PSTraceSource.NewInvalidOperationException(
Modules.ModuleDriveInUse,
moduleName);
throw (invalidOperation);
}
// Add module to remove list.
moduleList.Add(module);
}
actualModulesToRemove[entry.Key] = moduleList;
}
// Now remove the modules, first checking the RequiredModules dependencies
Dictionary<PSModuleInfo, List<PSModuleInfo>> requiredDependencies = GetRequiredDependencies();
foreach (var entry in actualModulesToRemove)
{
foreach (var module in entry.Value)
{
if (!BaseForce)
{
List<PSModuleInfo> requiredBy = null;
if (requiredDependencies.TryGetValue(module, out requiredBy))
{
for (int i = requiredBy.Count - 1; i >= 0; i--)
{
if (actualModulesToRemove.ContainsKey(requiredBy[i]))
{
requiredBy.RemoveAt(i);
}
}
if (requiredBy.Count > 0)
{
string message = StringUtil.Format(Modules.ModuleIsRequired, module.Name, requiredBy[0].Name);
InvalidOperationException moduleNotRemoved = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(moduleNotRemoved, "Modules_ModuleIsRequired",
ErrorCategory.PermissionDenied, module);
WriteError(er);
continue;
}
}
}
_numberRemoved++;
this.RemoveModule(module, entry.Key.Name);
}
}
}
private bool ModuleProvidesCurrentSessionDrive(PSModuleInfo module)
{
if (module.ModuleType == ModuleType.Binary)
{
Dictionary<string, List<ProviderInfo>> providers = Context.TopLevelSessionState.Providers;
foreach (KeyValuePair<string, List<ProviderInfo>> pList in providers)
{
Dbg.Assert(pList.Value != null, "There should never be a null list of entries in the provider table");
foreach (ProviderInfo pInfo in pList.Value)
{
string implTypeAssemblyLocation = pInfo.ImplementingType.Assembly.Location;
if (implTypeAssemblyLocation.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
{
foreach (PSDriveInfo dInfo in Context.TopLevelSessionState.GetDrivesForProvider(pInfo.FullName))
{
if (dInfo == SessionState.Drive.Current)
{
return true;
}
}
}
}
}
}
return false;
}
private void GetAllNestedModules(PSModuleInfo module, ref List<PSModuleInfo> nestedModulesWithNoCircularReference)
{
List<PSModuleInfo> nestedModules = new List<PSModuleInfo>();
if (module.NestedModules != null && module.NestedModules.Count > 0)
{
foreach (var nestedModule in module.NestedModules)
{
if (!nestedModulesWithNoCircularReference.Contains(nestedModule))
{
nestedModulesWithNoCircularReference.Add(nestedModule);
nestedModules.Add(nestedModule);
}
}
foreach (PSModuleInfo child in nestedModules)
{
GetAllNestedModules(child, ref nestedModulesWithNoCircularReference);
}
}
}
/// <summary>
/// Returns a map from a module to the list of modules that require it.
/// </summary>
private Dictionary<PSModuleInfo, List<PSModuleInfo>> GetRequiredDependencies()
{
Dictionary<PSModuleInfo, List<PSModuleInfo>> requiredDependencies = new Dictionary<PSModuleInfo, List<PSModuleInfo>>();
foreach (PSModuleInfo module in Context.Modules.GetModules(new string[] { "*" }, false))
{
foreach (PSModuleInfo requiredModule in module.RequiredModules)
{
List<PSModuleInfo> requiredByList = null;
if (!requiredDependencies.TryGetValue(requiredModule, out requiredByList))
{
requiredDependencies.Add(requiredModule, requiredByList = new List<PSModuleInfo>());
}
requiredByList.Add(module);
}
}
return requiredDependencies;
}
/// <summary>
/// Reports an error if no modules were removed...
/// </summary>
protected override void EndProcessing()
{
// Write an error record if specific modules were to be removed.
// By specific, we mean either a name sting with no wildcards or
// or a PSModuleInfo object. If the removal request only includes patterns
// then we won't write the error.
if (_numberRemoved == 0 && !MyInvocation.BoundParameters.ContainsKey("WhatIf"))
{
bool hasWildcards = true;
bool isEngineModule = true;
foreach (string n in _name)
{
if (!InitialSessionState.IsEngineModule(n))
{
isEngineModule = false;
}
if (!WildcardPattern.ContainsWildcardCharacters(n))
hasWildcards = false;
}
if (FullyQualifiedName != null && (FullyQualifiedName.Any(static moduleSpec => !InitialSessionState.IsEngineModule(moduleSpec.Name))))
{
isEngineModule = false;
}
if (!isEngineModule && (!hasWildcards || _moduleInfo.Length != 0 || (FullyQualifiedName != null && FullyQualifiedName.Length != 0)))
{
string message = StringUtil.Format(Modules.NoModulesRemoved);
InvalidOperationException invalidOp = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(invalidOp, "Modules_NoModulesRemoved",
ErrorCategory.ResourceUnavailable, null);
WriteError(er);
}
}
}
}
#endregion Remove-Module
}
| |
// Copyright (c) 2011, Eric Maupin
// 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 Gablarski nor the names of its
// contributors may be used to endorse or promote products
// or services 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.Collections.Generic;
using System.Linq;
using Cadenza.Collections;
namespace Gablarski.Client
{
internal class ClientUserManager
: IClientUserManager
{
public IUserInfo this[int userId]
{
get
{
UserInfo user;
lock (syncRoot)
{
this.users.TryGetValue (userId, out user);
}
return user;
}
}
public void Join (IUserInfo user)
{
if (user == null)
throw new ArgumentNullException ("user");
var u = new UserInfo (user);
Update (u);
}
public bool GetIsJoined (IUserInfo user)
{
if (user == null)
throw new ArgumentNullException ("user");
lock (syncRoot)
return users.ContainsKey (user.UserId);
}
public bool GetIsIgnored (IUserInfo user)
{
if (user == null)
throw new ArgumentNullException ("user");
lock (this.syncRoot)
return this.ignores.Contains (user.UserId);
}
public bool Depart (IUserInfo user)
{
if (user == null)
throw new ArgumentNullException ("user");
lock (this.syncRoot)
{
this.ignores.Remove (user.UserId);
UserInfo realUser;
if (this.users.TryGetValue (user.UserId, out realUser))
{
this.users.Remove (user.UserId);
return this.channels.Remove (user.CurrentChannelId, realUser);
}
else
return false;
}
}
public void Update (IEnumerable<IUserInfo> userUpdate)
{
if (userUpdate == null)
throw new ArgumentNullException ("userUpdate");
lock (this.syncRoot)
{
this.ignores = new HashSet<int> (this.ignores.Intersect (userUpdate.Select (u => u.UserId)));
this.users = userUpdate.ToDictionary (u => u.UserId, u => new UserInfo (u));
this.channels =
new MutableLookup<int, UserInfo> (userUpdate.ToLookup (u => u.CurrentChannelId, u => new UserInfo (u)));
}
}
public void Update (IUserInfo user)
{
if (user == null)
throw new ArgumentNullException ("user");
lock (this.syncRoot)
{
UserInfo oldUser;
if (users.TryGetValue (user.UserId, out oldUser))
channels.Remove (oldUser.CurrentChannelId, oldUser);
channels.Add (user.CurrentChannelId, users[user.UserId] = new UserInfo (user));
}
}
public void Clear ()
{
lock (this.syncRoot)
{
ignores.Clear();
users.Clear();
channels.Clear();
}
}
public IEnumerable<IUserInfo> GetUsersInChannel (int channelId)
{
lock (this.syncRoot)
{
return this.channels[channelId].Cast<IUserInfo>().ToList();
}
}
public bool ToggleIgnore (IUserInfo user)
{
if (user == null)
throw new ArgumentNullException ("user");
bool ignored;
lock (this.syncRoot)
{
if (!(ignored = ignores.Remove (user.UserId)))
ignores.Add (user.UserId);
}
return !ignored;
}
public void ToggleMute (IUserInfo user)
{
if (user == null)
throw new ArgumentNullException ("user");
lock (this.syncRoot)
{
UserInfo oldUser;
if (!users.TryGetValue (user.UserId, out oldUser))
oldUser = new UserInfo (user);
users[user.UserId] = new UserInfo (oldUser.Nickname, user.Phonetic, user.Username, user.UserId, user.CurrentChannelId, !user.IsMuted);
}
}
public IEnumerator<IUserInfo> GetEnumerator ()
{
IEnumerable<IUserInfo> returnUsers;
lock (this.syncRoot)
{
returnUsers = this.users.Values.Cast<IUserInfo>().ToList();
}
return returnUsers.GetEnumerator ();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
object IClientUserManager.SyncRoot
{
get { return this.syncRoot; }
}
private readonly object syncRoot = new object ();
private HashSet<int> ignores = new HashSet<int>();
private Dictionary<int, UserInfo> users = new Dictionary<int, UserInfo> ();
private MutableLookup<int, UserInfo> channels = new MutableLookup<int, UserInfo> ();
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#define LLVM
namespace Microsoft.Zelig.Runtime
{
using System;
using System.Runtime.CompilerServices;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
using ISA = TargetModel.ArmProcessor.InstructionSetVersion;
[ExtendClass(typeof(System.Threading.Interlocked), NoConstructors=true, PlatformVersionFilter=(ISA.Platform_Version__ARMv6M | ISA.Platform_Version__ARM_legacy))]
public static class InterlockedImpl_ARMv6M
{
//
// Helper Methods
//
public static int Increment( ref int location )
{
return InternalAdd( ref location, 1 );
}
public static long Increment( ref long location )
{
using(SmartHandles.InterruptState.DisableAll())
{
return ++location;
}
}
public static int Decrement( ref int location )
{
return InternalAdd( ref location, -1 );
}
public static long Decrement( ref long location )
{
using(SmartHandles.InterruptState.DisableAll())
{
return --location;
}
}
public static int Exchange( ref int location1 ,
int value )
{
return InternalExchange( ref location1, value );
}
public static long Exchange( ref long location1 ,
long value )
{
using(SmartHandles.InterruptState.DisableAll())
{
long oldValue = location1;
location1 = value;
return oldValue;
}
}
public static float Exchange( ref float location1 ,
float value )
{
return InternalExchange( ref location1, value );
}
public static double Exchange( ref double location1 ,
double value )
{
using(SmartHandles.InterruptState.DisableAll())
{
double oldValue = location1;
location1 = value;
return oldValue;
}
}
public static Object Exchange( ref Object location1 ,
Object value )
{
return InternalExchange( ref location1, value );
}
public static IntPtr Exchange( ref IntPtr location1, IntPtr value )
{
return InternalExchange( ref location1, value );
}
public static T Exchange<T>( ref T location1 ,
T value ) where T : class
{
return InternalExchange( ref location1, value );
}
//--//
public static int CompareExchange( ref int location1 ,
int value ,
int comparand )
{
return InternalCompareExchange( ref location1, value, comparand );
}
public static long CompareExchange( ref long location1 ,
long value ,
long comparand )
{
using(SmartHandles.InterruptState.DisableAll())
{
long oldValue = location1;
if(oldValue == comparand)
{
location1 = value;
}
return oldValue;
}
}
public static float CompareExchange( ref float location1 ,
float value ,
float comparand )
{
return InternalCompareExchange( ref location1, value, comparand );
}
public static double CompareExchange( ref double location1 ,
double value ,
double comparand )
{
using(SmartHandles.InterruptState.DisableAll())
{
double oldValue = location1;
if(oldValue == comparand)
{
location1 = value;
}
return oldValue;
}
}
public static Object CompareExchange( ref Object location1 ,
Object value ,
Object comparand )
{
return InternalCompareExchange( ref location1, value, comparand );
}
public static IntPtr CompareExchange( ref IntPtr location1 ,
IntPtr value ,
IntPtr comparand )
{
return InternalCompareExchange( ref location1, value, comparand );
}
public static T CompareExchange<T>( ref T location1 ,
T value ,
T comparand ) where T : class
{
return InternalCompareExchange( ref location1, value, comparand );
}
public static int Add( ref int location1 ,
int value )
{
return InternalAdd( ref location1, value );
}
public static long Add( ref long location1 ,
long value )
{
using(SmartHandles.InterruptState.DisableAll())
{
long res = location1 + value;
location1 = res;
return res;
}
}
//--//
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalExchange_int" )]
internal static int InternalExchange( ref int location1,
int value )
{
using(SmartHandles.InterruptState.DisableAll( ))
{
int oldValue = location1;
location1 = value;
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalExchange_float" )]
internal static float InternalExchange( ref float location1,
float value )
{
using(SmartHandles.InterruptState.DisableAll( ))
{
float oldValue = location1;
location1 = value;
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalExchange_IntPtr" )]
internal static IntPtr InternalExchange( ref IntPtr location1,
IntPtr value )
{
using(SmartHandles.InterruptState.DisableAll( ))
{
IntPtr oldValue = location1;
location1 = value;
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalExchange_Template" )]
[TS.DisableAutomaticReferenceCounting]
internal static T InternalExchange<T>( ref T location1,
T value ) where T : class
{
using(SmartHandles.InterruptState.DisableAll( ))
{
T oldValue = location1;
location1 = value;
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_int" )]
internal static int InternalCompareExchange( ref int location1,
int value,
int comparand )
{
using(SmartHandles.InterruptState.DisableAll( ))
{
int oldValue = location1;
if(oldValue == comparand)
{
location1 = value;
}
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_float" )]
internal static float InternalCompareExchange( ref float location1,
float value,
float comparand )
{
using(SmartHandles.InterruptState.DisableAll( ))
{
float oldValue = location1;
if(oldValue == comparand)
{
location1 = value;
}
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_IntPtr" )]
internal static IntPtr InternalCompareExchange( ref IntPtr location1,
IntPtr value,
IntPtr comparand )
{
using(SmartHandles.InterruptState.DisableAll( ))
{
IntPtr oldValue = location1;
if(oldValue == comparand)
{
location1 = value;
}
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalCompareExchange_Template" )]
[TS.DisableAutomaticReferenceCounting]
internal static T InternalCompareExchange<T>( ref T location1,
T value,
T comparand ) where T : class
{
using(SmartHandles.InterruptState.DisableAll( ))
{
T oldValue = location1;
if(Object.ReferenceEquals( oldValue, comparand ))
{
location1 = value;
}
return oldValue;
}
}
[Inline]
[TS.WellKnownMethod( "InterlockedImpl_InternalAdd_int" )]
internal static int InternalAdd( ref int location1,
int value )
{
using(SmartHandles.InterruptState.DisableAll( ))
{
int res = location1 + value;
location1 = res;
return res;
}
}
}
}
| |
// 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 System.IO;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security.Cryptography.Asn1;
using Internal.Cryptography;
namespace System.Security.Cryptography
{
public abstract partial class DSA : AsymmetricAlgorithm
{
public abstract DSAParameters ExportParameters(bool includePrivateParameters);
public abstract void ImportParameters(DSAParameters parameters);
protected DSA() { }
public static new DSA Create(string algName)
{
return (DSA)CryptoConfig.CreateFromName(algName);
}
public static DSA Create(int keySizeInBits)
{
DSA dsa = Create();
try
{
dsa.KeySize = keySizeInBits;
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
public static DSA Create(DSAParameters parameters)
{
DSA dsa = Create();
try
{
dsa.ImportParameters(parameters);
return dsa;
}
catch
{
dsa.Dispose();
throw;
}
}
// DSA does not encode the algorithm identifier into the signature blob, therefore CreateSignature and
// VerifySignature do not need the HashAlgorithmName value, only SignData and VerifyData do.
abstract public byte[] CreateSignature(byte[] rgbHash);
abstract public bool VerifySignature(byte[] rgbHash, byte[] rgbSignature);
protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
{
throw DerivedClassMustOverride();
}
public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
return SignData(data, 0, data.Length, hashAlgorithm);
}
public virtual byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); }
if (count < 0 || count > data.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return CreateSignature(hash);
}
public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, hashAlgorithm);
return CreateSignature(hash);
}
public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
return VerifyData(data, 0, data.Length, signature, hashAlgorithm);
}
public virtual bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (offset < 0 || offset > data.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); }
if (count < 0 || count > data.Length - offset) { throw new ArgumentOutOfRangeException(nameof(count)); }
if (signature == null) { throw new ArgumentNullException(nameof(signature)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, offset, count, hashAlgorithm);
return VerifySignature(hash, signature);
}
public virtual bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm)
{
if (data == null) { throw new ArgumentNullException(nameof(data)); }
if (signature == null) { throw new ArgumentNullException(nameof(signature)); }
if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); }
byte[] hash = HashData(data, hashAlgorithm);
return VerifySignature(hash, signature);
}
public virtual bool TryCreateSignature(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten)
{
byte[] sig = CreateSignature(hash.ToArray());
if (sig.Length <= destination.Length)
{
new ReadOnlySpan<byte>(sig).CopyTo(destination);
bytesWritten = sig.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
byte[] array = ArrayPool<byte>.Shared.Rent(data.Length);
try
{
data.CopyTo(array);
byte[] hash = HashData(array, 0, data.Length, hashAlgorithm);
if (destination.Length >= hash.Length)
{
new ReadOnlySpan<byte>(hash).CopyTo(destination);
bytesWritten = hash.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
finally
{
Array.Clear(array, 0, data.Length);
ArrayPool<byte>.Shared.Return(array);
}
}
public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
if (TryHashData(data, destination, hashAlgorithm, out int hashLength) &&
TryCreateSignature(destination.Slice(0, hashLength), destination, out bytesWritten))
{
return true;
}
bytesWritten = 0;
return false;
}
public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm)
{
if (string.IsNullOrEmpty(hashAlgorithm.Name))
{
throw HashAlgorithmNameNullOrEmpty();
}
for (int i = 256; ; i = checked(i * 2))
{
int hashLength = 0;
byte[] hash = ArrayPool<byte>.Shared.Rent(i);
try
{
if (TryHashData(data, hash, hashAlgorithm, out hashLength))
{
return VerifySignature(new ReadOnlySpan<byte>(hash, 0, hashLength), signature);
}
}
finally
{
Array.Clear(hash, 0, hashLength);
ArrayPool<byte>.Shared.Return(hash);
}
}
}
public virtual bool VerifySignature(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature) =>
VerifySignature(hash.ToArray(), signature.ToArray());
private static Exception DerivedClassMustOverride() =>
new NotImplementedException(SR.NotSupported_SubclassOverride);
internal static Exception HashAlgorithmNameNullOrEmpty() =>
new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
ReadOnlySpan<char>.Empty,
passwordBytes);
using (AsnWriter pkcs8PrivateKey = WritePkcs8())
using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
passwordBytes,
pkcs8PrivateKey,
pbeParameters))
{
return writer.TryEncode(destination, out bytesWritten);
}
}
public override bool TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
PbeParameters pbeParameters,
Span<byte> destination,
out int bytesWritten)
{
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
PasswordBasedEncryption.ValidatePbeParameters(
pbeParameters,
password,
ReadOnlySpan<byte>.Empty);
using (AsnWriter pkcs8PrivateKey = WritePkcs8())
using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8(
password,
pkcs8PrivateKey,
pbeParameters))
{
return writer.TryEncode(destination, out bytesWritten);
}
}
public override bool TryExportPkcs8PrivateKey(
Span<byte> destination,
out int bytesWritten)
{
using (AsnWriter writer = WritePkcs8())
{
return writer.TryEncode(destination, out bytesWritten);
}
}
public override bool TryExportSubjectPublicKeyInfo(
Span<byte> destination,
out int bytesWritten)
{
using (AsnWriter writer = WriteSubjectPublicKeyInfo())
{
return writer.TryEncode(destination, out bytesWritten);
}
}
private unsafe AsnWriter WritePkcs8()
{
DSAParameters dsaParameters = ExportParameters(true);
fixed (byte* privPin = dsaParameters.X)
{
try
{
return DSAKeyFormatHelper.WritePkcs8(dsaParameters);
}
finally
{
CryptographicOperations.ZeroMemory(dsaParameters.X);
}
}
}
private AsnWriter WriteSubjectPublicKeyInfo()
{
DSAParameters dsaParameters = ExportParameters(false);
return DSAKeyFormatHelper.WriteSubjectPublicKeyInfo(dsaParameters);
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadEncryptedPkcs8(
source,
passwordBytes,
out int localRead,
out DSAParameters ret);
fixed (byte* privPin = ret.X)
{
try
{
ImportParameters(ret);
}
finally
{
CryptographicOperations.ZeroMemory(ret.X);
}
}
bytesRead = localRead;
}
public override unsafe void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadEncryptedPkcs8(
source,
password,
out int localRead,
out DSAParameters ret);
fixed (byte* privPin = ret.X)
{
try
{
ImportParameters(ret);
}
finally
{
CryptographicOperations.ZeroMemory(ret.X);
}
}
bytesRead = localRead;
}
public override unsafe void ImportPkcs8PrivateKey(
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadPkcs8(
source,
out int localRead,
out DSAParameters key);
fixed (byte* privPin = key.X)
{
try
{
ImportParameters(key);
}
finally
{
CryptographicOperations.ZeroMemory(key.X);
}
}
bytesRead = localRead;
}
public override void ImportSubjectPublicKeyInfo(
ReadOnlySpan<byte> source,
out int bytesRead)
{
DSAKeyFormatHelper.ReadSubjectPublicKeyInfo(
source,
out int localRead,
out DSAParameters key);
ImportParameters(key);
bytesRead = localRead;
}
}
}
| |
/*
* 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.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.World.Estate
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XEstate")]
public class EstateModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected List<Scene> m_Scenes = new List<Scene>();
protected bool m_InInfoUpdate = false;
private string token = "7db8eh2gvgg45jj";
protected bool m_enabled = false;
public bool InInfoUpdate
{
get { return m_InInfoUpdate; }
set { m_InInfoUpdate = value; }
}
public List<Scene> Scenes
{
get { return m_Scenes; }
}
protected EstateConnector m_EstateConnector;
public void Initialise(IConfigSource config)
{
uint port = MainServer.Instance.Port;
IConfig estateConfig = config.Configs["Estates"];
if (estateConfig != null)
{
if (estateConfig.GetString("EstateCommunicationsHandler", Name) == Name)
m_enabled = true;
else
return;
port = (uint)estateConfig.GetInt("Port", 0);
// this will need to came from somewhere else
token = estateConfig.GetString("Token", token);
}
else
{
m_enabled = true;
}
m_EstateConnector = new EstateConnector(this, token, port);
if(port == 0)
port = MainServer.Instance.Port;
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer(port);
server.AddStreamHandler(new EstateRequestHandler(this, token));
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
lock (m_Scenes)
m_Scenes.Add(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_enabled)
return;
IEstateModule em = scene.RequestModuleInterface<IEstateModule>();
em.OnRegionInfoChange += OnRegionInfoChange;
em.OnEstateInfoChange += OnEstateInfoChange;
em.OnEstateMessage += OnEstateMessage;
em.OnEstateTeleportOneUserHomeRequest += OnEstateTeleportOneUserHomeRequest;
em.OnEstateTeleportAllUsersHomeRequest += OnEstateTeleportAllUsersHomeRequest;
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
lock (m_Scenes)
m_Scenes.Remove(scene);
}
public string Name
{
get { return "EstateModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
private Scene FindScene(UUID RegionID)
{
foreach (Scene s in Scenes)
{
if (s.RegionInfo.RegionID == RegionID)
return s;
}
return null;
}
private void OnRegionInfoChange(UUID RegionID)
{
Scene s = FindScene(RegionID);
if (s == null)
return;
if (!m_InInfoUpdate)
m_EstateConnector.SendUpdateCovenant(s.RegionInfo.EstateSettings.EstateID, s.RegionInfo.RegionSettings.Covenant);
}
private void OnEstateInfoChange(UUID RegionID)
{
Scene s = FindScene(RegionID);
if (s == null)
return;
if (!m_InInfoUpdate)
m_EstateConnector.SendUpdateEstate(s.RegionInfo.EstateSettings.EstateID);
}
private void OnEstateMessage(UUID RegionID, UUID FromID, string FromName, string Message)
{
Scene senderScenes = FindScene(RegionID);
if (senderScenes == null)
return;
uint estateID = senderScenes.RegionInfo.EstateSettings.EstateID;
foreach (Scene s in Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == estateID)
{
IDialogModule dm = s.RequestModuleInterface<IDialogModule>();
if (dm != null)
{
dm.SendNotificationToUsersInRegion(FromID, FromName,
Message);
}
}
}
if (!m_InInfoUpdate)
m_EstateConnector.SendEstateMessage(estateID, FromID, FromName, Message);
}
private void OnEstateTeleportOneUserHomeRequest(IClientAPI client, UUID invoice, UUID senderID, UUID prey)
{
if (prey == UUID.Zero)
return;
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
uint estateID = scene.RegionInfo.EstateSettings.EstateID;
if (!scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
return;
foreach (Scene s in Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID != estateID)
continue;
ScenePresence p = scene.GetScenePresence(prey);
if (p != null && !p.IsChildAgent )
{
if(!p.IsDeleted && !p.IsInTransit)
{
p.ControllingClient.SendTeleportStart(16);
scene.TeleportClientHome(prey, p.ControllingClient);
}
return;
}
}
m_EstateConnector.SendTeleportHomeOneUser(estateID, prey);
}
private void OnEstateTeleportAllUsersHomeRequest(IClientAPI client, UUID invoice, UUID senderID)
{
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
uint estateID = scene.RegionInfo.EstateSettings.EstateID;
if (!scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
return;
foreach (Scene s in Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID != estateID)
continue;
scene.ForEachScenePresence(delegate(ScenePresence p) {
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
scene.TeleportClientHome(p.ControllingClient.AgentId, p.ControllingClient);
}
});
}
m_EstateConnector.SendTeleportHomeAllUsers(estateID);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using Dbg = System.Management.Automation;
using System;
using System.Management.Automation;
using System.Management.Automation.Security;
using System.Management.Automation.Internal;
using System.IO;
using System.Collections.ObjectModel;
using System.Management.Automation.Host;
using System.Management.Automation.Language;
using System.Security;
using System.Security.Cryptography.X509Certificates;
#if CORECLR
// Use stub for SecurityZone
using Microsoft.PowerShell.CoreClr.Stubs;
using Environment = System.Management.Automation.Environment;
#endif
namespace Microsoft.PowerShell
{
/// <summary>
/// Defines the authorization policy that controls the way scripts
/// (and other command types) are handled by Monad. This authorization
/// policy enforces one of four levels, as defined by the 'ExecutionPolicy'
/// value in one of the following locations:
///
/// In priority-order (highest priority first,) these come from:
///
/// - Machine-wide Group Policy
/// HKLM\Software\Policies\Microsoft\Windows\PowerShell
/// - Current-user Group Policy
/// HKCU\Software\Policies\Microsoft\Windows\PowerShell.
/// - Current session preference
/// ENV:PSExecutionPolicyPreference
/// - Current user machine preference
/// HKEY_CURRENT_USER\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
/// - Local machine preference
/// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell
///
/// Restricted - All .ps1 files are blocked. ps1xml files must be digitally
/// signed, and by a trusted publisher. If you haven't made a trust decision
/// on the publisher yet, prompting is done as in AllSigned mode.
/// AllSigned - All .ps1 and .ps1xml files must be digitally signed. If
/// signed and executed, Monad prompts to determine if files from the
/// signing publisher should be run or not.
/// RemoteSigned - Only .ps1 and .ps1xml files originating from the internet
/// must be digitally signed. If remote, signed, and executed, Monad
/// prompts to determine if files from the signing publisher should be
/// run or not. This is the default setting.
/// Unrestricted - No files must be signed. If a file originates from the
/// internet, Monad provides a warning prompt to alert the user. To
/// suppress this warning message, right-click on the file in File Explorer,
/// select "Properties," and then "Unblock."
/// Bypass - No files must be signed, and internet origin is not verified
///
/// </summary>
public sealed class PSAuthorizationManager : AuthorizationManager
{
internal enum RunPromptDecision
{
NeverRun = 0,
DoNotRun = 1,
RunOnce = 2,
AlwaysRun = 3,
Suspend = 4
}
#region constructor
// execution policy that dictates what can run in msh
private ExecutionPolicy _executionPolicy;
//shellId supplied by runspace configuration
private string _shellId;
/// <summary>
/// Initializes a new instance of the PSAuthorizationManager
/// class, for a given ShellId.
/// </summary>
/// <param name="shellId">
/// The shell identifier that the authorization manager applies
/// to. For example, Microsoft.PowerShell
/// </param>
public PSAuthorizationManager(string shellId)
: base(shellId)
{
if (string.IsNullOrEmpty(shellId))
{
throw PSTraceSource.NewArgumentNullException("shellId");
}
_shellId = shellId;
}
#endregion constructor
#region signing check
private static bool IsSupportedExtension(string ext)
{
return (
ext.Equals(".ps1", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".ps1xml", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".psm1", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".psd1", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".xaml", StringComparison.OrdinalIgnoreCase) ||
ext.Equals(".cdxml", StringComparison.OrdinalIgnoreCase));
}
private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason)
{
bool policyCheckPassed = false;
reason = null;
string path = script.Path;
string reasonMessage;
// path is assumed to be fully qualified here
if (path.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0)
{
throw PSTraceSource.NewArgumentException("path");
}
if (path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) == (path.Length - 1))
{
throw PSTraceSource.NewArgumentException("path");
}
FileInfo fi = new FileInfo(path);
// Return false if the file does not exist, so that
// we don't introduce a race condition
if (!fi.Exists)
{
reason = new FileNotFoundException(path);
return false;
}
// Quick exit if we don't support the file type
if (!IsSupportedExtension(fi.Extension))
return true;
// Product binaries are always trusted
if (SecuritySupport.IsProductBinary(path))
return true;
// Get the execution policy
_executionPolicy = SecuritySupport.GetExecutionPolicy(_shellId);
// See if they want to bypass the authorization manager
if (_executionPolicy == ExecutionPolicy.Bypass)
return true;
#if !CORECLR
// Always check the SAFER APIs if code integrity isn't being handled system-wide through
// WLDP or AppLocker. In those cases, the scripts will be run in ConstrainedLanguage.
// Otherwise, block.
// SAFER APIs are not on CSS or OneCore
if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)
{
SaferPolicy saferPolicy = SaferPolicy.Disallowed;
int saferAttempt = 0;
bool gotSaferPolicy = false;
// We need to put in a retry workaround, as the SAFER APIs fail when under stress.
while ((!gotSaferPolicy) && (saferAttempt < 5))
{
try
{
saferPolicy = SecuritySupport.GetSaferPolicy(path, null);
gotSaferPolicy = true;
}
catch (System.ComponentModel.Win32Exception)
{
if (saferAttempt > 4) { throw; }
saferAttempt++;
System.Threading.Thread.Sleep(100);
}
}
// If the script is disallowed via AppLocker, block the file
// unless the system-wide lockdown policy is "Enforce" (where all PowerShell
// scripts are in blocked). If the system policy is "Enforce", then the
// script will be allowed (but ConstrainedLanguage will be applied).
if (saferPolicy == SaferPolicy.Disallowed)
{
reasonMessage = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path);
reason = new UnauthorizedAccessException(reasonMessage);
return false;
}
}
#endif
if (_executionPolicy == ExecutionPolicy.Unrestricted)
{
// We need to give the "Remote File" warning
// if the file originated from the internet
if (!IsLocalFile(fi.FullName))
{
// Get the signature of the file.
if (String.IsNullOrEmpty(script.ScriptContents))
{
reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
reason = new UnauthorizedAccessException(reasonMessage);
return false;
}
Signature signature = GetSignatureWithEncodingRetry(path, script);
// The file is signed, with a publisher that
// we trust
if (signature.Status == SignatureStatus.Valid)
{
// The file is signed by a trusted publisher
if (IsTrustedPublisher(signature, path))
{
policyCheckPassed = true;
}
}
// We don't care about the signature. If you distrust them,
// or the signature does not exist, we prompt you only
// because it's remote.
if (!policyCheckPassed)
{
RunPromptDecision decision = RunPromptDecision.DoNotRun;
// Get their remote prompt answer, allowing them to
// enter nested prompts, if wanted.
do
{
decision = RemoteFilePrompt(path, host);
if (decision == RunPromptDecision.Suspend)
host.EnterNestedPrompt();
} while (decision == RunPromptDecision.Suspend);
switch (decision)
{
case RunPromptDecision.RunOnce:
policyCheckPassed = true;
break;
case RunPromptDecision.DoNotRun:
default:
policyCheckPassed = false;
reasonMessage = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
reason = new UnauthorizedAccessException(reasonMessage);
break;
}
}
}
else
{
policyCheckPassed = true;
}
}
// Don't need to check the signature if the file is local
// and we're in "RemoteSigned" mode
else if ((IsLocalFile(fi.FullName)) &&
(_executionPolicy == ExecutionPolicy.RemoteSigned))
{
policyCheckPassed = true;
}
else if ((_executionPolicy == ExecutionPolicy.AllSigned) ||
(_executionPolicy == ExecutionPolicy.RemoteSigned))
{
// if policy requires signature verification,
// make it so.
// Get the signature of the file.
if (String.IsNullOrEmpty(script.ScriptContents))
{
reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
reason = new UnauthorizedAccessException(reasonMessage);
return false;
}
Signature signature = GetSignatureWithEncodingRetry(path, script);
// The file is signed.
if (signature.Status == SignatureStatus.Valid)
{
// The file is signed by a trusted publisher
if (IsTrustedPublisher(signature, path))
{
policyCheckPassed = true;
}
// The file is signed by an unknown publisher,
// So prompt.
else
{
policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
}
}
// The file is UnknownError, NotSigned, HashMismatch,
// NotTrusted, NotSupportedFileFormat
else
{
policyCheckPassed = false;
if (signature.Status == SignatureStatus.NotTrusted)
{
reason = new UnauthorizedAccessException(
StringUtil.Format(Authenticode.Reason_NotTrusted,
path,
signature.SignerCertificate.SubjectName.Name));
}
else
{
reason = new UnauthorizedAccessException(
StringUtil.Format(Authenticode.Reason_Unknown,
path,
signature.StatusMessage));
}
}
}
else // if(executionPolicy == ExecutionPolicy.Restricted)
{
// Deny everything
policyCheckPassed = false;
// But accept mshxml files from publishers that we
// trust, or files in the system protected directories
bool reasonSet = false;
if (String.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
{
string[] trustedDirectories = new string[]
{ Environment.GetFolderPath(Environment.SpecialFolder.System),
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
};
foreach (string trustedDirectory in trustedDirectories)
{
if (fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase))
policyCheckPassed = true;
}
if (!policyCheckPassed)
{
// Get the signature of the file.
Signature signature = GetSignatureWithEncodingRetry(path, script);
// The file is signed by a trusted publisher
if (signature.Status == SignatureStatus.Valid)
{
if (IsTrustedPublisher(signature, path))
{
policyCheckPassed = true;
}
// The file is signed by an unknown publisher,
// So prompt.
else
{
policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
reasonSet = true;
}
}
}
}
if (!policyCheckPassed && !reasonSet)
{
reason = new UnauthorizedAccessException(
StringUtil.Format(Authenticode.Reason_RestrictedMode,
path));
}
}
return policyCheckPassed;
}
private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, Signature signature)
{
bool policyCheckPassed = false;
string reasonMessage;
RunPromptDecision decision = AuthenticodePrompt(path, signature, host);
switch (decision)
{
case RunPromptDecision.RunOnce:
policyCheckPassed = true; break;
case RunPromptDecision.AlwaysRun:
{
TrustPublisher(signature);
policyCheckPassed = true;
}; break;
case RunPromptDecision.DoNotRun:
policyCheckPassed = false;
reasonMessage = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
reason = new UnauthorizedAccessException(reasonMessage);
break;
case RunPromptDecision.NeverRun:
{
UntrustPublisher(signature);
reasonMessage = StringUtil.Format(Authenticode.Reason_NeverRun, path);
reason = new UnauthorizedAccessException(reasonMessage);
policyCheckPassed = false;
}; break;
}
return policyCheckPassed;
}
private bool IsLocalFile(string filename)
{
SecurityZone zone = ClrFacade.GetFileSecurityZone(filename);
if (zone == SecurityZone.MyComputer ||
zone == SecurityZone.Intranet ||
zone == SecurityZone.Trusted)
{
return true;
}
return false;
}
// Checks that a publisher is trusted by the system or is one of
// the signed product binaries
private bool IsTrustedPublisher(Signature signature, string file)
{
// Get the thumbprint of the current signature
X509Certificate2 signerCertificate = signature.SignerCertificate;
string thumbprint = signerCertificate.Thumbprint;
// See if it matches any in the list of trusted publishers
X509Store trustedPublishers = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
trustedPublishers.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates)
{
if (String.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase))
if (!IsUntrustedPublisher(signature, file)) return true;
}
return false;
}
private bool IsUntrustedPublisher(Signature signature, string file)
{
// Get the thumbprint of the current signature
X509Certificate2 signerCertificate = signature.SignerCertificate;
string thumbprint = signerCertificate.Thumbprint;
// See if it matches any in the list of trusted publishers
X509Store trustedPublishers = new X509Store(StoreName.Disallowed, StoreLocation.CurrentUser);
trustedPublishers.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates)
{
if (String.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// Trust a publisher by adding it to the "Trusted Publishers" store
/// </summary>
/// <param name="signature"></param>
private void TrustPublisher(Signature signature)
{
// Get the certificate of the signer
X509Certificate2 signerCertificate = signature.SignerCertificate;
X509Store trustedPublishers = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
try
{
// Add it to the list of trusted publishers
trustedPublishers.Open(OpenFlags.ReadWrite);
trustedPublishers.Add(signerCertificate);
}
finally
{
trustedPublishers.Close();
}
}
private void UntrustPublisher(Signature signature)
{
// Get the certificate of the signer
X509Certificate2 signerCertificate = signature.SignerCertificate;
X509Store untrustedPublishers = new X509Store(StoreName.Disallowed, StoreLocation.CurrentUser);
X509Store trustedPublishers = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
// Remove it from the list of trusted publishers
try
{
// Remove the signer, if it's there
trustedPublishers.Open(OpenFlags.ReadWrite);
trustedPublishers.Remove(signerCertificate);
}
finally
{
trustedPublishers.Close();
}
try
{
// Add it to the list of untrusted publishers
untrustedPublishers.Open(OpenFlags.ReadWrite);
untrustedPublishers.Add(signerCertificate);
}
finally
{
untrustedPublishers.Close();
}
}
private Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script)
{
string verificationContents = System.Text.Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents;
Signature signature = SignatureHelper.GetSignature(path, verificationContents);
// If the file was originally ASCII or UTF8, the SIP may have added the Unicode BOM
if ((signature.Status != SignatureStatus.Valid) && (script.OriginalEncoding != System.Text.Encoding.Unicode))
{
verificationContents = System.Text.Encoding.Unicode.GetString(System.Text.Encoding.Unicode.GetPreamble()) + script.ScriptContents;
Signature fallbackSignature = SignatureHelper.GetSignature(path, verificationContents);
if (fallbackSignature.Status == SignatureStatus.Valid)
signature = fallbackSignature;
}
return signature;
}
#endregion signing check
/// <summary>
/// Determines if should run the specified command. Please see the
/// class summary for an overview of the semantics enforced by this
/// authorization manager.
/// </summary>
///
/// <param name="commandInfo">
/// The command to be run.
/// </param>
/// <param name="origin">
/// The origin of the command.
/// </param>
/// <param name="host">
/// The PSHost executing the command.
/// </param>
/// <param name="reason">
/// If access is denied, this parameter provides a specialized
/// Exception as the reason.
/// </param>
///
/// <returns>
/// True if the command should be run. False otherwise.
/// </returns>
///
/// <exception cref="System.ArgumentException">
/// CommandInfo is invalid. This may occur if
/// commandInfo.Name is null or empty.
/// </exception>
///
/// <exception cref="System.ArgumentNullException">
/// CommandInfo is null.
/// </exception>
///
/// <exception cref="System.IO.FileNotFoundException">
/// The file specified by commandInfo.Path is not found.
/// </exception>
protected internal override bool ShouldRun(CommandInfo commandInfo,
CommandOrigin origin,
PSHost host,
out Exception reason)
{
Dbg.Diagnostics.Assert(commandInfo != null, "caller should validate the parameter");
bool allowRun = false;
reason = null;
Utils.CheckArgForNull(commandInfo, "commandInfo");
Utils.CheckArgForNullOrEmpty(commandInfo.Name, "commandInfo.Name");
switch (commandInfo.CommandType)
{
case CommandTypes.Cmdlet:
// Always allow cmdlets to run
allowRun = true;
break;
case CommandTypes.Alias:
//
// we do not care about verifying an alias as we will
// get subsequent call(s) for commands/scripts
// when the alias is expanded.
//
allowRun = true;
break;
case CommandTypes.Function:
case CommandTypes.Filter:
case CommandTypes.Workflow:
case CommandTypes.Configuration:
//
// we do not check functions/filters.
// we only perform script level check.
//
allowRun = true;
break;
case CommandTypes.Script:
//
// Allow scripts that are built into the
// runspace configuration to run.
//
allowRun = true;
break;
case CommandTypes.ExternalScript:
ExternalScriptInfo si = commandInfo as ExternalScriptInfo;
if (si == null)
{
reason = PSTraceSource.NewArgumentException("scriptInfo");
}
else
{
bool etwEnabled = ParserEventSource.Log.IsEnabled();
if (etwEnabled) ParserEventSource.Log.CheckSecurityStart(si.Path);
allowRun = CheckPolicy(si, host, out reason);
if (etwEnabled) ParserEventSource.Log.CheckSecurityStop(si.Path);
}
break;
case CommandTypes.Application:
//
// We do not check executables -- that is done by Windows
//
allowRun = true;
break;
}
return allowRun;
}
private RunPromptDecision AuthenticodePrompt(string path,
Signature signature,
PSHost host)
{
if ((host == null) || (host.UI == null))
{
return RunPromptDecision.DoNotRun;
}
RunPromptDecision decision = RunPromptDecision.DoNotRun;
if (signature == null)
{
return decision;
}
switch (signature.Status)
{
//
// we do not allow execution in any one of the
// following cases
//
case SignatureStatus.UnknownError:
case SignatureStatus.NotSigned:
case SignatureStatus.HashMismatch:
case SignatureStatus.NotSupportedFileFormat:
decision = RunPromptDecision.DoNotRun;
break;
case SignatureStatus.Valid:
Collection<ChoiceDescription> choices = GetAuthenticodePromptChoices();
string promptCaption =
Authenticode.AuthenticodePromptCaption;
string promptText;
if (signature.SignerCertificate == null)
{
promptText =
StringUtil.Format(Authenticode.AuthenticodePromptText_UnknownPublisher,
path);
}
else
{
promptText =
StringUtil.Format(Authenticode.AuthenticodePromptText,
path,
signature.SignerCertificate.SubjectName.Name
);
}
int userChoice =
host.UI.PromptForChoice(promptCaption,
promptText,
choices,
(int)RunPromptDecision.DoNotRun);
decision = (RunPromptDecision)userChoice;
break;
//
// if the publisher is not trusted, we prompt and
// ask the user if s/he wants to allow it to run
//
default:
decision = RunPromptDecision.DoNotRun;
break;
}
return decision;
}
private RunPromptDecision RemoteFilePrompt(string path, PSHost host)
{
if ((host == null) || (host.UI == null))
{
return RunPromptDecision.DoNotRun;
}
Collection<ChoiceDescription> choices = GetRemoteFilePromptChoices();
string promptCaption =
Authenticode.RemoteFilePromptCaption;
string promptText =
StringUtil.Format(Authenticode.RemoteFilePromptText,
path);
int userChoice = host.UI.PromptForChoice(promptCaption,
promptText,
choices,
0);
switch (userChoice)
{
case 0: return RunPromptDecision.DoNotRun;
case 1: return RunPromptDecision.RunOnce;
case 2: return RunPromptDecision.Suspend;
default: return RunPromptDecision.DoNotRun;
}
}
private Collection<ChoiceDescription> GetAuthenticodePromptChoices()
{
Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
string neverRun = Authenticode.Choice_NeverRun;
string neverRunHelp = Authenticode.Choice_NeverRun_Help;
string doNotRun = Authenticode.Choice_DoNotRun;
string doNotRunHelp = Authenticode.Choice_DoNotRun_Help;
string runOnce = Authenticode.Choice_RunOnce;
string runOnceHelp = Authenticode.Choice_RunOnce_Help;
string alwaysRun = Authenticode.Choice_AlwaysRun;
string alwaysRunHelp = Authenticode.Choice_AlwaysRun_Help;
choices.Add(new ChoiceDescription(neverRun, neverRunHelp));
choices.Add(new ChoiceDescription(doNotRun, doNotRunHelp));
choices.Add(new ChoiceDescription(runOnce, runOnceHelp));
choices.Add(new ChoiceDescription(alwaysRun, alwaysRunHelp));
return choices;
}
private Collection<ChoiceDescription> GetRemoteFilePromptChoices()
{
Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
string doNotRun = Authenticode.Choice_DoNotRun;
string doNotRunHelp = Authenticode.Choice_DoNotRun_Help;
string runOnce = Authenticode.Choice_RunOnce;
string runOnceHelp = Authenticode.Choice_RunOnce_Help;
string suspend = Authenticode.Choice_Suspend;
string suspendHelp = Authenticode.Choice_Suspend_Help;
choices.Add(new ChoiceDescription(doNotRun, doNotRunHelp));
choices.Add(new ChoiceDescription(runOnce, runOnceHelp));
choices.Add(new ChoiceDescription(suspend, suspendHelp));
return choices;
}
}
}
| |
/*
* CodeCompiler.cs - Implementation of the
* System.CodeDom.Compiler.CodeCompiler class.
*
* Copyright (C) 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.CodeDom.Compiler
{
#if CONFIG_CODEDOM
using System.IO;
using System.Collections;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Text;
public abstract class CodeCompiler : CodeGenerator, ICodeCompiler
{
// Constructor.
protected CodeCompiler() : base() {}
// Join an array of strings with a separator.
protected static String JoinStringArray(String[] sa, String separator)
{
if(sa == null || sa.Length == 0)
{
return String.Empty;
}
return ProcessStartInfo.ArgVToArguments(sa, 0, separator);
}
// Get the name of the compiler.
protected abstract String CompilerName { get; }
// Get the file extension to use for source files.
protected abstract String FileExtension { get; }
// Convert compiler parameters into compiler arguments.
protected abstract String CmdArgsFromParameters
(CompilerParameters options);
// Compile a CodeDom compile unit.
protected virtual CompilerResults FromDom
(CompilerParameters options, CodeCompileUnit e)
{
CodeCompileUnit[] list = new CodeCompileUnit [1];
list[0] = e;
return FromDomBatch(options, list);
}
// Compile an array of CodeDom compile units.
protected virtual CompilerResults FromDomBatch
(CompilerParameters options, CodeCompileUnit[] ea)
{
// Write all of the CodeDom units to temporary files.
String[] tempFiles = new String [ea.Length];
int src;
Stream stream;
StreamWriter writer;
for(src = 0; src < ea.Length; ++src)
{
foreach(String assembly in ea[src].ReferencedAssemblies)
{
if(!options.ReferencedAssemblies.Contains(assembly))
{
options.ReferencedAssemblies.Add(assembly);
}
}
tempFiles[src] = options.TempFiles.AddExtension
(src + FileExtension);
stream = new FileStream(tempFiles[src], FileMode.Create,
FileAccess.Write, FileShare.Read);
try
{
writer = new StreamWriter(stream, Encoding.UTF8);
((ICodeGenerator)this).GenerateCodeFromCompileUnit
(ea[src], writer, Options);
writer.Flush();
writer.Close();
}
finally
{
stream.Close();
}
}
// Compile the temporary files.
return FromFileBatch(options, tempFiles);
}
// Compile a file.
protected virtual CompilerResults FromFile
(CompilerParameters options, String fileName)
{
// Verify that the file can be read, throwing an
// exception to the caller if it cannot.
(new FileStream(fileName, FileMode.Open, FileAccess.Read))
.Close();
// Pass the filename to "FromFileBatch".
String[] list = new String [1];
list[0] = fileName;
return FromFileBatch(options, list);
}
// Compile an array of files.
protected virtual CompilerResults FromFileBatch
(CompilerParameters options, String[] fileNames)
{
// Add an output filename to the options if necessary.
if(options.OutputAssembly == null ||
options.OutputAssembly.Length == 0)
{
if(options.GenerateExecutable)
{
options.OutputAssembly = options.TempFiles.AddExtension
("exe", !(options.GenerateInMemory));
}
else
{
options.OutputAssembly = options.TempFiles.AddExtension
("dll", !(options.GenerateInMemory));
}
}
// Build the full command-line to pass to the compiler.
String args = CmdArgsFromParameters(options);
args = args + " " + JoinStringArray(fileNames, " ");
// If the argument array is too long, then write the
// command-line to a temporary file and use "@file".
if(args.Length > 8192) // string length > 8k
{
args = GetResponseFileCmdArgs(options, args);
}
// Create a compiler results block.
CompilerResults results;
results = new CompilerResults(options.TempFiles);
// Build the process start info block.
ProcessStartInfo startInfo;
startInfo = new ProcessStartInfo(CompilerName, args);
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
// Create and run the process.
Process process = Process.Start(startInfo);
// Read the stderr stream until EOF.
String line;
while((line = process.StandardError.ReadLine()) != null)
{
results.Output.Add(line);
ProcessCompilerOutputLine(results, line);
}
// Wait for the process to exit and record the return code.
process.WaitForExit();
results.NativeCompilerReturnValue = process.ExitCode;
process.Close();
// Load the assembly into memory if necessary.
if(!(results.Errors.HasErrors) && options.GenerateInMemory)
{
FileStream stream;
stream = new FileStream(options.OutputAssembly,
FileMode.Open, FileAccess.Read,
FileShare.Read);
try
{
// We must use the memory-based load method,
// because "OutputAssembly" may be deleted
// before we are done with the assembly.
byte[] buf = new byte [(int)(stream.Length)];
stream.Read(buf, 0, buf.Length);
results.CompiledAssembly = Assembly.Load(buf);
}
finally
{
stream.Close();
}
}
else
{
results.PathToAssembly = options.OutputAssembly;
}
// Return the final results to the caller.
return results;
}
// Compile a source string.
protected virtual CompilerResults FromSource
(CompilerParameters options, String source)
{
String[] list = new String [1];
list[0] = source;
return FromSourceBatch(options, list);
}
// Compile an array of source strings.
protected virtual CompilerResults FromSourceBatch
(CompilerParameters options, String[] sources)
{
// Write all of the sources to temporary files.
String[] tempFiles = new String [sources.Length];
int src;
Stream stream;
StreamWriter writer;
for(src = 0; src < sources.Length; ++src)
{
tempFiles[src] = options.TempFiles.AddExtension
(src + "." + FileExtension);
stream = new FileStream(tempFiles[src], FileMode.Create,
FileAccess.Write, FileShare.Read);
try
{
writer = new StreamWriter(stream, Encoding.UTF8);
writer.Write(sources[src]);
writer.Flush();
writer.Close();
}
finally
{
stream.Close();
}
}
// Compile the temporary files.
return FromFileBatch(options, tempFiles);
}
// Get the response file command arguments.
protected virtual String GetResponseFileCmdArgs
(CompilerParameters options, String cmdArgs)
{
// Get a temporary file to use for the response file.
String responseFile = options.TempFiles.AddExtension("cmdline");
// Write the arguments to the response file.
Stream stream = new FileStream(responseFile, FileMode.Create,
FileAccess.Write,
FileShare.Read);
try
{
StreamWriter writer = new StreamWriter
(stream, Encoding.UTF8);
writer.Write(cmdArgs);
writer.Flush();
writer.Close();
}
finally
{
stream.Close();
}
// Build the new command-line containing the response file.
return "@\"" + responseFile + "\"";
}
// Internal version of "ProcessCompilerOutputLine".
// The line may have one of the following forms:
//
// FILENAME(LINE,COLUMN): error CODE: message
// FILENAME(LINE,COLUMN): fatal error CODE: message
// FILENAME(LINE,COLUMN): warning CODE: message
// FILENAME:LINE: message
// FILENAME:LINE:COLUMN: message
// FILENAME:LINE: warning: message
// FILENAME:LINE:COLUMN: warning: message
//
internal static CompilerError ProcessCompilerOutputLine(String line)
{
CompilerError error;
int posn, start;
// Bail out if the line is empty.
if(line == null || line.Length == 0)
{
return null;
}
// Create the error block.
error = new CompilerError();
// Parse out the filename.
posn = 0;
if(line.Length >= 3 && Char.IsLetter(line[0]) &&
line[1] == ':' && (line[2] == '/' || line[2] == '\\'))
{
// Filename starting with a Windows drive specification.
posn += 3;
}
while(posn < line.Length && line[posn] != ':' &&
line[posn] != '(')
{
++posn;
}
if(posn >= line.Length)
{
return null;
}
error.FileName = line.Substring(0, posn);
// Parse out the line and column numbers.
if(line[posn] == '(')
{
// (LINE,COLUMN) format.
++posn;
start = posn;
while(posn < line.Length && line[posn] != ')' &&
line[posn] != ',')
{
++posn;
}
error.Line = Int32.Parse
(line.Substring(start, posn - start));
if(posn < line.Length && line[posn] == ',')
{
++posn;
start = posn;
while(posn < line.Length && line[posn] != ')' &&
line[posn] != ',')
{
++posn;
}
error.Column = Int32.Parse
(line.Substring(start, posn - start));
}
while(posn < line.Length && line[posn] != ')')
{
++posn;
}
if(posn < line.Length)
{
++posn;
}
if(posn < line.Length && line[posn] == ':')
{
++posn;
}
}
else
{
// LINE:COLUMN format.
++posn;
start = posn;
while(posn < line.Length && line[posn] != ':')
{
++posn;
}
try {
error.Line = Int32.Parse
(line.Substring(start, posn - start));
if(posn < line.Length && line[posn + 1] != ' ')
{
++posn;
start = posn;
while(posn < line.Length && line[posn] != ':')
{
++posn;
}
error.Column = Int32.Parse
(line.Substring(start, posn - start));
}
if(posn < line.Length)
{
++posn;
}
}
catch {
// compiler output could be XXXX: no such library.
// so Int32.Parse(XXXX: no such library) would throw an exception
error.Line = 0;
error.Column = 0;
error.ErrorText = line;
return error;
}
}
// Skip white space.
while(posn < line.Length && line[posn] == ' ')
{
++posn;
}
// Parse the error type.
bool needCode = true;
if((line.Length - posn) >= 6 &&
String.CompareOrdinal("error ", 0, line, posn, 6) == 0)
{
posn += 6;
}
else if((line.Length - posn) >= 12 &&
String.CompareOrdinal
("fatal error ", 0, line, posn, 12) == 0)
{
posn += 12;
}
else if((line.Length - posn) >= 8 &&
String.CompareOrdinal
("warning ", 0, line, posn, 8) == 0)
{
error.IsWarning = true;
posn += 8;
}
else if((line.Length - posn) >= 8 &&
String.CompareOrdinal
("warning:", 0, line, posn, 8) == 0)
{
error.IsWarning = true;
posn += 8;
needCode = false;
}
else
{
needCode = false;
}
// Parse the error code.
if(needCode)
{
start = posn;
while(posn < line.Length && line[posn] != ':')
{
++posn;
}
error.ErrorNumber = line.Substring(posn, posn - start);
if(posn < line.Length)
{
++posn;
}
}
// Skip white space.
while(posn < line.Length && line[posn] == ' ')
{
++posn;
}
// Extract the error text.
error.ErrorText = line.Substring(posn);
// Return the error block to the caller.
return error;
}
// Process an output line from the compiler.
protected abstract void ProcessCompilerOutputLine
(CompilerResults results, String line);
// Compile an assembly from a CodeDom compile unit.
CompilerResults ICodeCompiler.CompileAssemblyFromDom
(CompilerParameters options, CodeCompileUnit compilationUnit)
{
try
{
return FromDom(options, compilationUnit);
}
finally
{
options.TempFiles.Delete();
}
}
// Compile an assembly from an array of CodeDom compile units.
CompilerResults ICodeCompiler.CompileAssemblyFromDomBatch
(CompilerParameters options, CodeCompileUnit[] compilationUnits)
{
try
{
return FromDomBatch(options, compilationUnits);
}
finally
{
options.TempFiles.Delete();
}
}
// Compile an assembly from the contents of a source file.
CompilerResults ICodeCompiler.CompileAssemblyFromFile
(CompilerParameters options, String fileName)
{
try
{
return FromFile(options, fileName);
}
finally
{
options.TempFiles.Delete();
}
}
// Compile an assembly from the contents of an array of source files.
CompilerResults ICodeCompiler.CompileAssemblyFromFileBatch
(CompilerParameters options, String[] fileNames)
{
try
{
return FromFileBatch(options, fileNames);
}
finally
{
options.TempFiles.Delete();
}
}
// Compile an assembly from the contents of a source string.
CompilerResults ICodeCompiler.CompileAssemblyFromSource
(CompilerParameters options, String source)
{
try
{
return FromSource(options, source);
}
finally
{
options.TempFiles.Delete();
}
}
// Compile an assembly from the contents of an array of source strings.
CompilerResults ICodeCompiler.CompileAssemblyFromSourceBatch
(CompilerParameters options, String[] sources)
{
try
{
return FromSourceBatch(options, sources);
}
finally
{
options.TempFiles.Delete();
}
}
}; // class CodeCompiler
#endif // CONFIG_CODEDOM
}; // namespace System.CodeDom.Compiler
| |
namespace Nancy.Tests.Unit
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using FakeItEasy;
using Nancy.IO;
using Xunit;
using Xunit.Extensions;
public class RequestFixture
{
[Fact]
public void Should_dispose_request_stream_when_being_disposed()
{
// Given
var stream = A.Fake<RequestStream>(x =>
{
x.Implements(typeof(IDisposable));
x.WithArgumentsForConstructor(() => new RequestStream(0, false));
});
var url = new Url()
{
Scheme = "http",
Path = "localhost"
};
var request = new Request("GET", url, stream);
// When
request.Dispose();
// Then
A.CallTo(() => ((IDisposable)stream).Dispose()).MustHaveHappened();
}
[Fact]
public void Should_be_disposable()
{
// Given, When, Then
typeof(Request).ShouldImplementInterface<IDisposable>();
}
[Fact]
public void Should_override_request_method_on_post()
{
// Given
const string bodyContent = "_method=GET";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } };
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
request.Method.ShouldEqual("GET");
}
[Theory]
[InlineData("GET")]
[InlineData("PUT")]
[InlineData("DELETE")]
[InlineData("HEAD")]
public void Should_only_override_method_on_post(string method)
{
// Given
const string bodyContent = "_method=TEST";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>> { { "content-type", new[] { "application/x-www-form-urlencoded" } } };
// When
var request = new Request(method, new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
request.Method.ShouldEqual(method);
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_method()
{
// Given, When
var exception =
Record.Exception(() => new Request(null, "/", "http"));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_empty_method()
{
// Given, When
var exception =
Record.Exception(() => new Request(string.Empty, "/", "http"));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_throw_null_exception_when_initialized_with_null_uri()
{
// Given, When
var exception =
Record.Exception(() => new Request("GET", null, "http"));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_set_method_parameter_value_to_method_property_when_initialized()
{
// Given
const string method = "GET";
// When
var request = new Request(method, "/", "http");
// Then
request.Method.ShouldEqual(method);
}
[Fact]
public void Should_set_uri_parameter_value_to_uri_property_when_initialized()
{
// Given
const string path = "/";
// When
var request = new Request("GET", path, "http");
// Then
request.Path.ShouldEqual(path);
}
[Fact]
public void Should_set_header_parameter_value_to_header_property_when_initialized()
{
// Given
var headers = new Dictionary<string, IEnumerable<string>>()
{
{ "content-type", new[] {"foo"} }
};
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(), headers);
// Then
request.Headers.ContentType.ShouldNotBeEmpty();
}
[Fact]
public void Should_set_body_parameter_value_to_body_property_when_initialized()
{
// Given
var body = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http" }, body, new Dictionary<string, IEnumerable<string>>());
// Then
request.Body.ShouldBeSameAs(body);
}
[Fact]
public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded()
{
// Given
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
}
[Fact]
public void Should_set_extract_form_data_from_body_when_content_type_is_x_www_form_urlencoded_with_character_set()
{
// Given
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
}
[Fact]
public void Should_set_extracted_form_data_from_body_when_content_type_is_multipart_form_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>
{
{ "name", "John Doe"},
{ "age", "42"}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
((string)request.Form.age).ShouldEqual("42");
}
[Fact]
public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded()
{
// Given
StaticConfiguration.CaseSensitive = false;
const string bodyContent = "key=value&key=value&KEY=VALUE";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.key).ShouldEqual("value,value,VALUE");
((string)request.Form.KEY).ShouldEqual("value,value,VALUE");
}
[Fact]
public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_x_www_form_urlencoded()
{
// Given
StaticConfiguration.CaseSensitive = true;
const string bodyContent = "key=value&key=value&KEY=VALUE";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((string)request.Form.key).ShouldEqual("value,value");
((string)request.Form.KEY).ShouldEqual("VALUE");
}
[Fact]
public void Should_respect_case_insensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data()
{
// Given
StaticConfiguration.CaseSensitive = false;
var memory =
new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.InvariantCulture)
{
{ "key", "value" },
{ "KEY", "VALUE" }
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.key).ShouldEqual("value,VALUE");
((string)request.Form.KEY).ShouldEqual("value,VALUE");
}
[Fact]
public void Should_respect_case_sensitivity_when_extracting_form_data_from_body_when_content_type_is_multipart_form_data()
{
// Given
StaticConfiguration.CaseSensitive = true;
var memory =
new MemoryStream(BuildMultipartFormValues(new Dictionary<string, string>(StringComparer.InvariantCulture)
{
{ "key", "value" },
{ "KEY", "VALUE" }
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.key).ShouldEqual("value");
((string)request.Form.KEY).ShouldEqual("VALUE");
}
[Fact]
public void Should_set_extracted_files_to_files_collection_when_body_content_type_is_multipart_form_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "test", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.ShouldHaveCount(1);
}
[Fact]
public void Should_set_content_type_on_file_extracted_from_multipart_form_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.First().ContentType.ShouldEqual("content/type");
}
[Fact]
public void Should_set_name_on_file_extracted_from_multipart_form_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.First().Name.ShouldEqual("sample.txt");
}
[Fact]
public void Should_value_on_file_extracted_from_multipart_form_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
GetStringValue(request.Files.First().Value).ShouldEqual("some test content");
}
[Fact]
public void Should_set_key_on_file_extracted_from_multipart_data_body()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "fieldname")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
request.Files.First().Key.ShouldEqual("fieldname");
}
private static string GetStringValue(Stream stream)
{
var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
[Fact]
public void Should_be_able_to_invoke_form_repeatedly()
{
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = new MemoryStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.name).ShouldEqual("John Doe");
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_null_protocol()
{
// Given, When
var exception =
Record.Exception(() => new Request("GET", "/", null));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_throw_argumentoutofrangeexception_when_initialized_with_an_empty_protocol()
{
// Given, When
var exception =
Record.Exception(() => new Request("GET", "/", string.Empty));
// Then
exception.ShouldBeOfType<ArgumentOutOfRangeException>();
}
[Fact]
public void Should_set_protocol_parameter_value_to_protocol_property_when_initialized()
{
// Given
const string protocol = "http";
// When
var request = new Request("GET", "/", protocol);
// Then
request.Url.Scheme.ShouldEqual(protocol);
}
[Fact]
public void Should_split_cookie_in_two_parts_only()
{
// Given, when
var cookieName = "_nc";
var cookieData = "Y+M3rcC/7ssXvHTx9pwCbwQVV4g=sp0hUZVApYgGbKZIU4bvXbBCVl9fhSEssEXSGdrt4jVag6PO1oed8lSd+EJD1nzWx4OTTCTZKjYRWeHE97QVND4jJIl+DuKRgJnSl3hWI5gdgGjcxqCSTvMOMGmW3NHLVyKpajGD8tq1DXhXMyXHjTzrCAYl8TGzwyJJGx/gd7VMJeRbAy9JdHOxEUlCKUnPneWN6q+/ITFryAa5hAdfcjXmh4Fgym75whKOMkWO+yM2icdsciX0ShcvnEQ/bXcTHTya6d7dJVfZl7qQ8AgIQv8ucQHxD3NxIvHNPBwms2ClaPds0HG5N+7pu7eMSFZjUHpDrrCnFvYN+JDiG3GMpf98LuCCvxemvipJo2MUkY4J1LvaDFoWA5tIxAfItZJkSIW2d8JPDwFk8OHJy8zhyn8AjD2JFqWaUZr4y9KZOtgI0V0Qlq0mS3mDSlLn29xapgoPHBvykwQjR6TwF2pBLpStsfZa/tXbEv2mc3VO3CnErIA1lEfKNqn9C/Dw6hqW";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string>();
cookies.Add(string.Format("{0}={1}", cookieName, cookieData));
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_secure_attribute()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; Secure", cookieName, cookieData)} ;
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; HttpOnly; Secure", cookieName, cookieData) };
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_httponly_and_secure_attribute_ignoring_case()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; httponly; secure", cookieName, cookieData) };
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_split_cookie_in_two_parts_with_httponly_attribute()
{
// Given, when
const string cookieName = "path";
const string cookieData = "/";
var headers = new Dictionary<string, IEnumerable<string>>();
var cookies = new List<string> { string.Format("{0}={1}; HttpOnly", cookieName, cookieData) };
headers.Add("cookie", cookies);
var newUrl = new Url
{
Path = "/"
};
var request = new Request("GET", newUrl, null, headers);
// Then
request.Cookies[cookieName].ShouldEqual(cookieData);
}
[Fact]
public void Should_move_request_body_position_to_zero_after_parsing_url_encoded_data()
{
// Given
const string bodyContent = "name=John+Doe&gender=male&family=5&city=kent&city=miami&other=abc%0D%0Adef&nickname=J%26D";
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(bodyContent);
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded; charset=UTF-8" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
memory.Position.ShouldEqual(0L);
}
[Fact]
public void Should_move_request_body_position_to_zero_after_parsing_multipart_encoded_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFileValues(new Dictionary<string, Tuple<string, string, string>>
{
{ "sample.txt", new Tuple<string, string, string>("content/type", "some test content", "whatever")}
}));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
memory.Position.ShouldEqual(0L);
}
[Fact]
public void Should_preserve_all_values_when_multiple_are_posted_using_same_name_after_parsing_multipart_encoded_data()
{
// Given
var memory =
new MemoryStream(BuildMultipartFormValues(
new KeyValuePair<string, string>("age", "32"),
new KeyValuePair<string, string>("age", "42"),
new KeyValuePair<string, string>("age", "52")
));
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "multipart/form-data; boundary=----NancyFormBoundary" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, CreateRequestStream(memory), headers);
// Then
((string)request.Form.age).ShouldEqual("32,42,52");
}
[Fact]
public void Should_limit_the_amount_of_form_fields_parsed()
{
// Given
var sb = new StringBuilder();
for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++)
{
if (i > 0)
{
sb.Append('&');
}
sb.AppendFormat("Field{0}=Value{0}", i);
}
var memory = CreateRequestStream();
var writer = new StreamWriter(memory);
writer.Write(sb.ToString());
writer.Flush();
memory.Position = 0;
var headers =
new Dictionary<string, IEnumerable<string>>
{
{ "content-type", new[] { "application/x-www-form-urlencoded" } }
};
// When
var request = new Request("POST", new Url { Path = "/", Scheme = "http" }, memory, headers);
// Then
((IEnumerable<string>)request.Form.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);
}
[Fact]
public void Should_limit_the_amount_of_querystring_fields_parsed()
{
// Given
var sb = new StringBuilder();
for (int i = 0; i < StaticConfiguration.RequestQueryFormMultipartLimit + 10; i++)
{
if (i > 0)
{
sb.Append('&');
}
sb.AppendFormat("Field{0}=Value{0}", i);
}
var memory = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = sb.ToString() }, memory, new Dictionary<string, IEnumerable<string>>());
// Then
((IEnumerable<string>)request.Query.GetDynamicMemberNames()).Count().ShouldEqual(StaticConfiguration.RequestQueryFormMultipartLimit);
}
[Fact]
public void Should_change_empty_path_to_root()
{
var request = new Request("GET", "", "http");
request.Path.ShouldEqual("/");
}
[Fact]
public void Should_replace_value_of_query_key_without_value_with_true()
{
// Given
var memory = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = "key1" }, memory);
// Then
((bool)request.Query.key1).ShouldBeTrue();
((string)request.Query.key1).ShouldEqual("key1");
}
[Fact]
public void Should_not_replace_equal_key_value_query_with_bool()
{
// Given
var memory = CreateRequestStream();
// When
var request = new Request("GET", new Url { Path = "/", Scheme = "http", Query = "key1=key1" }, memory);
// Then
ShouldAssertExtensions.ShouldBeOfType<string>(request.Query["key1"].Value);
}
private static RequestStream CreateRequestStream()
{
return CreateRequestStream(new MemoryStream());
}
private static RequestStream CreateRequestStream(Stream stream)
{
return RequestStream.FromStream(stream);
}
private static byte[] BuildMultipartFormValues(params KeyValuePair<string, string>[] values)
{
var boundaryBuilder = new StringBuilder();
foreach (var pair in values)
{
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("--");
boundaryBuilder.Append("----NancyFormBoundary");
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{0}\"", pair.Key);
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append(pair.Value);
}
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("------NancyFormBoundary--");
var bytes =
Encoding.ASCII.GetBytes(boundaryBuilder.ToString());
return bytes;
}
private static byte[] BuildMultipartFormValues(Dictionary<string, string> formValues)
{
var pairs =
formValues.Keys.Select(key => new KeyValuePair<string, string>(key, formValues[key]));
return BuildMultipartFormValues(pairs.ToArray());
}
private static byte[] BuildMultipartFileValues(Dictionary<string, Tuple<string, string, string>> formValues)
{
var boundaryBuilder = new StringBuilder();
foreach (var key in formValues.Keys)
{
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("--");
boundaryBuilder.Append("----NancyFormBoundary");
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.AppendFormat("Content-Disposition: form-data; name=\"{1}\"; filename=\"{0}\"", key, formValues[key].Item3);
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.AppendFormat("Content-Type: {0}", formValues[key].Item1);
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append(formValues[key].Item2);
}
boundaryBuilder.Append('\r');
boundaryBuilder.Append('\n');
boundaryBuilder.Append("------NancyFormBoundary--");
var bytes =
Encoding.ASCII.GetBytes(boundaryBuilder.ToString());
return bytes;
}
}
}
| |
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// Language governing permissions and limitations under the License.
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ArcGISRuntime.UWP.Samples.GeodatabaseTransactions
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Geodatabase transactions",
category: "Data",
description: "Use transactions to manage how changes are committed to a geodatabase.",
instructions: "When the sample loads, a feature service is taken offline as a geodatabase. When the geodatabase is ready, you can add multiple types of features. To apply edits directly, uncheck the 'Require a transaction for edits' checkbox. When using transactions, use the buttons to start editing and stop editing. When you stop editing, you can choose to commit the changes or roll them back. At any point, you can synchronize the local geodatabase with the feature service.",
tags: new[] { "commit", "database", "geodatabase", "transact", "transactions" })]
public partial class GeodatabaseTransactions
{
// URL for the editable feature service
private const string SyncServiceUrl = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/SaveTheBaySync/FeatureServer/";
// Work in a small extent south of Galveston, TX
private Envelope _extent = new Envelope(-95.3035, 29.0100, -95.1053, 29.1298, SpatialReferences.Wgs84);
// Store the local geodatabase to edit
private Geodatabase _localGeodatabase;
// Store references to two tables to edit: Birds and Marine points
private GeodatabaseFeatureTable _birdTable;
private GeodatabaseFeatureTable _marineTable;
public GeodatabaseTransactions()
{
InitializeComponent();
// When the map view loads, add a new map
MyMapView.Loaded += (s, e) =>
{
// Create a new map with the oceans basemap and add it to the map view
Map map = new Map(BasemapStyle.ArcGISOceans);
MyMapView.Map = map;
};
// When the spatial reference changes (the map loads) add the local geodatabase tables as feature layers
MyMapView.SpatialReferenceChanged += async (s, e) =>
{
// Call a function (and await it) to get the local geodatabase (or generate it from the feature service)
await GetLocalGeodatabase();
// Once the local geodatabase is available, load the tables as layers to the map
LoadLocalGeodatabaseTables();
};
}
private async Task GetLocalGeodatabase()
{
// Get the path to the local geodatabase for this platform (temp directory, for example)
string localGeodatabasePath = GetGdbPath();
try
{
// See if the geodatabase file is already present
if (File.Exists(localGeodatabasePath))
{
// If the geodatabase is already available, open it, hide the progress control, and update the message
_localGeodatabase = await Geodatabase.OpenAsync(localGeodatabasePath);
LoadingProgressBar.Visibility = Visibility.Collapsed;
MessageTextBlock.Text = "Using local geodatabase from '" + _localGeodatabase.Path + "'";
}
else
{
// Create a new GeodatabaseSyncTask with the uri of the feature server to pull from
Uri uri = new Uri(SyncServiceUrl);
GeodatabaseSyncTask gdbTask = await GeodatabaseSyncTask.CreateAsync(uri);
// Create parameters for the task: layers and extent to include, out spatial reference, and sync model
GenerateGeodatabaseParameters gdbParams = await gdbTask.CreateDefaultGenerateGeodatabaseParametersAsync(_extent);
gdbParams.OutSpatialReference = MyMapView.SpatialReference;
gdbParams.SyncModel = SyncModel.Layer;
gdbParams.LayerOptions.Clear();
gdbParams.LayerOptions.Add(new GenerateLayerOption(0));
gdbParams.LayerOptions.Add(new GenerateLayerOption(1));
// Create a geodatabase job that generates the geodatabase
GenerateGeodatabaseJob generateGdbJob = gdbTask.GenerateGeodatabase(gdbParams, localGeodatabasePath);
// Handle the job changed event and check the status of the job; store the geodatabase when it's ready
generateGdbJob.JobChanged += async (s, e) =>
{
// See if the job succeeded
if (generateGdbJob.Status == JobStatus.Succeeded)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Hide the progress control and update the message
LoadingProgressBar.Visibility = Visibility.Collapsed;
MessageTextBlock.Text = "Created local geodatabase";
});
}
else if (generateGdbJob.Status == JobStatus.Failed)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// Hide the progress control and report the exception
LoadingProgressBar.Visibility = Visibility.Collapsed;
MessageTextBlock.Text = "Unable to create local geodatabase: " + generateGdbJob.Error.Message;
});
}
};
// Start the generate geodatabase job
_localGeodatabase = await generateGdbJob.GetResultAsync();
}
}
catch (Exception ex)
{
// Show a message for the exception encountered
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await new MessageDialog("Unable to create offline database: " + ex.Message).ShowAsync();
});
}
}
// Function that loads the two point tables from the local geodatabase and displays them as feature layers
private async void LoadLocalGeodatabaseTables()
{
if(_localGeodatabase == null) { return; }
// Read the geodatabase tables and add them as layers
foreach (GeodatabaseFeatureTable table in _localGeodatabase.GeodatabaseFeatureTables)
{
try
{
// Load the table so the TableName can be read
await table.LoadAsync();
// Store a reference to the Birds table
if (table.TableName.ToLower().Contains("birds"))
{
_birdTable = table;
}
// Store a reference to the Marine table
if (table.TableName.ToLower().Contains("marine"))
{
_marineTable = table;
}
// Create a new feature layer to show the table in the map
FeatureLayer layer = new FeatureLayer(table);
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => MyMapView.Map.OperationalLayers.Add(layer));
}
catch (Exception e)
{
await new MessageDialog(e.ToString(), "Error").ShowAsync();
}
}
// Handle the transaction status changed event
_localGeodatabase.TransactionStatusChanged += GdbTransactionStatusChanged;
// Zoom the map view to the extent of the generated local datasets
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MyMapView.SetViewpoint(new Viewpoint(_marineTable.Extent));
StartEditingButton.IsEnabled = true;
});
}
private async void GdbTransactionStatusChanged(object sender, TransactionStatusChangedEventArgs e)
{
// Update UI controls based on whether the geodatabase has a current transaction
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// These buttons should be enabled when there IS a transaction
AddBirdButton.IsEnabled = e.IsInTransaction;
AddMarineButton.IsEnabled = e.IsInTransaction;
StopEditingButton.IsEnabled = e.IsInTransaction;
// These buttons should be enabled when there is NOT a transaction
StartEditingButton.IsEnabled = !e.IsInTransaction;
SyncEditsButton.IsEnabled = !e.IsInTransaction;
});
}
private string GetGdbPath()
{
// Get the UWP-specific path for storing the geodatabase
string folder = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
return Path.Combine(folder, "savethebay.geodatabase");
}
private void BeginTransaction(object sender, RoutedEventArgs e)
{
// See if there is a transaction active for the geodatabase
if (!_localGeodatabase.IsInTransaction)
{
// If not, begin a transaction
_localGeodatabase.BeginTransaction();
MessageTextBlock.Text = "Transaction started";
}
}
private async void AddNewFeature(object sender, RoutedEventArgs args)
{
// See if it was the "Birds" or "Marine" button that was clicked
Button addFeatureButton = (Button)sender;
try
{
// Cancel execution of the sketch task if it is already active
if (MyMapView.SketchEditor.CancelCommand.CanExecute(null))
{
MyMapView.SketchEditor.CancelCommand.Execute(null);
}
// Store the correct table to edit (for the button clicked)
GeodatabaseFeatureTable editTable = null;
if (addFeatureButton == AddBirdButton)
{
editTable = _birdTable;
}
else
{
editTable = _marineTable;
}
// Inform the user which table is being edited
MessageTextBlock.Text = "Click the map to add a new feature to the geodatabase table '" + editTable.TableName + "'";
// Create a random value for the 'type' attribute (integer between 1 and 7)
Random random = new Random(DateTime.Now.Millisecond);
int featureType = random.Next(1, 7);
// Use the sketch editor to allow the user to draw a point on the map
MapPoint clickPoint = await MyMapView.SketchEditor.StartAsync(Esri.ArcGISRuntime.UI.SketchCreationMode.Point, false) as MapPoint;
// Create a new feature (row) in the selected table
Feature newFeature = editTable.CreateFeature();
// Set the geometry with the point the user clicked and the 'type' with the random integer
newFeature.Geometry = clickPoint;
newFeature.SetAttributeValue("type", featureType);
// Add the new feature to the table
await editTable.AddFeatureAsync(newFeature);
// Clear the message
MessageTextBlock.Text = "New feature added to the '" + editTable.TableName + "' table";
}
catch (TaskCanceledException)
{
// Ignore if the edit was canceled
}
catch (Exception ex)
{
// Report other exception messages
MessageTextBlock.Text = ex.Message;
}
}
private async void StopEditTransaction(object sender, RoutedEventArgs e)
{
// Create a new dialog that prompts for commit, rollback, or cancel
MessageDialog promptDialog = new MessageDialog("Commit your edits to the local geodatabase or rollback to discard them.", "Stop Editing");
UICommand commitCommand = new UICommand("Commit");
UICommand rollbackCommand = new UICommand("Rollback");
UICommand cancelCommand = new UICommand("Cancel");
promptDialog.Options = MessageDialogOptions.None;
promptDialog.Commands.Add(commitCommand);
promptDialog.Commands.Add(rollbackCommand);
promptDialog.Commands.Add(cancelCommand);
// Ask the user if they want to commit or rollback the transaction (or cancel to keep working in the transaction)
IUICommand cmd = await promptDialog.ShowAsync();
if (cmd == commitCommand)
{
// See if there is a transaction active for the geodatabase
if (_localGeodatabase.IsInTransaction)
{
// If there is, commit the transaction to store the edits (this will also end the transaction)
_localGeodatabase.CommitTransaction();
MessageTextBlock.Text = "Edits were committed to the local geodatabase.";
}
}
else if (cmd == rollbackCommand)
{
// See if there is a transaction active for the geodatabase
if (_localGeodatabase.IsInTransaction)
{
// If there is, rollback the transaction to discard the edits (this will also end the transaction)
_localGeodatabase.RollbackTransaction();
MessageTextBlock.Text = "Edits were rolled back and not stored to the local geodatabase.";
}
}
else
{
// For 'cancel' don't end the transaction with a commit or rollback
}
}
// Change which controls are enabled if the user chooses to require/not require transactions for edits
private async void RequireTransactionChanged(object sender, RoutedEventArgs e)
{
// If the local geodatabase isn't created yet, return
if (_localGeodatabase == null) { return; }
// Get the value of the "require transactions" checkbox
bool mustHaveTransaction = RequireTransactionCheckBox.IsChecked == true;
// Warn the user if disabling transactions while a transaction is active
if (!mustHaveTransaction && _localGeodatabase.IsInTransaction)
{
await new MessageDialog("Stop editing to end the current transaction.", "Current Transaction").ShowAsync();
RequireTransactionCheckBox.IsChecked = true;
return;
}
// Enable or disable controls according to the checkbox value
StartEditingButton.IsEnabled = mustHaveTransaction;
StopEditingButton.IsEnabled = mustHaveTransaction && _localGeodatabase.IsInTransaction;
AddBirdButton.IsEnabled = !mustHaveTransaction;
AddMarineButton.IsEnabled = !mustHaveTransaction;
}
// Synchronize edits in the local geodatabase with the service
public async void SynchronizeEdits(object sender, RoutedEventArgs e)
{
// Show the progress bar while the sync is working
LoadingProgressBar.Visibility = Visibility.Visible;
try
{
// Create a sync task with the URL of the feature service to sync
GeodatabaseSyncTask syncTask = await GeodatabaseSyncTask.CreateAsync(new Uri(SyncServiceUrl));
// Create sync parameters
SyncGeodatabaseParameters taskParameters = await syncTask.CreateDefaultSyncGeodatabaseParametersAsync(_localGeodatabase);
// Create a synchronize geodatabase job, pass in the parameters and the geodatabase
SyncGeodatabaseJob job = syncTask.SyncGeodatabase(taskParameters, _localGeodatabase);
// Handle the JobChanged event for the job
job.JobChanged += async (s, arg) =>
{
// Report changes in the job status
if (job.Status == JobStatus.Succeeded)
{
// Report success ...
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => MessageTextBlock.Text = "Synchronization is complete!");
}
else if (job.Status == JobStatus.Failed)
{
// Report failure ...
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => MessageTextBlock.Text = job.Error.Message);
}
else
{
// Report that the job is in progress ...
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => MessageTextBlock.Text = "Sync in progress ...");
}
};
// Await the completion of the job
await job.GetResultAsync();
}
catch (Exception ex)
{
// Show the message if an exception occurred
MessageTextBlock.Text = "Error when synchronizing: " + ex.Message;
}
finally
{
// Hide the progress bar when the sync job is complete
LoadingProgressBar.Visibility = Visibility.Collapsed;
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace NetGore.Collections
{
/// <summary>
/// A thread-safe implementation of a Dictionary.
/// </summary>
/// <typeparam name="TKey">Type of the key to use.</typeparam>
/// <typeparam name="TValue">Type of the value to store.</typeparam>
public class TSDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
readonly Dictionary<TKey, TValue> _dict;
readonly object _threadSync = new object();
/// <summary>
/// Initializes a new instance of the <see cref="TSDictionary{TKey, TValue}"/> class.
/// </summary>
public TSDictionary()
{
_dict = new Dictionary<TKey, TValue>();
}
/// <summary>
/// Initializes a new instance of the <see cref="TSDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="capacity">The initial capacity.</param>
public TSDictionary(int capacity)
{
_dict = new Dictionary<TKey, TValue>(capacity);
}
/// <summary>
/// Initializes a new instance of the <see cref="TSDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="comparer">The key comparer to use.</param>
public TSDictionary(IEqualityComparer<TKey> comparer)
{
_dict = new Dictionary<TKey, TValue>(comparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="TSDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="dictionary">A <see cref="IDictionary{TKey, TValue}"/> to copy the values from.</param>
public TSDictionary(IDictionary<TKey, TValue> dictionary)
{
_dict = new Dictionary<TKey, TValue>(dictionary);
}
/// <summary>
/// Initializes a new instance of the <see cref="TSDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="capacity">The initial capacity.</param>
/// <param name="comparer">The key comparer to use.</param>
public TSDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_dict = new Dictionary<TKey, TValue>(capacity, comparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="TSDictionary{TKey, TValue}"/> class.
/// </summary>
/// <param name="dictionary">A <see cref="IDictionary{TKey, TValue}"/> to copy the values from.</param>
/// <param name="comparer">The key comparer to use.</param>
public TSDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer)
{
_dict = new Dictionary<TKey, TValue>(dictionary, comparer);
}
/// <summary>
/// Determines whether a sequence contains a specified element by using a specified
/// <see cref="IEqualityComparer{T}"/>.
/// </summary>
/// <param name="value">The value to locate in the sequence.</param>
/// <param name="comparer">An equality comparer to compare values.</param>
/// <returns>
/// True if the source sequence contains an element that has the specified value; otherwise, false.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> value, IEqualityComparer<KeyValuePair<TKey, TValue>> comparer)
{
lock (_threadSync)
return _dict.Contains(value, comparer);
}
/// <summary>
/// Determines whether the <see cref="TSDictionary{TKey,TValue}"/> contains a specific value.
/// </summary>
/// <param name="value">The value to locate in the <see cref="TSDictionary{TKey,TValue}"/>.
/// The value can be null for reference types.</param>
/// <returns>True if the <see cref="TSDictionary{TKey,TValue}"/> contains an element with the specified value;
/// otherwise, false.</returns>
public bool ContainsValue(TValue value)
{
lock (_threadSync)
{
return _dict.ContainsValue(value);
}
}
#region IDictionary<TKey,TValue> Members
/// <summary>
/// Gets or sets the <see cref="TValue"/> with the specified key.
/// </summary>
public TValue this[TKey key]
{
get
{
lock (_threadSync)
{
return _dict[key];
}
}
set
{
lock (_threadSync)
{
_dict[key] = value;
}
}
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</returns>
public int Count
{
get
{
lock (_threadSync)
{
return _dict.Count;
}
}
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only;
/// otherwise, false.</returns>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the
/// <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that
/// implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.</returns>
public ICollection<TKey> Keys
{
get
{
lock (_threadSync)
{
return new List<TKey>(_dict.Keys);
}
}
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the
/// <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the
/// object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.</returns>
public ICollection<TValue> Values
{
get
{
lock (_threadSync)
{
return new List<TValue>(_dict.Values);
}
}
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/>
/// is read-only.</exception>
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
lock (_threadSync)
{
_dict.Add(item.Key, item.Value);
}
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.</exception>
/// <exception cref="T:System.ArgumentException">An element with the same key already exists in the
/// <see cref="T:System.Collections.Generic.IDictionary`2"/>.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/>
/// is read-only.</exception>
public void Add(TKey key, TValue value)
{
lock (_threadSync)
{
_dict.Add(key, value);
}
}
/// <summary>
/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/>
/// is read-only. </exception>
public void Clear()
{
lock (_threadSync)
{
_dict.Clear();
}
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>;
/// otherwise, false.
/// </returns>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
lock (_threadSync)
{
return _dict.Contains(item);
}
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the
/// specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key;
/// otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception>
public bool ContainsKey(TKey key)
{
lock (_threadSync)
{
return _dict.ContainsKey(key);
}
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an
/// <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements
/// copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/>
/// must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="array"/> is null.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="arrayIndex"/> is less than 0.</exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="array"/> is multidimensional.-or-<paramref name="arrayIndex"/> is equal to or greater than
/// the length of <paramref name="array"/>.-or-The number of elements in the source
/// <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from
/// <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-The type
/// cannot be cast automatically to the type of the destination
/// <paramref name="array"/>.</exception>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
lock (_threadSync)
{
((ICollection<KeyValuePair<TKey, TValue>>)_dict).CopyTo(array, arrayIndex);
}
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
lock (_threadSync)
{
return this.ToImmutable().GetEnumerator();
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the
/// <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false
/// if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/>
/// is read-only.</exception>
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
lock (_threadSync)
{
return ((ICollection<KeyValuePair<TKey, TValue>>)_dict).Remove(item);
}
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if
/// <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/>
/// is read-only.</exception>
public bool Remove(TKey key)
{
lock (_threadSync)
{
return _dict.Remove(key);
}
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found;
/// otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter
/// is passed uninitialized.</param>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>
/// contains an element with the specified key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.</exception>
public bool TryGetValue(TKey key, out TValue value)
{
lock (_threadSync)
{
return _dict.TryGetValue(key, out value);
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="KinectFusionHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.KinectFusionExplorer
{
using System;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Media.Media3D;
using Microsoft.Kinect;
using Microsoft.Kinect.Fusion;
/// <summary>
/// A helper class for common operations.
/// </summary>
public static class KinectFusionHelper
{
/// <summary>
/// Save mesh in binary .STL file
/// </summary>
/// <param name="mesh">Calculated mesh object</param>
/// <param name="writer">Binary file writer</param>
/// <param name="flipAxes">Flag to determine whether the Y and Z values are flipped on save,
/// default should be true.</param>
public static void SaveBinaryStlMesh(ColorMesh mesh, BinaryWriter writer, bool flipAxes)
{
if (null == mesh || null == writer)
{
return;
}
var vertices = mesh.GetVertices();
var normals = mesh.GetNormals();
var indices = mesh.GetTriangleIndexes();
// Check mesh arguments
if (0 == vertices.Count || 0 != vertices.Count % 3 || vertices.Count != indices.Count)
{
throw new ArgumentException("Invalid Mesh");
}
char[] header = new char[80];
writer.Write(header);
// Write number of triangles
int triangles = vertices.Count / 3;
writer.Write(triangles);
// Sequentially write the normal, 3 vertices of the triangle and attribute, for each triangle
for (int i = 0; i < triangles; i++)
{
// Write normal
var normal = normals[i * 3];
writer.Write(normal.X);
writer.Write(flipAxes ? -normal.Y : normal.Y);
writer.Write(flipAxes ? -normal.Z : normal.Z);
// Write vertices
for (int j = 0; j < 3; j++)
{
var vertex = vertices[(i * 3) + j];
writer.Write(vertex.X);
writer.Write(flipAxes ? -vertex.Y : vertex.Y);
writer.Write(flipAxes ? -vertex.Z : vertex.Z);
}
ushort attribute = 0;
writer.Write(attribute);
}
}
/// <summary>
/// Save mesh in ASCII WaveFront .OBJ file
/// </summary>
/// <param name="mesh">Calculated mesh object</param>
/// <param name="writer">The text writer</param>
/// <param name="flipAxes">Flag to determine whether the Y and Z values are flipped on save,
/// default should be true.</param>
public static void SaveAsciiObjMesh(ColorMesh mesh, TextWriter writer, bool flipAxes)
{
if (null == mesh || null == writer)
{
return;
}
var vertices = mesh.GetVertices();
var normals = mesh.GetNormals();
var indices = mesh.GetTriangleIndexes();
// Check mesh arguments
if (0 == vertices.Count || 0 != vertices.Count % 3 || vertices.Count != indices.Count)
{
throw new ArgumentException();
}
// Write the header lines
writer.WriteLine("#");
writer.WriteLine("# OBJ file created by Microsoft Kinect Fusion");
writer.WriteLine("#");
// Sequentially write the 3 vertices of the triangle, for each triangle
for (int i = 0; i < vertices.Count; i++)
{
var vertex = vertices[i];
string vertexString = "v " + vertex.X.ToString(CultureInfo.InvariantCulture) + " ";
if (flipAxes)
{
vertexString += (-vertex.Y).ToString(CultureInfo.InvariantCulture) + " " + (-vertex.Z).ToString(CultureInfo.InvariantCulture);
}
else
{
vertexString += vertex.Y.ToString(CultureInfo.InvariantCulture) + " " + vertex.Z.ToString(CultureInfo.InvariantCulture);
}
writer.WriteLine(vertexString);
}
// Sequentially write the 3 normals of the triangle, for each triangle
for (int i = 0; i < normals.Count; i++)
{
var normal = normals[i];
string normalString = "vn " + normal.X.ToString(CultureInfo.InvariantCulture) + " ";
if (flipAxes)
{
normalString += (-normal.Y).ToString(CultureInfo.InvariantCulture) + " " + (-normal.Z).ToString(CultureInfo.InvariantCulture);
}
else
{
normalString += normal.Y.ToString(CultureInfo.InvariantCulture) + " " + normal.Z.ToString(CultureInfo.InvariantCulture);
}
writer.WriteLine(normalString);
}
// Sequentially write the 3 vertex indices of the triangle face, for each triangle
// Note this is typically 1-indexed in an OBJ file when using absolute referencing!
for (int i = 0; i < vertices.Count / 3; i++)
{
string baseIndex0 = ((i * 3) + 1).ToString(CultureInfo.InvariantCulture);
string baseIndex1 = ((i * 3) + 2).ToString(CultureInfo.InvariantCulture);
string baseIndex2 = ((i * 3) + 3).ToString(CultureInfo.InvariantCulture);
string faceString = "f " + baseIndex0 + "//" + baseIndex0 + " " + baseIndex1 + "//" + baseIndex1 + " " + baseIndex2 + "//" + baseIndex2;
writer.WriteLine(faceString);
}
}
/// <summary>
/// Save mesh in ASCII .PLY file with per-vertex color
/// </summary>
/// <param name="mesh">Calculated mesh object</param>
/// <param name="writer">The text writer</param>
/// <param name="flipAxes">Flag to determine whether the Y and Z values are flipped on save,
/// default should be true.</param>
/// <param name="outputColor">Set this true to write out the surface color to the file when it has been captured.</param>
public static void SaveAsciiPlyMesh(ColorMesh mesh, TextWriter writer, bool flipAxes, bool outputColor)
{
if (null == mesh || null == writer)
{
return;
}
var vertices = mesh.GetVertices();
var indices = mesh.GetTriangleIndexes();
var colors = mesh.GetColors();
// Check mesh arguments
if (0 == vertices.Count || 0 != vertices.Count % 3 || vertices.Count != indices.Count || (outputColor && vertices.Count != colors.Count))
{
throw new ArgumentException();
}
int faces = indices.Count / 3;
// Write the PLY header lines
writer.WriteLine("ply");
writer.WriteLine("format ascii 1.0");
writer.WriteLine("comment file created by Microsoft Kinect Fusion");
writer.WriteLine("element vertex " + vertices.Count.ToString(CultureInfo.InvariantCulture));
writer.WriteLine("property float x");
writer.WriteLine("property float y");
writer.WriteLine("property float z");
if (outputColor)
{
writer.WriteLine("property uchar red");
writer.WriteLine("property uchar green");
writer.WriteLine("property uchar blue");
}
writer.WriteLine("element face " + faces.ToString(CultureInfo.InvariantCulture));
writer.WriteLine("property list uchar int vertex_index");
writer.WriteLine("end_header");
// Sequentially write the 3 vertices of the triangle, for each triangle
for (int i = 0; i < vertices.Count; i++)
{
var vertex = vertices[i];
string vertexString = vertex.X.ToString(CultureInfo.InvariantCulture) + " ";
if (flipAxes)
{
vertexString += (-vertex.Y).ToString(CultureInfo.InvariantCulture) + " " + (-vertex.Z).ToString(CultureInfo.InvariantCulture);
}
else
{
vertexString += vertex.Y.ToString(CultureInfo.InvariantCulture) + " " + vertex.Z.ToString(CultureInfo.InvariantCulture);
}
if (outputColor)
{
int red = (colors[i] >> 16) & 255;
int green = (colors[i] >> 8) & 255;
int blue = colors[i] & 255;
vertexString += " " + red.ToString(CultureInfo.InvariantCulture) + " " + green.ToString(CultureInfo.InvariantCulture) + " "
+ blue.ToString(CultureInfo.InvariantCulture);
}
writer.WriteLine(vertexString);
}
// Sequentially write the 3 vertex indices of the triangle face, for each triangle, 0-referenced in PLY files
for (int i = 0; i < faces; i++)
{
string baseIndex0 = (i * 3).ToString(CultureInfo.InvariantCulture);
string baseIndex1 = ((i * 3) + 1).ToString(CultureInfo.InvariantCulture);
string baseIndex2 = ((i * 3) + 2).ToString(CultureInfo.InvariantCulture);
string faceString = "3 " + baseIndex0 + " " + baseIndex1 + " " + baseIndex2;
writer.WriteLine(faceString);
}
}
/// <summary>
/// Clamp a float value if outside two given thresholds
/// </summary>summary>
/// <param name="valueToClamp">The value to clamp.</param>
/// <param name="minimumThreshold">The minimum inclusive threshold.</param>
/// <param name="maximumThreshold">The maximum inclusive threshold.</param>
/// <returns>Returns the clamped value.</returns>
public static float ClampFloatingPoint(float valueToClamp, float minimumThreshold, float maximumThreshold)
{
if (valueToClamp < minimumThreshold)
{
return minimumThreshold;
}
else if (valueToClamp > maximumThreshold)
{
return maximumThreshold;
}
else
{
return valueToClamp;
}
}
/// <summary>
/// Convert radians to degrees
/// </summary>
/// <param name="radians">The angle in radians.</param>
/// <returns>Angle in degrees.</returns>
public static float RadiansToDegrees(float radians)
{
return radians * (180.0f / (float)Math.PI);
}
/// <summary>
/// Convert degrees to radians
/// </summary>
/// <param name="degrees">The angle in degrees.</param>
/// <returns>Angle in radians.</returns>
public static float DegreesToRadians(float degrees)
{
return degrees * ((float)Math.PI / 180.0f);
}
/// <summary>
/// Straight Conversion from Kinect Fusion Matrix4 to WPF Matrix3D type
/// </summary>
/// <param name="mat">The Matrix4 to convert.</param>
/// <returns>Returns a Matrix3D converted from the Matrix4.</returns>
public static Matrix3D ConvertMatrix4ToMatrix3D(Matrix4 mat)
{
return new Matrix3D(mat.M11, mat.M12, mat.M13, mat.M14, mat.M21, mat.M22, mat.M23, mat.M24, mat.M31, mat.M32, mat.M33, mat.M34, mat.M41, mat.M42, mat.M43, mat.M44);
}
/// <summary>
/// Straight Conversion from WPF Matrix3D to Kinect Fusion Matrix4 type
/// </summary>
/// <param name="mat">The Matrix3D to convert.</param>
/// <returns>Returns a Matrix4 converted from the Matrix3D.</returns>
public static Matrix4 ConvertMatrix3DToMatrix4(Matrix3D mat)
{
Matrix4 converted = new Matrix4();
converted.M11 = (float)mat.M11;
converted.M12 = (float)mat.M12;
converted.M13 = (float)mat.M13;
converted.M14 = (float)mat.M14;
converted.M21 = (float)mat.M21;
converted.M22 = (float)mat.M22;
converted.M23 = (float)mat.M23;
converted.M24 = (float)mat.M24;
converted.M31 = (float)mat.M31;
converted.M32 = (float)mat.M32;
converted.M33 = (float)mat.M33;
converted.M34 = (float)mat.M34;
converted.M41 = (float)mat.OffsetX;
converted.M42 = (float)mat.OffsetY;
converted.M43 = (float)mat.OffsetZ;
converted.M44 = (float)mat.M44;
return converted;
}
/// <summary>
/// Get Quaternion from Matrix3D rotation
/// </summary>
/// <param name="mat">A Matrix3D.</param>
/// <returns>Returns the equivalent quaternion.</returns>
public static Quaternion Matrix3DToQuaternion(Matrix3D mat)
{
double x, y, z, w;
double trace = mat.M11 + mat.M22 + mat.M33;
if (trace > 0)
{
double s = 0.5f / Math.Sqrt(trace + 1.0f);
x = (mat.M23 - mat.M32) * s;
y = (mat.M31 - mat.M13) * s;
z = (mat.M12 - mat.M21) * s;
w = 0.25f / s;
}
else
{
if (mat.M11 > mat.M22 && mat.M11 > mat.M33)
{
double s = 2.0f * Math.Sqrt(1.0f + mat.M11 - mat.M22 - mat.M33);
x = 0.25f * s;
y = (mat.M12 + mat.M21) / s;
z = (mat.M13 + mat.M31) / s;
w = (mat.M23 - mat.M32) / s;
}
else if (mat.M22 > mat.M33)
{
double s = 2.0f * Math.Sqrt(1.0f + mat.M22 - mat.M11 - mat.M33);
x = (mat.M12 + mat.M21) / s;
y = 0.25f * s;
z = (mat.M23 + mat.M32) / s;
w = (mat.M31 - mat.M13) / s;
}
else
{
double s = 2.0f * Math.Sqrt(1.0f + mat.M33 - mat.M11 - mat.M22);
x = (mat.M13 + mat.M31) / s;
y = (mat.M23 + mat.M32) / s;
z = 0.25f * s;
w = (mat.M12 - mat.M21) / s;
}
}
return new Quaternion(x, y, z, w);
}
/// <summary>
/// Set Identity in a Matrix4
/// </summary>
/// <param name="mat">The matrix to set to identity</param>
public static void SetIdentityMatrix(ref Matrix4 mat)
{
mat.M11 = 1;
mat.M12 = 0;
mat.M13 = 0;
mat.M14 = 0;
mat.M21 = 0;
mat.M22 = 1;
mat.M23 = 0;
mat.M24 = 0;
mat.M31 = 0;
mat.M32 = 0;
mat.M33 = 1;
mat.M34 = 0;
mat.M41 = 0;
mat.M42 = 0;
mat.M43 = 0;
mat.M44 = 1;
}
/// <summary>
/// Set translation vector into the Matrix4 4x4 transformation in M41,M42,M43
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <param name="translationX">Floating point value for translation in X.</param>
/// <param name="translationY">Floating point value for translation in Y.</param>
/// <param name="translationZ">Floating point value for translation in Z.</param>
public static void SetTranslationMatrix(ref Matrix4 transform, float translationX, float translationY, float translationZ)
{
transform.M41 = translationX;
transform.M42 = translationY;
transform.M43 = translationZ;
}
/// <summary>
/// Create a translation Matrix4
/// </summary>
/// <param name="translationX">Floating point value for translation in X.</param>
/// <param name="translationY">Floating point value for translation in Y.</param>
/// <param name="translationZ">Floating point value for translation in Z.</param>
/// <returns>A Matrix4 translation matrix.</returns>
public static Matrix4 CreateTranslationMatrix(float translationX, float translationY, float translationZ)
{
Matrix4 transform = Matrix4.Identity;
transform.M41 = translationX;
transform.M42 = translationY;
transform.M43 = translationZ;
return transform;
}
/// <summary>
/// Extract translation Vector3 from the Matrix4 4x4 transformation in M41,M42,M43
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <param name="translationX">Floating point value for translation in X.</param>
/// <param name="translationY">Floating point value for translation in Y.</param>
/// <param name="translationZ">Floating point value for translation in Z.</param>
public static void ExtractTranslation(Matrix4 transform, out float translationX, out float translationY, out float translationZ)
{
translationX = transform.M41;
translationY = transform.M42;
translationZ = transform.M43;
}
/// <summary>
/// Extract translation Vector3 from the 4x4 Matrix in M41,M42,M43
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <returns>Returns a Vector3 containing the translation.</returns>
public static Vector3 ExtractTranslationVector3(Matrix4 transform)
{
Vector3 translation = new Vector3();
translation.X = transform.M41;
translation.Y = transform.M42;
translation.Z = transform.M43;
return translation;
}
/// <summary>
/// Extract translation from the Matrix4 4x4 transformation in M41,M42,M43
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <returns>Array of floating point values for translation in x,y,z.</returns>
public static float[] ExtractTranslationFloatArray(Matrix4 transform)
{
float[] translation = new float[3];
translation[0] = transform.M41;
translation[1] = transform.M42;
translation[2] = transform.M43;
return translation;
}
/// <summary>
/// Extract 3x3 rotation from the 4x4 Matrix and return in new Matrix4
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <returns>Returns a Matrix4 containing the rotation.</returns>
public static Matrix4 ExtractRotationMatrix(Matrix4 transform)
{
Matrix4 rotation = Matrix4.Identity;
rotation.M11 = transform.M11;
rotation.M12 = transform.M12;
rotation.M13 = transform.M13;
rotation.M14 = 0;
rotation.M21 = transform.M21;
rotation.M22 = transform.M22;
rotation.M23 = transform.M23;
rotation.M24 = 0;
rotation.M31 = transform.M31;
rotation.M32 = transform.M32;
rotation.M33 = transform.M33;
rotation.M34 = 0;
rotation.M41 = 0;
rotation.M42 = 0;
rotation.M43 = 0;
rotation.M44 = 1;
return rotation;
}
/// <summary>
/// Extract 3x3 rotation matrix from the Matrix4 4x4 transformation:
/// Then convert to Euler angles.
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <param name="rotationX">Floating point value for euler angle rotation around X.</param>
/// <param name="rotationY">Floating point value for euler angle rotation around Y.</param>
/// <param name="rotationZ">Floating point value for euler angle rotation around Z.</param>
public static void RotationMatrixToEuler(Matrix4 transform, out float rotationX, out float rotationY, out float rotationZ)
{
float phi = (float)Math.Atan2(transform.M23, transform.M33);
float theta = (float)Math.Asin(-transform.M13);
float psi = (float)Math.Atan2(transform.M12, transform.M11);
rotationX = phi; // This is rotation about x,y,z, or pitch, yaw, roll respectively
rotationY = theta;
rotationZ = psi;
}
/// <summary>
/// Extract 3x3 rotation matrix from the Matrix4 4x4 transformation,
/// then convert to Euler angles.
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <returns>Array of floating point values for Euler angle rotations around x,y,z.</returns>
public static Vector3 RotationMatrixToEulerVector3(Matrix4 transform)
{
Vector3 rotation = new Vector3();
float phi = (float)Math.Atan2(transform.M23, transform.M33);
float theta = (float)Math.Asin(-transform.M13);
float psi = (float)Math.Atan2(transform.M12, transform.M11);
rotation.X = phi; // This is rotation about x,y,z, or pitch, yaw, roll respectively
rotation.Y = theta;
rotation.Z = psi;
return rotation;
}
/// <summary>
/// Extract 3x3 rotation matrix from the Matrix4 4x4 transformation,
/// then convert to Euler angles.
/// </summary>
/// <param name="transform">The transform matrix.</param>
/// <returns>Array of floating point values for Euler angle rotations around x,y,z.</returns>
public static float[] RotationMatrixToEulerFloatArray(Matrix4 transform)
{
float[] rotation = new float[3];
float phi = (float)Math.Atan2(transform.M23, transform.M33);
float theta = (float)Math.Asin(-transform.M13);
float psi = (float)Math.Atan2(transform.M12, transform.M11);
rotation[0] = phi; // This is rotation about x,y,z, or pitch, yaw, roll respectively
rotation[1] = theta;
rotation[2] = psi;
return rotation;
}
/// <summary>
/// Test whether the camera moved too far between sequential frames by looking at starting
/// and end transformation matrix. We assume that if the camera moves or rotates beyond a
/// reasonable threshold, that we have lost track.
/// Note that on lower end machines, if the processing frame rate decreases below 30Hz,
/// this limit will potentially have to be increased as frames will be dropped and hence
/// there will be a greater motion between successive frames.
/// </summary>
/// <param name="initial">The transform matrix from the previous frame.</param>
/// <param name="final">The transform matrix from the current frame.</param>
/// <param name="maxTrans">
/// The maximum translation in meters we expect per x,y,z component between frames under normal motion.
/// </param>
/// <param name="maxRotDegrees">
/// The maximum rotation in degrees we expect about the x,y,z axes between frames under normal motion.
/// </param>
/// <returns>
/// True if camera transformation is greater than the threshold, otherwise false.
/// </returns>
public static bool CameraTransformFailed(Matrix4 initial, Matrix4 final, float maxTrans, float maxRotDegrees)
{
// Check if the transform is too far out to be reasonable
float deltaTrans = maxTrans;
float angDeg = maxRotDegrees;
float deltaRot = (angDeg * (float)Math.PI) / 180.0f;
// Calculate the deltas
float[] eulerInitial = RotationMatrixToEulerFloatArray(initial);
float[] eulerFinal = RotationMatrixToEulerFloatArray(final);
float[] transInitial = ExtractTranslationFloatArray(initial);
float[] transFinal = ExtractTranslationFloatArray(final);
bool failRot = false;
bool failTrans = false;
float[] eulerDeltas = new float[3];
float[] transDeltas = new float[3];
for (int i = 0; i < 3; i++)
{
// Handle when one angle is near PI, and the other is near -PI.
if (eulerInitial[i] >= Math.PI - deltaRot && eulerFinal[i] < deltaRot - Math.PI)
{
eulerInitial[i] -= (float)(Math.PI * 2);
}
else if (eulerFinal[i] >= Math.PI - deltaRot && eulerInitial[i] < deltaRot - Math.PI)
{
eulerFinal[i] -= (float)(Math.PI * 2);
}
eulerDeltas[i] = eulerInitial[i] - eulerFinal[i];
transDeltas[i] = transInitial[i] - transFinal[i];
if (Math.Abs(eulerDeltas[i]) > deltaRot)
{
failRot = true;
break;
}
if (Math.Abs(transDeltas[i]) > deltaTrans)
{
failTrans = true;
break;
}
}
return failRot || failTrans;
}
/// <summary>
/// Invert/Transpose the 3x3 Rotation Matrix Component of a 4x4 matrix in place
/// </summary>
/// <param name="rot">The rotation matrix to invert.</param>
public static void InvertRotation(ref Matrix4 rot)
{
// Invert equivalent to a transpose for 3x3 rotation when orthogonal
float tmp = rot.M12;
rot.M12 = rot.M21;
rot.M21 = tmp;
tmp = rot.M13;
rot.M13 = rot.M31;
rot.M31 = tmp;
tmp = rot.M23;
rot.M23 = rot.M32;
rot.M32 = tmp;
}
/// <summary>
/// Negate the 3x3 Rotation Matrix Component of a 4x4 matrix in place
/// </summary>
/// <param name="rot">The rotation matrix to negate.</param>
public static void NegateRotation(ref Matrix4 rot)
{
rot.M11 = -rot.M11;
rot.M12 = -rot.M12;
rot.M13 = -rot.M13;
rot.M21 = -rot.M21;
rot.M22 = -rot.M22;
rot.M23 = -rot.M23;
rot.M31 = -rot.M31;
rot.M32 = -rot.M32;
rot.M33 = -rot.M33;
}
/// <summary>
/// Length of a Vector3
/// </summary>
/// <param name="vector">The Vector3.</param>
/// <returns>Returns a the Vector3 length as float value</returns>
public static float Length(Vector3 vector)
{
return (float)Math.Sqrt((vector.X * vector.X) + (vector.Y * vector.Y) + (vector.Z * vector.Z));
}
/// <summary>
/// Normalize a Vector3
/// </summary>
/// <param name="vector">The Vector3.</param>
/// <returns>Returns a normalized Vector3</returns>
public static Vector3 Normalize(Vector3 vector)
{
Vector3 result = new Vector3();
float oneOverlen = 1.0f / Length(vector);
result.X = vector.X * oneOverlen;
result.Y = vector.Y * oneOverlen;
result.Z = vector.Z * oneOverlen;
return result;
}
/// <summary>
/// Normalize a Vector3 in place
/// </summary>
/// <param name="vector">The Vector3 to normalize.</param>
public static void NormalizeInPlace(ref Vector3 vector)
{
float oneOverlen = 1.0f / Length(vector);
vector.X *= oneOverlen;
vector.Y *= oneOverlen;
vector.Z *= oneOverlen;
}
/// <summary>
/// Rotate a vector with the 3x3 Rotation Matrix Component of a 4x4 matrix
/// </summary>
/// <param name="vector">The Vector3 to rotate.</param>
/// <param name="rotation">Rotation matrix.</param>
/// <returns>The rotated Vector3.</returns>
public static Vector3 RotateVector(Vector3 vector, Matrix4 rotation)
{
// we only use the rotation component here
Vector3 result = new Vector3();
// Multiply row vector with column in mat
result.X = (rotation.M11 * vector.X) + (rotation.M21 * vector.Y) + (rotation.M31 * vector.Z);
result.Y = (rotation.M12 * vector.X) + (rotation.M22 * vector.Y) + (rotation.M32 * vector.Z);
result.Z = (rotation.M13 * vector.X) + (rotation.M23 * vector.Y) + (rotation.M33 * vector.Z);
return result;
}
/// <summary>
/// Create Right Hand rotation matrix for counter-clockwise rotation of angle around axis
/// </summary>
/// <param name="axis">Rotation axis as Vector3</param>
/// <param name="angle">Angle of rotation around axis in Radians</param>
/// <returns>A Matrix4 rotation matrix.</returns>
public static Matrix4 CreateRotationMatrixFromAxisAngle(Vector3 axis, float angle)
{
// initialize to identity
Matrix4 result = Matrix4.Identity;
// angle is in radians
if (Length(axis) != 0 && angle != 0)
{
// Assumes normalized axis
float c = (float)Math.Cos(angle);
float s = (float)Math.Sin(angle);
float t = 1.0f - c;
result.M11 = c + (axis.X * axis.X * t);
result.M22 = c + (axis.Y * axis.Y * t);
result.M33 = c + (axis.Z * axis.Z * t);
float tmp1 = axis.X * axis.Y * t;
float tmp2 = axis.Z * s;
result.M12 = tmp1 + tmp2;
result.M21 = tmp1 - tmp2;
tmp1 = axis.X * axis.Z * t;
tmp2 = axis.Y * s;
result.M13 = tmp1 - tmp2;
result.M31 = tmp1 + tmp2;
tmp1 = axis.Y * axis.Z * t;
tmp2 = axis.X * s;
result.M23 = tmp1 + tmp2;
result.M32 = tmp1 - tmp2;
}
return result;
}
/// <summary>
/// Multiply4 with another Matrix4
/// </summary>
/// <param name="matA">First Matrix4.</param>
/// <param name="matB">Second Matrix4.</param>///
/// <returns>Returns multiplication result Matrix.</returns>
public static Matrix4 MultiplyMatrix4(Matrix4 matA, Matrix4 matB)
{
Matrix4 result = Matrix4.Identity;
result.M11 = (matA.M11 * matB.M11) + (matA.M12 * matB.M21) + (matA.M13 * matB.M31) + (matA.M14 * matB.M41);
result.M12 = (matA.M11 * matB.M12) + (matA.M12 * matB.M22) + (matA.M13 * matB.M32) + (matA.M14 * matB.M42);
result.M13 = (matA.M11 * matB.M13) + (matA.M12 * matB.M23) + (matA.M13 * matB.M33) + (matA.M14 * matB.M43);
result.M14 = (matA.M11 * matB.M14) + (matA.M12 * matB.M24) + (matA.M13 * matB.M34) + (matA.M14 * matB.M44);
result.M21 = (matA.M21 * matB.M11) + (matA.M22 * matB.M21) + (matA.M23 * matB.M31) + (matA.M24 * matB.M41);
result.M22 = (matA.M21 * matB.M12) + (matA.M22 * matB.M22) + (matA.M23 * matB.M32) + (matA.M24 * matB.M42);
result.M23 = (matA.M21 * matB.M13) + (matA.M22 * matB.M23) + (matA.M23 * matB.M33) + (matA.M24 * matB.M43);
result.M24 = (matA.M21 * matB.M14) + (matA.M22 * matB.M24) + (matA.M23 * matB.M34) + (matA.M24 * matB.M44);
result.M31 = (matA.M31 * matB.M11) + (matA.M32 * matB.M21) + (matA.M33 * matB.M31) + (matA.M34 * matB.M41);
result.M32 = (matA.M31 * matB.M12) + (matA.M32 * matB.M22) + (matA.M33 * matB.M32) + (matA.M34 * matB.M42);
result.M33 = (matA.M31 * matB.M13) + (matA.M32 * matB.M23) + (matA.M33 * matB.M33) + (matA.M34 * matB.M43);
result.M34 = (matA.M31 * matB.M14) + (matA.M32 * matB.M24) + (matA.M33 * matB.M34) + (matA.M34 * matB.M44);
result.M41 = (matA.M41 * matB.M11) + (matA.M42 * matB.M21) + (matA.M43 * matB.M31) + (matA.M44 * matB.M41);
result.M42 = (matA.M41 * matB.M12) + (matA.M42 * matB.M22) + (matA.M43 * matB.M32) + (matA.M44 * matB.M42);
result.M43 = (matA.M41 * matB.M13) + (matA.M42 * matB.M23) + (matA.M43 * matB.M33) + (matA.M44 * matB.M43);
result.M44 = (matA.M41 * matB.M14) + (matA.M42 * matB.M24) + (matA.M43 * matB.M34) + (matA.M44 * matB.M44);
return result;
}
/// <summary>
/// Multiply Rotation 3x3 with another Rotation 3x3 inside Matrix4s
/// </summary>
/// <param name="matA">First Matrix4.</param>
/// <param name="matB">Second Matrix4.</param>///
/// <returns>Returns multiplication result Matrix</returns>
public static Matrix4 MultiplyRotationMatrix4(Matrix4 matA, Matrix4 matB)
{
Matrix4 result = Matrix4.Identity;
result.M11 = (matA.M11 * matB.M11) + (matA.M12 * matB.M21) + (matA.M13 * matB.M31);
result.M12 = (matA.M11 * matB.M12) + (matA.M12 * matB.M22) + (matA.M13 * matB.M32);
result.M13 = (matA.M11 * matB.M13) + (matA.M12 * matB.M23) + (matA.M13 * matB.M33);
result.M21 = (matA.M21 * matB.M11) + (matA.M22 * matB.M21) + (matA.M23 * matB.M31);
result.M22 = (matA.M21 * matB.M12) + (matA.M22 * matB.M22) + (matA.M23 * matB.M32);
result.M23 = (matA.M21 * matB.M13) + (matA.M22 * matB.M23) + (matA.M23 * matB.M33);
result.M31 = (matA.M31 * matB.M11) + (matA.M32 * matB.M21) + (matA.M33 * matB.M31);
result.M32 = (matA.M31 * matB.M12) + (matA.M32 * matB.M22) + (matA.M33 * matB.M32);
result.M33 = (matA.M31 * matB.M13) + (matA.M32 * matB.M23) + (matA.M33 * matB.M33);
return result;
}
/// <summary>
/// Create 4x4 matrix with rotation around X-axis
/// </summary>
/// <param name="angleDegrees">The angle to rotate.</param>
/// <returns>Returns a Matrix4 containing the rotation matrix.</returns>
public static Matrix4 CreateRotationMatrixX(float angleDegrees)
{
Matrix4 result = Matrix4.Identity;
float angleRads = angleDegrees / 180.0f * (float)Math.PI;
// Note this is for XNA-like row vector multiplication with row-major matrices
result.M22 = (float)Math.Cos(angleRads);
result.M23 = (float)Math.Sin(angleRads);
result.M32 = -(float)Math.Sin(angleRads);
result.M33 = (float)Math.Cos(angleRads);
return result;
}
/// <summary>
/// Create 4x4 matrix with rotation around Y-axis
/// </summary>
/// <param name="angleDegrees">The angle to rotate.</param>
/// <returns>Returns a Matrix4 containing the rotation matrix.</returns>
public static Matrix4 CreateRotationMatrixY(float angleDegrees)
{
Matrix4 result = Matrix4.Identity;
float angleRads = angleDegrees / 180.0f * (float)Math.PI;
// Note this is for XNA-like row vector multiplication with row-major matrices
result.M11 = (float)Math.Cos(angleRads);
result.M13 = -(float)Math.Sin(angleRads);
result.M31 = (float)Math.Sin(angleRads);
result.M33 = (float)Math.Cos(angleRads);
return result;
}
/// <summary>
/// Create 4x4 matrix with rotation around Z-axis
/// </summary>
/// <param name="angleDegrees">The angle to rotate.</param>
/// <returns>Returns a Matrix4 containing the rotation matrix.</returns>
public static Matrix4 CreateRotationMatrixZ(float angleDegrees)
{
Matrix4 result = Matrix4.Identity;
float angleRads = angleDegrees / 180.0f * (float)Math.PI;
// Note this is for XNA-like row vector multiplication with row-major matrices
result.M11 = (float)Math.Cos(angleRads);
result.M12 = (float)Math.Sin(angleRads);
result.M21 = -(float)Math.Sin(angleRads);
result.M22 = (float)Math.Cos(angleRads);
return result;
}
/// <summary>
/// Invert Matrix4 Pose either from WorldToCameraTransform (view) matrix to CameraToWorldTransform camera pose matrix (world/SE3) or vice versa
/// </summary>
/// <param name="transform">The camera pose transform matrix.</param>
/// <returns>Returns a Matrix4 containing the inverted camera pose.</returns>
public static Matrix4 InvertTransformationMatrixPose(Matrix4 transform)
{
// Given the SE3 world transform transform T = [R|t], the inverse view transform matrix is simply:
// T^-1 = [R^T | -R^T . t ]
// This also works the opposite way to get the world transform, given the view transform matrix.
Matrix4 rotation = ExtractRotationMatrix(transform);
Matrix4 invRotation = rotation;
InvertRotation(ref invRotation); // invert(transpose) 3x3 rotation
Matrix4 negRotation = invRotation;
NegateRotation(ref negRotation); // negate 3x3 rotation
Vector3 translation = ExtractTranslationVector3(transform);
Vector3 invTranslation = RotateVector(translation, negRotation);
// Add the translation back in
invRotation.M41 = invTranslation.X;
invRotation.M42 = invTranslation.Y;
invRotation.M43 = invTranslation.Z;
return invRotation;
}
/// <summary>
/// Back-project 3D point assuming Z is the depth (parallel to the optical axis).
/// </summary>
/// <param name="x">Input x in pixels of 2D image.</param>
/// <param name="y">Input y in pixels of 2D image.</param>
/// <param name="z">Input depth to calculate 3D point for.</param>
/// <param name="principalPointX">Principal point in x axis (non-normalized).</param>
/// <param name="principalPointY">Principal point in y axis (non-normalized).</param>
/// <param name="inverseFocalLengthX">Inverse focal length in X (non-normalized).</param>
/// <param name="inverseFocalLengthY">Inverse focal length in Y (non-normalized).</param>
/// <returns>Returns the back-projected Point3D.</returns>
public static Point3D BackProject(float x, float y, float z, float principalPointX, float principalPointY, float inverseFocalLengthX, float inverseFocalLengthY)
{
Point3D pt = new Point3D();
float u = (x - principalPointX) * inverseFocalLengthX;
float v = (y - principalPointY) * inverseFocalLengthY;
// Assuming depths are measurements along Z.
pt.X = u * z;
pt.Y = v * z;
pt.Z = z;
return pt;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Rotation3DAnimation.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a Rotation3D property using linear interpolation
/// between two values. The values are determined by the combination of
/// From, To, or By values that are set on the animation.
/// </summary>
public partial class Rotation3DAnimation :
Rotation3DAnimationBase
{
#region Data
/// <summary>
/// This is used if the user has specified From, To, and/or By values.
/// </summary>
private Rotation3D[] _keyValues;
private AnimationType _animationType;
private bool _isAnimationFunctionValid;
#endregion
#region Constructors
/// <summary>
/// Static ctor for Rotation3DAnimation establishes
/// dependency properties, using as much shared data as possible.
/// </summary>
static Rotation3DAnimation()
{
Type typeofProp = typeof(Rotation3D);
Type typeofThis = typeof(Rotation3DAnimation);
PropertyChangedCallback propCallback = new PropertyChangedCallback(AnimationFunction_Changed);
ValidateValueCallback validateCallback = new ValidateValueCallback(ValidateFromToOrByValue);
FromProperty = DependencyProperty.Register(
"From",
typeofProp,
typeofThis,
new PropertyMetadata((Rotation3D)null, propCallback),
validateCallback);
ToProperty = DependencyProperty.Register(
"To",
typeofProp,
typeofThis,
new PropertyMetadata((Rotation3D)null, propCallback),
validateCallback);
ByProperty = DependencyProperty.Register(
"By",
typeofProp,
typeofThis,
new PropertyMetadata((Rotation3D)null, propCallback),
validateCallback);
EasingFunctionProperty = DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeofThis);
}
/// <summary>
/// Creates a new Rotation3DAnimation with all properties set to
/// their default values.
/// </summary>
public Rotation3DAnimation()
: base()
{
}
/// <summary>
/// Creates a new Rotation3DAnimation that will animate a
/// Rotation3D property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public Rotation3DAnimation(Rotation3D toValue, Duration duration)
: this()
{
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new Rotation3DAnimation that will animate a
/// Rotation3D property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public Rotation3DAnimation(Rotation3D toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
/// <summary>
/// Creates a new Rotation3DAnimation that will animate a
/// Rotation3D property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public Rotation3DAnimation(Rotation3D fromValue, Rotation3D toValue, Duration duration)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new Rotation3DAnimation that will animate a
/// Rotation3D property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public Rotation3DAnimation(Rotation3D fromValue, Rotation3D toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this Rotation3DAnimation
/// </summary>
/// <returns>The copy</returns>
public new Rotation3DAnimation Clone()
{
return (Rotation3DAnimation)base.Clone();
}
//
// Note that we don't override the Clone virtuals (CloneCore, CloneCurrentValueCore,
// GetAsFrozenCore, and GetCurrentValueAsFrozenCore) even though this class has state
// not stored in a DP.
//
// We don't need to clone _animationType and _keyValues because they are the the cached
// results of animation function validation, which can be recomputed. The other remaining
// field, isAnimationFunctionValid, defaults to false, which causes this recomputation to happen.
//
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Rotation3DAnimation();
}
#endregion
#region Methods
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected override Rotation3D GetCurrentValueCore(Rotation3D defaultOriginValue, Rotation3D defaultDestinationValue, AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (!_isAnimationFunctionValid)
{
ValidateAnimationFunction();
}
double progress = animationClock.CurrentProgress.Value;
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
progress = easingFunction.Ease(progress);
}
Rotation3D from = Rotation3D.Identity;
Rotation3D to = Rotation3D.Identity;
Rotation3D accumulated = Rotation3D.Identity;
Rotation3D foundation = Rotation3D.Identity;
// need to validate the default origin and destination values if
// the animation uses them as the from, to, or foundation values
bool validateOrigin = false;
bool validateDestination = false;
switch(_animationType)
{
case AnimationType.Automatic:
from = defaultOriginValue;
to = defaultDestinationValue;
validateOrigin = true;
validateDestination = true;
break;
case AnimationType.From:
from = _keyValues[0];
to = defaultDestinationValue;
validateDestination = true;
break;
case AnimationType.To:
from = defaultOriginValue;
to = _keyValues[0];
validateOrigin = true;
break;
case AnimationType.By:
// According to the SMIL specification, a By animation is
// always additive. But we don't force this so that a
// user can re-use a By animation and have it replace the
// animations that precede it in the list without having
// to manually set the From value to the base value.
to = _keyValues[0];
foundation = defaultOriginValue;
validateOrigin = true;
break;
case AnimationType.FromTo:
from = _keyValues[0];
to = _keyValues[1];
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
case AnimationType.FromBy:
from = _keyValues[0];
to = AnimatedTypeHelpers.AddRotation3D(_keyValues[0], _keyValues[1]);
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
default:
Debug.Fail("Unknown animation type.");
break;
}
if (validateOrigin
&& !AnimatedTypeHelpers.IsValidAnimationValueRotation3D(defaultOriginValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"origin",
defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
}
if (validateDestination
&& !AnimatedTypeHelpers.IsValidAnimationValueRotation3D(defaultDestinationValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"destination",
defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
}
if (IsCumulative)
{
double currentRepeat = (double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
Rotation3D accumulator = AnimatedTypeHelpers.SubtractRotation3D(to, from);
accumulated = AnimatedTypeHelpers.ScaleRotation3D(accumulator, currentRepeat);
}
}
// return foundation + accumulated + from + ((to - from) * progress)
return AnimatedTypeHelpers.AddRotation3D(
foundation,
AnimatedTypeHelpers.AddRotation3D(
accumulated,
AnimatedTypeHelpers.InterpolateRotation3D(from, to, progress)));
}
private void ValidateAnimationFunction()
{
_animationType = AnimationType.Automatic;
_keyValues = null;
if (From != null)
{
if (To != null)
{
_animationType = AnimationType.FromTo;
_keyValues = new Rotation3D[2];
_keyValues[0] = From;
_keyValues[1] = To;
}
else if (By != null)
{
_animationType = AnimationType.FromBy;
_keyValues = new Rotation3D[2];
_keyValues[0] = From;
_keyValues[1] = By;
}
else
{
_animationType = AnimationType.From;
_keyValues = new Rotation3D[1];
_keyValues[0] = From;
}
}
else if (To != null)
{
_animationType = AnimationType.To;
_keyValues = new Rotation3D[1];
_keyValues[0] = To;
}
else if (By != null)
{
_animationType = AnimationType.By;
_keyValues = new Rotation3D[1];
_keyValues[0] = By;
}
_isAnimationFunctionValid = true;
}
#endregion
#region Properties
private static void AnimationFunction_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Rotation3DAnimation a = (Rotation3DAnimation)d;
a._isAnimationFunctionValid = false;
a.PropertyChanged(e.Property);
}
private static bool ValidateFromToOrByValue(object value)
{
Rotation3D typedValue = (Rotation3D)value;
if (typedValue != null)
{
return AnimatedTypeHelpers.IsValidAnimationValueRotation3D(typedValue);
}
else
{
return true;
}
}
/// <summary>
/// FromProperty
/// </summary>
public static readonly DependencyProperty FromProperty;
/// <summary>
/// From
/// </summary>
public Rotation3D From
{
get
{
return (Rotation3D)GetValue(FromProperty);
}
set
{
SetValueInternal(FromProperty, value);
}
}
/// <summary>
/// ToProperty
/// </summary>
public static readonly DependencyProperty ToProperty;
/// <summary>
/// To
/// </summary>
public Rotation3D To
{
get
{
return (Rotation3D)GetValue(ToProperty);
}
set
{
SetValueInternal(ToProperty, value);
}
}
/// <summary>
/// ByProperty
/// </summary>
public static readonly DependencyProperty ByProperty;
/// <summary>
/// By
/// </summary>
public Rotation3D By
{
get
{
return (Rotation3D)GetValue(ByProperty);
}
set
{
SetValueInternal(ByProperty, value);
}
}
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty;
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
/// <summary>
/// If this property is set to true the animation will add its value to
/// the base value instead of replacing it entirely.
/// </summary>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// It this property is set to true, the animation will accumulate its
/// value over repeats. For instance if you have a From value of 0.0 and
/// a To value of 1.0, the animation return values from 1.0 to 2.0 over
/// the second reteat cycle, and 2.0 to 3.0 over the third, etc.
/// </summary>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.SiteRecovery.Models;
namespace Microsoft.Azure.Management.SiteRecovery.Models
{
/// <summary>
/// The detaisl of a Process Server.
/// </summary>
public partial class ProcessServer
{
private string _agentVersion;
/// <summary>
/// Optional. The version of the scout component on the server.
/// </summary>
public string AgentVersion
{
get { return this._agentVersion; }
set { this._agentVersion = value; }
}
private long _availableMemoryInBytes;
/// <summary>
/// Optional. The available memory.
/// </summary>
public long AvailableMemoryInBytes
{
get { return this._availableMemoryInBytes; }
set { this._availableMemoryInBytes = value; }
}
private long _availableSpaceInBytes;
/// <summary>
/// Optional. The available space.
/// </summary>
public long AvailableSpaceInBytes
{
get { return this._availableSpaceInBytes; }
set { this._availableSpaceInBytes = value; }
}
private string _cpuLoad;
/// <summary>
/// Optional. The percentage of the CPU load.
/// </summary>
public string CpuLoad
{
get { return this._cpuLoad; }
set { this._cpuLoad = value; }
}
private string _cpuLoadStatus;
/// <summary>
/// Optional. The CPU load status.
/// </summary>
public string CpuLoadStatus
{
get { return this._cpuLoadStatus; }
set { this._cpuLoadStatus = value; }
}
private string _friendlyName;
/// <summary>
/// Optional. The Process Server's friendly name.
/// </summary>
public string FriendlyName
{
get { return this._friendlyName; }
set { this._friendlyName = value; }
}
private string _hostId;
/// <summary>
/// Optional. The agent generated Id.
/// </summary>
public string HostId
{
get { return this._hostId; }
set { this._hostId = value; }
}
private string _id;
/// <summary>
/// Optional. The Process Server Id.
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
private string _ipAddress;
/// <summary>
/// Optional. The IP address of the server.
/// </summary>
public string IpAddress
{
get { return this._ipAddress; }
set { this._ipAddress = value; }
}
private System.DateTime? _lastHeartbeat;
/// <summary>
/// Optional. The last heartbeat received from the server.
/// </summary>
public System.DateTime? LastHeartbeat
{
get { return this._lastHeartbeat; }
set { this._lastHeartbeat = value; }
}
private string _memoryUsageStatus;
/// <summary>
/// Optional. The memory usage status.
/// </summary>
public string MemoryUsageStatus
{
get { return this._memoryUsageStatus; }
set { this._memoryUsageStatus = value; }
}
private string _osType;
/// <summary>
/// Optional. The OS type of the server.
/// </summary>
public string OsType
{
get { return this._osType; }
set { this._osType = value; }
}
private string _psServiceStatus;
/// <summary>
/// Optional. The PS service status.
/// </summary>
public string PsServiceStatus
{
get { return this._psServiceStatus; }
set { this._psServiceStatus = value; }
}
private string _replicationPairCount;
/// <summary>
/// Optional. The number of replication pairs configured in this PS.
/// </summary>
public string ReplicationPairCount
{
get { return this._replicationPairCount; }
set { this._replicationPairCount = value; }
}
private string _serverCount;
/// <summary>
/// Optional. The servers configured with this PS.
/// </summary>
public string ServerCount
{
get { return this._serverCount; }
set { this._serverCount = value; }
}
private string _spaceUsageStatus;
/// <summary>
/// Optional. The space usage status.
/// </summary>
public string SpaceUsageStatus
{
get { return this._spaceUsageStatus; }
set { this._spaceUsageStatus = value; }
}
private string _systemLoad;
/// <summary>
/// Optional. The percentage of the system load.
/// </summary>
public string SystemLoad
{
get { return this._systemLoad; }
set { this._systemLoad = value; }
}
private string _systemLoadStatus;
/// <summary>
/// Optional. The system load status.
/// </summary>
public string SystemLoadStatus
{
get { return this._systemLoadStatus; }
set { this._systemLoadStatus = value; }
}
private long _totalMemoryInBytes;
/// <summary>
/// Optional. The total memory.
/// </summary>
public long TotalMemoryInBytes
{
get { return this._totalMemoryInBytes; }
set { this._totalMemoryInBytes = value; }
}
private long _totalSpaceInBytes;
/// <summary>
/// Optional. The total space.
/// </summary>
public long TotalSpaceInBytes
{
get { return this._totalSpaceInBytes; }
set { this._totalSpaceInBytes = value; }
}
private IList<MobilityServiceUpdate> _updates;
/// <summary>
/// Optional. The list of the mobility service updates available on the
/// Process Server.
/// </summary>
public IList<MobilityServiceUpdate> Updates
{
get { return this._updates; }
set { this._updates = value; }
}
private string _versionStatus;
/// <summary>
/// Optional. Gets or sets version status
/// </summary>
public string VersionStatus
{
get { return this._versionStatus; }
set { this._versionStatus = value; }
}
/// <summary>
/// Initializes a new instance of the ProcessServer class.
/// </summary>
public ProcessServer()
{
this.Updates = new LazyList<MobilityServiceUpdate>();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using NUnit.Framework;
namespace SequelocityDotNet.Tests.SqlServer.DatabaseCommandExtensionsTests
{
[TestFixture]
public class GenerateInsertsForSqlServerTests
{
public struct Customer
{
public int? CustomerId;
public string FirstName;
public string LastName;
public DateTime DateOfBirth;
}
[Test]
public void Should_Return_The_Last_Inserted_Ids()
{
// Arrange
const string sql = @"
IF ( EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer' ) )
BEGIN
DROP TABLE Customer
END
IF ( NOT EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer') )
BEGIN
CREATE TABLE Customer
(
CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
FirstName NVARCHAR(120) NOT NULL,
LastName NVARCHAR(120) NOT NULL,
DateOfBirth DATETIME NOT NULL
);
END
";
var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );
new DatabaseCommand( dbConnection )
.SetCommandText( sql )
.ExecuteNonQuery( true );
var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
var list = new List<Customer> { customer1, customer2, customer3 };
// Act
var customerIds = new DatabaseCommand( dbConnection )
.GenerateInsertsForSqlServer( list )
.ExecuteToList<long>();
// Assert
Assert.That( customerIds.Count == 3 );
Assert.That( customerIds[0] == 1 );
Assert.That( customerIds[1] == 2 );
Assert.That( customerIds[2] == 3 );
}
[Test]
public void Should_Handle_Generating_Inserts_For_A_Strongly_Typed_Object()
{
// Arrange
const string createSchemaSql = @"
IF ( EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer' ) )
BEGIN
DROP TABLE Customer
END
IF ( NOT EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer') )
BEGIN
CREATE TABLE Customer
(
CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
FirstName NVARCHAR(120) NOT NULL,
LastName NVARCHAR(120) NOT NULL,
DateOfBirth DATETIME NOT NULL
);
END
";
var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );
new DatabaseCommand( dbConnection )
.SetCommandText( createSchemaSql )
.ExecuteNonQuery( true );
var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
var list = new List<Customer> { customer1, customer2, customer3 };
// Act
var customerIds = new DatabaseCommand( dbConnection )
.GenerateInsertsForSqlServer( list )
.ExecuteToList<long>( true );
const string selectCustomerQuery = @"
SELECT CustomerId,
FirstName,
LastName,
DateOfBirth
FROM Customer
WHERE CustomerId IN ( @CustomerIds );
";
var customers = new DatabaseCommand( dbConnection )
.SetCommandText( selectCustomerQuery )
.AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
.ExecuteToList<Customer>()
.OrderBy( x => x.CustomerId )
.ToList();
// Assert
Assert.That( customers.Count == 3 );
Assert.That( customers[0].CustomerId == 1 );
Assert.That( customers[0].FirstName == customer1.FirstName );
Assert.That( customers[0].LastName == customer1.LastName );
Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );
Assert.That( customers[1].CustomerId == 2 );
Assert.That( customers[1].FirstName == customer2.FirstName );
Assert.That( customers[1].LastName == customer2.LastName );
Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );
Assert.That( customers[2].CustomerId == 3 );
Assert.That( customers[2].FirstName == customer3.FirstName );
Assert.That( customers[2].LastName == customer3.LastName );
Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
}
[Test]
public void Should_Be_Able_To_Specify_The_Table_Name()
{
// Arrange
const string sql = @"
IF ( EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Person' ) )
BEGIN
DROP TABLE Person
END
IF ( NOT EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Person') )
BEGIN
CREATE TABLE Person
(
CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
FirstName NVARCHAR(120) NOT NULL,
LastName NVARCHAR(120) NOT NULL,
DateOfBirth DATETIME NOT NULL
);
END
";
var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );
new DatabaseCommand( dbConnection )
.SetCommandText( sql )
.ExecuteNonQuery( true );
var customer1 = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
var customer2 = new Customer { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
var customer3 = new Customer { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
var list = new List<Customer> { customer1, customer2, customer3 };
// Act
var numberOfAffectedRecords = new DatabaseCommand( dbConnection )
.GenerateInsertsForSqlServer( list, "[Person]" ) // Specifying a table name of Person
.ExecuteNonQuery( true );
// Assert
Assert.That( numberOfAffectedRecords == list.Count );
}
[Test]
public void Should_Throw_An_Exception_When_Passing_An_Anonymous_Object_And_Not_Specifying_A_TableName()
{
// Arrange
const string sql = @"
IF ( EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Person' ) )
BEGIN
DROP TABLE Person
END
IF ( NOT EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Person') )
BEGIN
CREATE TABLE Person
(
CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
FirstName NVARCHAR(120) NOT NULL,
LastName NVARCHAR(120) NOT NULL,
DateOfBirth DATETIME NOT NULL
);
END
";
var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );
new DatabaseCommand( dbConnection )
.SetCommandText( sql )
.ExecuteNonQuery( true );
var customer1 = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
var customer2 = new { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
var customer3 = new { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
var list = new List<object> { customer1, customer2, customer3 };
// Act
TestDelegate action = () => new DatabaseCommand( dbConnection )
.GenerateInsertsForSqlServer( list )
.ExecuteScalar( true )
.ToInt();
// Assert
var exception = Assert.Catch<ArgumentNullException>( action );
Assert.That( exception.Message.Contains( "The 'tableName' parameter must be provided when the object supplied is an anonymous type." ) );
}
[Test]
public void Should_Handle_Generating_Inserts_For_An_Anonymous_Object()
{
// Arrange
const string createSchemaSql = @"
IF ( EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer' ) )
BEGIN
DROP TABLE Customer
END
IF ( NOT EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer') )
BEGIN
CREATE TABLE Customer
(
CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
FirstName NVARCHAR(120) NOT NULL,
LastName NVARCHAR(120) NOT NULL,
DateOfBirth DATETIME NOT NULL
);
END
";
var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );
new DatabaseCommand( dbConnection )
.SetCommandText( createSchemaSql )
.ExecuteNonQuery( true );
var customer1 = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) };
var customer2 = new { FirstName = "Bruce", LastName = "Wayne", DateOfBirth = DateTime.Parse( "05/27/1939" ) };
var customer3 = new { FirstName = "Peter", LastName = "Parker", DateOfBirth = DateTime.Parse( "08/18/1962" ) };
var list = new List<object> { customer1, customer2, customer3 };
// Act
var customerIds = new DatabaseCommand( dbConnection )
.GenerateInsertsForSqlServer( list, "Customer" )
.ExecuteToList<long>( true );
const string selectCustomerQuery = @"
SELECT CustomerId,
FirstName,
LastName,
DateOfBirth
FROM Customer
WHERE CustomerId IN ( @CustomerIds );
";
var customers = new DatabaseCommand( dbConnection )
.SetCommandText( selectCustomerQuery )
.AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
.ExecuteToList<Customer>()
.OrderBy( x => x.CustomerId )
.ToList();
// Assert
Assert.That( customers.Count == 3 );
Assert.That( customers[0].CustomerId == 1 );
Assert.That( customers[0].FirstName == customer1.FirstName );
Assert.That( customers[0].LastName == customer1.LastName );
Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );
Assert.That( customers[1].CustomerId == 2 );
Assert.That( customers[1].FirstName == customer2.FirstName );
Assert.That( customers[1].LastName == customer2.LastName );
Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );
Assert.That( customers[2].CustomerId == 3 );
Assert.That( customers[2].FirstName == customer3.FirstName );
Assert.That( customers[2].LastName == customer3.LastName );
Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
}
[Test]
public void Should_Handle_Generating_Inserts_For_A_Dynamic_Object()
{
// Arrange
const string createSchemaSql = @"
IF ( EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer' ) )
BEGIN
DROP TABLE Customer
END
IF ( NOT EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'Customer') )
BEGIN
CREATE TABLE Customer
(
CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
FirstName NVARCHAR(120) NOT NULL,
LastName NVARCHAR(120) NOT NULL,
DateOfBirth DATETIME NOT NULL
);
END
";
var dbConnection = Sequelocity.CreateDbConnection( ConnectionStringsNames.SqlServerConnectionString );
new DatabaseCommand( dbConnection )
.SetCommandText( createSchemaSql )
.ExecuteNonQuery( true );
dynamic customer1 = new ExpandoObject();
customer1.FirstName = "Clark";
customer1.LastName = "Kent";
customer1.DateOfBirth = DateTime.Parse( "06/18/1938" );
dynamic customer2 = new ExpandoObject();
customer2.FirstName = "Bruce";
customer2.LastName = "Wayne";
customer2.DateOfBirth = DateTime.Parse( "05/27/1939" );
dynamic customer3 = new ExpandoObject();
customer3.FirstName = "Peter";
customer3.LastName = "Parker";
customer3.DateOfBirth = DateTime.Parse( "08/18/1962" );
var list = new List<dynamic> { customer1, customer2, customer3 };
// Act
var customerIds = new DatabaseCommand( dbConnection )
.GenerateInsertsForSqlServer( list, "Customer" )
.ExecuteToList<long>( true );
const string selectCustomerQuery = @"
SELECT CustomerId,
FirstName,
LastName,
DateOfBirth
FROM Customer
WHERE CustomerId IN ( @CustomerIds );
";
var customers = new DatabaseCommand( dbConnection )
.SetCommandText( selectCustomerQuery )
.AddParameters( "@CustomerIds", customerIds, DbType.Int64 )
.ExecuteToList<Customer>()
.OrderBy( x => x.CustomerId )
.ToList();
// Assert
Assert.That( customers.Count == 3 );
Assert.That( customers[0].CustomerId == 1 );
Assert.That( customers[0].FirstName == customer1.FirstName );
Assert.That( customers[0].LastName == customer1.LastName );
Assert.That( customers[0].DateOfBirth == customer1.DateOfBirth );
Assert.That( customers[1].CustomerId == 2 );
Assert.That( customers[1].FirstName == customer2.FirstName );
Assert.That( customers[1].LastName == customer2.LastName );
Assert.That( customers[1].DateOfBirth == customer2.DateOfBirth );
Assert.That( customers[2].CustomerId == 3 );
Assert.That( customers[2].FirstName == customer3.FirstName );
Assert.That( customers[2].LastName == customer3.LastName );
Assert.That( customers[2].DateOfBirth == customer3.DateOfBirth );
}
}
}
| |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Ocelot.Configuration.File;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Shouldly;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.IntegrationTests
{
public class ThreadSafeHeadersTests : IDisposable
{
private readonly HttpClient _httpClient;
private IWebHost _builder;
private IWebHostBuilder _webHostBuilder;
private readonly string _ocelotBaseUrl;
private IWebHost _downstreamBuilder;
private readonly Random _random;
private readonly ConcurrentBag<ThreadSafeHeadersTestResult> _results;
public ThreadSafeHeadersTests()
{
_results = new ConcurrentBag<ThreadSafeHeadersTestResult>();
_random = new Random();
_httpClient = new HttpClient();
_ocelotBaseUrl = "http://localhost:5001";
_httpClient.BaseAddress = new Uri(_ocelotBaseUrl);
}
[Fact]
public void should_return_same_response_for_each_different_header_under_load_to_downsteam_service()
{
var configuration = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamPathTemplate = "/",
DownstreamScheme = "http",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 51611,
},
},
UpstreamPathTemplate = "/",
UpstreamHttpMethod = new List<string> { "Get" },
},
},
};
this.Given(x => GivenThereIsAConfiguration(configuration))
.And(x => GivenThereIsAServiceRunningOn("http://localhost:51611"))
.And(x => GivenOcelotIsRunning())
.When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues("/", 300))
.Then(x => ThenTheSameHeaderValuesAreReturnedByTheDownstreamService())
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string url)
{
_downstreamBuilder = new WebHostBuilder()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(url)
.Configure(app =>
{
app.Run(async context =>
{
var header = context.Request.Headers["ThreadSafeHeadersTest"];
context.Response.StatusCode = 200;
await context.Response.WriteAsync(header[0]);
});
})
.Build();
_downstreamBuilder.Start();
}
private void GivenOcelotIsRunning()
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false);
config.AddJsonFile("ocelot.json", false, false);
config.AddEnvironmentVariables();
})
.ConfigureServices(x =>
{
x.AddOcelot();
})
.Configure(app =>
{
app.UseOcelot().Wait();
});
_builder = _webHostBuilder.Build();
_builder.Start();
}
private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration)
{
var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json";
var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration);
if (File.Exists(configurationPath))
{
File.Delete(configurationPath);
}
File.WriteAllText(configurationPath, jsonConfiguration);
var text = File.ReadAllText(configurationPath);
configurationPath = $"{AppContext.BaseDirectory}/ocelot.json";
if (File.Exists(configurationPath))
{
File.Delete(configurationPath);
}
File.WriteAllText(configurationPath, jsonConfiguration);
text = File.ReadAllText(configurationPath);
}
private void WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues(string url, int times)
{
var tasks = new Task[times];
for (int i = 0; i < times; i++)
{
var urlCopy = url;
var random = _random.Next(0, 50);
tasks[i] = GetForThreadSafeHeadersTest(urlCopy, random);
}
Task.WaitAll(tasks);
}
private async Task GetForThreadSafeHeadersTest(string url, int random)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("ThreadSafeHeadersTest", new List<string> { random.ToString() });
var response = await _httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
int result = int.Parse(content);
var tshtr = new ThreadSafeHeadersTestResult(result, random);
_results.Add(tshtr);
}
private void ThenTheSameHeaderValuesAreReturnedByTheDownstreamService()
{
foreach (var result in _results)
{
result.Result.ShouldBe(result.Random);
}
}
public void Dispose()
{
_builder?.Dispose();
_httpClient?.Dispose();
_downstreamBuilder?.Dispose();
}
private class ThreadSafeHeadersTestResult
{
public ThreadSafeHeadersTestResult(int result, int random)
{
Result = result;
Random = random;
}
public int Result { get; private set; }
public int Random { get; private set; }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Permissions
{
using System;
using System.IO;
using System.Security.Util;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security;
using System.Reflection;
using System.Globalization;
using System.Diagnostics.Contracts;
[ComVisible(true)]
[Flags]
[Serializable]
public enum ReflectionPermissionFlag
{
NoFlags = 0x00,
[Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
TypeInformation = 0x01,
MemberAccess = 0x02,
[Obsolete("This permission is no longer used by the CLR.")]
ReflectionEmit = 0x04,
[ComVisible(false)]
RestrictedMemberAccess = 0x08,
[Obsolete("This permission has been deprecated. Use PermissionState.Unrestricted to get full access.")]
AllFlags = 0x07
}
[ComVisible(true)]
[Serializable]
sealed public class ReflectionPermission
: CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
// ReflectionPermissionFlag.AllFlags doesn't contain the new value RestrictedMemberAccess,
// but we cannot change its value now because that will break apps that have that old value baked in.
// We should use this const that truely contains "all" flags instead of ReflectionPermissionFlag.AllFlags.
#pragma warning disable 618
internal const ReflectionPermissionFlag AllFlagsAndMore = ReflectionPermissionFlag.AllFlags | ReflectionPermissionFlag.RestrictedMemberAccess;
#pragma warning restore 618
private ReflectionPermissionFlag m_flags;
//
// Public Constructors
//
public ReflectionPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
SetUnrestricted( true );
}
else if (state == PermissionState.None)
{
SetUnrestricted( false );
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
// Parameters:
//
public ReflectionPermission(ReflectionPermissionFlag flag)
{
VerifyAccess(flag);
SetUnrestricted(false);
m_flags = flag;
}
//------------------------------------------------------
//
// PRIVATE AND PROTECTED MODIFIERS
//
//------------------------------------------------------
private void SetUnrestricted(bool unrestricted)
{
if (unrestricted)
{
m_flags = ReflectionPermission.AllFlagsAndMore;
}
else
{
Reset();
}
}
private void Reset()
{
m_flags = ReflectionPermissionFlag.NoFlags;
}
public ReflectionPermissionFlag Flags
{
set
{
VerifyAccess(value);
m_flags = value;
}
get
{
return m_flags;
}
}
#if ZERO // Do not remove this code, useful for debugging
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("ReflectionPermission(");
if (IsUnrestricted())
{
sb.Append("Unrestricted");
}
else
{
if (GetFlag(ReflectionPermissionFlag.TypeInformation))
sb.Append("TypeInformation; ");
if (GetFlag(ReflectionPermissionFlag.MemberAccess))
sb.Append("MemberAccess; ");
#pragma warning disable 618
if (GetFlag(ReflectionPermissionFlag.ReflectionEmit))
sb.Append("ReflectionEmit; ");
#pragma warning restore 618
}
sb.Append(")");
return sb.ToString();
}
#endif
//
// CodeAccessPermission implementation
//
public bool IsUnrestricted()
{
return m_flags == ReflectionPermission.AllFlagsAndMore;
}
//
// IPermission implementation
//
public override IPermission Union(IPermission other)
{
if (other == null)
{
return this.Copy();
}
else if (!VerifyType(other))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
ReflectionPermission operand = (ReflectionPermission)other;
if (this.IsUnrestricted() || operand.IsUnrestricted())
{
return new ReflectionPermission( PermissionState.Unrestricted );
}
else
{
ReflectionPermissionFlag flag_union = (ReflectionPermissionFlag)(m_flags | operand.m_flags);
return(new ReflectionPermission(flag_union));
}
}
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
return m_flags == ReflectionPermissionFlag.NoFlags;
}
try
{
ReflectionPermission operand = (ReflectionPermission)target;
if (operand.IsUnrestricted())
return true;
else if (this.IsUnrestricted())
return false;
else
return (((int)this.m_flags) & ~((int)operand.m_flags)) == 0;
}
catch (InvalidCastException)
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
return null;
else if (!VerifyType(target))
{
throw new
ArgumentException(
Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)
);
}
ReflectionPermission operand = (ReflectionPermission)target;
ReflectionPermissionFlag newFlags = operand.m_flags & this.m_flags;
if (newFlags == ReflectionPermissionFlag.NoFlags)
return null;
else
return new ReflectionPermission( newFlags );
}
public override IPermission Copy()
{
if (this.IsUnrestricted())
{
return new ReflectionPermission(PermissionState.Unrestricted);
}
else
{
return new ReflectionPermission((ReflectionPermissionFlag)m_flags);
}
}
//
// IEncodable Interface
private
void VerifyAccess(ReflectionPermissionFlag type)
{
if ((type & ~ReflectionPermission.AllFlagsAndMore) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)type));
Contract.EndContractBlock();
}
#if FEATURE_CAS_POLICY
//------------------------------------------------------
//
// PUBLIC ENCODING METHODS
//
//------------------------------------------------------
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.ReflectionPermission" );
if (!IsUnrestricted())
{
esd.AddAttribute( "Flags", XMLUtil.BitFieldEnumToString( typeof( ReflectionPermissionFlag ), m_flags ) );
}
else
{
esd.AddAttribute( "Unrestricted", "true" );
}
return esd;
}
public override void FromXml(SecurityElement esd)
{
CodeAccessPermission.ValidateElement( esd, this );
if (XMLUtil.IsUnrestricted( esd ))
{
m_flags = ReflectionPermission.AllFlagsAndMore;
return;
}
Reset () ;
SetUnrestricted (false) ;
String flags = esd.Attribute( "Flags" );
if (flags != null)
m_flags = (ReflectionPermissionFlag)Enum.Parse( typeof( ReflectionPermissionFlag ), flags );
}
#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return ReflectionPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.ReflectionPermissionIndex;
}
}
}
| |
#region Namespaces
using System;
using System.Data;
using System.Windows.Forms;
using System.Collections.Generic;
using Epi;
//using Epi.Analysis;
using EpiInfo.Plugin;
using Epi.Collections;
using Epi.Windows.Dialogs;
#endregion Namespaces
using VariableCollection = Epi.Collections.NamedObjectCollection<Epi.IVariable>;
namespace Epi.Windows.MakeView.Dialogs
{
/// <summary>
/// Command Design Dialog
/// </summary>
public partial class CommandDesignDialog : DialogBase
{
#region private Class members
/// <summary>
/// Command processing modes
/// </summary>
public enum CommandProcessingMode
{
Save_And_Execute,
Save_Only
}
private CommandProcessingMode processingMode = CommandProcessingMode.Save_And_Execute;
public CommandProcessingMode ProcessingMode
{
get { return this.processingMode; }
}
private string commandText = string.Empty;
#endregion private Class members
#region Protected Data Members
/// <summary>
/// The EpiIterpreter object accessable by Inherited Dialogs
/// </summary>
protected EpiInfo.Plugin.IEnterInterpreter EpiInterpreter;
/// <summary>
/// The ICommand Processor for the dialog
/// </summary>
protected ICommandProcessor dialogCommandProcessor;
#endregion //Protected Data Members
#region Constructors
/// <summary>
/// Default Constructor for execlusive use by the designer
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public CommandDesignDialog()
{
InitializeComponent();
}
/// <summary>
/// Constructor for Command Design Dialog
/// </summary>
/// <param name="frm">The main form</param>
public CommandDesignDialog(Epi.Windows.MakeView.Forms.MakeViewMainForm frm)
: base(frm)
{
InitializeComponent();
this.EpiInterpreter = frm.EpiInterpreter;
//dialogCommandProcessor = Module.GetService(typeof(ICommandProcessor)) as ICommandProcessor;
//if (dialogCommandProcessor == null)
//{
// throw new GeneralException("Command processor is required but not available.");
//}
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Returns the current Module
/// </summary>
public new IWindowsModule Module
{
get
{
return base.Module as IWindowsModule;
}
}
/// <summary>
/// Accessor method for property commandText
/// </summary>
public string CommandText
{
get
{
return commandText;
}
set
{
commandText = value;
}
}
#endregion Public Properties
#region Event Handlers
/// <summary>
/// Sets the processing mode and generates command
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected virtual void btnOK_Click(object sender, System.EventArgs e)
{
processingMode = CommandProcessingMode.Save_And_Execute;
OnOK();
}
/// <summary>
/// Sets the processing mode and generates command
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected void btnSaveOnly_Click(object sender, System.EventArgs e)
{
processingMode = CommandProcessingMode.Save_Only;
OnOK();
}
/// <summary>
/// Closes the dialog
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected void btnCancel_Click(object sender, System.EventArgs e)
{
this.Close();
}
#endregion Event Handlers
#region Protected Methods
/// <summary>
/// FillVariableListBox()
/// ListBox and ComboBox both derive from ListControl
/// According to Help file Items property of ListControl is Public.
/// Contrary to helpfile there is no such property.
/// So polymorphism could not be used as expected
/// </summary>
/// <param name="lbx">ListBox to be filled</param>
/// <param name="scopeWord">The scope of the variable</param>
protected void FillVariableListBox(ListBox lbx, VariableType scopeWord)
{
lbx.Items.Clear();
List<EpiInfo.Plugin.IVariable> vars = this.EpiInterpreter.Context.GetVariablesInScope((VariableScope)scopeWord);
lbx.BeginUpdate();
foreach (EpiInfo.Plugin.IVariable var in vars)
{
if (!(var is Epi.Fields.PredefinedDataField))
{
lbx.Items.Add(var.Name.ToString());
}
}
lbx.EndUpdate();
lbx.Sorted = true;
lbx.Refresh();
}
/// <summary>
/// FillvariableCombo()
/// </summary>
/// <param name="cmb">ComboBox to be filled</param>
/// <param name="scopeWord">The scope of the variable</param>
protected void FillVariableCombo(ComboBox cmb, VariableType scopeWord)
{
cmb.Items.Clear();
List<EpiInfo.Plugin.IVariable> vars = this.EpiInterpreter.Context.GetVariablesInScope((VariableScope)scopeWord);
cmb.BeginUpdate();
foreach (EpiInfo.Plugin.IVariable var in vars)
{
if (!(var is Epi.Fields.PredefinedDataField))
{
cmb.Items.Add(var.Name.ToString());
}
}
cmb.EndUpdate();
cmb.Sorted = true;
cmb.Refresh();
}
/// <summary>
/// FillvariableCombo()
/// </summary>
/// <param name="cmb">ComboBox to be filled</param>
/// <param name="scopeWord">The scope of the variable</param>
/// <param name="typ">Limit selection to (DataType)</param>
protected void FillVariableCombo(ComboBox cmb, VariableType scopeWord, DataType typ)
{
cmb.Items.Clear();
List<EpiInfo.Plugin.IVariable> vars = this.EpiInterpreter.Context.GetVariablesInScope((VariableScope)scopeWord);
cmb.BeginUpdate();
foreach (EpiInfo.Plugin.IVariable var in vars)
{
int VType = (int)var.DataType;
int FType = (int)typ;
if (!(var is Epi.Fields.PredefinedDataField) && ((VType & FType) == VType))
{
cmb.Items.Add(var.Name.ToString());
}
}
cmb.EndUpdate();
cmb.Sorted = true;
cmb.Refresh();
}
/// <summary>
/// Method for generating Commands
/// </summary>
protected virtual void GenerateCommand()
{
}
/// <summary>
/// Method for preprocessing commands
/// </summary>
protected virtual void PreProcess()
{
}
#endregion Protected Methods
#region Private Methods
/// <summary>
/// If validation passes command is generated
/// </summary>
protected void OnOK()
{
if (ValidateInput() == true)
{
GenerateCommand();
PreProcess();
this.DialogResult = DialogResult.OK;
this.Hide();
}
else
{
this.DialogResult = DialogResult.None;
ShowErrorMessages();
}
}
#endregion Private Methods
} // Class
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Orleans.Streams;
using Orleans.Runtime.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Orleankka.Cluster
{
using Core;
using Core.Streams;
using Behaviors;
using Utility;
using Annotations;
public sealed class ClusterConfigurator
{
readonly ActorInterfaceRegistry registry =
new ActorInterfaceRegistry();
readonly HashSet<string> conventions = new HashSet<string>();
readonly HashSet<BootstrapProviderConfiguration> bootstrapProviders =
new HashSet<BootstrapProviderConfiguration>();
readonly HashSet<StreamProviderConfiguration> streamProviders =
new HashSet<StreamProviderConfiguration>();
readonly ActorInvocationPipeline pipeline = new ActorInvocationPipeline();
IActorRefInvoker invoker;
Action<IServiceCollection> di;
internal ClusterConfigurator()
{
Configuration = new ClusterConfiguration();
}
public ClusterConfiguration Configuration { get; set; }
public ClusterConfigurator From(ClusterConfiguration config)
{
Requires.NotNull(config, nameof(config));
Configuration = config;
return this;
}
public ClusterConfigurator Assemblies(params Assembly[] assemblies)
{
registry.Register(assemblies, a => a.ActorTypes());
return this;
}
public ClusterConfigurator Bootstrapper<T>(object properties = null) where T : IBootstrapper
{
var configuration = new BootstrapProviderConfiguration(typeof(T), properties);
if (!bootstrapProviders.Add(configuration))
throw new ArgumentException($"Bootstrapper of the type {typeof(T)} has been already registered");
return this;
}
public ClusterConfigurator StreamProvider<T>(string name, IDictionary<string, string> properties = null) where T : IStreamProviderImpl
{
Requires.NotNullOrWhitespace(name, nameof(name));
var configuration = new StreamProviderConfiguration(name, typeof(T), properties);
if (!streamProviders.Add(configuration))
throw new ArgumentException($"Stream provider of the type {typeof(T)} has been already registered under '{name}' name");
return this;
}
public ClusterConfigurator Services(Action<IServiceCollection> configure)
{
Requires.NotNull(configure, nameof(configure));
if (di != null)
throw new InvalidOperationException("Services configurator has been already set");
di = configure;
return this;
}
/// <summary>
/// Registers global actor invoker (interceptor). This invoker will be used for every actor
/// which doesn't specify an individual invoker via <see cref="InvokerAttribute"/> attribute.
/// </summary>
/// <param name="global">The invoker.</param>
public ClusterConfigurator ActorInvoker(IActorInvoker global)
{
pipeline.Register(global);
return this;
}
/// <summary>
/// Registers named actor invoker (interceptor). For this invoker to be used an actor need
/// to specify its name via <see cref="InvokerAttribute"/> attribute.
/// The invoker is inherited by all subclasses.
/// </summary>
/// <param name="name">The name of the invoker</param>
/// <param name="invoker">The invoker.</param>
public ClusterConfigurator ActorInvoker(string name, IActorInvoker invoker)
{
pipeline.Register(name, invoker);
return this;
}
/// <summary>
/// Registers global <see cref="ActorRef"/> invoker (interceptor)
/// </summary>
/// <param name="invoker">The invoker.</param>
public ClusterConfigurator ActorRefInvoker(IActorRefInvoker invoker)
{
Requires.NotNull(invoker, nameof(invoker));
if (this.invoker != null)
throw new InvalidOperationException("ActorRef invoker has been already registered");
this.invoker = invoker;
return this;
}
public ClusterConfigurator HandlerNamingConventions(params string[] conventions)
{
Requires.NotNull(conventions, nameof(conventions));
if (conventions.Length == 0)
throw new ArgumentException("conventions are empty", nameof(conventions));
Array.ForEach(conventions, x => this.conventions.Add(x));
return this;
}
public ClusterActorSystem Done()
{
Configure();
return new ClusterActorSystem(Configuration, di, pipeline, invoker);
}
void Configure()
{
RegisterInterfaces();
RegisterTypes();
RegisterAutoruns();
RegisterStreamProviders();
RegisterStreamSubscriptions();
RegisterBootstrappers();
RegisterBehaviors();
}
void RegisterInterfaces() => ActorInterface.Register(registry.Assemblies, registry.Mappings);
void RegisterTypes() => ActorType.Register(registry.Assemblies, conventions.Count > 0 ? conventions.ToArray() : null);
void RegisterAutoruns()
{
var autoruns = new Dictionary<string, string[]>();
foreach (var actor in registry.Assemblies.SelectMany(x => x.ActorTypes()))
{
var ids = AutorunAttribute.From(actor);
if (ids.Length > 0)
autoruns.Add(ActorTypeName.Of(actor), ids);
}
Bootstrapper<AutorunBootstrapper>(autoruns);
}
void RegisterStreamProviders()
{
foreach (var each in streamProviders)
each.Register(Configuration);
}
void RegisterBootstrappers()
{
foreach (var each in bootstrapProviders)
each.Register(Configuration.Globals);
}
void RegisterBehaviors()
{
foreach (var actor in registry.Assemblies.SelectMany(x => x.ActorTypes()))
ActorBehavior.Register(actor);
}
void RegisterStreamSubscriptions()
{
foreach (var actor in ActorType.Registered())
StreamSubscriptionMatcher.Register(actor.Name, actor.Subscriptions());
const string id = "stream-subscription-boot";
var properties = new Dictionary<string, string>();
properties["providers"] = string.Join(";", streamProviders
.Where(x => x.IsPersistentStreamProvider())
.Select(x => x.Name));
Configuration.Globals.RegisterStorageProvider<StreamSubscriptionBootstrapper>(id, properties);
}
[UsedImplicitly]
class AutorunBootstrapper : Bootstrapper<Dictionary<string, string[]>>
{
protected override Task Run(IActorSystem system, Dictionary<string, string[]> properties) =>
Task.WhenAll(properties.SelectMany(x => Autorun(system, x.Key, x.Value)));
static IEnumerable<Task> Autorun(IActorSystem system, string type, IEnumerable<string> ids) =>
ids.Select(id => system.ActorOf(type, id).Autorun());
}
}
public static class ClusterConfiguratorExtensions
{
public static ClusterConfigurator Cluster(this IActorSystemConfigurator root)
{
return new ClusterConfigurator();
}
public static ClusterConfiguration LoadFromEmbeddedResource<TNamespaceScope>(this ClusterConfiguration config, string resourceName)
{
return LoadFromEmbeddedResource(config, typeof(TNamespaceScope), resourceName);
}
public static ClusterConfiguration LoadFromEmbeddedResource(this ClusterConfiguration config, Type namespaceScope, string resourceName)
{
if (namespaceScope.Namespace == null)
throw new ArgumentException("Resource assembly and scope cannot be determined from type '0' since it has no namespace.\nUse overload that takes Assembly and string path to provide full path of the embedded resource");
return LoadFromEmbeddedResource(config, namespaceScope.Assembly, $"{namespaceScope.Namespace}.{resourceName}");
}
public static ClusterConfiguration LoadFromEmbeddedResource(this ClusterConfiguration config, Assembly assembly, string fullResourcePath)
{
var result = new ClusterConfiguration();
result.Load(assembly.LoadEmbeddedResource(fullResourcePath));
return result;
}
public static ClusterConfiguration DefaultKeepAliveTimeout(this ClusterConfiguration config, TimeSpan idle)
{
Requires.NotNull(config, nameof(config));
config.Globals.Application.SetDefaultCollectionAgeLimit(idle);
return config;
}
}
}
| |
// 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.Xml;
using System.Globalization;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || uapaot
public class XmlWriterDelegator
#else
internal class XmlWriterDelegator
#endif
{
protected XmlWriter writer;
protected XmlDictionaryWriter dictionaryWriter;
internal int depth;
private int _prefixes;
public XmlWriterDelegator(XmlWriter writer)
{
XmlObjectSerializer.CheckNull(writer, nameof(writer));
this.writer = writer;
this.dictionaryWriter = writer as XmlDictionaryWriter;
}
internal XmlWriter Writer
{
get { return writer; }
}
internal void Flush()
{
writer.Flush();
}
internal string LookupPrefix(string ns)
{
return writer.LookupPrefix(ns);
}
private void WriteEndAttribute()
{
writer.WriteEndAttribute();
}
#if USE_REFEMIT
public void WriteEndElement()
#else
internal void WriteEndElement()
#endif
{
writer.WriteEndElement();
depth--;
}
internal void WriteRaw(char[] buffer, int index, int count)
{
writer.WriteRaw(buffer, index, count);
}
internal void WriteRaw(string data)
{
writer.WriteRaw(data);
}
internal void WriteXmlnsAttribute(XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
if (ns != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
}
else
WriteXmlnsAttribute(ns.Value);
}
internal void WriteXmlnsAttribute(string ns)
{
if (ns != null)
{
if (ns.Length == 0)
writer.WriteAttributeString("xmlns", string.Empty, null, ns);
else
{
if (dictionaryWriter != null)
dictionaryWriter.WriteXmlnsAttribute(null, ns);
else
{
string prefix = writer.LookupPrefix(ns);
if (prefix == null)
{
prefix = string.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, _prefixes);
_prefixes++;
writer.WriteAttributeString("xmlns", prefix, null, ns);
}
}
}
}
}
internal void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
if (dictionaryWriter != null)
{
dictionaryWriter.WriteXmlnsAttribute(prefix, ns);
}
else
{
writer.WriteAttributeString("xmlns", prefix, null, ns.Value);
}
}
private void WriteStartAttribute(string prefix, string localName, string ns)
{
writer.WriteStartAttribute(prefix, localName, ns);
}
private void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri);
else
writer.WriteStartAttribute(prefix,
(localName == null ? null : localName.Value),
(namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteAttributeString(string prefix, string localName, string ns, string value)
{
WriteStartAttribute(prefix, localName, ns);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
private void WriteAttributeStringValue(string value)
{
writer.WriteValue(value);
}
internal void WriteAttributeString(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeStringValue(value);
WriteEndAttribute();
}
private void WriteAttributeStringValue(XmlDictionaryString value)
{
if (dictionaryWriter == null)
writer.WriteString(value.Value);
else
dictionaryWriter.WriteString(value);
}
internal void WriteAttributeInt(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, int value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeIntValue(value);
WriteEndAttribute();
}
private void WriteAttributeIntValue(int value)
{
writer.WriteValue(value);
}
internal void WriteAttributeBool(string prefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, bool value)
{
WriteStartAttribute(prefix, attrName, attrNs);
WriteAttributeBoolValue(value);
WriteEndAttribute();
}
private void WriteAttributeBoolValue(bool value)
{
writer.WriteValue(value);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
private void WriteAttributeQualifiedNameValue(string name, string ns)
{
writer.WriteQualifiedName(name, ns);
}
internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteXmlnsAttribute(ns);
WriteStartAttribute(attrPrefix, attrName, attrNs);
WriteAttributeQualifiedNameValue(name, ns);
WriteEndAttribute();
}
private void WriteAttributeQualifiedNameValue(XmlDictionaryString name, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(name.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(name, ns);
}
internal void WriteStartElement(string localName, string ns)
{
WriteStartElement(null, localName, ns);
}
internal virtual void WriteStartElement(string prefix, string localName, string ns)
{
writer.WriteStartElement(prefix, localName, ns);
depth++;
_prefixes = 1;
}
#if USE_REFEMIT
public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
#else
internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
#endif
{
WriteStartElement(null, localName, namespaceUri);
}
internal void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri);
else
writer.WriteStartElement(prefix, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
depth++;
_prefixes = 1;
}
internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
{
if (dictionaryWriter != null)
dictionaryWriter.WriteStartElement(null, localName, namespaceUri);
else
writer.WriteStartElement(null, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value));
}
internal void WriteEndElementPrimitive()
{
writer.WriteEndElement();
}
internal WriteState WriteState
{
get { return writer.WriteState; }
}
internal string XmlLang
{
get { return writer.XmlLang; }
}
internal XmlSpace XmlSpace
{
get { return writer.XmlSpace; }
}
#if USE_REFEMIT
public void WriteNamespaceDecl(XmlDictionaryString ns)
#else
internal void WriteNamespaceDecl(XmlDictionaryString ns)
#endif
{
WriteXmlnsAttribute(ns);
}
private Exception CreateInvalidPrimitiveTypeException(Type type)
{
return new InvalidDataContractException(SR.Format(SR.InvalidPrimitiveType_Serialization, DataContract.GetClrTypeFullName(type)));
}
internal void WriteAnyType(object value)
{
WriteAnyType(value, value.GetType());
}
internal void WriteAnyType(object value, Type valueType)
{
bool handled = true;
switch (valueType.GetTypeCode())
{
case TypeCode.Boolean:
WriteBoolean((bool)value);
break;
case TypeCode.Char:
WriteChar((char)value);
break;
case TypeCode.Byte:
WriteUnsignedByte((byte)value);
break;
case TypeCode.Int16:
WriteShort((short)value);
break;
case TypeCode.Int32:
WriteInt((int)value);
break;
case TypeCode.Int64:
WriteLong((long)value);
break;
case TypeCode.Single:
WriteFloat((float)value);
break;
case TypeCode.Double:
WriteDouble((double)value);
break;
case TypeCode.Decimal:
WriteDecimal((decimal)value);
break;
case TypeCode.DateTime:
WriteDateTime((DateTime)value);
break;
case TypeCode.String:
WriteString((string)value);
break;
case TypeCode.SByte:
WriteSignedByte((sbyte)value);
break;
case TypeCode.UInt16:
WriteUnsignedShort((ushort)value);
break;
case TypeCode.UInt32:
WriteUnsignedInt((uint)value);
break;
case TypeCode.UInt64:
WriteUnsignedLong((ulong)value);
break;
case TypeCode.Empty:
case TypeCode.Object:
default:
if (valueType == Globals.TypeOfByteArray)
WriteBase64((byte[])value);
else if (valueType == Globals.TypeOfObject)
{
//Write Nothing
}
else if (valueType == Globals.TypeOfTimeSpan)
WriteTimeSpan((TimeSpan)value);
else if (valueType == Globals.TypeOfGuid)
WriteGuid((Guid)value);
else if (valueType == Globals.TypeOfUri)
WriteUri((Uri)value);
else if (valueType == Globals.TypeOfXmlQualifiedName)
WriteQName((XmlQualifiedName)value);
else
handled = false;
break;
}
if (!handled)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType));
}
internal void WriteExtensionData(IDataNode dataNode)
{
bool handled = true;
Type valueType = dataNode.DataType;
switch (Type.GetTypeCode(valueType))
{
case TypeCode.Boolean:
WriteBoolean(((DataNode<bool>)dataNode).GetValue());
break;
case TypeCode.Char:
WriteChar(((DataNode<char>)dataNode).GetValue());
break;
case TypeCode.Byte:
WriteUnsignedByte(((DataNode<byte>)dataNode).GetValue());
break;
case TypeCode.Int16:
WriteShort(((DataNode<short>)dataNode).GetValue());
break;
case TypeCode.Int32:
WriteInt(((DataNode<int>)dataNode).GetValue());
break;
case TypeCode.Int64:
WriteLong(((DataNode<long>)dataNode).GetValue());
break;
case TypeCode.Single:
WriteFloat(((DataNode<float>)dataNode).GetValue());
break;
case TypeCode.Double:
WriteDouble(((DataNode<double>)dataNode).GetValue());
break;
case TypeCode.Decimal:
WriteDecimal(((DataNode<decimal>)dataNode).GetValue());
break;
case TypeCode.DateTime:
WriteDateTime(((DataNode<DateTime>)dataNode).GetValue());
break;
case TypeCode.String:
WriteString(((DataNode<string>)dataNode).GetValue());
break;
case TypeCode.SByte:
WriteSignedByte(((DataNode<sbyte>)dataNode).GetValue());
break;
case TypeCode.UInt16:
WriteUnsignedShort(((DataNode<ushort>)dataNode).GetValue());
break;
case TypeCode.UInt32:
WriteUnsignedInt(((DataNode<uint>)dataNode).GetValue());
break;
case TypeCode.UInt64:
WriteUnsignedLong(((DataNode<ulong>)dataNode).GetValue());
break;
case TypeCode.Empty:
case TypeCode.DBNull:
case TypeCode.Object:
default:
if (valueType == Globals.TypeOfByteArray)
WriteBase64(((DataNode<byte[]>)dataNode).GetValue());
else if (valueType == Globals.TypeOfObject)
{
object obj = dataNode.Value;
if (obj != null)
WriteAnyType(obj);
}
else if (valueType == Globals.TypeOfTimeSpan)
WriteTimeSpan(((DataNode<TimeSpan>)dataNode).GetValue());
else if (valueType == Globals.TypeOfGuid)
WriteGuid(((DataNode<Guid>)dataNode).GetValue());
else if (valueType == Globals.TypeOfUri)
WriteUri(((DataNode<Uri>)dataNode).GetValue());
else if (valueType == Globals.TypeOfXmlQualifiedName)
WriteQName(((DataNode<XmlQualifiedName>)dataNode).GetValue());
else
handled = false;
break;
}
if (!handled)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType));
}
}
internal void WriteString(string value)
{
writer.WriteValue(value);
}
internal virtual void WriteBoolean(bool value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteBoolean(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDateTime(DateTime value)
{
WriteString(XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind));
}
#if USE_REFEMIT
public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDateTime(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDecimal(decimal value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDecimal(value);
WriteEndElementPrimitive();
}
internal virtual void WriteDouble(double value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteDouble(value);
WriteEndElementPrimitive();
}
internal virtual void WriteInt(int value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteLong(long value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteFloat(float value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteFloat(value);
WriteEndElementPrimitive();
}
internal virtual void WriteBase64(byte[] bytes)
{
if (bytes == null)
return;
writer.WriteBase64(bytes, 0, bytes.Length);
}
internal virtual void WriteShort(short value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedByte(byte value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteSignedByte(sbyte value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteSignedByte(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedInt(uint value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedInt(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedLong(ulong value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedLong(value);
WriteEndElementPrimitive();
}
internal virtual void WriteUnsignedShort(ushort value)
{
writer.WriteValue(value);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteUnsignedShort(value);
WriteEndElementPrimitive();
}
internal virtual void WriteChar(char value)
{
writer.WriteValue((int)value);
}
#if USE_REFEMIT
public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteChar(value);
WriteEndElementPrimitive();
}
internal void WriteTimeSpan(TimeSpan value)
{
writer.WriteRaw(XmlConvert.ToString(value));
}
internal void WriteTimeSpan(char value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
writer.WriteRaw(XmlConvert.ToString(value));
WriteEndElementPrimitive();
}
#if USE_REFEMIT
public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteTimeSpan(value);
WriteEndElementPrimitive();
}
internal void WriteGuid(Guid value)
{
writer.WriteRaw(value.ToString());
}
#if USE_REFEMIT
public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
WriteStartElementPrimitive(name, ns);
WriteGuid(value);
WriteEndElementPrimitive();
}
internal void WriteUri(Uri value)
{
writer.WriteString(value.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped));
}
internal void WriteUri(Uri value, XmlDictionaryString name, XmlDictionaryString ns)
{
WriteStartElementPrimitive(name, ns);
WriteUri(value);
WriteEndElementPrimitive();
}
internal virtual void WriteQName(XmlQualifiedName value)
{
if (value != XmlQualifiedName.Empty)
{
WriteXmlnsAttribute(value.Namespace);
WriteQualifiedName(value.Name, value.Namespace);
}
}
internal void WriteQualifiedName(string localName, string ns)
{
writer.WriteQualifiedName(localName, ns);
}
internal void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString ns)
{
if (dictionaryWriter == null)
writer.WriteQualifiedName(localName.Value, ns.Value);
else
dictionaryWriter.WriteQualifiedName(localName, ns);
}
#if USE_REFEMIT
public void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteBoolean(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDateTime(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDecimal(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteInt(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteLong(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteFloat(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
#if USE_REFEMIT
public void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#else
internal void WriteDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
#endif
{
if (dictionaryWriter == null)
{
for (int i = 0; i < value.Length; i++)
{
WriteDouble(value[i], itemName, itemNamespace);
}
}
else
{
dictionaryWriter.WriteArray(null, itemName, itemNamespace, value, 0, value.Length);
}
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime
{
/// <summary>
/// This class collects runtime statistics for all silos in the current deployment for use by placement.
/// </summary>
internal class DeploymentLoadPublisher : SystemTarget, IDeploymentLoadPublisher, ISiloStatusListener
{
private readonly Silo silo;
private readonly ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> periodicStats;
private readonly TimeSpan statisticsRefreshTime;
private readonly IList<ISiloStatisticsChangeListener> siloStatisticsChangeListeners;
private readonly TraceLogger logger = TraceLogger.GetLogger("DeploymentLoadPublisher", TraceLogger.LoggerType.Runtime);
public static DeploymentLoadPublisher Instance { get; private set; }
public ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> PeriodicStatistics { get { return periodicStats; } }
public static void CreateDeploymentLoadPublisher(Silo silo, GlobalConfiguration config)
{
Instance = new DeploymentLoadPublisher(silo, config.DeploymentLoadPublisherRefreshTime);
}
private DeploymentLoadPublisher(Silo silo, TimeSpan freshnessTime)
: base(Constants.DeploymentLoadPublisherSystemTargetId, silo.SiloAddress)
{
this.silo = silo;
statisticsRefreshTime = freshnessTime;
periodicStats = new ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>();
siloStatisticsChangeListeners = new List<ISiloStatisticsChangeListener>();
}
public async Task Start()
{
logger.Info("Starting DeploymentLoadPublisher.");
if (statisticsRefreshTime > TimeSpan.Zero)
{
var random = new SafeRandom();
// Randomize PublishStatistics timer,
// but also upon start publish my stats to everyone and take everyone's stats for me to start with something.
var randomTimerOffset = random.NextTimeSpan(statisticsRefreshTime);
var t = GrainTimer.FromTaskCallback(PublishStatistics, null, randomTimerOffset, statisticsRefreshTime);
t.Start();
}
await RefreshStatistics();
await PublishStatistics(null);
logger.Info("Started DeploymentLoadPublisher.");
}
private async Task PublishStatistics(object _)
{
try
{
if(logger.IsVerbose) logger.Verbose("PublishStatistics.");
List<SiloAddress> members = silo.LocalSiloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToList();
var tasks = new List<Task>();
var myStats = new SiloRuntimeStatistics(silo.Metrics, DateTime.UtcNow);
foreach (var siloAddress in members)
{
try
{
tasks.Add(DeploymentLoadPublisherFactory.GetSystemTarget(
Constants.DeploymentLoadPublisherSystemTargetId, siloAddress)
.UpdateRuntimeStatistics(silo.SiloAddress, myStats));
}
catch (Exception)
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_1,
String.Format("An unexpected exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignored."));
}
}
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_2,
String.Format("An exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignoring."), exc);
}
}
public Task UpdateRuntimeStatistics(SiloAddress siloAddress, SiloRuntimeStatistics siloStats)
{
if (logger.IsVerbose) logger.Verbose("UpdateRuntimeStatistics from {0}", siloAddress);
if (!silo.LocalSiloStatusOracle.GetApproximateSiloStatus(siloAddress).Equals(SiloStatus.Active))
return TaskDone.Done;
SiloRuntimeStatistics old;
// Take only if newer.
if (periodicStats.TryGetValue(siloAddress, out old) && old.DateTime > siloStats.DateTime)
return TaskDone.Done;
periodicStats[siloAddress] = siloStats;
NotifyAllStatisticsChangeEventsSubscribers(siloAddress, siloStats);
return TaskDone.Done;
}
internal async Task<ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>> RefreshStatistics()
{
if (logger.IsVerbose) logger.Verbose("RefreshStatistics.");
await silo.LocalScheduler.RunOrQueueTask( () =>
{
var tasks = new List<Task>();
List<SiloAddress> members = silo.LocalSiloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToList();
foreach (var siloAddress in members)
{
var capture = siloAddress;
Task task = SiloControlFactory.GetSystemTarget(Constants.SiloControlId, capture)
.GetRuntimeStatistics()
.ContinueWith((Task<SiloRuntimeStatistics> statsTask) =>
{
if (statsTask.Status == TaskStatus.RanToCompletion)
{
UpdateRuntimeStatistics(capture, statsTask.Result);
}
else
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_3,
String.Format("An unexpected exception was thrown from RefreshStatistics by ISiloControl.GetRuntimeStatistics({0}). Will keep using stale statistics.", capture),
statsTask.Exception);
}
});
tasks.Add(task);
task.Ignore();
}
return Task.WhenAll(tasks);
}, SchedulingContext);
return periodicStats;
}
public bool SubscribeToStatisticsChangeEvents(ISiloStatisticsChangeListener observer)
{
lock (siloStatisticsChangeListeners)
{
if (siloStatisticsChangeListeners.Contains(observer)) return false;
siloStatisticsChangeListeners.Add(observer);
return true;
}
}
public bool UnsubscribeStatisticsChangeEvents(ISiloStatisticsChangeListener observer)
{
lock (siloStatisticsChangeListeners)
{
return siloStatisticsChangeListeners.Contains(observer) &&
siloStatisticsChangeListeners.Remove(observer);
}
}
private void NotifyAllStatisticsChangeEventsSubscribers(SiloAddress silo, SiloRuntimeStatistics stats)
{
lock (siloStatisticsChangeListeners)
{
foreach (var subscriber in siloStatisticsChangeListeners)
{
if (stats==null)
{
subscriber.RemoveSilo(silo);
}
else
{
subscriber.SiloStatisticsChangeNotification(silo, stats);
}
}
}
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
if (!status.Equals(SiloStatus.Stopping) && !status.Equals(SiloStatus.ShuttingDown) &&
!status.Equals(SiloStatus.Dead)) return;
SiloRuntimeStatistics ignore;
periodicStats.TryRemove(updatedSilo, out ignore);
NotifyAllStatisticsChangeEventsSubscribers(updatedSilo, null);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Options;
using System.Text;
namespace NUnit.Common
{
/// <summary>
/// CommandLineOptions is the base class the specific option classes
/// used for nunit3-console and nunitlite. It encapsulates all common
/// settings and features of both. This is done to ensure that common
/// features remain common and for the convenience of having the code
/// in a common location. The class inherits from the Mono
/// Options OptionSet class and provides a central location
/// for defining and parsing options.
/// </summary>
public class CommandLineOptions : OptionSet
{
private static readonly string DEFAULT_WORK_DIRECTORY =
#if PORTABLE
@"\My Documents";
#else
Directory.GetCurrentDirectory();
#endif
private bool validated;
#if !PORTABLE
private bool noresult;
#endif
#region Constructor
internal CommandLineOptions(IDefaultOptionsProvider defaultOptionsProvider, params string[] args)
{
// Apply default options
if (defaultOptionsProvider == null) throw new ArgumentNullException("defaultOptionsProvider");
TeamCity = defaultOptionsProvider.TeamCity;
ConfigureOptions();
if (args != null)
Parse(PreParse(args));
}
public CommandLineOptions(params string[] args)
{
ConfigureOptions();
if (args != null)
Parse(PreParse(args));
}
#if PORTABLE
internal IEnumerable<string> PreParse(IEnumerable<string> args)
{
return args;
}
#else
private int _nesting = 0;
internal IEnumerable<string> PreParse(IEnumerable<string> args)
{
if (++_nesting > 3)
{
ErrorMessages.Add("@ nesting exceeds maximum depth of 3.");
--_nesting;
return args;
}
var listArgs = new List<string>();
foreach (var arg in args)
{
if (arg.Length == 0 || arg[0] != '@')
{
listArgs.Add(arg);
continue;
}
if (arg.Length == 1)
{
ErrorMessages.Add("You must include a file name after @.");
continue;
}
var filename = arg.Substring(1);
if (!File.Exists(filename))
{
ErrorMessages.Add("The file \"" + filename + "\" was not found.");
continue;
}
try
{
listArgs.AddRange(PreParse(GetArgsFromFile(filename)));
}
catch (IOException ex)
{
ErrorMessages.Add("Error reading \"" + filename + "\": " + ex.Message);
}
}
--_nesting;
return listArgs;
}
private static readonly Regex ArgsRegex = new Regex(@"\G(""((""""|[^""])+)""|(\S+)) *", RegexOptions.Compiled | RegexOptions.CultureInvariant);
// Get args from a string of args
internal static IEnumerable<string> GetArgs(string commandLine)
{
foreach (Match m in ArgsRegex.Matches(commandLine))
yield return Regex.Replace(m.Groups[2].Success ? m.Groups[2].Value : m.Groups[4].Value, @"""""", @"""");
}
// Get args from an included file
private static IEnumerable<string> GetArgsFromFile(string filename)
{
var sb = new StringBuilder();
foreach (var line in File.ReadAllLines(filename))
{
if (!string.IsNullOrEmpty(line) && line[0] != '#' && line.Trim().Length > 0)
{
if (sb.Length > 0)
sb.Append(' ');
sb.Append(line);
}
}
return GetArgs(sb.ToString());
}
#endif
#endregion
#region Properties
// Action to Perform
public bool Explore { get; private set; }
public bool ShowHelp { get; private set; }
public bool ShowVersion { get; private set; }
// Select tests
private List<string> inputFiles = new List<string>();
public IList<string> InputFiles { get { return inputFiles; } }
private List<string> testList = new List<string>();
public IList<string> TestList { get { return testList; } }
private IDictionary<string, string> testParameters = new Dictionary<string, string>();
public IDictionary<string, string> TestParameters { get { return testParameters; } }
public string WhereClause { get; private set; }
public bool WhereClauseSpecified { get { return WhereClause != null; } }
private int defaultTimeout = -1;
public int DefaultTimeout { get { return defaultTimeout; } }
public bool DefaultTimeoutSpecified { get { return defaultTimeout >= 0; } }
private int randomSeed = -1;
public int RandomSeed { get { return randomSeed; } }
public bool RandomSeedSpecified { get { return randomSeed >= 0; } }
public string DefaultTestNamePattern { get; private set; }
private int numWorkers = -1;
public int NumberOfTestWorkers { get { return numWorkers; } }
public bool NumberOfTestWorkersSpecified { get { return numWorkers >= 0; } }
public bool StopOnError { get; private set; }
public bool WaitBeforeExit { get; private set; }
// Output Control
public bool NoHeader { get; private set; }
public bool NoColor { get; private set; }
public bool TeamCity { get; private set; }
public string OutFile { get; private set; }
public bool OutFileSpecified { get { return OutFile != null; } }
public string ErrFile { get; private set; }
public bool ErrFileSpecified { get { return ErrFile != null; } }
public string DisplayTestLabels { get; private set; }
#if !PORTABLE
private string workDirectory = null;
public string WorkDirectory
{
get { return workDirectory ?? DEFAULT_WORK_DIRECTORY; }
}
public bool WorkDirectorySpecified { get { return workDirectory != null; } }
#endif
public string InternalTraceLevel { get; private set; }
public bool InternalTraceLevelSpecified { get { return InternalTraceLevel != null; } }
#if !PORTABLE
private List<OutputSpecification> resultOutputSpecifications = new List<OutputSpecification>();
public IList<OutputSpecification> ResultOutputSpecifications
{
get
{
if (noresult)
return new OutputSpecification[0];
if (resultOutputSpecifications.Count == 0)
resultOutputSpecifications.Add(new OutputSpecification("TestResult.xml"));
return resultOutputSpecifications;
}
}
private List<OutputSpecification> exploreOutputSpecifications = new List<OutputSpecification>();
public IList<OutputSpecification> ExploreOutputSpecifications { get { return exploreOutputSpecifications; } }
#endif
// Error Processing
public List<string> errorMessages = new List<string>();
public IList<string> ErrorMessages { get { return errorMessages; } }
#endregion
#region Public Methods
public bool Validate()
{
if (!validated)
{
CheckOptionCombinations();
validated = true;
}
return ErrorMessages.Count == 0;
}
#endregion
#region Helper Methods
protected virtual void CheckOptionCombinations()
{
}
/// <summary>
/// Case is ignored when val is compared to validValues. When a match is found, the
/// returned value will be in the canonical case from validValues.
/// </summary>
protected string RequiredValue(string val, string option, params string[] validValues)
{
if (string.IsNullOrEmpty(val))
ErrorMessages.Add("Missing required value for option '" + option + "'.");
bool isValid = true;
if (validValues != null && validValues.Length > 0)
{
isValid = false;
foreach (string valid in validValues)
if (string.Compare(valid, val, StringComparison.OrdinalIgnoreCase) == 0)
return valid;
}
if (!isValid)
ErrorMessages.Add(string.Format("The value '{0}' is not valid for option '{1}'.", val, option));
return val;
}
protected int RequiredInt(string val, string option)
{
// We have to return something even though the value will
// be ignored if an error is reported. The -1 value seems
// like a safe bet in case it isn't ignored due to a bug.
int result = -1;
if (string.IsNullOrEmpty(val))
ErrorMessages.Add("Missing required value for option '" + option + "'.");
else
{
// NOTE: Don't replace this with TryParse or you'll break the CF build!
try
{
result = int.Parse(val);
}
catch (Exception)
{
ErrorMessages.Add("An int value was expected for option '{0}' but a value of '{1}' was used");
}
}
return result;
}
private string ExpandToFullPath(string path)
{
if (path == null) return null;
#if PORTABLE
return Path.Combine(DEFAULT_WORK_DIRECTORY , path);
#else
return Path.GetFullPath(path);
#endif
}
protected virtual void ConfigureOptions()
{
// NOTE: The order in which patterns are added
// determines the display order for the help.
// Select Tests
this.Add("test=", "Comma-separated list of {NAMES} of tests to run or explore. This option may be repeated.",
v => ((List<string>)TestList).AddRange(TestNameParser.Parse(RequiredValue(v, "--test"))));
#if !PORTABLE
this.Add("testlist=", "File {PATH} containing a list of tests to run, one per line. This option may be repeated.",
v =>
{
string testListFile = RequiredValue(v, "--testlist");
var fullTestListPath = ExpandToFullPath(testListFile);
if (!File.Exists(fullTestListPath))
ErrorMessages.Add("Unable to locate file: " + testListFile);
else
{
try
{
using (var str = new FileStream(fullTestListPath, FileMode.Open))
using (var rdr = new StreamReader(str))
{
while (!rdr.EndOfStream)
{
var line = rdr.ReadLine().Trim();
if (!string.IsNullOrEmpty(line) && line[0] != '#')
((List<string>)TestList).Add(line);
}
}
}
catch (IOException)
{
ErrorMessages.Add("Unable to read file: " + testListFile);
}
}
});
#endif
this.Add("where=", "Test selection {EXPRESSION} indicating what tests will be run. See description below.",
v => WhereClause = RequiredValue(v, "--where"));
this.Add("params|p=", "Define a test parameter.",
v =>
{
string parameters = RequiredValue(v, "--params");
// This can be changed without breaking backwards compatibility with frameworks.
foreach (string param in parameters.Split(new[] { ';' }))
{
int eq = param.IndexOf("=");
if (eq == -1 || eq == param.Length - 1)
{
ErrorMessages.Add("Invalid format for test parameter. Use NAME=VALUE.");
}
else
{
string name = param.Substring(0, eq);
string val = param.Substring(eq + 1);
TestParameters[name] = val;
}
}
});
this.Add("timeout=", "Set timeout for each test case in {MILLISECONDS}.",
v => defaultTimeout = RequiredInt(v, "--timeout"));
this.Add("seed=", "Set the random {SEED} used to generate test cases.",
v => randomSeed = RequiredInt(v, "--seed"));
#if !PORTABLE
this.Add("workers=", "Specify the {NUMBER} of worker threads to be used in running tests. If not specified, defaults to 2 or the number of processors, whichever is greater.",
v => numWorkers = RequiredInt(v, "--workers"));
#endif
this.Add("stoponerror", "Stop run immediately upon any test failure or error.",
v => StopOnError = v != null);
this.Add("wait", "Wait for input before closing console window.",
v => WaitBeforeExit = v != null);
#if !PORTABLE
// Output Control
this.Add("work=", "{PATH} of the directory to use for output files. If not specified, defaults to the current directory.",
v => workDirectory = RequiredValue(v, "--work"));
this.Add("output|out=", "File {PATH} to contain text output from the tests.",
v => OutFile = RequiredValue(v, "--output"));
this.Add("err=", "File {PATH} to contain error output from the tests.",
v => ErrFile = RequiredValue(v, "--err"));
this.Add("result=", "An output {SPEC} for saving the test results.\nThis option may be repeated.",
v => resultOutputSpecifications.Add(new OutputSpecification(RequiredValue(v, "--resultxml"))));
this.Add("explore:", "Display or save test info rather than running tests. Optionally provide an output {SPEC} for saving the test info. This option may be repeated.", v =>
{
Explore = true;
if (v != null)
ExploreOutputSpecifications.Add(new OutputSpecification(v));
});
this.Add("noresult", "Don't save any test results.",
v => noresult = v != null);
#endif
this.Add("labels=", "Specify whether to write test case names to the output. Values: Off, On, All",
v => DisplayTestLabels = RequiredValue(v, "--labels", "Off", "On", "All"));
this.Add("test-name-format=", "Non-standard naming pattern to use in generating test names.",
v => DefaultTestNamePattern = RequiredValue(v, "--test-name-format"));
this.Add("teamcity", "Turns on use of TeamCity service messages.",
v => TeamCity = v != null);
#if !PORTABLE
this.Add("trace=", "Set internal trace {LEVEL}.\nValues: Off, Error, Warning, Info, Verbose (Debug)",
v => InternalTraceLevel = RequiredValue(v, "--trace", "Off", "Error", "Warning", "Info", "Verbose", "Debug"));
this.Add("noheader|noh", "Suppress display of program information at start of run.",
v => NoHeader = v != null);
this.Add("nocolor|noc", "Displays console output without color.",
v => NoColor = v != null);
#endif
this.Add("help|h", "Display this message and exit.",
v => ShowHelp = v != null);
this.Add("version|V", "Display the header and exit.",
v => ShowVersion = v != null);
// Default
this.Add("<>", v =>
{
#if PORTABLE
if (v.StartsWith("-") || v.StartsWith("/") && Environment.NewLine == "\r\n")
#else
if (v.StartsWith("-") || v.StartsWith("/") && Path.DirectorySeparatorChar != '/')
#endif
ErrorMessages.Add("Invalid argument: " + v);
else
InputFiles.Add(v);
});
}
#endregion
}
}
| |
//
// EditPackagesDialog.cs: Allows you to add and remove pkg-config packages to the project
//
// Authors:
// Marcos David Marin Amador <MarcosMarin@gmail.com>
//
// Copyright (C) 2007 Marcos David Marin Amador
//
//
// This source code is licenced under The 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.IO;
using System.Collections.Generic;
using Mono.Addins;
using MonoDevelop.Projects;
using MonoDevelop.Ide;
namespace MonoDevelop.ValaBinding
{
public partial class EditPackagesDialog : Gtk.Dialog
{
private Gtk.ListStore normalPackageListStore = new Gtk.ListStore (typeof(bool), typeof(string), typeof(string));
private Gtk.ListStore projectPackageListStore = new Gtk.ListStore (typeof(bool), typeof(string), typeof(string));
private Gtk.ListStore selectedPackageListStore = new Gtk.ListStore (typeof(string), typeof(string));
private ValaProject project;
private ProjectPackageCollection selectedPackages = new ProjectPackageCollection ();
private List<ProjectPackage> packagesOfProjects;
private List<ProjectPackage> packages = new List<ProjectPackage> ();
// Column IDs
const int NormalPackageToggleID = 0;
const int NormalPackageNameID = 1;
const int NormalPackageVersionID = 2;
const int ProjectPackageToggleID = 0;
const int ProjectPackageNameID = 1;
const int ProjectPackageVersionID = 2;
const int SelectedPackageNameID = 0;
const int SelectedPackageVersionID = 1;
public EditPackagesDialog(ValaProject project)
{
this.Build();
this.project = project;
selectedPackages.Project = project;
selectedPackages.AddRange (project.Packages);
Gtk.CellRendererText textRenderer = new Gtk.CellRendererText ();
Gtk.CellRendererPixbuf pixbufRenderer = new Gtk.CellRendererPixbuf ();
pixbufRenderer.StockId = "md-package";
normalPackageListStore.DefaultSortFunc = NormalPackageCompareNodes;
projectPackageListStore.DefaultSortFunc = ProjectPackageCompareNodes;
selectedPackageListStore.DefaultSortFunc = SelectedPackageCompareNodes;
normalPackageListStore.SetSortColumnId (NormalPackageNameID, Gtk.SortType.Ascending);
projectPackageListStore.SetSortColumnId (ProjectPackageNameID, Gtk.SortType.Ascending);
selectedPackageListStore.SetSortColumnId (SelectedPackageNameID, Gtk.SortType.Ascending);
normalPackageTreeView.SearchColumn = NormalPackageNameID;
projectPackageTreeView.SearchColumn = ProjectPackageNameID;
selectedPackageTreeView.SearchColumn = SelectedPackageNameID;
// <!-- Normal packages -->
Gtk.CellRendererToggle normalPackageToggleRenderer = new Gtk.CellRendererToggle ();
normalPackageToggleRenderer.Activatable = true;
normalPackageToggleRenderer.Toggled += OnNormalPackageToggled;
normalPackageToggleRenderer.Xalign = 0;
Gtk.TreeViewColumn normalPackageColumn = new Gtk.TreeViewColumn ();
normalPackageColumn.Title = "Package";
normalPackageColumn.PackStart (pixbufRenderer, false);
normalPackageColumn.PackStart (textRenderer, true);
normalPackageColumn.AddAttribute (textRenderer, "text", NormalPackageNameID);
normalPackageTreeView.Model = normalPackageListStore;
normalPackageTreeView.HeadersVisible = true;
normalPackageTreeView.AppendColumn ("", normalPackageToggleRenderer, "active", NormalPackageToggleID);
normalPackageTreeView.AppendColumn (normalPackageColumn);
normalPackageTreeView.AppendColumn ("Version", textRenderer, "text", NormalPackageVersionID);
// <!-- Project packages -->
Gtk.CellRendererToggle projectPackageToggleRenderer = new Gtk.CellRendererToggle ();
projectPackageToggleRenderer.Activatable = true;
projectPackageToggleRenderer.Toggled += OnProjectPackageToggled;
projectPackageToggleRenderer.Xalign = 0;
Gtk.TreeViewColumn projectPackageColumn = new Gtk.TreeViewColumn ();
projectPackageColumn.Title = "Package";
projectPackageColumn.PackStart (pixbufRenderer, false);
projectPackageColumn.PackStart (textRenderer, true);
projectPackageColumn.AddAttribute (textRenderer, "text", ProjectPackageNameID);
projectPackageTreeView.Model = projectPackageListStore;
projectPackageTreeView.HeadersVisible = true;
projectPackageTreeView.AppendColumn ("", projectPackageToggleRenderer, "active", ProjectPackageToggleID);
projectPackageTreeView.AppendColumn (projectPackageColumn);
projectPackageTreeView.AppendColumn ("Version", textRenderer, "text", ProjectPackageVersionID);
// <!-- Selected packages -->
Gtk.TreeViewColumn selectedPackageColumn = new Gtk.TreeViewColumn ();
selectedPackageColumn.Title = "Package";
selectedPackageColumn.PackStart (pixbufRenderer, false);
selectedPackageColumn.PackStart (textRenderer, true);
selectedPackageColumn.AddAttribute (textRenderer, "text", SelectedPackageNameID);
selectedPackageTreeView.Model = selectedPackageListStore;
selectedPackageTreeView.HeadersVisible = true;
selectedPackageTreeView.AppendColumn (selectedPackageColumn);
selectedPackageTreeView.AppendColumn ("Version", textRenderer, "text", SelectedPackageVersionID);
// Fill up the project tree view
packagesOfProjects = GetPackagesOfProjects (project);
foreach (ProjectPackage p in packagesOfProjects) {
if (p.Name == project.Name) continue;
packages.Add (p);
string version = p.Version;
bool inProject = selectedPackages.Contains (p);
if (!IsPackageInStore (projectPackageListStore, p.Name, version, ProjectPackageNameID, ProjectPackageVersionID)) {
projectPackageListStore.AppendValues (inProject, p.Name, version);
if (inProject)
selectedPackageListStore.AppendValues (p.Name, version);
}
}
// Fill up the normal tree view
foreach (string dir in ScanDirs ()) {
if (Directory.Exists (dir)) {
DirectoryInfo di = new DirectoryInfo (dir);
FileInfo[] availablePackages = di.GetFiles ("*.vapi");
foreach (FileInfo f in availablePackages) {
if (!IsValidPackage (f.FullName)) {
continue;
}
string packagename = f.FullName;
GLib.Idle.Add (delegate {
ProjectPackage package = new ProjectPackage (packagename);
packages.Add (package);
string name = package.Name;
string version = package.Version;
bool inProject = selectedPackages.Contains (package);
if (!IsPackageInStore (normalPackageListStore, name, version, NormalPackageNameID, NormalPackageVersionID)) {
normalPackageListStore.AppendValues (inProject, name, version);
if (inProject)
selectedPackageListStore.AppendValues (name, version);
}
return false;
});
}
}
}
}
private List<ProjectPackage> GetPackagesOfProjects (Project project)
{
List<ProjectPackage> packages = new List<ProjectPackage>();
ProjectPackage package;
foreach (Project c in IdeApp.Workspace.GetAllProjects()) {
if (c is ValaProject) {
ValaProject proj = c as ValaProject;
ValaProjectConfiguration conf = proj.GetConfiguration (IdeApp.Workspace.ActiveConfiguration) as ValaProjectConfiguration;
if (conf.CompileTarget != CompileTarget.Bin) {
proj.WriteMDPkgPackage (conf.Selector);
package = new ProjectPackage (proj);
packages.Add (package);
}
}
}
return packages;
}
private bool IsPackageInStore (Gtk.ListStore store, string pname, string pversion, int pname_col, int pversion_col)
{
Gtk.TreeIter search_iter;
bool has_elem = store.GetIterFirst (out search_iter);
if (has_elem) {
while (true) {
string name = (string)store.GetValue (search_iter, pname_col);
string version = (string)store.GetValue (search_iter, pversion_col);
if (name == pname && version == pversion)
return true;
if (!store.IterNext (ref search_iter))
break;
}
}
return false;
}
private string[] ScanDirs ()
{
return new string[]{ ValaProject.vapidir };
}
private void OnOkButtonClick (object sender, EventArgs e)
{
// Use this instead of clear, since clear seems to not update the packages tree
while (project.Packages.Count > 0) {
project.Packages.RemoveAt (0);
}
project.Packages.AddRange (selectedPackages);
Destroy ();
}
private void OnCancelButtonClick (object sender, EventArgs e)
{
Destroy ();
}
private void OnRemoveButtonClick (object sender, EventArgs e)
{
Gtk.TreeIter iter;
selectedPackageTreeView.Selection.GetSelected (out iter);
if (!selectedPackageListStore.IterIsValid (iter)) return;
string package = (string)selectedPackageListStore.GetValue (iter, SelectedPackageNameID);
bool isProject = false;
foreach (ProjectPackage p in selectedPackages) {
if (p.Name == package) {
isProject = p.IsProject;
selectedPackages.Remove (p);
break;
}
}
selectedPackageListStore.Remove (ref iter);
if (!isProject) {
Gtk.TreeIter search_iter;
bool has_elem = normalPackageListStore.GetIterFirst (out search_iter);
if (has_elem) {
while (true) {
string current = (string)normalPackageListStore.GetValue (search_iter, NormalPackageNameID);
if (current.Equals (package)) {
normalPackageListStore.SetValue (search_iter, NormalPackageToggleID, false);
break;
}
if (!normalPackageListStore.IterNext (ref search_iter))
break;
}
}
} else {
Gtk.TreeIter search_iter;
bool has_elem = projectPackageListStore.GetIterFirst (out search_iter);
if (has_elem) {
while (true) {
string current = (string)projectPackageListStore.GetValue (search_iter, ProjectPackageNameID);
if (current.Equals (package)) {
projectPackageListStore.SetValue (search_iter, ProjectPackageToggleID, false);
break;
}
if (!projectPackageListStore.IterNext (ref search_iter))
break;
}
}
}
}
private void OnNormalPackageToggled (object sender, Gtk.ToggledArgs args)
{
Gtk.TreeIter iter;
bool old = true;
string name;
string version;
if (normalPackageListStore.GetIter (out iter, new Gtk.TreePath (args.Path))) {
old = (bool)normalPackageListStore.GetValue (iter, NormalPackageToggleID);
normalPackageListStore.SetValue (iter, NormalPackageToggleID, !old);
}
name = (string)normalPackageListStore.GetValue (iter, NormalPackageNameID);
version = (string)normalPackageListStore.GetValue(iter, NormalPackageVersionID);
if (old == false) {
selectedPackageListStore.AppendValues (name, version);
foreach (ProjectPackage package in packages) {
if (package.Name == name /* && package.Version == version */) {
selectedPackages.Add (package);
break;
}
}
} else {
Gtk.TreeIter search_iter;
bool has_elem = selectedPackageListStore.GetIterFirst (out search_iter);
if (has_elem) {
while (true) {
string current = (string)selectedPackageListStore.GetValue (search_iter, SelectedPackageNameID);
if (current.Equals (name)) {
selectedPackageListStore.Remove (ref search_iter);
foreach (ProjectPackage p in selectedPackages) {
if (p.Name == name) {
selectedPackages.Remove (p);
break;
}
}
break;
}
if (!selectedPackageListStore.IterNext (ref search_iter))
break;
}
}
}
}
private void OnProjectPackageToggled (object sender, Gtk.ToggledArgs args)
{
Gtk.TreeIter iter;
bool old = true;
string name;
string version;
if (projectPackageListStore.GetIter (out iter, new Gtk.TreePath (args.Path))) {
old = (bool)projectPackageListStore.GetValue (iter, ProjectPackageToggleID);
projectPackageListStore.SetValue (iter, ProjectPackageToggleID, !old);
}
name = (string)projectPackageListStore.GetValue (iter, ProjectPackageNameID);
version = (string)projectPackageListStore.GetValue(iter, ProjectPackageVersionID);
if (old == false) {
selectedPackageListStore.AppendValues (name, version);
foreach (ProjectPackage p in packagesOfProjects) {
if (p.Name == name) {
selectedPackages.Add (p);
break;
}
}
} else {
Gtk.TreeIter search_iter;
bool has_elem = selectedPackageListStore.GetIterFirst (out search_iter);
if (has_elem)
{
while (true) {
string current = (string)selectedPackageListStore.GetValue (search_iter, SelectedPackageNameID);
if (current.Equals (name)) {
selectedPackageListStore.Remove (ref search_iter);
foreach (ProjectPackage p in selectedPackages) {
if (p.Name == name) {
selectedPackages.Remove (p);
break;
}
}
break;
}
if (!selectedPackageListStore.IterNext (ref search_iter))
break;
}
}
}
}
private bool IsValidPackage (string package)
{
return true;
}
int NormalPackageCompareNodes (Gtk.TreeModel model, Gtk.TreeIter a, Gtk.TreeIter b)
{
string name1 = (string)model.GetValue (a, NormalPackageNameID);
string name2 = (string)model.GetValue (b, NormalPackageNameID);
return string.Compare (name1, name2, true);
}
int ProjectPackageCompareNodes (Gtk.TreeModel model, Gtk.TreeIter a, Gtk.TreeIter b)
{
string name1 = (string)model.GetValue (a, ProjectPackageNameID);
string name2 = (string)model.GetValue (b, ProjectPackageNameID);
return string.Compare (name1, name2, true);
}
int SelectedPackageCompareNodes (Gtk.TreeModel model, Gtk.TreeIter a, Gtk.TreeIter b)
{
string name1 = (string)model.GetValue (a, SelectedPackageNameID);
string name2 = (string)model.GetValue (b, SelectedPackageNameID);
return string.Compare (name1, name2, true);
}
protected virtual void OnSelectedPackagesTreeViewCursorChanged (object sender, System.EventArgs e)
{
removeButton.Sensitive = true;
}
protected virtual void OnRemoveButtonClicked (object sender, System.EventArgs e)
{
removeButton.Sensitive = false;
}
protected virtual void OnDetailsButtonClicked (object sender, System.EventArgs e)
{
Gtk.TreeIter iter;
Gtk.Widget active_tab = notebook1.Children [notebook1.Page];
string tab_label = notebook1.GetTabLabelText (active_tab);
string name = string.Empty;
// string version = string.Empty;
ProjectPackage package = null;
if (tab_label == "System Packages") {
normalPackageTreeView.Selection.GetSelected (out iter);
name = (string)normalPackageListStore.GetValue (iter, NormalPackageNameID);
// version = (string)normalPackageListStore.GetValue (iter, NormalPackageVersionID);
} else if (tab_label == "Project Packages") {
projectPackageTreeView.Selection.GetSelected (out iter);
name = (string)projectPackageListStore.GetValue (iter, ProjectPackageNameID);
// version = (string)projectPackageListStore.GetValue (iter, ProjectPackageVersionID);
} else {
return;
}
foreach (ProjectPackage p in packages) {
if (p.Name == name /* && p.Version == version */) {
package = p;
break;
}
}
if (package == null)
return;
PackageDetails details = new PackageDetails (package);
details.Modal = true;
details.Show ();
}
protected virtual void OnNonSelectedPackageCursorChanged (object o, EventArgs e)
{
detailsButton.Sensitive = true;
}
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using NUnit.Core;
using NUnit.Tests.Assemblies;
namespace NUnit.Util.Tests
{
[TestFixture]
public class TestDomainFixture
{
private static TestDomain testDomain;
private static ITest loadedTest;
[TestFixtureSetUp]
public void MakeAppDomain()
{
testDomain = new TestDomain();
testDomain.Load( new TestPackage( "mock-assembly.dll" ) );
loadedTest = testDomain.Test;
}
[TestFixtureTearDown]
public void UnloadTestDomain()
{
if ( testDomain != null )
testDomain.Unload();
loadedTest = null;
testDomain = null;
}
[Test]
public void AssemblyIsLoadedCorrectly()
{
Assert.IsNotNull(loadedTest, "Test not loaded");
Assert.AreEqual(MockAssembly.Tests, loadedTest.TestCount );
}
[Test]
public void AppDomainIsSetUpCorrectly()
{
AppDomain domain = testDomain.AppDomain;
AppDomainSetup setup = testDomain.AppDomain.SetupInformation;
Assert.AreEqual( "Tests", setup.ApplicationName, "ApplicationName" );
Assert.AreEqual( Environment.CurrentDirectory, setup.ApplicationBase, "ApplicationBase" );
Assert.AreEqual( "mock-assembly.dll.config", Path.GetFileName( setup.ConfigurationFile ), "ConfigurationFile" );
Assert.AreEqual( null, setup.PrivateBinPath, "PrivateBinPath" );
Assert.AreEqual( Environment.CurrentDirectory, setup.ShadowCopyDirectories, "ShadowCopyDirectories" );
Assert.AreEqual( Environment.CurrentDirectory, domain.BaseDirectory, "BaseDirectory" );
Assert.AreEqual( "domain-mock-assembly.dll", domain.FriendlyName, "FriendlyName" );
Assert.IsTrue( testDomain.AppDomain.ShadowCopyFiles, "ShadowCopyFiles" );
}
[Test]
public void CanRunMockAssemblyTests()
{
TestResult result = testDomain.Run( NullListener.NULL );
Assert.IsNotNull(result);
Assert.AreEqual(false, result.IsFailure, "Test run failed");
ResultSummarizer summarizer = new ResultSummarizer(result);
Assert.AreEqual(MockAssembly.Tests - MockAssembly.NotRun, summarizer.ResultCount);
Assert.AreEqual(MockAssembly.Ignored, summarizer.TestsNotRun);
}
}
[TestFixture]
public class TestDomainRunnerTests : NUnit.Core.Tests.BasicRunnerTests
{
protected override TestRunner CreateRunner(int runnerID)
{
return new TestDomain(runnerID);
}
}
[TestFixture]
public class TestDomainTests
{
private TestDomain testDomain;
[SetUp]
public void SetUp()
{
testDomain = new TestDomain();
}
[TearDown]
public void TearDown()
{
testDomain.Unload();
}
[Test]
[ExpectedException(typeof(FileNotFoundException))]
public void FileNotFound()
{
testDomain.Load( new TestPackage( "xxxx.dll" ) );
}
[Test]
public void InvalidTestFixture()
{
TestPackage package = new TestPackage( "mock-assembly.dll" );
package.TestName = "NUnit.Tests.Assemblies.Bogus";
Assert.IsFalse( testDomain.Load( package ) );
}
// Doesn't work under .NET 2.0 Beta 2
//[Test]
//[ExpectedException(typeof(BadImageFormatException))]
public void FileFoundButNotValidAssembly()
{
string badfile = "x.dll";
//FileInfo file = new FileInfo( badfile );
try
{
StreamWriter sw = new StreamWriter( badfile );
//StreamWriter sw = file.AppendText();
sw.WriteLine("This is a new entry to add to the file");
sw.WriteLine("This is yet another line to add...");
sw.Flush();
sw.Close();
testDomain.Load( new TestPackage( badfile ) );
}
finally
{
if ( File.Exists( badfile ) )
File.Delete( badfile );
}
}
[Test]
public void SpecificTestFixture()
{
TestPackage package = new TestPackage( "mock-assembly.dll" );
package.TestName = "NUnit.Tests.Assemblies.MockTestFixture";
testDomain.Load( package );
TestResult result = testDomain.Run( NullListener.NULL );
Assert.AreEqual(true, result.IsSuccess);
ResultSummarizer summarizer = new ResultSummarizer(result);
Assert.AreEqual(MockTestFixture.Tests - MockTestFixture.NotRun, summarizer.ResultCount);
Assert.AreEqual(MockTestFixture.Ignored, summarizer.TestsNotRun);
}
[Test]
public void ConfigFileOverrideIsHonored()
{
TestPackage package = new TestPackage( "MyProject.nunit" );
package.Assemblies.Add( "mock-assembly.dll" );
package.ConfigurationFile = "override.config";
testDomain.Load( package );
Assert.AreEqual( "override.config",
Path.GetFileName( testDomain.AppDomain.SetupInformation.ConfigurationFile ) );
}
[Test]
public void BasePathOverrideIsHonored()
{
TestPackage package = new TestPackage( "MyProject.nunit" );
package.Assemblies.Add( "mock-assembly.dll" );
package.BasePath = Path.GetDirectoryName( Environment.CurrentDirectory );
package.PrivateBinPath = Path.GetFileName( Environment.CurrentDirectory );
testDomain.Load( package );
Assert.AreEqual( package.BasePath, testDomain.AppDomain.BaseDirectory );
}
[Test]
public void BinPathOverrideIsHonored()
{
TestPackage package = new TestPackage( "MyProject.nunit" );
package.Assemblies.Add( "mock-assembly.dll" );
package.PrivateBinPath = "dummy;junk";
testDomain.Load( package );
Assert.AreEqual( "dummy;junk",
testDomain.AppDomain.SetupInformation.PrivateBinPath );
}
// Turning off shadow copy only works when done for the primary app domain
// So this test can only work if it's already off
// This doesn't seem to be documented anywhere
[Test]
public void TurnOffShadowCopy()
{
TestPackage package = new TestPackage( "mock-assembly.dll" );
package.Settings["ShadowCopyFiles"] = false;
testDomain.Load( package );
Assert.IsFalse( testDomain.AppDomain.ShadowCopyFiles );
// Prove that shadow copy is really off
// string location = "NOT_FOUND";
// foreach( Assembly assembly in testDomain.AppDomain.GetAssemblies() )
// {
// if ( assembly.FullName.StartsWith( "mock-assembly" ) )
// {
// location = Path.GetDirectoryName( assembly.Location );
// break;
// }
// }
//
// StringAssert.StartsWith( AppDomain.CurrentDomain.BaseDirectory.ToLower(), location.ToLower() );
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using Orleans.TestingHost.Utils;
namespace Orleans.TestingHost
{
public class TestClusterPortAllocator : ITestClusterPortAllocator
{
private bool disposed;
private readonly object lockObj = new object();
private readonly Dictionary<int, string> allocatedPorts = new Dictionary<int, string>();
public (int, int) AllocateConsecutivePortPairs(int numPorts = 5)
{
// Evaluate current system tcp connections
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();
// each returned port in the pair will have to have at least this amount of available ports following it
return (GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 22300, 30000, numPorts),
GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 40000, 50000, numPorts));
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
lock (lockObj)
{
if (disposed)
{
return;
}
foreach (var pair in allocatedPorts)
{
MutexManager.Instance.SignalRelease(pair.Value);
}
allocatedPorts.Clear();
disposed = true;
}
}
~TestClusterPortAllocator()
{
Dispose(false);
}
private int GetAvailableConsecutiveServerPorts(IPEndPoint[] tcpConnInfoArray, int portStartRange, int portEndRange, int consecutivePortsToCheck)
{
const int MaxAttempts = 100;
var allocations = new List<(int Port, string Mutex)>();
for (int attempts = 0; attempts < MaxAttempts; attempts++)
{
int basePort = ThreadSafeRandom.Next(portStartRange, portEndRange);
// get ports in buckets, so we don't interfere with parallel runs of this same function
basePort = basePort - (basePort % consecutivePortsToCheck);
int endPort = basePort + consecutivePortsToCheck;
// make sure none of the ports in the sub range are in use
if (tcpConnInfoArray.All(endpoint => endpoint.Port < basePort || endpoint.Port >= endPort))
{
for (var i = 0; i < consecutivePortsToCheck; i++)
{
var port = basePort + i;
var name = $"Global.TestCluster.{port.ToString(CultureInfo.InvariantCulture)}";
if (MutexManager.Instance.Acquire(name))
{
allocations.Add((port, name));
}
else
{
foreach (var allocation in allocations)
{
MutexManager.Instance.SignalRelease(allocation.Mutex);
}
allocations.Clear();
break;
}
}
if (allocations.Count == 0)
{
// Try a different range.
continue;
}
lock (lockObj)
{
foreach (var allocation in allocations)
{
allocatedPorts[allocation.Port] = allocation.Mutex;
}
}
return basePort;
}
}
throw new InvalidOperationException("Cannot find enough free ports to spin up a cluster");
}
private class MutexManager
{
private readonly Dictionary<string, Mutex> _mutexes = new Dictionary<string, Mutex>();
private readonly BlockingCollection<Action> _workItems = new BlockingCollection<Action>();
private readonly Thread _thread;
public static MutexManager Instance { get; } = new MutexManager();
private MutexManager()
{
_thread = new Thread(Run)
{
Name = "MutexManager.Worker",
IsBackground = true,
};
_thread.Start();
AppDomain.CurrentDomain.DomainUnload += this.OnAppDomainUnload;
}
private void OnAppDomainUnload(object sender, EventArgs e)
{
Shutdown();
}
private void Shutdown()
{
_workItems.CompleteAdding();
_thread.Join();
}
public bool Acquire(string name)
{
var result = new [] { 0 };
var signal = new ManualResetEventSlim(initialState: false);
_workItems.Add(() =>
{
try
{
if (!_mutexes.TryGetValue(name, out var mutex))
{
mutex = new Mutex(false, name);
if (mutex.WaitOne(500))
{
// Acquired
_mutexes[name] = mutex;
Interlocked.Increment(ref result[0]);
return;
}
// Failed to acquire: the mutex is already held by another process.
try
{
mutex.ReleaseMutex();
}
finally
{
mutex.Close();
}
}
// Failed to acquire: the mutex is already held by this process.
}
finally
{
signal.Set();
}
});
if (!signal.Wait(TimeSpan.FromSeconds(10)))
{
throw new TimeoutException("Timed out while waiting for MutexManager to acquire mutex.");
}
return result[0] == 1;
}
public void SignalRelease(string name)
{
if (_workItems.IsAddingCompleted) return;
try
{
_workItems.Add(() =>
{
if (_mutexes.TryGetValue(name, out var value))
{
_mutexes.Remove(name);
value.ReleaseMutex();
value.Close();
}
});
}
catch
{
}
}
private void Run()
{
try
{
foreach (var action in _workItems.GetConsumingEnumerable())
{
try
{
action();
}
catch
{
}
}
}
catch
{
}
finally
{
foreach (var mutex in _mutexes.Values)
{
try
{
mutex.ReleaseMutex();
}
catch { }
finally
{
mutex.Close();
}
}
_mutexes.Clear();
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ImagesDownloader.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
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 Licence...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using IO = System.IO;
using Path = System.IO.Path;
namespace WixSharp
{
/// <summary>
/// Controls activation of the Wix# compiler features.
/// </summary>
public enum CompilerSupportState
{
/// <summary>
/// The feature will be enabled automatically when needed
/// </summary>
Automatic,
/// <summary>
/// The feature will be enabled
/// </summary>
Enabled,
/// <summary>
/// The feature will be disabled
/// </summary>
Disabled
}
/// <summary>
/// Automatically insert elements required for satisfy odd MSI restrictions.
/// <para>- You must set KeyPath you install in the user profile.</para>
/// <para>- You must use a registry key under HKCU as component's KeyPath, not a file. </para>
/// <para>- The Component element cannot have multiple key path set. </para>
/// <para>- The project must have at least one directory element. </para>
/// <para>- All directories installed in the user profile must have corresponding RemoveDirectory
/// elements. </para>
/// <para>...</para>
/// <para>
/// The MSI always wants registry keys as the key paths for per-user components.
/// It has to do with the way profiles work with advertised content in enterprise deployments.
/// The fact that you do not want to install any registry doesn't matter. MSI is the boss.
/// </para>
/// <para>The following link is a good example of the technique:
/// http://stackoverflow.com/questions/16119708/component-testcomp-installs-to-user-profile-it-must-use-a-registry-key-under-hk</para>
/// </summary>
public static class AutoElements
{
/// <summary>
/// Controls automatic insertion of CreateFolder and RemoveFolder for the directories containing no files.
/// Required for: NativeBootstrapper, EmbeddedMultipleActions, EmptyDirectories, InstallDir, Properties,
/// ReleaseFolder, Shortcuts and WildCardFiles samples.
/// <para>If set to <c>Automatic</c> then the compiler will enable this feature only if any empty directory
/// is detected in the project definition.</para>
/// </summary>
public static CompilerSupportState SupportEmptyDirectories = CompilerSupportState.Automatic;
/// <summary>
/// Disables automatic insertion of <c>KeyPath=yes</c> attribute for the Component element.
/// Required for: NativeBootstrapper, EmbeddedMultipleActions, EmptyDirectories, InstallDir, Properties,
/// ReleaseFolder, Shortcuts and WildCardFiles samples.
/// <para>Can also be managed by disabling ICE validation via Light.exe command line arguments.</para>
/// <para>
/// This flag is a lighter alternative of DisableAutoCreateFolder.
/// See: http://stackoverflow.com/questions/10358989/wix-using-keypath-on-components-directories-files-registry-etc-etc
/// for some background info.
/// </para>
/// </summary>
public static bool DisableAutoKeyPath = false;
/// <summary>
/// Forces all <see cref="T:WixSharp.Condition"/> values to be always encoded as CDATA.
/// </summary>
public static bool ForceCDataForConditions = false;
/// <summary>
/// Disables automatic insertion of user profile registry elements.
/// Required for: AllInOne, ConditionalInstallation, CustomAttributes, ReleaseFolder, Shortcuts,
/// Shortcuts (advertised), Shortcuts-2, WildCardFiles samples.
/// <para>Can also be managed by disabling ICE validation via Light.exe command line arguments.</para>
/// </summary>
public static bool DisableAutoUserProfileRegistry = false;
static void InsertRemoveFolder(XElement xDir, XElement xComponent, string when = "uninstall")
{
if (!xDir.IsUserProfileRoot())
{
string dirId = xDir.Attribute("Id").Value;
bool alreadyPresent = xComponent.Elements("RemoveFolder")
.Where(x => x.HasAttribute("Id", dirId))
.Any();
if (!alreadyPresent)
xComponent.Add(new XElement("RemoveFolder",
new XAttribute("Id", xDir.Attribute("Id").Value),
new XAttribute("On", when)));
}
}
internal static XElement InsertUserProfileRemoveFolder(this XElement xComponent)
{
var xDir = xComponent.Parent("Directory");
if (!xDir.Descendants("RemoveFolder").Any() && !xDir.IsUserProfileRoot())
xComponent.Add(new XElement("RemoveFolder",
new XAttribute("Id", xDir.Attribute("Id").Value),
new XAttribute("On", "uninstall")));
return xComponent;
}
static void InsertCreateFolder(XElement xComponent)
{
//prevent adding more than 1 CreateFolder elements - elements that don't specify @Directory
if (xComponent.Elements("CreateFolder").All(element => element.HasAttribute("Directory")))
xComponent.Add(new XElement("CreateFolder"));
EnsureKeyPath(xComponent);
}
static void EnsureKeyPath(XElement xComponent)
{
if (!DisableAutoKeyPath)
{
//a component must have KeyPath set on itself or on a single (just one) nested element
if (!xComponent.HasKeyPathElements())
xComponent.SetAttribute("KeyPath=yes");
}
}
internal static string FindInstallDirId(this XElement product)
{
if (product.FindAll("Directory")
.Any(p => p.HasAttribute("Id", Compiler.AutoGeneration.InstallDirDefaultId)))
return Compiler.AutoGeneration.InstallDirDefaultId;
return null;
}
internal static bool HasKeyPathElements(this XElement xComponent)
{
return xComponent.Descendants()
.Where(e => e.HasKeyPathSet())
.Any();
}
internal static XElement ClearKeyPath(this XElement element)
{
return element.SetAttribute("KeyPath", null);
}
internal static bool HasKeyPathSet(this XElement element)
{
var attr = element.Attribute("KeyPath");
if (attr != null && attr.Value == "yes")
return true;
return false;
}
internal static XElement InsertUserProfileRegValue(this XElement xComponent)
{
//UserProfileRegValue has to be a KeyPath fo need to remove any KeyPath on other elements
var keyPathes = xComponent.Descendants()
.ForEach(e => e.ClearKeyPath());
xComponent.ClearKeyPath();
xComponent.Add(
new XElement("RegistryKey",
new XAttribute("Root", "HKCU"),
new XAttribute("Key", @"Software\WixSharp\Used"),
new XElement("RegistryValue",
new XAttribute("Value", "0"),
new XAttribute("Type", "string"),
new XAttribute("KeyPath", "yes"))));
return xComponent;
}
static void InsertDummyUserProfileRegistry(XElement xComponent)
{
if (!DisableAutoUserProfileRegistry)
{
InsertUserProfileRegValue(xComponent);
}
}
static void SetFileKeyPath(XElement element, bool isKeyPath = true)
{
if (element.Attribute("KeyPath") == null)
element.Add(new XAttribute("KeyPath", isKeyPath ? "yes" : "no"));
}
static bool ContainsDummyUserProfileRegistry(this XElement xComponent)
{
return (from e in xComponent.Elements("RegistryKey")
where e.Attribute("Key") != null && e.Attribute("Key").Value == @"Software\WixSharp\Used"
select e).Count() != 0;
}
static bool ContainsAnyRemoveFolder(this XElement xDir)
{
//RemoveFolder is expected to be enclosed in Component and appear only once per Directory element
return xDir.Elements("Component")
.SelectMany(c => c.Elements("RemoveFolder"))
.Any();
}
static bool ContainsFiles(this XElement xComp)
{
return xComp.Elements("File").Any();
}
static bool ContainsComponents(this XElement xDir)
{
return xDir.Elements("Component").Any();
}
static bool ContainsAdvertisedShortcuts(this XElement xComp)
{
var advertisedShortcuts = from e in xComp.Descendants("Shortcut")
where e.Attribute("Advertise") != null && e.Attribute("Advertise").Value == "yes"
select e;
return (advertisedShortcuts.Count() != 0);
}
static bool ContainsNonAdvertisedShortcuts(this XElement xComp)
{
var nonAdvertisedShortcuts = from e in xComp.Descendants("Shortcut")
where e.Attribute("Advertise") == null || e.Attribute("Advertise").Value == "no"
select e;
return (nonAdvertisedShortcuts.Count() != 0);
}
static XElement CrteateComponentFor(this XDocument doc, XElement xDir)
{
string compId = xDir.Attribute("Id").Value;
XElement xComponent = xDir.AddElement(
new XElement("Component",
new XAttribute("Id", compId),
new XAttribute("Guid", WixGuid.NewGuid(compId))));
foreach (XElement xFeature in doc.Root.Descendants("Feature"))
xFeature.Add(new XElement("ComponentRef",
new XAttribute("Id", xComponent.Attribute("Id").Value)));
return xComponent;
}
private static string[] GetUserProfileFolders()
{
return new[]
{
"ProgramMenuFolder",
"AppDataFolder",
"LocalAppDataFolder",
"TempFolder",
"PersonalFolder",
"DesktopFolder"
};
}
static bool InUserProfile(this XElement xDir)
{
string[] userProfileFolders = GetUserProfileFolders();
XElement xParentDir = xDir;
do
{
if (xParentDir.Name == "Directory")
{
var attrName = xParentDir.Attribute("Name").Value;
if (userProfileFolders.Contains(attrName))
return true;
}
xParentDir = xParentDir.Parent;
}
while (xParentDir != null);
return false;
}
static bool IsUserProfileRoot(this XElement xDir)
{
string[] userProfileFolders = GetUserProfileFolders();
return userProfileFolders.Contains(xDir.Attribute("Name").Value);
}
internal static void InjectShortcutIcons(XDocument doc)
{
var shortcuts = from s in doc.Root.Descendants("Shortcut")
where s.HasAttribute("Icon")
select s;
int iconIndex = 1;
var icons = new Dictionary<string, string>();
foreach (var iconFile in (from s in shortcuts
select s.Attribute("Icon").Value).Distinct())
{
icons.Add(iconFile,
"IconFile" + (iconIndex++) + "_" + IO.Path.GetFileName(iconFile).Expand());
}
foreach (XElement shortcut in shortcuts)
{
string iconFile = shortcut.Attribute("Icon").Value;
string iconId = icons[iconFile];
shortcut.Attribute("Icon").Value = iconId;
}
XElement product = doc.Root.Select("Product");
foreach (string file in icons.Keys)
product.AddElement(
new XElement("Icon",
new XAttribute("Id", icons[file]),
new XAttribute("SourceFile", file)));
}
static void InjectPlatformAttributes(XDocument doc)
{
var is64BitPlatform = doc.Root.Select("Product/Package").HasAttribute("Platform", val => val == "x64");
if (is64BitPlatform)
doc.Descendants("Component")
.ForEach(comp =>
{
//components may already have explicitly set platform attribute (e.g. RegValue.Win64)
//if (!comp.HasAttribute("Win64"))
comp.SetAttributeValue("Win64", "yes");
});
}
static void ExpandCustomAttributes(XDocument doc)
{
foreach (XAttribute instructionAttr in doc.Root.Descendants().Select(x => x.Attribute("WixSharpCustomAttributes")).Where(x => x != null))
{
XElement sourceElement = instructionAttr.Parent;
foreach (string item in instructionAttr.Value.Split(';'))
if (item.IsNotEmpty())
{
if (!ExpandCustomAttribute(sourceElement, item))
throw new ApplicationException("Cannot resolve custom attribute definition:" + item);
}
instructionAttr.Remove();
}
}
static Func<XElement, string, bool> ExpandCustomAttribute = DefaultExpandCustomAttribute;
static bool DefaultExpandCustomAttribute(XElement source, string item)
{
var attrParts = item.Split('=');
var keyParts = attrParts.First().Split(':');
string element = keyParts.First();
string key = keyParts.Last();
string value = attrParts.Last();
if (element == "Component")
{
XElement destElement = source.Parent("Component");
if (destElement != null)
{
destElement.SetAttributeValue(key, value);
return true;
}
}
if (element == "Icon" && source.Name.LocalName == "Property")
{
source.Parent("Product")
.SelectOrCreate("Icon")
.SetAttributeValue(key, value);
return true;
}
if (element == "Custom" && source.Name.LocalName == "CustomAction")
{
string id = source.Attribute("Id").Value;
var elements = source.Document.Descendants("Custom").Where(e => e.Attribute("Action").Value == id);
if (elements.Any())
{
elements.ForEach(e => e.SetAttributeValue(key, value));
return true;
}
}
if (key.StartsWith("xml_include"))
{
var parts = value.Split('|');
string parentName = parts[0];
string xmlFile = parts[1];
var placement = source;
if (!parentName.IsEmpty())
placement = source.Parent(parentName);
if (placement != null)
{
placement.Add(new XProcessingInstruction("include", xmlFile));
return true;
}
}
return false;
}
internal static void HandleEmptyDirectories(XDocument doc)
{
XElement product = doc.Root.Select("Product");
var dummyDirs = product.Descendants("Directory")
.SelectMany(x => x.Elements("Component"))
.Where(e => e.HasAttribute("Id", v => v.EndsWith(".EmptyDirectory")))
.Select(x => x.Parent("Directory"));
if (SupportEmptyDirectories == CompilerSupportState.Automatic)
{
SupportEmptyDirectories = dummyDirs.Any() ? CompilerSupportState.Enabled : CompilerSupportState.Disabled; //it wasn't set by user so set it if any empty dir is detected
Compiler.OutputWriteLine("Wix# support for EmptyDirectories is automatically " + SupportEmptyDirectories.ToString().ToLower());
}
if (SupportEmptyDirectories == CompilerSupportState.Enabled)
{
if (dummyDirs.Any())
{
foreach (var item in dummyDirs)
{
XElement parent = item.Parent("Directory");
while (parent != null)
{
if (parent.Element("Component") == null)
{
var dirId = parent.Attribute("Id").Value;
if (Compiler.EnvironmentConstantsMapping.ContainsValue(dirId))
break; //stop when reached start of user defined subdirs chain: TARGETDIR/ProgramFilesFolder!!!/ProgramFilesFolder.Company/INSTALLDIR
//just folder with nothing in it but not the last leaf
doc.CrteateComponentFor(parent);
}
parent = parent.Parent("Directory");
}
}
}
foreach (XElement xDir in product.Descendants("Directory").ToArray())
{
var dirComponents = xDir.Elements("Component");
if (dirComponents.Any())
{
var componentsWithNoFiles = dirComponents.Where(x => !x.ContainsFiles()).ToArray();
//'EMPTY DIRECTORY' support processing section
foreach (XElement item in componentsWithNoFiles)
{
// Ridiculous MSI constrains:
// * you cannot install install empty folders
// - workaround is to insert empty component with CreateFolder element
// * if Component+CreateFolder element is inserted the folder will not be removed on uninstall
// - workaround is to insert RemoveFolder element in to empty component as well
// * if Component+CreateFolder+RemoveFolder elements are placed in a dummy component to handle an empty folder
// any parent folder with no files/components will not be removed on uninstall.
// - workaround is to insert Component+Create+RemoveFolder elements in any parent folder with no files.
//
// OMG!!!! If it is not over-engineering I don't know what is.
bool oldAlgorithm = false;
if (!oldAlgorithm)
{
//current approach
InsertCreateFolder(item);
if (!xDir.ContainsAnyRemoveFolder())
InsertRemoveFolder(xDir, item, "uninstall");
}
else
{
//old approach
if (!item.Attribute("Id").Value.EndsWith(".EmptyDirectory"))
InsertCreateFolder(item);
else if (!xDir.ContainsAnyRemoveFolder())
InsertRemoveFolder(xDir, item, "uninstall"); //to keep WiX/compiler happy and allow removal of the dummy directory
}
}
}
}
}
}
internal static void InjectAutoElementsHandler(XDocument doc)
{
ExpandCustomAttributes(doc);
InjectShortcutIcons(doc);
HandleEmptyDirectories(doc);
InjectPlatformAttributes(doc);
XElement product = doc.Root.Select("Product");
int? absPathCount = null;
foreach (XElement dir in product.Element("Directory").Elements("Directory"))
{
XElement installDir = dir;
XAttribute installDirName = installDir.Attribute("Name");
if (IO.Path.IsPathRooted(installDirName.Value))
{
string absolutePath = installDirName.Value;
if (dir == product.Element("Directory").Elements("Directory").First()) //only for the first root dir
{
//ManagedUI will need some hint on the install dir as it cannot rely on the session action (e.g. Set_INSTALLDIR_AbsolutePath)
//because it is running outside of the sequence and analyses the tables directly for the INSTALLDIR
product.AddElement("Property", "Id=INSTALLDIR_ABSOLUTEPATH; Value=" + absolutePath);
}
installDirName.Value = $"ABSOLUTEPATH{absPathCount}";
//<SetProperty> for INSTALLDIR is an attractive approach but it doesn't allow conditional setting of 'ui' and 'execute' as required depending on UI level
// it is ether hard-coded 'both' or hard coded-both 'ui' or 'execute'
// <SetProperty Id="INSTALLDIR" Value="C:\My Company\MyProduct" Sequence="both" Before="AppSearch">
string actualDirName = installDir.Attribute("Id").Value;
string customAction = $"Set_DirAbsolutePath{absPathCount}";
product.Add(new XElement("CustomAction",
new XAttribute("Id", customAction),
new XAttribute("Property", actualDirName),
new XAttribute("Value", absolutePath)));
product.SelectOrCreate("InstallExecuteSequence").Add(
new XElement("Custom", $"(NOT Installed) AND (UILevel < 5) AND ({actualDirName} = ABSOLUTEPATH{absPathCount})",
new XAttribute("Action", customAction),
new XAttribute("Before", "AppSearch")));
product.SelectOrCreate("InstallUISequence").Add(
new XElement("Custom", $"(NOT Installed) AND (UILevel = 5) AND ({actualDirName} = ABSOLUTEPATH{absPathCount})",
new XAttribute("Action", customAction),
new XAttribute("Before", "AppSearch")));
if (absPathCount == null)
absPathCount = 0;
absPathCount++;
}
}
foreach (XElement xDir in product.Descendants("Directory").ToArray())
{
var dirComponents = xDir.Elements("Component");
if (dirComponents.Any())
{
var componentsWithNoFiles = dirComponents.Where(x => !x.ContainsFiles()).ToArray();
foreach (XElement item in componentsWithNoFiles)
{
//if (!item.Attribute("Id").Value.EndsWith(".EmptyDirectory"))
EnsureKeyPath(item);
if (!xDir.ContainsAnyRemoveFolder())
InsertRemoveFolder(xDir, item, "uninstall"); //to keep WiX/compiler happy and allow removal of the dummy directory
}
}
foreach (XElement xComp in dirComponents)
{
if (xDir.InUserProfile())
{
if (!xDir.ContainsAnyRemoveFolder())
InsertRemoveFolder(xDir, xComp);
if (!xComp.ContainsDummyUserProfileRegistry())
InsertDummyUserProfileRegistry(xComp);
}
else
{
if (xComp.ContainsNonAdvertisedShortcuts())
if (!xComp.ContainsDummyUserProfileRegistry())
InsertDummyUserProfileRegistry(xComp);
}
foreach (XElement xFile in xComp.Elements("File"))
if (xFile.ContainsAdvertisedShortcuts() && !xComp.ContainsDummyUserProfileRegistry())
SetFileKeyPath(xFile);
}
if (!xDir.ContainsComponents() && xDir.InUserProfile())
{
if (!xDir.IsUserProfileRoot())
{
XElement xComp1 = doc.CrteateComponentFor(xDir);
if (!xDir.ContainsAnyRemoveFolder())
InsertRemoveFolder(xDir, xComp1);
if (!xComp1.ContainsDummyUserProfileRegistry())
InsertDummyUserProfileRegistry(xComp1);
}
}
}
//Not a property Id as MSI requires
Predicate<string> needsProperty =
value => value.Contains("\\") ||
value.Contains("//") ||
value.Contains("%") ||
value.Contains("[") ||
value.Contains("]");
foreach (XElement xShortcut in product.Descendants("Shortcut"))
{
if (xShortcut.HasAttribute("WorkingDirectory", x => needsProperty(x)))
{
string workingDirectory = xShortcut.Attribute("WorkingDirectory").Value;
if (workingDirectory.StartsWith("%") && workingDirectory.EndsWith("%")) //%INSTALLDIR%
{
workingDirectory = workingDirectory.ExpandWixEnvConsts();
xShortcut.SetAttributeValue("WorkingDirectory", workingDirectory.Replace("%", ""));
}
else if (workingDirectory.StartsWith("[") && workingDirectory.EndsWith("]")) //[INSTALLDIR]
{
xShortcut.SetAttributeValue("WorkingDirectory", workingDirectory.Replace("[", "").Replace("]", ""));
}
else
{
string workinDirPath = workingDirectory.ReplaceWixSharpEnvConsts();
XElement existingProperty = product.Descendants("Property")
.Where(p => p.HasAttribute("Value", workingDirectory))
.FirstOrDefault();
if (existingProperty != null)
{
xShortcut.SetAttributeValue("WorkingDirectory", existingProperty.Attribute("Id").Value);
}
else
{
string propId = xShortcut.Attribute("Id").Value + ".WorkDir";
product.AddElement("Property", "Id=" + propId + "; Value=" + workinDirPath);
xShortcut.SetAttributeValue("WorkingDirectory", propId);
}
}
}
}
}
internal static void NormalizeFilePaths(XDocument doc, string sourceBaseDir, bool emitRelativePaths)
{
string rootDir = sourceBaseDir;
if (rootDir.IsEmpty())
rootDir = Environment.CurrentDirectory;
rootDir = IO.Path.GetFullPath(rootDir);
Action<IEnumerable<XElement>, string> normalize = (elements, attributeName) =>
{
elements.Where(e => e.HasAttribute(attributeName))
.ForEach(e =>
{
var attr = e.Attribute(attributeName);
if (emitRelativePaths)
attr.Value = Utils.MakeRelative(attr.Value, rootDir);
else
attr.Value = Path.GetFullPath(attr.Value);
});
};
normalize(doc.Root.FindAll("Icon"), "SourceFile");
normalize(doc.Root.FindAll("File"), "Source");
normalize(doc.Root.FindAll("Merge"), "SourceFile");
normalize(doc.Root.FindAll("Binary"), "SourceFile");
normalize(doc.Root.FindAll("EmbeddedUI"), "SourceFile");
normalize(doc.Root.FindAll("Payload"), "SourceFile");
normalize(doc.Root.FindAll("MsiPackage"), "SourceFile");
normalize(doc.Root.FindAll("ExePackage"), "SourceFile");
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.Cecil.Mdb {
public sealed class MdbWriterProvider : ISymbolWriterProvider {
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, string fileName)
{
Mixin.CheckModule (module);
Mixin.CheckFileName (fileName);
return new MdbWriter (module, fileName);
}
public ISymbolWriter GetSymbolWriter (ModuleDefinition module, Stream symbolStream)
{
throw new NotImplementedException ();
}
}
public sealed class MdbWriter : ISymbolWriter {
readonly ModuleDefinition module;
readonly MonoSymbolWriter writer;
readonly Dictionary<string, SourceFile> source_files;
public MdbWriter (ModuleDefinition module, string assembly)
{
this.module = module;
this.writer = new MonoSymbolWriter (assembly);
this.source_files = new Dictionary<string, SourceFile> ();
}
public ISymbolReaderProvider GetReaderProvider ()
{
return new MdbReaderProvider ();
}
SourceFile GetSourceFile (Document document)
{
var url = document.Url;
SourceFile source_file;
if (source_files.TryGetValue (url, out source_file))
return source_file;
var entry = writer.DefineDocument (url, null, document.Hash != null && document.Hash.Length == 16 ? document.Hash : null);
var compile_unit = writer.DefineCompilationUnit (entry);
source_file = new SourceFile (compile_unit, entry);
source_files.Add (url, source_file);
return source_file;
}
void Populate (Collection<SequencePoint> sequencePoints, int [] offsets,
int [] startRows, int [] endRows, int [] startCols, int [] endCols, out SourceFile file)
{
SourceFile source_file = null;
for (int i = 0; i < sequencePoints.Count; i++) {
var sequence_point = sequencePoints [i];
offsets [i] = sequence_point.Offset;
if (source_file == null)
source_file = GetSourceFile (sequence_point.Document);
startRows [i] = sequence_point.StartLine;
endRows [i] = sequence_point.EndLine;
startCols [i] = sequence_point.StartColumn;
endCols [i] = sequence_point.EndColumn;
}
file = source_file;
}
public void Write (MethodDebugInformation info)
{
var method = new SourceMethod (info.method);
var sequence_points = info.SequencePoints;
int count = sequence_points.Count;
if (count == 0)
return;
var offsets = new int [count];
var start_rows = new int [count];
var end_rows = new int [count];
var start_cols = new int [count];
var end_cols = new int [count];
SourceFile file;
Populate (sequence_points, offsets, start_rows, end_rows, start_cols, end_cols, out file);
var builder = writer.OpenMethod (file.CompilationUnit, 0, method);
for (int i = 0; i < count; i++) {
builder.MarkSequencePoint (
offsets [i],
file.CompilationUnit.SourceFile,
start_rows [i],
start_cols [i],
end_rows [i],
end_cols [i],
false);
}
if (info.scope != null)
WriteRootScope (info.scope, info);
writer.CloseMethod ();
}
void WriteRootScope (ScopeDebugInformation scope, MethodDebugInformation info)
{
WriteScopeVariables (scope);
if (scope.HasScopes)
WriteScopes (scope.Scopes, info);
}
void WriteScope (ScopeDebugInformation scope, MethodDebugInformation info)
{
writer.OpenScope (scope.Start.Offset);
WriteScopeVariables (scope);
if (scope.HasScopes)
WriteScopes (scope.Scopes, info);
writer.CloseScope (scope.End.IsEndOfMethod ? info.code_size : scope.End.Offset);
}
void WriteScopes (Collection<ScopeDebugInformation> scopes, MethodDebugInformation info)
{
for (int i = 0; i < scopes.Count; i++)
WriteScope (scopes [i], info);
}
void WriteScopeVariables (ScopeDebugInformation scope)
{
if (!scope.HasVariables)
return;
foreach (var variable in scope.variables)
if (!string.IsNullOrEmpty (variable.Name))
writer.DefineLocalVariable (variable.Index, variable.Name);
}
public ImageDebugHeader GetDebugHeader ()
{
return new ImageDebugHeader ();
}
public void Dispose ()
{
writer.WriteSymbolFile (module.Mvid);
}
class SourceFile : ISourceFile {
readonly CompileUnitEntry compilation_unit;
readonly SourceFileEntry entry;
public SourceFileEntry Entry {
get { return entry; }
}
public CompileUnitEntry CompilationUnit {
get { return compilation_unit; }
}
public SourceFile (CompileUnitEntry comp_unit, SourceFileEntry entry)
{
this.compilation_unit = comp_unit;
this.entry = entry;
}
}
class SourceMethod : IMethodDef {
readonly MethodDefinition method;
public string Name {
get { return method.Name; }
}
public int Token {
get { return method.MetadataToken.ToInt32 (); }
}
public SourceMethod (MethodDefinition method)
{
this.method = method;
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// QueryOperator.cs
//
// <OWNER>[....]</OWNER>
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.Contracts;
namespace System.Linq.Parallel
{
/// <summary>
/// This is the abstract base class for all query operators in the system. It
/// implements the ParallelQuery{T} type so that it can be bound as the source
/// of parallel queries and so that it can be returned as the result of parallel query
/// operations. Not much is in here, although it does serve as the "entry point" for
/// opening all query operators: it will lazily analyze and cache a plan the first
/// time the tree is opened, and will open the tree upon calls to GetEnumerator.
///
/// Notes:
/// This class implements ParallelQuery so that any parallel query operator
/// can bind to the parallel query provider overloads. This allows us to string
/// together operators w/out the user always specifying AsParallel, e.g.
/// Select(Where(..., ...), ...), and so forth.
/// </summary>
/// <typeparam name="TOutput"></typeparam>
internal abstract class QueryOperator<TOutput> : ParallelQuery<TOutput>
{
protected bool m_outputOrdered;
internal QueryOperator(QuerySettings settings)
:this(false, settings)
{
}
internal QueryOperator(bool isOrdered, QuerySettings settings)
:base(settings)
{
m_outputOrdered = isOrdered;
}
//---------------------------------------------------------------------------------------
// Opening the query operator will do whatever is necessary to begin enumerating its
// results. This includes in some cases actually introducing parallelism, enumerating
// other query operators, and so on. This is abstract and left to the specific concrete
// operator classes to implement.
//
// Arguments:
// settings - various flags and settings to control query execution
// preferStriping - flag representing whether the caller prefers striped partitioning
// over range partitioning
//
// Return Values:
// Either a single enumerator, or a partition (for partition parallelism).
//
internal abstract QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping);
//---------------------------------------------------------------------------------------
// The GetEnumerator method is the standard IEnumerable mechanism for walking the
// contents of a query. Note that GetEnumerator is only ever called on the root node:
// we then proceed by calling Open on all of the subsequent query nodes.
//
// Arguments:
// usePipelining - whether the returned enumerator will pipeline (i.e. return
// control to the caller when the query is spawned) or not
// (i.e. use the calling thread to execute the query). Note
// that there are some conditions during which this hint will
// be ignored -- currently, that happens only if a sort is
// found anywhere in the query graph.
// suppressOrderPreservation - whether to shut order preservation off, regardless
// of the contents of the query
//
// Return Value:
// An enumerator that retrieves elements from the query output.
//
// Notes:
// The default mode of execution is to pipeline the query execution with respect
// to the GetEnumerator caller (aka the consumer). An overload is available
// that can be used to override the default with an explicit choice.
//
public override IEnumerator<TOutput> GetEnumerator()
{
// Buffering is unspecified and order preservation is not suppressed.
return GetEnumerator(null, false);
}
public IEnumerator<TOutput> GetEnumerator(ParallelMergeOptions? mergeOptions)
{
// Pass through the value supplied for pipelining, and do not suppress
// order preservation by default.
return GetEnumerator(mergeOptions, false);
}
//---------------------------------------------------------------------------------------
// Is the output of this operator ordered?
//
internal bool OutputOrdered
{
get { return m_outputOrdered; }
}
internal virtual IEnumerator<TOutput> GetEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrderPreservation)
{
// Return a dummy enumerator that will call back GetOpenedEnumerator() on 'this' QueryOperator
// the first time the user calls MoveNext(). We do this to prevent executing the query if user
// never calls MoveNext().
return new QueryOpeningEnumerator<TOutput>(this, mergeOptions, suppressOrderPreservation);
}
//---------------------------------------------------------------------------------------
// The GetOpenedEnumerator method return an enumerator that walks the contents of a query.
// The enumerator will be "opened", which means that PLINQ will start executing the query
// immediately, even before the user calls MoveNext() for the first time.
//
internal IEnumerator<TOutput> GetOpenedEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrder, bool forEffect,
QuerySettings querySettings)
{
// If the top-level enumerator forces a premature merge, run the query sequentially.
if (querySettings.ExecutionMode.Value == ParallelExecutionMode.Default && LimitsParallelism)
{
IEnumerable<TOutput> opSequential = AsSequentialQuery(querySettings.CancellationState.ExternalCancellationToken);
return ExceptionAggregator.WrapEnumerable(opSequential, querySettings.CancellationState).GetEnumerator();
}
QueryResults<TOutput> queryResults = GetQueryResults(querySettings);
if (mergeOptions == null)
{
mergeOptions = querySettings.MergeOptions;
}
Contract.Assert(mergeOptions != null);
// Top-level pre-emptive cancellation test.
// This handles situations where cancellation has occured before execution commences
// The handling for in-execution occurs in QueryTaskGroupState.QueryEnd()
if(querySettings.CancellationState.MergedCancellationToken.IsCancellationRequested)
{
if (querySettings.CancellationState.ExternalCancellationToken.IsCancellationRequested)
throw new OperationCanceledException(querySettings.CancellationState.ExternalCancellationToken);
else
throw new OperationCanceledException();
}
bool orderedMerge = OutputOrdered && !suppressOrder;
PartitionedStreamMerger<TOutput> merger = new PartitionedStreamMerger<TOutput>(forEffect, mergeOptions.GetValueOrDefault(),
querySettings.TaskScheduler,
orderedMerge,
querySettings.CancellationState,
querySettings.QueryId);
queryResults.GivePartitionedStream(merger); // hook up the data flow between the operator-executors, starting from the merger.
if (forEffect)
{
return null;
}
return merger.MergeExecutor.GetEnumerator();
}
// This method is called only once on the 'head operator' which is the last specified operator in the query
// This method then recursively uses Open() to prepare itself and the other enumerators.
private QueryResults<TOutput> GetQueryResults(QuerySettings querySettings)
{
TraceHelpers.TraceInfo("[timing]: {0}: starting execution - QueryOperator<>::GetQueryResults", DateTime.Now.Ticks);
// All mandatory query settings must be specified
Contract.Assert(querySettings.TaskScheduler != null);
Contract.Assert(querySettings.DegreeOfParallelism.HasValue);
Contract.Assert(querySettings.ExecutionMode.HasValue);
// Now just open the query tree's root operator, supplying a specific DOP
return Open(querySettings, false);
}
//---------------------------------------------------------------------------------------
// Executes the query and returns the results in an array.
//
internal TOutput[] ExecuteAndGetResultsAsArray()
{
QuerySettings querySettings =
SpecifiedQuerySettings
.WithPerExecutionSettings()
.WithDefaults();
QueryLifecycle.LogicalQueryExecutionBegin(querySettings.QueryId);
try
{
if (querySettings.ExecutionMode.Value == ParallelExecutionMode.Default && LimitsParallelism)
{
IEnumerable<TOutput> opSequential = AsSequentialQuery(querySettings.CancellationState.ExternalCancellationToken);
IEnumerable<TOutput> opSequentialWithCancelChecks = CancellableEnumerable.Wrap(opSequential, querySettings.CancellationState.ExternalCancellationToken);
return ExceptionAggregator.WrapEnumerable(opSequentialWithCancelChecks, querySettings.CancellationState).ToArray();
}
QueryResults<TOutput> results = GetQueryResults(querySettings);
if (results.IsIndexible && OutputOrdered)
{
// The special array-based merge performs better if the output is ordered, because
// it does not have to pay for ordering. In the unordered case, we it appears that
// the stop-and-go merge performs a little better.
ArrayMergeHelper<TOutput> merger = new ArrayMergeHelper<TOutput>(SpecifiedQuerySettings, results);
merger.Execute();
TOutput[] output = merger.GetResultsAsArray();
querySettings.CleanStateAtQueryEnd();
return output;
}
else
{
PartitionedStreamMerger<TOutput> merger =
new PartitionedStreamMerger<TOutput>(false, ParallelMergeOptions.FullyBuffered, querySettings.TaskScheduler,
OutputOrdered, querySettings.CancellationState, querySettings.QueryId);
results.GivePartitionedStream(merger);
TOutput[] output = merger.MergeExecutor.GetResultsAsArray();
querySettings.CleanStateAtQueryEnd();
return output;
}
}
finally
{
QueryLifecycle.LogicalQueryExecutionEnd(querySettings.QueryId);
}
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
// Note that iterating the returned enumerable will not wrap exceptions AggregateException.
// Before this enumerable is returned to the user, we must wrap it with an
// ExceptionAggregator.
//
internal abstract IEnumerable<TOutput> AsSequentialQuery(CancellationToken token);
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge.
//
internal abstract bool LimitsParallelism { get; }
//---------------------------------------------------------------------------------------
// The state of the order index of the results returned by this operator.
//
internal abstract OrdinalIndexState OrdinalIndexState { get; }
//---------------------------------------------------------------------------------------
// A helper method that executes the query rooted at the openedChild operator, and returns
// the results as ListQueryResults<TSource>.
//
internal static ListQueryResults<TOutput> ExecuteAndCollectResults<TKey>(
PartitionedStream<TOutput, TKey> openedChild,
int partitionCount,
bool outputOrdered,
bool useStriping,
QuerySettings settings)
{
TaskScheduler taskScheduler = settings.TaskScheduler;
MergeExecutor<TOutput> executor = MergeExecutor<TOutput>.Execute<TKey>(
openedChild, false, ParallelMergeOptions.FullyBuffered, taskScheduler, outputOrdered,
settings.CancellationState, settings.QueryId);
return new ListQueryResults<TOutput>(executor.GetResultsAsArray(), partitionCount, useStriping);
}
//---------------------------------------------------------------------------------------
// Returns a QueryOperator<T> for any IEnumerable<T> data source. This will just do a
// cast and return a reference to the same data source if the source is another query
// operator, but will lazily allocate a scan operation and return that otherwise.
//
// Arguments:
// source - any enumerable data source to be wrapped
//
// Return Value:
// A query operator.
//
internal static QueryOperator<TOutput> AsQueryOperator(IEnumerable<TOutput> source)
{
Contract.Assert(source != null);
// Just try casting the data source to a query operator, in the case that
// our child is just another query operator.
QueryOperator<TOutput> sourceAsOperator = source as QueryOperator<TOutput>;
if (sourceAsOperator == null)
{
OrderedParallelQuery<TOutput> orderedQuery = source as OrderedParallelQuery<TOutput>;
if (orderedQuery != null)
{
// We have to handle OrderedParallelQuery<T> specially. In all other cases,
// ParallelQuery *is* the QueryOperator<T>. But, OrderedParallelQuery<T>
// is not QueryOperator<T>, it only has a reference to one. Ideally, we
// would want SortQueryOperator<T> to inherit from OrderedParallelQuery<T>,
// but that conflicts with other constraints on our class hierarchy.
sourceAsOperator = (QueryOperator<TOutput>)orderedQuery.SortOperator;
}
else
{
// If the cast failed, then the data source is a real piece of data. We
// just construct a new scan operator on top of it.
sourceAsOperator = new ScanQueryOperator<TOutput>(source);
}
}
Contract.Assert(sourceAsOperator != null);
return sourceAsOperator;
}
}
}
| |
// 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;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// Provides support for EventSource activities by marking the start and
/// end of a particular operation.
/// </summary>
internal sealed class EventSourceActivity
: IDisposable
{
/// <summary>
/// Initializes a new instance of the EventSourceActivity class that
/// is attached to the specified event source. The new activity will
/// not be attached to any related (parent) activity.
/// The activity is created in the Initialized state.
/// </summary>
/// <param name="eventSource">
/// The event source to which the activity information is written.
/// </param>
public EventSourceActivity(EventSource eventSource)
{
if (eventSource == null)
throw new ArgumentNullException(nameof(eventSource));
Contract.EndContractBlock();
this.eventSource = eventSource;
}
/// <summary>
/// You can make an activity out of just an EventSource.
/// </summary>
public static implicit operator EventSourceActivity(EventSource eventSource) { return new EventSourceActivity(eventSource); }
/* Properties */
/// <summary>
/// Gets the event source to which this activity writes events.
/// </summary>
public EventSource EventSource
{
get { return this.eventSource; }
}
/// <summary>
/// Gets this activity's unique identifier, or the default Guid if the
/// event source was disabled when the activity was initialized.
/// </summary>
public Guid Id
{
get { return this.activityId; }
}
#if false // don't expose RelatedActivityId unless there is a need.
/// <summary>
/// Gets the unique identifier of this activity's related (parent)
/// activity.
/// </summary>
public Guid RelatedId
{
get { return this.relatedActivityId; }
}
#endif
/// <summary>
/// Writes a Start event with the specified name and data. If the start event is not active (because the provider
/// is not on or keyword-level indiates the event is off, then the returned activity is simply the 'this' poitner
/// and it is effectively like the Start d
///
/// A new activityID GUID is generated and the returned
/// EventSourceActivity remembers this activity and will mark every event (including the start stop and any writes)
/// with this activityID. In addition the Start activity will log a 'relatedActivityID' that was the activity
/// ID before the start event. This way event processors can form a linked list of all the activities that
/// caused this one (directly or indirectly).
/// </summary>
/// <param name="eventName">
/// The name to use for the event. It is strongly suggested that this name end in 'Start' (e.g. DownloadStart).
/// If you do this, then the Stop() method will automatically replace the 'Start' suffix with a 'Stop' suffix.
/// </param>
/// <param name="options">Allow options (keywords, level) to be set for the write associated with this start
/// These will also be used for the stop event.</param>
/// <param name="data">The data to include in the event.</param>
public EventSourceActivity Start<T>(string eventName, EventSourceOptions options, T data)
{
return this.Start(eventName, ref options, ref data);
}
/// <summary>
/// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords
/// and level==Info) Data payload is empty.
/// </summary>
public EventSourceActivity Start(string eventName)
{
var options = new EventSourceOptions();
var data = new EmptyStruct();
return this.Start(eventName, ref options, ref data);
}
/// <summary>
/// Shortcut version see Start(string eventName, EventSourceOptions options, T data). Data payload is empty.
/// </summary>
public EventSourceActivity Start(string eventName, EventSourceOptions options)
{
var data = new EmptyStruct();
return this.Start(eventName, ref options, ref data);
}
/// <summary>
/// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords
/// and level==Info)
/// </summary>
public EventSourceActivity Start<T>(string eventName, T data)
{
var options = new EventSourceOptions();
return this.Start(eventName, ref options, ref data);
}
/// <summary>
/// Writes a Stop event with the specified data, and sets the activity
/// to the Stopped state. The name is determined by the eventName used in Start.
/// If that Start event name is suffixed with 'Start' that is removed, and regardless
/// 'Stop' is appended to the result to form the Stop event name.
/// May only be called when the activity is in the Started state.
/// </summary>
/// <param name="data">The data to include in the event.</param>
public void Stop<T>(T data)
{
this.Stop(null, ref data);
}
/// <summary>
/// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop')
/// This can be useful to indicate unusual ways of stoping (but it is still STRONGLY recommeded that
/// you start with the same prefix used for the start event and you end with the 'Stop' suffix.
/// </summary>
public void Stop<T>(string eventName)
{
var data = new EmptyStruct();
this.Stop(eventName, ref data);
}
/// <summary>
/// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop')
/// This can be useful to indicate unusual ways of stoping (but it is still STRONGLY recommeded that
/// you start with the same prefix used for the start event and you end with the 'Stop' suffix.
/// </summary>
public void Stop<T>(string eventName, T data)
{
this.Stop(eventName, ref data);
}
/// <summary>
/// Writes an event associated with this activity to the eventSource associted with this activity.
/// May only be called when the activity is in the Started state.
/// </summary>
/// <param name="eventName">
/// The name to use for the event. If null, the name is determined from
/// data's type.
/// </param>
/// <param name="options">
/// The options to use for the event.
/// </param>
/// <param name="data">The data to include in the event.</param>
public void Write<T>(string eventName, EventSourceOptions options, T data)
{
this.Write(this.eventSource, eventName, ref options, ref data);
}
/// <summary>
/// Writes an event associated with this activity.
/// May only be called when the activity is in the Started state.
/// </summary>
/// <param name="eventName">
/// The name to use for the event. If null, the name is determined from
/// data's type.
/// </param>
/// <param name="data">The data to include in the event.</param>
public void Write<T>(string eventName, T data)
{
var options = new EventSourceOptions();
this.Write(this.eventSource, eventName, ref options, ref data);
}
/// <summary>
/// Writes a trivial event associated with this activity.
/// May only be called when the activity is in the Started state.
/// </summary>
/// <param name="eventName">
/// The name to use for the event. Must not be null.
/// </param>
/// <param name="options">
/// The options to use for the event.
/// </param>
public void Write(string eventName, EventSourceOptions options)
{
var data = new EmptyStruct();
this.Write(this.eventSource, eventName, ref options, ref data);
}
/// <summary>
/// Writes a trivial event associated with this activity.
/// May only be called when the activity is in the Started state.
/// </summary>
/// <param name="eventName">
/// The name to use for the event. Must not be null.
/// </param>
public void Write(string eventName)
{
var options = new EventSourceOptions();
var data = new EmptyStruct();
this.Write(this.eventSource, eventName, ref options, ref data);
}
/// <summary>
/// Writes an event to a arbitrary eventSource stamped with the activity ID of this activity.
/// </summary>
public void Write<T>(EventSource source, string eventName, EventSourceOptions options, T data)
{
this.Write(source, eventName, ref options, ref data);
}
/// <summary>
/// Releases any unmanaged resources associated with this object.
/// If the activity is in the Started state, calls Stop().
/// </summary>
public void Dispose()
{
if (this.state == State.Started)
{
var data = new EmptyStruct();
this.Stop(null, ref data);
}
}
#region private
private EventSourceActivity Start<T>(string eventName, ref EventSourceOptions options, ref T data)
{
if (this.state != State.Started)
throw new InvalidOperationException();
// If the source is not on at all, then we don't need to do anything and we can simply return ourselves.
if (!this.eventSource.IsEnabled())
return this;
var newActivity = new EventSourceActivity(eventSource);
if (!this.eventSource.IsEnabled(options.Level, options.Keywords))
{
// newActivity.relatedActivityId = this.Id;
Guid relatedActivityId = this.Id;
newActivity.activityId = Guid.NewGuid();
newActivity.startStopOptions = options;
newActivity.eventName = eventName;
newActivity.startStopOptions.Opcode = EventOpcode.Start;
this.eventSource.Write(eventName, ref newActivity.startStopOptions, ref newActivity.activityId, ref relatedActivityId, ref data);
}
else
{
// If we are not active, we don't set the eventName, which basically also turns off the Stop event as well.
newActivity.activityId = this.Id;
}
return newActivity;
}
private void Write<T>(EventSource eventSource, string eventName, ref EventSourceOptions options, ref T data)
{
if (this.state != State.Started)
throw new InvalidOperationException(); // Write after stop.
if (eventName == null)
throw new ArgumentNullException();
eventSource.Write(eventName, ref options, ref this.activityId, ref s_empty, ref data);
}
private void Stop<T>(string eventName, ref T data)
{
if (this.state != State.Started)
throw new InvalidOperationException();
// If start was not fired, then stop isn't as well.
if (!StartEventWasFired)
return;
this.state = State.Stopped;
if (eventName == null)
{
eventName = this.eventName;
if (eventName.EndsWith("Start"))
eventName = eventName.Substring(0, eventName.Length - 5);
eventName = eventName + "Stop";
}
this.startStopOptions.Opcode = EventOpcode.Stop;
this.eventSource.Write(eventName, ref this.startStopOptions, ref this.activityId, ref s_empty, ref data);
}
private enum State
{
Started,
Stopped
}
/// <summary>
/// If eventName is non-null then we logged a start event
/// </summary>
private bool StartEventWasFired { get { return eventName != null; } }
private readonly EventSource eventSource;
private EventSourceOptions startStopOptions;
internal Guid activityId;
// internal Guid relatedActivityId;
private State state;
private string eventName;
static internal Guid s_empty;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryAddTests
{
#region Test methods
[Fact]
public static void CheckByteAddTest()
{
byte[] array = new byte[] { 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyByteAdd(array[i], array[j]);
}
}
}
[Fact]
public static void CheckSByteAddTest()
{
sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifySByteAdd(array[i], array[j]);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUShortAddTest(bool useInterpreter)
{
ushort[] array = new ushort[] { 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUShortAdd(array[i], array[j], useInterpreter);
VerifyUShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckShortAddTest(bool useInterpreter)
{
short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyShortAdd(array[i], array[j], useInterpreter);
VerifyShortAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckUIntAddTest(bool useInterpreter)
{
uint[] array = new uint[] { 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyUIntAdd(array[i], array[j], useInterpreter);
VerifyUIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckIntAddTest(bool useInterpreter)
{
int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyIntAdd(array[i], array[j], useInterpreter);
VerifyIntAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckULongAddTest(bool useInterpreter)
{
ulong[] array = new ulong[] { 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyULongAdd(array[i], array[j], useInterpreter);
VerifyULongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckLongAddTest(bool useInterpreter)
{
long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyLongAdd(array[i], array[j], useInterpreter);
VerifyLongAddOvf(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckFloatAddTest(bool useInterpreter)
{
float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyFloatAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDoubleAddTest(bool useInterpreter)
{
double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDoubleAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckDecimalAddTest(bool useInterpreter)
{
decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyDecimalAdd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckCharAddTest(bool useInterpreter)
{
char[] array = new char[] { '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyCharAdd(array[i], array[j]);
}
}
}
#endregion
#region Test verifiers
private static void VerifyByteAdd(byte a, byte b)
{
Expression aExp = Expression.Constant(a, typeof(byte));
Expression bExp = Expression.Constant(b, typeof(byte));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifySByteAdd(sbyte a, sbyte b)
{
Expression aExp = Expression.Constant(a, typeof(sbyte));
Expression bExp = Expression.Constant(b, typeof(sbyte));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
private static void VerifyUShortAdd(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.Add(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((ushort)(a + b)), f());
}
private static void VerifyUShortAddOvf(ushort a, ushort b, bool useInterpreter)
{
Expression<Func<ushort>> e =
Expression.Lambda<Func<ushort>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ushort)),
Expression.Constant(b, typeof(ushort))),
Enumerable.Empty<ParameterExpression>());
Func<ushort> f = e.Compile(useInterpreter);
int expected = a + b;
if (expected < 0 || expected > ushort.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyShortAdd(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.Add(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
Assert.Equal(unchecked((short)(a + b)), f());
}
private static void VerifyShortAddOvf(short a, short b, bool useInterpreter)
{
Expression<Func<short>> e =
Expression.Lambda<Func<short>>(
Expression.AddChecked(
Expression.Constant(a, typeof(short)),
Expression.Constant(b, typeof(short))),
Enumerable.Empty<ParameterExpression>());
Func<short> f = e.Compile(useInterpreter);
int expected = a + b;
if (expected < short.MinValue || expected > short.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyUIntAdd(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.Add(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyUIntAddOvf(uint a, uint b, bool useInterpreter)
{
Expression<Func<uint>> e =
Expression.Lambda<Func<uint>>(
Expression.AddChecked(
Expression.Constant(a, typeof(uint)),
Expression.Constant(b, typeof(uint))),
Enumerable.Empty<ParameterExpression>());
Func<uint> f = e.Compile(useInterpreter);
long expected = a + (long)b;
if (expected < 0 || expected > uint.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyIntAdd(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.Add(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyIntAddOvf(int a, int b, bool useInterpreter)
{
Expression<Func<int>> e =
Expression.Lambda<Func<int>>(
Expression.AddChecked(
Expression.Constant(a, typeof(int)),
Expression.Constant(b, typeof(int))),
Enumerable.Empty<ParameterExpression>());
Func<int> f = e.Compile(useInterpreter);
long expected = a + (long)b;
if (expected < int.MinValue || expected > int.MaxValue)
Assert.Throws<OverflowException>(() => f());
else
Assert.Equal(expected, f());
}
private static void VerifyULongAdd(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.Add(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyULongAddOvf(ulong a, ulong b, bool useInterpreter)
{
Expression<Func<ulong>> e =
Expression.Lambda<Func<ulong>>(
Expression.AddChecked(
Expression.Constant(a, typeof(ulong)),
Expression.Constant(b, typeof(ulong))),
Enumerable.Empty<ParameterExpression>());
Func<ulong> f = e.Compile(useInterpreter);
ulong expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyLongAdd(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.Add(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
Assert.Equal(unchecked(a + b), f());
}
private static void VerifyLongAddOvf(long a, long b, bool useInterpreter)
{
Expression<Func<long>> e =
Expression.Lambda<Func<long>>(
Expression.AddChecked(
Expression.Constant(a, typeof(long)),
Expression.Constant(b, typeof(long))),
Enumerable.Empty<ParameterExpression>());
Func<long> f = e.Compile(useInterpreter);
long expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyFloatAdd(float a, float b, bool useInterpreter)
{
Expression<Func<float>> e =
Expression.Lambda<Func<float>>(
Expression.Add(
Expression.Constant(a, typeof(float)),
Expression.Constant(b, typeof(float))),
Enumerable.Empty<ParameterExpression>());
Func<float> f = e.Compile(useInterpreter);
float expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyDoubleAdd(double a, double b, bool useInterpreter)
{
Expression<Func<double>> e =
Expression.Lambda<Func<double>>(
Expression.Add(
Expression.Constant(a, typeof(double)),
Expression.Constant(b, typeof(double))),
Enumerable.Empty<ParameterExpression>());
Func<double> f = e.Compile(useInterpreter);
double expected = 0;
try
{
expected = checked(a + b);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyDecimalAdd(decimal a, decimal b, bool useInterpreter)
{
Expression<Func<decimal>> e =
Expression.Lambda<Func<decimal>>(
Expression.Add(
Expression.Constant(a, typeof(decimal)),
Expression.Constant(b, typeof(decimal))),
Enumerable.Empty<ParameterExpression>());
Func<decimal> f = e.Compile(useInterpreter);
decimal expected = 0;
try
{
expected = a + b;
}
catch(OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
private static void VerifyCharAdd(char a, char b)
{
Expression aExp = Expression.Constant(a, typeof(char));
Expression bExp = Expression.Constant(b, typeof(char));
Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp));
}
#endregion
[Fact]
public static void CannotReduce()
{
Expression exp = Expression.Add(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void CannotReduceChecked()
{
Expression exp = Expression.AddChecked(Expression.Constant(0), Expression.Constant(0));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void ThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.Add(null, Expression.Constant("")));
}
[Fact]
public static void ThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.Add(Expression.Constant(""), null));
}
[Fact]
public static void CheckedThrowsOnLeftNull()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.AddChecked(null, Expression.Constant("")));
}
[Fact]
public static void CheckedThrowsOnRightNull()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.AddChecked(Expression.Constant(""), null));
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
[Fact]
public static void ThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.Add(value, Expression.Constant(1)));
}
[Fact]
public static void ThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value));
}
[Fact]
public static void CheckedThrowsOnLeftUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("left", () => Expression.AddChecked(value, Expression.Constant(1)));
}
[Fact]
public static void CheckedThrowsOnRightUnreadable()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value));
}
[Fact]
public static void ToStringTest()
{
BinaryExpression e1 = Expression.Add(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a + b)", e1.ToString());
BinaryExpression e2 = Expression.AddChecked(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("(a + b)", e2.ToString());
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents an automation friendly version of a language-specific project.
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProject : VSProject
{
#region fields
private ProjectNode project;
private OAVSProjectEvents events;
#endregion
#region ctors
internal OAVSProject(ProjectNode project)
{
this.project = project;
}
#endregion
#region VSProject Members
public virtual ProjectItem AddWebReference(string bstrUrl)
{
throw new NotImplementedException();
}
public virtual BuildManager BuildManager
{
get
{
throw new NotImplementedException();
//return new OABuildManager(this.project);
}
}
public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword)
{
throw new NotImplementedException();
}
public virtual ProjectItem CreateWebReferencesFolder()
{
throw new NotImplementedException();
}
public virtual DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
public virtual VSProjectEvents Events
{
get
{
if (events == null)
events = new OAVSProjectEvents(this);
return events;
}
}
public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut)
{
throw new NotImplementedException(); ;
}
public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile)
{
throw new NotImplementedException(); ;
}
public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt)
{
throw new NotImplementedException(); ;
}
public virtual Imports Imports
{
get
{
throw new NotImplementedException();
}
}
public virtual EnvDTE.Project Project
{
get
{
return this.project.GetAutomationObject() as EnvDTE.Project;
}
}
public virtual References References
{
get
{
ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode;
if (null == references)
{
return new OAReferences(null, project);
}
return references.Object as References;
}
}
public virtual void Refresh()
{
}
public virtual string TemplatePath
{
get
{
throw new NotImplementedException();
}
}
public virtual ProjectItem WebReferencesFolder
{
get
{
throw new NotImplementedException();
}
}
public virtual bool WorkOffline
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
/// <summary>
/// Provides access to language-specific project events
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProjectEvents : VSProjectEvents
{
#region fields
private OAVSProject vsProject;
#endregion
#region ctors
public OAVSProjectEvents(OAVSProject vsProject)
{
this.vsProject = vsProject;
}
#endregion
#region VSProjectEvents Members
public virtual BuildManagerEvents BuildManagerEvents
{
get
{
return vsProject.BuildManager as BuildManagerEvents;
}
}
public virtual ImportsEvents ImportsEvents
{
get
{
throw new NotImplementedException();
}
}
public virtual ReferencesEvents ReferencesEvents
{
get
{
return vsProject.References as ReferencesEvents;
}
}
#endregion
}
}
| |
//
// UriTest.cs - NUnit Test Cases for System.Uri
//
// Authors:
// Lawrence Pit (loz@cable.a2000.nl)
// Martin Willemoes Hansen (mwh@sysrq.dk)
// Ben Maurer (bmaurer@users.sourceforge.net)
//
// (C) 2003 Martin Willemoes Hansen
// (C) 2003 Ben Maurer
//
using NUnit.Framework;
using System;
using System.IO;
namespace MonoTests.System
{
[TestFixture]
public class UriTest : Assertion
{
protected bool isWin32 = false;
[SetUp]
public void GetReady ()
{
isWin32 = (Path.DirectorySeparatorChar == '\\');
}
[Test]
public void Constructors ()
{
Uri uri = null;
/*
uri = new Uri ("http://www.ximian.com/foo" + ((char) 0xa9) + "/bar/index.cgi?a=1&b=" + ((char) 0xa9) + "left#fragm?ent2");
Print (uri);
uri = new Uri ("http://www.ximian.com/foo/xxx\"()-._;<=>@{|}~-,.`_^]\\[xx/" + ((char) 0xa9) + "/bar/index.cgi#fra+\">=@[gg]~gment2");
Print (uri);
uri = new Uri("http://11.22.33.588:9090");
Print (uri);
uri = new Uri("http://[11:22:33::88]:9090");
Print (uri);
uri = new Uri("http://[::127.11.22.33]:8080");
Print (uri);
uri = new Uri("http://[abcde::127.11.22.33]:8080");
Print (uri);
*/
/*
uri = new Uri ("http://www.contoso.com:1234/foo/bar/");
Print (uri);
uri = new Uri ("http://www.contoso.com:1234/foo/bar");
Print (uri);
uri = new Uri ("http://www.contoso.com:1234/");
Print (uri);
uri = new Uri ("http://www.contoso.com:1234");
Print (uri);
*/
uri = new Uri ("http://contoso.com?subject=uri");
AssertEquals ("#k1", "/", uri.AbsolutePath);
AssertEquals ("#k2", "http://contoso.com/?subject=uri", uri.AbsoluteUri);
AssertEquals ("#k3", "contoso.com", uri.Authority);
AssertEquals ("#k4", "", uri.Fragment);
AssertEquals ("#k5", "contoso.com", uri.Host);
AssertEquals ("#k6", UriHostNameType.Dns, uri.HostNameType);
AssertEquals ("#k7", true, uri.IsDefaultPort);
AssertEquals ("#k8", false, uri.IsFile);
AssertEquals ("#k9", false, uri.IsLoopback);
AssertEquals ("#k10", false, uri.IsUnc);
AssertEquals ("#k11", "/", uri.LocalPath);
AssertEquals ("#k12", "/?subject=uri", uri.PathAndQuery);
AssertEquals ("#k13", 80, uri.Port);
AssertEquals ("#k14", "?subject=uri", uri.Query);
AssertEquals ("#k15", "http", uri.Scheme);
AssertEquals ("#k16", false, uri.UserEscaped);
AssertEquals ("#k17", "", uri.UserInfo);
uri = new Uri ("mailto:user:pwd@contoso.com?subject=uri");
AssertEquals ("#m1", "", uri.AbsolutePath);
AssertEquals ("#m2", "mailto:user:pwd@contoso.com?subject=uri", uri.AbsoluteUri);
AssertEquals ("#m3", "contoso.com", uri.Authority);
AssertEquals ("#m4", "", uri.Fragment);
AssertEquals ("#m5", "contoso.com", uri.Host);
AssertEquals ("#m6", UriHostNameType.Dns, uri.HostNameType);
AssertEquals ("#m7", true, uri.IsDefaultPort);
AssertEquals ("#m8", false, uri.IsFile);
AssertEquals ("#m9", false, uri.IsLoopback);
AssertEquals ("#m10", false, uri.IsUnc);
AssertEquals ("#m11", "", uri.LocalPath);
AssertEquals ("#m12", "?subject=uri", uri.PathAndQuery);
AssertEquals ("#m13", 25, uri.Port);
AssertEquals ("#m14", "?subject=uri", uri.Query);
AssertEquals ("#m15", "mailto", uri.Scheme);
AssertEquals ("#m16", false, uri.UserEscaped);
AssertEquals ("#m17", "user:pwd", uri.UserInfo);
uri = new Uri (@"\\myserver\mydir\mysubdir\myfile.ext");
AssertEquals ("#n1", "/mydir/mysubdir/myfile.ext", uri.AbsolutePath);
AssertEquals ("#n2", "file://myserver/mydir/mysubdir/myfile.ext", uri.AbsoluteUri);
AssertEquals ("#n3", "myserver", uri.Authority);
AssertEquals ("#n4", "", uri.Fragment);
AssertEquals ("#n5", "myserver", uri.Host);
AssertEquals ("#n6", UriHostNameType.Dns, uri.HostNameType);
AssertEquals ("#n7", true, uri.IsDefaultPort);
AssertEquals ("#n8", true, uri.IsFile);
AssertEquals ("#n9", false, uri.IsLoopback);
AssertEquals ("#n10", true, uri.IsUnc);
if (isWin32)
AssertEquals ("#n11", @"\\myserver\mydir\mysubdir\myfile.ext", uri.LocalPath);
else
// myserver never could be the part of Unix path.
AssertEquals ("#n11", "/mydir/mysubdir/myfile.ext", uri.LocalPath);
AssertEquals ("#n12", "/mydir/mysubdir/myfile.ext", uri.PathAndQuery);
AssertEquals ("#n13", -1, uri.Port);
AssertEquals ("#n14", "", uri.Query);
AssertEquals ("#n15", "file", uri.Scheme);
AssertEquals ("#n16", false, uri.UserEscaped);
AssertEquals ("#n17", "", uri.UserInfo);
uri = new Uri (new Uri("http://www.contoso.com"), "Hello World.htm", true);
AssertEquals ("#rel1a", "http://www.contoso.com/Hello World.htm", uri.AbsoluteUri);
AssertEquals ("#rel1b", true, uri.UserEscaped);
uri = new Uri (new Uri("http://www.contoso.com"), "Hello World.htm", false);
AssertEquals ("#rel2a", "http://www.contoso.com/Hello%20World.htm", uri.AbsoluteUri);
AssertEquals ("#rel2b", false, uri.UserEscaped);
uri = new Uri (new Uri("http://www.contoso.com"), "http://www.xxx.com/Hello World.htm", false);
AssertEquals ("#rel3", "http://www.xxx.com/Hello%20World.htm", uri.AbsoluteUri);
//uri = new Uri (new Uri("http://www.contoso.com"), "foo:8080/bar/Hello World.htm", false);
//AssertEquals ("#rel4", "foo:8080/bar/Hello%20World.htm", uri.AbsoluteUri);
uri = new Uri (new Uri("http://www.contoso.com"), "foo/bar/Hello World.htm?x=0:8", false);
AssertEquals ("#rel5", "http://www.contoso.com/foo/bar/Hello%20World.htm?x=0:8", uri.AbsoluteUri);
uri = new Uri (new Uri("http://www.contoso.com/xxx/yyy/index.htm"), "foo/bar/Hello World.htm?x=0:8", false);
AssertEquals ("#rel6", "http://www.contoso.com/xxx/yyy/foo/bar/Hello%20World.htm?x=0:8", uri.AbsoluteUri);
uri = new Uri (new Uri("http://www.contoso.com/xxx/yyy/index.htm"), "/foo/bar/Hello World.htm?x=0:8", false);
AssertEquals ("#rel7", "http://www.contoso.com/foo/bar/Hello%20World.htm?x=0:8", uri.AbsoluteUri);
uri = new Uri (new Uri("http://www.contoso.com/xxx/yyy/index.htm"), "../foo/bar/Hello World.htm?x=0:8", false);
AssertEquals ("#rel8", "http://www.contoso.com/xxx/foo/bar/Hello%20World.htm?x=0:8", uri.AbsoluteUri);
uri = new Uri (new Uri("http://www.contoso.com/xxx/yyy/index.htm"), "../../../foo/bar/Hello World.htm?x=0:8", false);
AssertEquals ("#rel9", "http://www.contoso.com/../foo/bar/Hello%20World.htm?x=0:8", uri.AbsoluteUri);
uri = new Uri (new Uri("http://www.contoso.com/xxx/yyy/index.htm"), "./foo/bar/Hello World.htm?x=0:8", false);
AssertEquals ("#rel10", "http://www.contoso.com/xxx/yyy/foo/bar/Hello%20World.htm?x=0:8", uri.AbsoluteUri);
try {
uri = new Uri (null, "http://www.contoso.com/index.htm", false);
Fail ("#rel20");
} catch (NullReferenceException) {
}
try {
uri = new Uri (new Uri("http://www.contoso.com"), null, false);
Fail ("#rel21");
} catch (NullReferenceException) {
}
try {
uri = new Uri (new Uri("http://www.contoso.com/foo/bar/index.html?x=0"), String.Empty, false);
AssertEquals("#22", "http://www.contoso.com/foo/bar/index.html?x=0", uri.ToString ());
} catch (NullReferenceException) {
}
uri = new Uri (new Uri("http://www.xxx.com"), "?x=0");
AssertEquals ("#rel30", "http://www.xxx.com/?x=0", uri.ToString());
uri = new Uri (new Uri("http://www.xxx.com/index.htm"), "?x=0");
AssertEquals ("#rel31", "http://www.xxx.com/?x=0", uri.ToString());
uri = new Uri (new Uri("http://www.xxx.com/index.htm"), "#here");
AssertEquals ("#rel32", "http://www.xxx.com/index.htm#here", uri.ToString());
}
// regression for bug #47573
[Test]
public void RelativeCtor ()
{
Uri b = new Uri ("http://a/b/c/d;p?q");
// AssertEquals ("g:h", "g:h", new Uri (b, "g:h").ToString ()); this causes crash under MS.NET 1.1
AssertEquals ("#1", "http://a/g", new Uri (b, "/g").ToString ());
AssertEquals ("#2", "http://g/", new Uri (b, "//g").ToString ());
AssertEquals ("#3", "http://a/b/c/?y", new Uri (b, "?y").ToString ());
Assert ("#4", new Uri (b, "#s").ToString ().EndsWith ("#s"));
Uri u = new Uri (b, "/g?q=r");
AssertEquals ("#5", "http://a/g?q=r", u.ToString ());
AssertEquals ("#6", "?q=r", u.Query);
u = new Uri (b, "/g?q=r;. a");
AssertEquals ("#5", "http://a/g?q=r;. a", u.ToString ());
AssertEquals ("#6", "?q=r;.%20a", u.Query);
}
[Test]
[ExpectedException (typeof (UriFormatException))]
public void InvalidScheme ()
{
new Uri ("_:/");
}
[Test]
public void ConstructorsRejectRelativePath ()
{
string [] reluris = new string [] {
"readme.txt",
"thisdir/childdir/file",
"./testfile"
};
string [] winRelUris = new string [] {
"c:readme.txt"
};
for (int i = 0; i < reluris.Length; i++) {
try {
new Uri (reluris [i]);
Fail ("Should be failed: " + reluris [i]);
} catch (UriFormatException) {
}
}
if (isWin32) {
for (int i = 0; i < winRelUris.Length; i++) {
try {
new Uri (winRelUris [i]);
Fail ("Should be failed: " + winRelUris [i]);
} catch (UriFormatException) {
}
}
}
}
[Test]
public void LocalPath ()
{
Uri uri = new Uri ("c:\\tmp\\hello.txt");
AssertEquals ("#1a", "file:///c:/tmp/hello.txt", uri.ToString ());
AssertEquals ("#1b", "c:\\tmp\\hello.txt", uri.LocalPath);
AssertEquals ("#1c", "file", uri.Scheme);
AssertEquals ("#1d", "", uri.Host);
AssertEquals ("#1e", "c:/tmp/hello.txt", uri.AbsolutePath);
uri = new Uri ("file:////////cygwin/tmp/hello.txt");
AssertEquals ("#3a", "file://cygwin/tmp/hello.txt", uri.ToString ());
if (isWin32)
AssertEquals ("#3b win32", "\\\\cygwin\\tmp\\hello.txt", uri.LocalPath);
else
AssertEquals ("#3b *nix", "/tmp/hello.txt", uri.LocalPath);
AssertEquals ("#3c", "file", uri.Scheme);
AssertEquals ("#3d", "cygwin", uri.Host);
AssertEquals ("#3e", "/tmp/hello.txt", uri.AbsolutePath);
uri = new Uri ("file://mymachine/cygwin/tmp/hello.txt");
AssertEquals ("#4a", "file://mymachine/cygwin/tmp/hello.txt", uri.ToString ());
if (isWin32)
AssertEquals ("#4b win32", "\\\\mymachine\\cygwin\\tmp\\hello.txt", uri.LocalPath);
else
AssertEquals ("#4b *nix", "/cygwin/tmp/hello.txt", uri.LocalPath);
AssertEquals ("#4c", "file", uri.Scheme);
AssertEquals ("#4d", "mymachine", uri.Host);
AssertEquals ("#4e", "/cygwin/tmp/hello.txt", uri.AbsolutePath);
uri = new Uri ("file://///c:/cygwin/tmp/hello.txt");
AssertEquals ("#5a", "file:///c:/cygwin/tmp/hello.txt", uri.ToString ());
AssertEquals ("#5b", "c:\\cygwin\\tmp\\hello.txt", uri.LocalPath);
AssertEquals ("#5c", "file", uri.Scheme);
AssertEquals ("#5d", "", uri.Host);
AssertEquals ("#5e", "c:/cygwin/tmp/hello.txt", uri.AbsolutePath);
// Hmm, they should be regarded just as a host name, since all URIs are base on absolute path.
uri = new Uri("file://one_file.txt");
AssertEquals("#6a", "file://one_file.txt", uri.ToString());
if (isWin32)
AssertEquals("#6b", "\\\\one_file.txt", uri.LocalPath);
else
AssertEquals("#6b", "/", uri.LocalPath);
AssertEquals("#6c", "file", uri.Scheme);
AssertEquals("#6d", "one_file.txt", uri.Host);
AssertEquals("#6e", "", uri.AbsolutePath);
}
[Test]
public void UnixPath () {
if (!isWin32)
AssertEquals ("#6a", "file:///cygwin/tmp/hello.txt", new Uri ("/cygwin/tmp/hello.txt").ToString ());
}
[Test]
public void Unc ()
{
Uri uri = new Uri ("http://www.contoso.com");
Assert ("#1", !uri.IsUnc);
uri = new Uri ("news:123456@contoso.com");
Assert ("#2", !uri.IsUnc);
uri = new Uri ("file://server/filename.ext");
Assert ("#3", uri.IsUnc);
uri = new Uri (@"\\server\share\filename.ext");
Assert ("#6", uri.IsUnc);
uri = new Uri (@"a:\dir\filename.ext");
Assert ("#8", !uri.IsUnc);
}
[Test]
[Category("NotDotNet")]
public void UncFail ()
{
Uri uri = new Uri ("/home/user/dir/filename.ext");
Assert ("#7", !uri.IsUnc);
}
[Test]
public void FromHex ()
{
AssertEquals ("#1", 0, Uri.FromHex ('0'));
AssertEquals ("#2", 9, Uri.FromHex ('9'));
AssertEquals ("#3", 10, Uri.FromHex ('a'));
AssertEquals ("#4", 15, Uri.FromHex ('f'));
AssertEquals ("#5", 10, Uri.FromHex ('A'));
AssertEquals ("#6", 15, Uri.FromHex ('F'));
try {
Uri.FromHex ('G');
Fail ("#7");
} catch (ArgumentException) {}
try {
Uri.FromHex (' ');
Fail ("#8");
} catch (ArgumentException) {}
try {
Uri.FromHex ('%');
Fail ("#8");
} catch (ArgumentException) {}
}
class UriEx : Uri
{
public UriEx (string s) : base (s)
{
}
public string UnescapeString (string s)
{
return Unescape (s);
}
public static string UnescapeString (string uri, string target)
{
return new UriEx (uri).UnescapeString (target);
}
}
[Test]
public void Unescape ()
{
AssertEquals ("#1", "#", UriEx.UnescapeString ("file://localhost/c#", "%23"));
AssertEquals ("#2", "c#", UriEx.UnescapeString ("file://localhost/c#", "c%23"));
AssertEquals ("#3", "\xA9", UriEx.UnescapeString ("file://localhost/c#", "%A9"));
AssertEquals ("#1", "#", UriEx.UnescapeString ("http://localhost/c#", "%23"));
AssertEquals ("#2", "c#", UriEx.UnescapeString ("http://localhost/c#", "c%23"));
AssertEquals ("#3", "\xA9", UriEx.UnescapeString ("http://localhost/c#", "%A9"));
}
[Test]
public void HexEscape ()
{
AssertEquals ("#1","%20", Uri.HexEscape (' '));
AssertEquals ("#2","%A9", Uri.HexEscape ((char) 0xa9));
AssertEquals ("#3","%41", Uri.HexEscape ('A'));
try {
Uri.HexEscape ((char) 0x0369);
Fail ("#4");
} catch (ArgumentOutOfRangeException) {}
}
[Test]
public void HexUnescape ()
{
int i = 0;
AssertEquals ("#1", ' ', Uri.HexUnescape ("%20", ref i));
AssertEquals ("#2", 3, i);
i = 4;
AssertEquals ("#3", (char) 0xa9, Uri.HexUnescape ("test%a9test", ref i));
AssertEquals ("#4", 7, i);
AssertEquals ("#5", 't', Uri.HexUnescape ("test%a9test", ref i));
AssertEquals ("#6", 8, i);
i = 4;
AssertEquals ("#5", '%', Uri.HexUnescape ("test%a", ref i));
AssertEquals ("#6", 5, i);
AssertEquals ("#7", '%', Uri.HexUnescape ("testx%xx", ref i));
AssertEquals ("#8", 6, i);
}
[Test]
public void IsHexDigit ()
{
Assert ("#1", Uri.IsHexDigit ('a'));
Assert ("#2", Uri.IsHexDigit ('f'));
Assert ("#3", !Uri.IsHexDigit ('g'));
Assert ("#4", Uri.IsHexDigit ('0'));
Assert ("#5", Uri.IsHexDigit ('9'));
Assert ("#6", Uri.IsHexDigit ('A'));
Assert ("#7", Uri.IsHexDigit ('F'));
Assert ("#8", !Uri.IsHexDigit ('G'));
}
[Test]
public void IsHexEncoding ()
{
Assert ("#1", Uri.IsHexEncoding ("test%a9test", 4));
Assert ("#2", !Uri.IsHexEncoding ("test%a9test", 3));
Assert ("#3", Uri.IsHexEncoding ("test%a9", 4));
Assert ("#4", !Uri.IsHexEncoding ("test%a", 4));
}
[Test]
public void GetLeftPart ()
{
Uri uri = new Uri ("http://www.contoso.com/index.htm#main");
AssertEquals ("#1", "http://", uri.GetLeftPart (UriPartial.Scheme));
AssertEquals ("#2", "http://www.contoso.com", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#3", "http://www.contoso.com/index.htm", uri.GetLeftPart (UriPartial.Path));
uri = new Uri ("mailto:user@contoso.com?subject=uri");
AssertEquals ("#4", "mailto:", uri.GetLeftPart (UriPartial.Scheme));
AssertEquals ("#5", "", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#6", "mailto:user@contoso.com", uri.GetLeftPart (UriPartial.Path));
uri = new Uri ("nntp://news.contoso.com/123456@contoso.com");
AssertEquals ("#7", "nntp://", uri.GetLeftPart (UriPartial.Scheme));
AssertEquals ("#8", "nntp://news.contoso.com", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#9", "nntp://news.contoso.com/123456@contoso.com", uri.GetLeftPart (UriPartial.Path));
uri = new Uri ("news:123456@contoso.com");
AssertEquals ("#10", "news:", uri.GetLeftPart (UriPartial.Scheme));
AssertEquals ("#11", "", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#12", "news:123456@contoso.com", uri.GetLeftPart (UriPartial.Path));
uri = new Uri ("file://server/filename.ext");
AssertEquals ("#13", "file://", uri.GetLeftPart (UriPartial.Scheme));
AssertEquals ("#14", "file://server", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#15", "file://server/filename.ext", uri.GetLeftPart (UriPartial.Path));
uri = new Uri (@"\\server\share\filename.ext");
AssertEquals ("#20", "file://", uri.GetLeftPart (UriPartial.Scheme));
AssertEquals ("#21", "file://server", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#22", "file://server/share/filename.ext", uri.GetLeftPart (UriPartial.Path));
uri = new Uri ("http://www.contoso.com:8080/index.htm#main");
AssertEquals ("#23", "http://", uri.GetLeftPart (UriPartial.Scheme));
AssertEquals ("#24", "http://www.contoso.com:8080", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#25", "http://www.contoso.com:8080/index.htm", uri.GetLeftPart (UriPartial.Path));
}
[Test]
public void NewsDefaultPort ()
{
Uri uri = new Uri("news://localhost:119/");
AssertEquals ("#1", uri.IsDefaultPort, true);
}
[Test]
public void FragmentEscape ()
{
Uri u = new Uri("http://localhost/index.asp#main#start", false);
AssertEquals ("#1", u.Fragment, "#main%23start");
u = new Uri("http://localhost/index.asp#main#start", true);
AssertEquals ("#2", u.Fragment, "#main#start");
// The other code path uses a BaseUri
Uri b = new Uri ("http://www.gnome.org");
Uri n = new Uri (b, "blah#main#start");
AssertEquals ("#3", n.Fragment, "#main%23start");
n = new Uri (b, "blah#main#start", true);
AssertEquals ("#3", n.Fragment, "#main#start");
}
[Test]
[ExpectedException(typeof(UriFormatException))]
public void IncompleteSchemeDelimiter ()
{
new Uri ("file:/filename.ext");
}
[Test]
[Category("NotDotNet")]
public void CheckHostName1 ()
{
// reported to MSDN Product Feedback Center (FDBK28671)
AssertEquals ("#36 known to fail with ms.net: this is not a valid IPv6 address.", UriHostNameType.Unknown, Uri.CheckHostName (":11:22:33:44:55:66:77:88"));
}
[Test]
public void CheckHostName2 ()
{
AssertEquals ("#1", UriHostNameType.Unknown, Uri.CheckHostName (null));
AssertEquals ("#2", UriHostNameType.Unknown, Uri.CheckHostName (""));
AssertEquals ("#3", UriHostNameType.Unknown, Uri.CheckHostName ("^&()~`!@"));
AssertEquals ("#4", UriHostNameType.Dns, Uri.CheckHostName ("x"));
AssertEquals ("#5", UriHostNameType.IPv4, Uri.CheckHostName ("1.2.3.4"));
AssertEquals ("#6", UriHostNameType.IPv4, Uri.CheckHostName ("0001.002.03.4"));
AssertEquals ("#7", UriHostNameType.Dns, Uri.CheckHostName ("0001.002.03.256"));
AssertEquals ("#8", UriHostNameType.Dns, Uri.CheckHostName ("9001.002.03.4"));
AssertEquals ("#9", UriHostNameType.Dns, Uri.CheckHostName ("www.contoso.com"));
AssertEquals ("#10", UriHostNameType.Unknown, Uri.CheckHostName (".www.contoso.com"));
AssertEquals ("#11", UriHostNameType.Dns, Uri.CheckHostName ("www.contoso.com."));
AssertEquals ("#12", UriHostNameType.Dns, Uri.CheckHostName ("www.con-toso.com"));
AssertEquals ("#13", UriHostNameType.Dns, Uri.CheckHostName ("www.con_toso.com"));
AssertEquals ("#14", UriHostNameType.Unknown, Uri.CheckHostName ("www.con,toso.com"));
// test IPv6
AssertEquals ("#15", UriHostNameType.IPv6, Uri.CheckHostName ("11:22:33:44:55:66:77:88"));
AssertEquals ("#16", UriHostNameType.IPv6, Uri.CheckHostName ("11::33:44:55:66:77:88"));
AssertEquals ("#17", UriHostNameType.IPv6, Uri.CheckHostName ("::22:33:44:55:66:77:88"));
AssertEquals ("#18", UriHostNameType.IPv6, Uri.CheckHostName ("11:22:33:44:55:66:77::"));
AssertEquals ("#19", UriHostNameType.IPv6, Uri.CheckHostName ("11::88"));
AssertEquals ("#20", UriHostNameType.IPv6, Uri.CheckHostName ("11::77:88"));
AssertEquals ("#21", UriHostNameType.IPv6, Uri.CheckHostName ("11:22::88"));
AssertEquals ("#22", UriHostNameType.IPv6, Uri.CheckHostName ("11::"));
AssertEquals ("#23", UriHostNameType.IPv6, Uri.CheckHostName ("::88"));
AssertEquals ("#24", UriHostNameType.IPv6, Uri.CheckHostName ("::1"));
AssertEquals ("#25", UriHostNameType.IPv6, Uri.CheckHostName ("::"));
AssertEquals ("#26", UriHostNameType.IPv6, Uri.CheckHostName ("0:0:0:0:0:0:127.0.0.1"));
AssertEquals ("#27", UriHostNameType.IPv6, Uri.CheckHostName ("::127.0.0.1"));
AssertEquals ("#28", UriHostNameType.IPv6, Uri.CheckHostName ("::ffFF:169.32.14.5"));
AssertEquals ("#29", UriHostNameType.IPv6, Uri.CheckHostName ("2001:03A0::/35"));
AssertEquals ("#30", UriHostNameType.IPv6, Uri.CheckHostName ("[2001:03A0::/35]"));
AssertEquals ("#33", UriHostNameType.IPv6, Uri.CheckHostName ("2001::03A0:1.2.3.4"));
AssertEquals ("#31", UriHostNameType.Unknown, Uri.CheckHostName ("2001::03A0::/35"));
AssertEquals ("#32", UriHostNameType.Unknown, Uri.CheckHostName ("2001:03A0::/35a"));
AssertEquals ("#34", UriHostNameType.Unknown, Uri.CheckHostName ("::ffff:123.256.155.43"));
AssertEquals ("#35", UriHostNameType.Unknown, Uri.CheckHostName (":127.0.0.1"));
AssertEquals ("#37", UriHostNameType.Unknown, Uri.CheckHostName ("::11:22:33:44:55:66:77:88"));
AssertEquals ("#38", UriHostNameType.Unknown, Uri.CheckHostName ("11:22:33:44:55:66:77:88::"));
AssertEquals ("#39", UriHostNameType.Unknown, Uri.CheckHostName ("11:22:33:44:55:66:77:88:"));
AssertEquals ("#40", UriHostNameType.Unknown, Uri.CheckHostName ("::acbde"));
AssertEquals ("#41", UriHostNameType.Unknown, Uri.CheckHostName ("::abce:"));
AssertEquals ("#42", UriHostNameType.Unknown, Uri.CheckHostName ("::abcg"));
AssertEquals ("#43", UriHostNameType.Unknown, Uri.CheckHostName (":::"));
AssertEquals ("#44", UriHostNameType.Unknown, Uri.CheckHostName (":"));
}
[Test]
public void IsLoopback ()
{
Uri uri = new Uri("http://loopback:8080");
AssertEquals ("#1", true, uri.IsLoopback);
uri = new Uri("http://localhost:8080");
AssertEquals ("#2", true, uri.IsLoopback);
uri = new Uri("http://127.0.0.1:8080");
AssertEquals ("#3", true, uri.IsLoopback);
uri = new Uri("http://127.0.0.001:8080");
AssertEquals ("#4", true, uri.IsLoopback);
uri = new Uri("http://[::1]");
AssertEquals ("#5", true, uri.IsLoopback);
uri = new Uri("http://[::1]:8080");
AssertEquals ("#6", true, uri.IsLoopback);
uri = new Uri("http://[::0001]:8080");
AssertEquals ("#7", true, uri.IsLoopback);
uri = new Uri("http://[0:0:0:0::1]:8080");
AssertEquals ("#8", true, uri.IsLoopback);
uri = new Uri("http://[0:0:0:0::127.0.0.1]:8080");
AssertEquals ("#9", true, uri.IsLoopback);
uri = new Uri("http://[0:0:0:0::127.11.22.33]:8080");
AssertEquals ("#10", false, uri.IsLoopback);
uri = new Uri("http://[::ffff:127.11.22.33]:8080");
AssertEquals ("#11", false, uri.IsLoopback);
uri = new Uri("http://[::ff00:7f11:2233]:8080");
AssertEquals ("#12", false, uri.IsLoopback);
uri = new Uri("http://[1:0:0:0::1]:8080");
AssertEquals ("#13", false, uri.IsLoopback);
}
[Test]
public void Equals1 ()
{
Uri uri1 = new Uri ("http://www.contoso.com/index.htm#main");
Uri uri2 = new Uri ("http://www.contoso.com/index.htm#fragment");
Assert ("#1", uri1.Equals (uri2));
Assert ("#3", !uri2.Equals ("http://www.contoso.com/index.html?x=1"));
Assert ("#4", !uri1.Equals ("http://www.contoso.com:8080/index.htm?x=1"));
}
[Test]
#if !NET_2_0
[Category("NotDotNet")]
#endif
public void Equals2 ()
{
Uri uri1 = new Uri ("http://www.contoso.com/index.htm#main");
Uri uri2 = new Uri ("http://www.contoso.com/index.htm?x=1");
Assert ("#2 known to fail with ms.net 1.x", !uri1.Equals (uri2));
}
[Test]
public void TestEquals2 ()
{
Uri a = new Uri ("http://www.go-mono.com");
Uri b = new Uri ("http://www.go-mono.com");
AssertEquals ("#1", a, b);
a = new Uri ("mailto:user:pwd@go-mono.com?subject=uri");
b = new Uri ("MAILTO:USER:PWD@GO-MONO.COM?SUBJECT=URI");
AssertEquals ("#2", a, b);
a = new Uri ("http://www.go-mono.com/ports/");
b = new Uri ("http://www.go-mono.com/PORTS/");
Assert ("#3", !a.Equals (b));
}
[Test]
public void GetHashCodeTest ()
{
Uri uri1 = new Uri ("http://www.contoso.com/index.htm#main");
Uri uri2 = new Uri ("http://www.contoso.com/index.htm#fragment");
AssertEquals ("#1", uri1.GetHashCode (), uri2.GetHashCode ());
uri2 = new Uri ("http://www.contoso.com/index.htm?x=1");
Assert ("#2", uri1.GetHashCode () != uri2.GetHashCode ());
uri2 = new Uri ("http://www.contoso.com:80/index.htm");
AssertEquals ("#3", uri1.GetHashCode (), uri2.GetHashCode ());
uri2 = new Uri ("http://www.contoso.com:8080/index.htm");
Assert ("#4", uri1.GetHashCode () != uri2.GetHashCode ());
}
[Test]
public void MakeRelative ()
{
Uri uri1 = new Uri ("http://www.contoso.com/index.htm?x=2");
Uri uri2 = new Uri ("http://www.contoso.com/foo/bar/index.htm#fragment");
Uri uri3 = new Uri ("http://www.contoso.com/bar/foo/index.htm?y=1");
Uri uri4 = new Uri ("http://www.contoso.com/bar/foo2/index.htm?x=0");
Uri uri5 = new Uri ("https://www.contoso.com/bar/foo/index.htm?y=1");
Uri uri6 = new Uri ("http://www.contoso2.com/bar/foo/index.htm?x=0");
Uri uri7 = new Uri ("http://www.contoso2.com/bar/foo/foobar.htm?z=0&y=5");
Uri uri8 = new Uri ("http://www.xxx.com/bar/foo/foobar.htm?z=0&y=5" + (char) 0xa9);
AssertEquals ("#1", "foo/bar/index.htm", uri1.MakeRelative (uri2));
AssertEquals ("#2", "../../index.htm", uri2.MakeRelative (uri1));
AssertEquals ("#3", "../../bar/foo/index.htm", uri2.MakeRelative (uri3));
AssertEquals ("#4", "../../foo/bar/index.htm", uri3.MakeRelative (uri2));
AssertEquals ("#5", "../foo2/index.htm", uri3.MakeRelative (uri4));
AssertEquals ("#6", "../foo/index.htm", uri4.MakeRelative (uri3));
AssertEquals ("#7", "https://www.contoso.com/bar/foo/index.htm?y=1",
uri4.MakeRelative (uri5));
AssertEquals ("#8", "http://www.contoso2.com/bar/foo/index.htm?x=0",
uri4.MakeRelative (uri6));
AssertEquals ("#9", "", uri6.MakeRelative (uri6));
AssertEquals ("#10", "foobar.htm", uri6.MakeRelative (uri7));
Uri uri10 = new Uri ("mailto:xxx@xxx.com");
Uri uri11 = new Uri ("mailto:xxx@xxx.com?subject=hola");
AssertEquals ("#11", "", uri10.MakeRelative (uri11));
Uri uri12 = new Uri ("mailto:xxx@mail.xxx.com?subject=hola");
AssertEquals ("#12", "mailto:xxx@mail.xxx.com?subject=hola", uri10.MakeRelative (uri12));
Uri uri13 = new Uri ("mailto:xxx@xxx.com/foo/bar");
AssertEquals ("#13", "/foo/bar", uri10.MakeRelative (uri13));
AssertEquals ("#14", "http://www.xxx.com/bar/foo/foobar.htm?z=0&y=5" + (char) 0xa9, uri1.MakeRelative (uri8));
}
[Test]
public void ToStringTest()
{
Uri uri = new Uri ("dummy://xxx");
AssertEquals ("#1", "dummy://xxx/", uri.ToString ());
}
[Test]
public void CheckSchemeName ()
{
AssertEquals ("#01", false, Uri.CheckSchemeName (null));
AssertEquals ("#02", false, Uri.CheckSchemeName (""));
AssertEquals ("#03", true, Uri.CheckSchemeName ("http"));
AssertEquals ("#04", true, Uri.CheckSchemeName ("http-"));
AssertEquals ("#05", false, Uri.CheckSchemeName ("6http-"));
AssertEquals ("#06", true, Uri.CheckSchemeName ("http6-"));
AssertEquals ("#07", false, Uri.CheckSchemeName ("http6,"));
AssertEquals ("#08", true, Uri.CheckSchemeName ("http6."));
AssertEquals ("#09", false, Uri.CheckSchemeName ("+http"));
AssertEquals ("#10", true, Uri.CheckSchemeName ("htt+p6"));
// 0x00E1 -> ã
AssertEquals ("#11", true, Uri.CheckSchemeName ("htt\u00E1+p6"));
}
[Test]
[ExpectedException (typeof (UriFormatException))]
public void NoHostname ()
{
Uri uri = new Uri ("http://");
}
[Test]
#if !NET_2_0
// MS.NET 1.x throws an IndexOutOfRangeException
[Category("NotDotNet")]
#endif
[Ignore("Bug #74144")]
public void NoHostname2 ()
{
Uri uri = new Uri ("file://");
AssertEquals ("#1", true, uri.IsFile);
AssertEquals ("#2", false, uri.IsUnc);
AssertEquals ("#3", "file", uri.Scheme);
AssertEquals ("#4", "/", uri.LocalPath);
AssertEquals ("#5", string.Empty, uri.Query);
AssertEquals ("#6", "/", uri.AbsolutePath);
AssertEquals ("#7", "file:///", uri.AbsoluteUri);
AssertEquals ("#8", string.Empty, uri.Authority);
AssertEquals ("#9", string.Empty, uri.Host);
AssertEquals ("#10", UriHostNameType.Basic, uri.HostNameType);
AssertEquals ("#11", string.Empty, uri.Fragment);
AssertEquals ("#12", true, uri.IsDefaultPort);
AssertEquals ("#13", true, uri.IsLoopback);
AssertEquals ("#14", "/", uri.PathAndQuery);
AssertEquals ("#15", false, uri.UserEscaped);
AssertEquals ("#16", string.Empty, uri.UserInfo);
AssertEquals ("#17", "file://", uri.GetLeftPart (UriPartial.Authority));
AssertEquals ("#18", "file:///", uri.GetLeftPart (UriPartial.Path));
AssertEquals ("#19", "file://", uri.GetLeftPart (UriPartial.Scheme));
}
[Test]
public void Segments1 ()
{
Uri uri = new Uri ("http://localhost/");
string [] segments = uri.Segments;
AssertEquals ("#01", 1, segments.Length);
AssertEquals ("#02", "/", segments [0]);
}
[Test]
public void Segments2 ()
{
Uri uri = new Uri ("http://localhost/dir/dummypage.html");
string [] segments = uri.Segments;
AssertEquals ("#01", 3, segments.Length);
AssertEquals ("#02", "/", segments [0]);
AssertEquals ("#03", "dir/", segments [1]);
AssertEquals ("#04", "dummypage.html", segments [2]);
}
[Test]
public void Segments3 ()
{
Uri uri = new Uri ("http://localhost/dir/dummypage/");
string [] segments = uri.Segments;
AssertEquals ("#01", 3, segments.Length);
AssertEquals ("#02", "/", segments [0]);
AssertEquals ("#03", "dir/", segments [1]);
AssertEquals ("#04", "dummypage/", segments [2]);
}
[Test]
public void Segments4 ()
{
Uri uri = new Uri ("file:///c:/hello");
string [] segments = uri.Segments;
AssertEquals ("#01", 3, segments.Length);
AssertEquals ("#02", "c:", segments [0]);
AssertEquals ("#03", "/", segments [1]);
AssertEquals ("#04", "hello", segments [2]);
}
[Test]
public void Segments5 ()
{
Uri uri = new Uri ("http://www.xxx.com/bar/foo/foobar.htm?z=0&y=5" + (char) 0xa9);
string [] segments = uri.Segments;
AssertEquals ("#01", 4, segments.Length);
AssertEquals ("#02", "/", segments [0]);
AssertEquals ("#03", "bar/", segments [1]);
AssertEquals ("#04", "foo/", segments [2]);
AssertEquals ("#05", "foobar.htm", segments [3]);
}
[Test]
[ExpectedException (typeof (UriFormatException))]
public void UriStartingWithColon()
{
new Uri("://");
}
[Test]
[ExpectedException (typeof (UriFormatException))]
public void EmptyScheme ()
{
new Uri ("hey");
}
[Test]
public void InvalidPortsThatWorkWithMS ()
{
new Uri ("http://www.contoso.com:12345678/foo/bar/");
// UInt32.MaxValue gives port == -1 !!!
new Uri ("http://www.contoso.com:4294967295/foo/bar/");
// ((uint) Int32.MaxValue + (uint) 1) gives port == -2147483648 !!!
new Uri ("http://www.contoso.com:2147483648/foo/bar/");
}
class UriEx2 : Uri
{
public UriEx2 (string s) : base (s)
{
}
protected override void Parse ()
{
}
}
[Test]
public void ParseOverride ()
{
// If this does not override base's Parse(), it will
// fail since this argument is not Absolute URI.
UriEx2 ex = new UriEx2 ("readme.txt");
}
[Test]
public void UnixLocalPath ()
{
// This works--the location is not part of the absolute path
string path = "file://localhost/tmp/foo/bar";
Uri fileUri = new Uri( path );
AssertEquals (path, "/tmp/foo/bar", fileUri.AbsolutePath);
// Empty path == localhost, in theory
path = "file:///c:/tmp/foo/bar";
fileUri = new Uri( path );
AssertEquals (path, "c:/tmp/foo/bar", fileUri.AbsolutePath);
}
// This test doesn't work on Linux, and arguably shouldn't work.
// new Uri("file:///tmp/foo/bar").AbsolutePath returns "/tmp/foo/bar"
// on Linux, as anyone sane would expect. It *doesn't* under .NET 1.1
// Apparently "tmp" is supposed to be a hostname (!)...
// Since "correct" behavior would confuse all Linux developers, and having
// an expected failure is evil, we'll just ignore this for now...
//
// Furthermore, Microsoft fixed this so it behaves sensibly in .NET 2.0.
//
// You are surrounded by conditional-compilation code, all alike.
// You are likely to be eaten by a Grue...
[Test]
#if ONLY_1_1
[Category ("NotWorking")]
#endif
public void UnixLocalPath_WTF ()
{
// Empty path == localhost, in theory
string path = "file:///tmp/foo/bar";
Uri fileUri = new Uri( path );
#if NET_2_0
AssertEquals (path, "/tmp/foo/bar", fileUri.AbsolutePath);
#else
AssertEquals (path, "/foo/bar", fileUri.AbsolutePath);
#endif
}
public static void Print (Uri uri)
{
Console.WriteLine ("ToString: " + uri.ToString ());
Console.WriteLine ("AbsolutePath: " + uri.AbsolutePath);
Console.WriteLine ("AbsoluteUri: " + uri.AbsoluteUri);
Console.WriteLine ("Authority: " + uri.Authority);
Console.WriteLine ("Fragment: " + uri.Fragment);
Console.WriteLine ("Host: " + uri.Host);
Console.WriteLine ("HostNameType: " + uri.HostNameType);
Console.WriteLine ("IsDefaultPort: " + uri.IsDefaultPort);
Console.WriteLine ("IsFile: " + uri.IsFile);
Console.WriteLine ("IsLoopback: " + uri.IsLoopback);
Console.WriteLine ("IsUnc: " + uri.IsUnc);
Console.WriteLine ("LocalPath: " + uri.LocalPath);
Console.WriteLine ("PathAndQuery: " + uri.PathAndQuery);
Console.WriteLine ("Port: " + uri.Port);
Console.WriteLine ("Query: " + uri.Query);
Console.WriteLine ("Scheme: " + uri.Scheme);
Console.WriteLine ("UserEscaped: " + uri.UserEscaped);
Console.WriteLine ("UserInfo: " + uri.UserInfo);
Console.WriteLine ("Segments:");
string [] segments = uri.Segments;
if (segments == null)
Console.WriteLine ("\tNo Segments");
else
for (int i = 0; i < segments.Length; i++)
Console.WriteLine ("\t" + segments[i]);
Console.WriteLine ("");
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoad.DataAccess;
using SelfLoad.DataAccess.ERCLevel;
namespace SelfLoad.Business.ERCLevel
{
/// <summary>
/// D03_Continent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="D03_Continent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="D02_Continent"/> collection.
/// </remarks>
[Serializable]
public partial class D03_Continent_ReChild : BusinessBase<D03_Continent_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Continent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name");
/// <summary>
/// Gets or sets the SubContinents Child Name.
/// </summary>
/// <value>The SubContinents Child Name.</value>
public string Continent_Child_Name
{
get { return GetProperty(Continent_Child_NameProperty); }
set { SetProperty(Continent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="D03_Continent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="D03_Continent_ReChild"/> object.</returns>
internal static D03_Continent_ReChild NewD03_Continent_ReChild()
{
return DataPortal.CreateChild<D03_Continent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="D03_Continent_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="continent_ID2">The Continent_ID2 parameter of the D03_Continent_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="D03_Continent_ReChild"/> object.</returns>
internal static D03_Continent_ReChild GetD03_Continent_ReChild(int continent_ID2)
{
return DataPortal.FetchChild<D03_Continent_ReChild>(continent_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="D03_Continent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public D03_Continent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="D03_Continent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="D03_Continent_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="continent_ID2">The Continent ID2.</param>
protected void Child_Fetch(int continent_ID2)
{
var args = new DataPortalHookArgs(continent_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var dal = dalManager.GetProvider<ID03_Continent_ReChildDal>();
var data = dal.Fetch(continent_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="D03_Continent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="D03_Continent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(D02_Continent parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<ID03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Continent_ID,
Continent_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="D03_Continent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(D02_Continent parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<ID03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Continent_ID,
Continent_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="D03_Continent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(D02_Continent parent)
{
using (var dalManager = DalFactorySelfLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<ID03_Continent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Continent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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 System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Authentication;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Communications.Local;
using System.Threading.Tasks;
namespace OpenSim.Region.Communications.OGS1
{
public class OGS1GridServices : IGridServices
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_useRemoteRegionCache = true;
/// <summary>
/// Encapsulate local backend services for manipulation of local regions
/// </summary>
private LocalBackEndServices m_localBackend = new LocalBackEndServices();
struct RegionInfoCacheEntry
{
public RegionInfo Info;
public DateTime CachedTime;
public bool Exists;
}
private Dictionary<ulong, RegionInfoCacheEntry> m_remoteRegionInfoCache = new Dictionary<ulong, RegionInfoCacheEntry>();
private Dictionary<string, string> m_queuedGridSettings = new Dictionary<string, string>();
private List<RegionInfo> m_regionsOnInstance = new List<RegionInfo>();
public BaseHttpServer httpListener;
public NetworkServersInfo serversInfo;
public BaseHttpServer httpServer;
public string gdebugRegionName
{
get { return m_localBackend.gdebugRegionName; }
set { m_localBackend.gdebugRegionName = value; }
}
public string rdebugRegionName
{
get { return _rdebugRegionName; }
set { _rdebugRegionName = value; }
}
private string _rdebugRegionName = String.Empty;
public bool RegionLoginsEnabled
{
get { return m_localBackend.RegionLoginsEnabled; }
set { m_localBackend.RegionLoginsEnabled = value; }
}
/// <summary>
/// Contructor. Adds "expect_user" and "check" xmlrpc method handlers
/// </summary>
/// <param name="servers_info"></param>
/// <param name="httpServe"></param>
public OGS1GridServices(NetworkServersInfo servers_info, BaseHttpServer httpServe)
{
serversInfo = servers_info;
httpServer = httpServe;
//Respond to Grid Services requests
httpServer.AddXmlRPCHandler("check", PingCheckReply);
httpServer.AddXmlRPCHandler("land_data", LandData);
// New Style
httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("check"), PingCheckReply));
httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("land_data"), LandData));
}
// see IGridServices
public RegionCommsListener RegisterRegion(RegionInfo regionInfo)
{
if (m_regionsOnInstance.Contains(regionInfo))
{
m_log.Debug("[OGS1 GRID SERVICES]: Error - region already registered " + regionInfo.RegionName);
Exception e = new Exception(String.Format("Unable to register region"));
throw e;
}
m_regionsOnInstance.Add(regionInfo);
m_log.InfoFormat(
"[OGS1 GRID SERVICES]: Attempting to register region {0} with grid at {1}",
regionInfo.RegionName, serversInfo.GridURL);
Hashtable GridParams = new Hashtable();
// Login / Authentication
GridParams["authkey"] = serversInfo.GridSendKey;
GridParams["recvkey"] = serversInfo.GridRecvKey;
GridParams["UUID"] = regionInfo.RegionID.ToString();
GridParams["sim_ip"] = regionInfo.ExternalHostName;
GridParams["sim_port"] = regionInfo.InternalEndPoint.Port.ToString();
GridParams["region_locx"] = regionInfo.RegionLocX.ToString();
GridParams["region_locy"] = regionInfo.RegionLocY.ToString();
GridParams["sim_name"] = regionInfo.RegionName;
GridParams["http_port"] = serversInfo.HttpListenerPort.ToString();
GridParams["remoting_port"] = ConfigSettings.DefaultRegionRemotingPort.ToString();
GridParams["map-image-id"] = regionInfo.RegionSettings.TerrainImageID.ToString();
GridParams["originUUID"] = regionInfo.originRegionID.ToString();
GridParams["region_secret"] = regionInfo.regionSecret;
GridParams["major_interface_version"] = VersionInfo.MajorInterfaceVersion.ToString();
if (regionInfo.MasterAvatarAssignedUUID != UUID.Zero)
GridParams["master_avatar_uuid"] = regionInfo.MasterAvatarAssignedUUID.ToString();
else
GridParams["master_avatar_uuid"] = regionInfo.EstateSettings.EstateOwner.ToString();
GridParams["maturity"] = regionInfo.RegionSettings.Maturity.ToString();
GridParams["product"] = Convert.ToInt32(regionInfo.Product).ToString();
if (regionInfo.OutsideIP != null) GridParams["outside_ip"] = regionInfo.OutsideIP;
// Package into an XMLRPC Request
ArrayList SendParams = new ArrayList();
SendParams.Add(GridParams);
// Send Request
string methodName = "simulator_login";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp;
try
{
// The timeout should always be significantly larger than the timeout for the grid server to request
// the initial status of the region before confirming registration.
GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 90000);
}
catch (Exception e)
{
Exception e2
= new Exception(
String.Format(
"Unable to register region with grid at {0}. Grid service not running?",
serversInfo.GridURL),
e);
throw e2;
}
Hashtable GridRespData = (Hashtable)GridResp.Value;
// Hashtable griddatahash = GridRespData;
// Process Response
if (GridRespData.ContainsKey("error"))
{
string errorstring = (string) GridRespData["error"];
Exception e = new Exception(
String.Format("Unable to connect to grid at {0}: {1}", serversInfo.GridURL, errorstring));
throw e;
}
else
{
// m_knownRegions = RequestNeighbours(regionInfo.RegionLocX, regionInfo.RegionLocY);
if (GridRespData.ContainsKey("allow_forceful_banlines"))
{
if ((string) GridRespData["allow_forceful_banlines"] != "TRUE")
{
//m_localBackend.SetForcefulBanlistsDisallowed(regionInfo.RegionHandle);
if (!m_queuedGridSettings.ContainsKey("allow_forceful_banlines"))
m_queuedGridSettings.Add("allow_forceful_banlines", "FALSE");
}
}
m_log.InfoFormat(
"[OGS1 GRID SERVICES]: Region {0} successfully registered with grid at {1}",
regionInfo.RegionName, serversInfo.GridURL);
}
return m_localBackend.RegisterRegion(regionInfo);
}
// see IGridServices
public bool DeregisterRegion(RegionInfo regionInfo)
{
Hashtable GridParams = new Hashtable();
GridParams["UUID"] = regionInfo.RegionID.ToString();
// Package into an XMLRPC Request
ArrayList SendParams = new ArrayList();
SendParams.Add(GridParams);
// Send Request
string methodName = "simulator_after_region_moved";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = null;
try
{
GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
}
catch (Exception e)
{
Exception e2
= new Exception(
String.Format(
"Unable to deregister region with grid at {0}. Grid service not running?",
serversInfo.GridURL),
e);
throw e2;
}
Hashtable GridRespData = (Hashtable) GridResp.Value;
// Hashtable griddatahash = GridRespData;
// Process Response
if (GridRespData != null && GridRespData.ContainsKey("error"))
{
string errorstring = (string)GridRespData["error"];
m_log.Error("Unable to connect to grid: " + errorstring);
return false;
}
return m_localBackend.DeregisterRegion(regionInfo);
}
public virtual Dictionary<string, string> GetGridSettings()
{
Dictionary<string, string> returnGridSettings = new Dictionary<string, string>();
lock (m_queuedGridSettings)
{
foreach (string Dictkey in m_queuedGridSettings.Keys)
{
returnGridSettings.Add(Dictkey, m_queuedGridSettings[Dictkey]);
}
m_queuedGridSettings.Clear();
}
return returnGridSettings;
}
// see IGridServices
public List<SimpleRegionInfo> RequestNeighbours(uint x, uint y)
{
Hashtable respData = MapBlockQuery((int) x - 1, (int) y - 1, (int) x + 1, (int) y + 1);
return ExtractRegionInfoFromMapBlockQuery(x, y, respData);
}
private static List<SimpleRegionInfo> ExtractRegionInfoFromMapBlockQuery(uint x, uint y, Hashtable respData)
{
List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
foreach (ArrayList neighboursList in respData.Values)
{
foreach (Hashtable neighbourData in neighboursList)
{
uint regX = Convert.ToUInt32(neighbourData["x"]);
uint regY = Convert.ToUInt32(neighbourData["y"]);
if ((x != regX) || (y != regY))
{
string simIp = (string)neighbourData["sim_ip"];
uint port = Convert.ToUInt32(neighbourData["sim_port"]);
SimpleRegionInfo sri = new SimpleRegionInfo(regX, regY, simIp, port);
sri.RegionID = new UUID((string)neighbourData["uuid"]);
sri.RemotingPort = Convert.ToUInt32(neighbourData["remoting_port"]);
if (neighbourData.ContainsKey("http_port"))
{
sri.HttpPort = Convert.ToUInt32(neighbourData["http_port"]);
}
if (neighbourData.ContainsKey("outside_ip"))
{
sri.OutsideIP = (string)neighbourData["outside_ip"];
}
neighbours.Add(sri);
}
}
}
return neighbours;
}
// More efficient call to see if there is a neighbour there, than fetching all neighbours and DNS lookups
// Return true if region at (x,y) has (nx,ny) as a neighbour.
public bool HasNeighbour(uint x, uint y, uint nx, uint ny)
{
Hashtable respData = MapBlockQuery((int)x - 1, (int)y - 1, (int)x + 1, (int)y + 1);
foreach (ArrayList neighboursList in respData.Values)
{
foreach (Hashtable neighbourData in neighboursList)
{
uint regX = Convert.ToUInt32(neighbourData["x"]);
uint regY = Convert.ToUInt32(neighbourData["y"]);
if ((nx == regX) && (ny == regY))
return true;
}
}
return false;
}
/// <summary>
/// Request information about a region.
/// </summary>
/// <param name="regionHandle"></param>
/// <returns>
/// null on a failure to contact or get a response from the grid server
/// FIXME: Might be nicer to return a proper exception here since we could inform the client more about the
/// nature of the faiulre.
/// </returns>
public RegionInfo RequestNeighbourInfo(UUID Region_UUID)
{
// don't ask the gridserver about regions on this instance...
foreach (RegionInfo info in m_regionsOnInstance)
{
if (info.RegionID == Region_UUID) return info;
}
// didn't find it so far, we have to go the long way
RegionInfo regionInfo;
Hashtable requestData = new Hashtable();
requestData["region_UUID"] = Region_UUID.ToString();
requestData["authkey"] = serversInfo.GridSendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
string methodName = "simulator_data_request";
XmlRpcRequest gridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse gridResp = null;
try
{
gridResp = gridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[OGS1 GRID SERVICES]: Communication with the grid server at {0} failed, {1}",
serversInfo.GridURL, e);
return null;
}
Hashtable responseData = (Hashtable)gridResp.Value;
if (responseData.ContainsKey("error"))
{
// this happens all the time normally and pollutes the log
// m_log.WarnFormat("[OGS1 GRID SERVICES]: Error received from grid server: {0}", responseData["error"]);
if (m_useRemoteRegionCache)
{
RegionInfoCacheEntry cacheEntry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = null,
Exists = false
};
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[Convert.ToUInt64((string)requestData["regionHandle"])] = cacheEntry;
}
}
return null;
}
regionInfo = buildRegionInfo(responseData, String.Empty);
if ((m_useRemoteRegionCache) && (requestData.ContainsKey("regionHandle")))
{
RegionInfoCacheEntry cacheEntry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = regionInfo,
Exists = true
};
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[Convert.ToUInt64((string)requestData["regionHandle"])] = cacheEntry;
}
}
return regionInfo;
}
/// <summary>
/// Request information about a region.
/// </summary>
/// <param name="regionHandle"></param>
/// <returns></returns>
public RegionInfo RequestNeighbourInfo(ulong regionHandle)
{
RegionInfo regionInfo = m_localBackend.RequestNeighbourInfo(regionHandle);
if (regionInfo != null)
{
return regionInfo;
}
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
RegionInfoCacheEntry entry;
if (m_remoteRegionInfoCache.TryGetValue(regionHandle, out entry))
{
if (DateTime.Now - entry.CachedTime < TimeSpan.FromMinutes(15.0))
{
if (entry.Exists)
{
return entry.Info;
}
else
{
return null;
}
}
else
{
m_remoteRegionInfoCache.Remove(regionHandle);
}
}
}
}
try
{
Hashtable requestData = new Hashtable();
requestData["region_handle"] = regionHandle.ToString();
requestData["authkey"] = serversInfo.GridSendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
string methodName = "simulator_data_request";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);
Hashtable responseData = (Hashtable) GridResp.Value;
if (responseData.ContainsKey("error"))
{
m_log.Error("[OGS1 GRID SERVICES]: Error received from grid server: " + responseData["error"]);
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
if (!m_remoteRegionInfoCache.ContainsKey(regionHandle))
{
RegionInfoCacheEntry entry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = null,
Exists = false
};
m_remoteRegionInfoCache[regionHandle] = entry;
}
}
}
return null;
}
uint regX = Convert.ToUInt32((string) responseData["region_locx"]);
uint regY = Convert.ToUInt32((string) responseData["region_locy"]);
string externalHostName = (string) responseData["sim_ip"];
uint simPort = Convert.ToUInt32(responseData["sim_port"]);
string regionName = (string)responseData["region_name"];
UUID regionID = new UUID((string)responseData["region_UUID"]);
uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
uint httpPort = 9000;
if (responseData.ContainsKey("http_port"))
{
httpPort = Convert.ToUInt32((string)responseData["http_port"]);
}
string outsideIp = null;
if (responseData.ContainsKey("outside_ip"))
outsideIp = (string)responseData["outside_ip"];
//IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(internalIpStr), (int) port);
regionInfo = RegionInfo.Create(regionID, regionName, regX, regY, externalHostName, httpPort, simPort, remotingPort, outsideIp);
if (requestData.ContainsKey("product"))
regionInfo.Product = (ProductRulesUse)Convert.ToInt32(requestData["product"]);
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
if (!m_remoteRegionInfoCache.ContainsKey(regionHandle))
{
RegionInfoCacheEntry entry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = regionInfo,
Exists = true
};
m_remoteRegionInfoCache[regionHandle] = entry;
}
}
}
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: " +
"Region lookup failed for: " + regionHandle.ToString() +
" - Is the GridServer down?" + e.ToString());
return null;
}
return regionInfo;
}
/// <summary>
/// Get information about a neighbouring region
/// </summary>
/// <param name="regionHandle"></param>
/// <returns></returns>
public RegionInfo RequestNeighbourInfo(string name)
{
// Not implemented yet
return null;
}
public RegionInfo RequestClosestRegion(string regionName)
{
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
foreach (RegionInfoCacheEntry ri in m_remoteRegionInfoCache.Values)
{
if (ri.Exists && ri.Info != null)
if (ri.Info.RegionName == regionName)
return ri.Info; // .Info is not valid if Exists is false
}
}
}
RegionInfo regionInfo = null;
try
{
Hashtable requestData = new Hashtable();
requestData["region_name_search"] = regionName;
requestData["authkey"] = serversInfo.GridSendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
string methodName = "simulator_data_request";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);
Hashtable responseData = (Hashtable) GridResp.Value;
if (responseData.ContainsKey("error"))
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: Error received from grid server: ", responseData["error"]);
#if NEEDS_REPLACEMENT
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[regionInfo.RegionHandle] = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = null,
Exists = false
};
}
#endif
return null;
}
regionInfo = buildRegionInfo(responseData, String.Empty);
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[regionInfo.RegionHandle] = new RegionInfoCacheEntry {
CachedTime = DateTime.Now,
Exists = true,
Info = regionInfo
};
}
}
}
catch
{
m_log.Error("[OGS1 GRID SERVICES]: " +
"Region lookup failed for: " + regionName +
" - Is the GridServer down?");
}
return regionInfo;
}
/// <summary>
///
/// </summary>
/// <param name="minX"></param>
/// <param name="minY"></param>
/// <param name="maxX"></param>
/// <param name="maxY"></param>
/// <returns></returns>
public List<MapBlockData> RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY)
{
int temp = 0;
if (minX > maxX)
{
temp = minX;
minX = maxX;
maxX = temp;
}
if (minY > maxY)
{
temp = minY;
minY = maxY;
maxY = temp;
}
Hashtable respData = MapBlockQuery(minX, minY, maxX, maxY);
List<MapBlockData> neighbours = new List<MapBlockData>();
foreach (ArrayList a in respData.Values)
{
foreach (Hashtable n in a)
{
MapBlockData neighbour = new MapBlockData();
neighbour.X = Convert.ToUInt16(n["x"]);
neighbour.Y = Convert.ToUInt16(n["y"]);
neighbour.Name = (string) n["name"];
neighbour.Access = Convert.ToByte(n["access"]);
neighbour.RegionFlags = Convert.ToUInt32(n["region-flags"]);
neighbour.WaterHeight = Convert.ToByte(n["water-height"]);
neighbour.MapImageId = new UUID((string) n["map-image-id"]);
neighbours.Add(neighbour);
}
}
return neighbours;
}
/// <summary>
/// Performs a XML-RPC query against the grid server returning mapblock information in the specified coordinates
/// </summary>
/// <param name="minX">Minimum X value</param>
/// <param name="minY">Minimum Y value</param>
/// <param name="maxX">Maximum X value</param>
/// <param name="maxY">Maximum Y value</param>
/// <returns>Hashtable of hashtables containing map data elements</returns>
private Hashtable MapBlockQuery(int minX, int minY, int maxX, int maxY)
{
Hashtable param = new Hashtable();
param["xmin"] = minX;
param["ymin"] = minY;
param["xmax"] = maxX;
param["ymax"] = maxY;
IList parameters = new ArrayList();
parameters.Add(param);
try
{
string methodName = "map_block";
XmlRpcRequest req = new XmlRpcRequest(methodName, parameters);
XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
Hashtable respData = (Hashtable)resp.Value;
if (respData != null && respData.Contains("faultCode"))
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: Got an error while contacting GridServer: {0}", respData["faultString"]);
return null;
}
return respData;
}
catch (Exception e)
{
m_log.Error("MapBlockQuery XMLRPC failure: " + e);
return new Hashtable();
}
}
/// <summary>
/// A ping / version check
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse PingCheckReply(XmlRpcRequest request,IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable respData = new Hashtable();
respData["online"] = "true";
m_localBackend.PingCheckReply(respData);
response.Value = respData;
return response;
}
/// <summary>
/// Received from the user server when a user starts logging in. This call allows
/// the region to prepare for direct communication from the client. Sends back an empty
/// xmlrpc response on completion.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse ExpectUser(XmlRpcRequest request)
{
Hashtable requestData = (Hashtable) request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string) requestData["session_id"]);
agentData.SecureSessionID = new UUID((string) requestData["secure_session_id"]);
agentData.FirstName = (string) requestData["firstname"];
agentData.LastName = (string) requestData["lastname"];
agentData.AgentID = new UUID((string) requestData["agent_id"]);
agentData.CircuitCode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
ulong regionHandle = Convert.ToUInt64((string) requestData["regionhandle"]);
// Appearance
if (requestData.ContainsKey("appearance"))
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
m_log.DebugFormat(
"[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
agentData.FirstName, agentData.LastName, agentData.AgentID, agentData.CircuitCode);
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
//m_log.Debug("[CLIENT]: Child agent detected");
agentData.child = true;
}
else
{
//m_log.Debug("[CLIENT]: Main agent detected");
agentData.startpos =
new Vector3((float)Convert.ToDouble((string)requestData["startpos_x"]),
(float)Convert.ToDouble((string)requestData["startpos_y"]),
(float)Convert.ToDouble((string)requestData["startpos_z"]));
agentData.child = false;
}
XmlRpcResponse resp = new XmlRpcResponse();
if (!RegionLoginsEnabled)
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because region login is currently disabled",
agentData.FirstName, agentData.LastName);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "region login currently disabled";
resp.Value = respdata;
}
else
{
RegionInfo[] regions = m_regionsOnInstance.ToArray();
bool banned = false;
for (int i = 0; i < regions.Length; i++)
{
if (regions[i] != null)
{
if (regions[i].RegionHandle == regionHandle)
{
if (regions[i].EstateSettings.IsBanned(agentData.AgentID))
{
banned = true;
break;
}
}
}
}
if (banned)
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is banned",
agentData.FirstName, agentData.LastName);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "banned";
resp.Value = respdata;
}
else
{
m_localBackend.TriggerExpectUser(regionHandle, agentData);
Hashtable respdata = new Hashtable();
respdata["success"] = "TRUE";
resp.Value = respdata;
}
}
return resp;
}
// Grid Request Processing
/// <summary>
/// Ooops, our Agent must be dead if we're getting this request!
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LogOffUser(XmlRpcRequest request)
{
m_log.Debug("[CONNECTION DEBUGGING]: LogOff User Called");
Hashtable requestData = (Hashtable)request.Params[0];
string message = (string)requestData["message"];
UUID agentID = UUID.Zero;
UUID RegionSecret = UUID.Zero;
UUID.TryParse((string)requestData["agent_id"], out agentID);
UUID.TryParse((string)requestData["region_secret"], out RegionSecret);
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
m_localBackend.TriggerLogOffUser(regionHandle, agentID, RegionSecret,message);
return new XmlRpcResponse();
}
private LandData RequestLandData(ulong regionHandle, uint x, uint y, int localLandID)
{
LandData landData = null;
Hashtable hash = new Hashtable();
hash["region_handle"] = regionHandle.ToString();
hash["x"] = x.ToString();
hash["y"] = y.ToString();
hash["land_id"] = localLandID.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
try
{
// this might be cached, as we probably requested it just a moment ago...
RegionInfo info = RequestNeighbourInfo(regionHandle);
if (info != null) // just to be sure
{
string methodName = "land_data";
XmlRpcRequest request = new XmlRpcRequest(methodName, paramList);
string uri = "http://" + info.ExternalHostName + ":" + info.HttpPort + "/";
XmlRpcResponse response = request.Send(Util.XmlRpcRequestURI(uri, methodName), 10000);
if (response.IsFault)
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: remote call returned an error: {0}", response.FaultString);
}
else
{
hash = (Hashtable)response.Value;
try
{
landData = new LandData();
landData.AABBMax = Vector3.Parse((string)hash["AABBMax"]);
landData.AABBMin = Vector3.Parse((string)hash["AABBMin"]);
landData.Area = Convert.ToInt32(hash["Area"]);
landData.AuctionID = Convert.ToUInt32(hash["AuctionID"]);
landData.Description = (string)hash["Description"];
landData.Flags = Convert.ToUInt32(hash["Flags"]);
landData.GlobalID = new UUID((string)hash["GlobalID"]);
landData.Name = (string)hash["Name"];
landData.OwnerID = new UUID((string)hash["OwnerID"]);
landData.SalePrice = Convert.ToInt32(hash["SalePrice"]);
landData.SnapshotID = new UUID((string)hash["SnapshotID"]);
landData.UserLocation = Vector3.Parse((string)hash["UserLocation"]);
// LandingType and UserLookAt were not included in the hash data prior to R1670.
// LandingType 0 means blocked, so where communicating with an older server, return 2 (anywhere).
landData.LandingType = hash.ContainsKey("LandingType") ? Convert.ToByte(hash["LandingType"]) : (byte)2;
landData.UserLookAt = hash.ContainsKey("UserLookAt") ? Vector3.Parse((string)hash["UserLookAt"]) : Vector3.Zero;
m_log.DebugFormat("[OGS1 GRID SERVICES]: Got land data for parcel {0}", landData.Name);
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: Got exception while parsing land-data:", e);
landData = null;
}
}
}
else m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region with handle {0}", regionHandle);
}
catch (WebException)
{
m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't contact region {0}: Region may be down.", regionHandle);
}
catch (Exception e)
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: Couldn't contact region {0}: {1}", regionHandle, e);
}
return landData;
}
public LandData RequestLandData(ulong regionHandle, uint x, uint y)
{
// m_log.DebugFormat("[OGS1 GRID SERVICES]: requests land data in {0}, at {1}, {2}", regionHandle, x, y);
LandData landData = m_localBackend.RequestLandData(regionHandle, x, y);
if (landData == null)
landData = RequestLandData(regionHandle, x, y, -1);
return landData;
}
public LandData RequestLandData(ulong regionHandle, int localLandID)
{
// m_log.DebugFormat("[OGS1 GRID SERVICES]: requests land data in {0}, with ID {1}", regionHandle, localLandID);
LandData landData = m_localBackend.RequestLandData(regionHandle, localLandID);
if (landData == null)
landData = RequestLandData(regionHandle, 128, 128, localLandID);
return landData;
}
// Grid Request Processing
/// <summary>
/// Someone asked us about parcel-information
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LandData(XmlRpcRequest request, IPEndPoint remoteClient)
{
LandData landData = null;
Hashtable requestData = (Hashtable)request.Params[0];
ulong regionHandle = Convert.ToUInt64(requestData["region_handle"]);
uint x = Convert.ToUInt32(requestData["x"]);
uint y = Convert.ToUInt32(requestData["y"]);
int localLandID = -1;
if (requestData.ContainsKey("land_id"))
{
localLandID = Convert.ToInt32(requestData["land_id"]);
}
if (localLandID == -1)
{
// look up by x/y coordinates
m_log.DebugFormat("[OGS1 GRID SERVICES]: Got XML request for land data at {0}, {1} in region {2}", x, y, regionHandle);
landData = m_localBackend.RequestLandData(regionHandle, x, y);
}
else
{
// look up by local land ID
m_log.DebugFormat("[OGS1 GRID SERVICES]: Got XML request for land data with ID {0} in region {1}", localLandID, regionHandle);
landData = m_localBackend.RequestLandData(regionHandle, localLandID);
}
Hashtable hash = new Hashtable();
if (landData != null)
{
// for now, only push out the data we need for answering a ParcelInfoReqeust
hash["AABBMax"] = landData.AABBMax.ToString();
hash["AABBMin"] = landData.AABBMin.ToString();
hash["Area"] = landData.Area.ToString();
hash["AuctionID"] = landData.AuctionID.ToString();
hash["Description"] = landData.Description;
hash["Flags"] = landData.Flags.ToString();
hash["GlobalID"] = landData.GlobalID.ToString();
hash["LandingType"] = landData.LandingType.ToString();
hash["Name"] = landData.Name;
hash["OwnerID"] = landData.OwnerID.ToString();
hash["SalePrice"] = landData.SalePrice.ToString();
hash["SnapshotID"] = landData.SnapshotID.ToString();
hash["UserLocation"] = landData.UserLocation.ToString();
hash["UserLookAt"] = landData.UserLookAt.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public List<RegionInfo> RequestNamedRegions (string name, int maxNumber)
{
// no asking of the local backend first, here, as we have to ask the gridserver anyway.
Hashtable hash = new Hashtable();
hash["name"] = name;
hash["maxNumber"] = maxNumber.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
Hashtable result = XmlRpcSearchForRegionByName(paramList);
if (result == null) return null;
uint numberFound = Convert.ToUInt32(result["numFound"]);
List<RegionInfo> infos = new List<RegionInfo>();
for (int i = 0; i < numberFound; ++i)
{
string prefix = "region" + i + ".";
RegionInfo info = buildRegionInfo(result, prefix);
infos.Add(info);
}
return infos;
}
private RegionInfo buildRegionInfo(Hashtable responseData, string prefix)
{
uint regX = Convert.ToUInt32((string) responseData[prefix + "region_locx"]);
uint regY = Convert.ToUInt32((string) responseData[prefix + "region_locy"]);
string internalIpStr = (string) responseData[prefix + "sim_ip"];
uint port = Convert.ToUInt32(responseData[prefix + "sim_port"]);
IPEndPoint neighbourInternalEndPoint = new IPEndPoint(Util.GetHostFromDNS(internalIpStr), (int) port);
RegionInfo regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, internalIpStr);
regionInfo.RemotingPort = Convert.ToUInt32((string) responseData[prefix + "remoting_port"]);
regionInfo.RemotingAddress = internalIpStr;
if (responseData.ContainsKey(prefix + "http_port"))
{
regionInfo.HttpPort = Convert.ToUInt32((string) responseData[prefix + "http_port"]);
}
regionInfo.RegionID = new UUID((string) responseData[prefix + "region_UUID"]);
regionInfo.RegionName = (string) responseData[prefix + "region_name"];
regionInfo.RegionSettings.TerrainImageID = new UUID((string) responseData[prefix + "map_UUID"]);
return regionInfo;
}
private Hashtable XmlRpcSearchForRegionByName(IList parameters)
{
try
{
string methodName = "search_for_region_by_name";
XmlRpcRequest request = new XmlRpcRequest(methodName, parameters);
XmlRpcResponse resp = request.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
Hashtable respData = (Hashtable) resp.Value;
if (respData != null && respData.Contains("faultCode"))
{
m_log.WarnFormat("[OGS1 GRID SERVICES]: Got an error while contacting GridServer: {0}", respData["faultString"]);
return null;
}
return respData;
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: MapBlockQuery XMLRPC failure: ", e);
return null;
}
}
public System.Threading.Tasks.Task<List<SimpleRegionInfo>> RequestNeighbors2Async(uint x, uint y, int maxDD)
{
Task<List<SimpleRegionInfo>> requestTask = new Task<List<SimpleRegionInfo>>(() =>
{
uint xmin, xmax, ymin, ymax;
Util.GetDrawDistanceBasedRegionRectangle((uint)maxDD, x, y, out xmin, out xmax, out ymin, out ymax);
Hashtable block = MapBlockQuery((int)xmin, (int)ymin, (int)xmax, (int)ymax);
if (block == null)
return new List<SimpleRegionInfo>();
return ExtractRegionInfoFromMapBlockQuery(x, y, block);
}
);
requestTask.Start();
return requestTask;
}
}
}
| |
using Peg.Base;
using System;
using System.IO;
using System.Text;
namespace calc0_direct
{
enum Ecalc0_direct {Expr= 1, Sum= 2, Product= 3, Value= 4, Number= 5, S= 6};
class calc0_direct : PegCharParser
{
class top{ // semantic top level block using C# as host language
internal double result;
internal bool print_(){Console.WriteLine("{0}",result);return true;}
}
top top;
#region Input Properties
public static EncodingClass encodingClass = EncodingClass.ascii;
public static UnicodeDetection unicodeDetection = UnicodeDetection.notApplicable;
#endregion Input Properties
#region Constructors
public calc0_direct ()
: base()
{
top= new top();
}
public calc0_direct (string src,StreamWriter FerrOut)
: base(src,FerrOut)
{
top= new top();
}
#endregion Constructors
#region Overrides
public override string GetRuleNameFromId(int id)
{
try
{
Ecalc0_direct ruleEnum = (Ecalc0_direct )id;
string s= ruleEnum.ToString();
int val;
if( int.TryParse(s,out val) ){
return base.GetRuleNameFromId(id);
}else{
return s;
}
}
catch (Exception)
{
return base.GetRuleNameFromId(id);
}
}
public override void GetProperties(out EncodingClass encoding, out UnicodeDetection detection)
{
encoding = encodingClass;
detection = unicodeDetection;
}
#endregion Overrides
#region Grammar Rules
public bool Expr() /*Expr: S Sum (!. print_ / FATAL<"following code not recognized">) ;*/
{
return And(()=>
S()
&& Sum()
&& (
And(()=> Not(()=> Any() ) && top.print_() )
|| Fatal("following code not recognized")) );
}
class _Sum{ //semantic rule related block using C# as host language (block can be implemented as nested struct)
internal _Sum(calc0_direct parent){parent_=parent;}
calc0_direct parent_;
double v;
internal bool save_(){v= parent_.top.result;parent_.top.result=0; return true;}
internal bool add_() {v+= parent_.top.result;parent_.top.result=0;return true;}
internal bool sub_() {v-= parent_.top.result;parent_.top.result=0;return true;}
internal bool store_(){parent_.top.result= v; return true;}
}
public bool Sum() /*Sum
{ //semantic rule related block using C# as host language (block can be implemented as nested struct)
internal _Sum(calc0_direct parent){parent_=parent;}
calc0_direct parent_;
double v;
internal bool save_(){v= parent_.top.result;parent_.top.result=0; return true;}
internal bool add_() {v+= parent_.top.result;parent_.top.result=0;return true;}
internal bool sub_() {v-= parent_.top.result;parent_.top.result=0;return true;}
internal bool store_(){parent_.top.result= v; return true;}
} :
Product save_
('+' S Product add_
/'-' S Product sub_)* store_ ;*/
{
var _sem= new _Sum(this);
return And(()=>
Product()
&& _sem.save_()
&& OptRepeat(()=>
And(()=>
Char('+')
&& S()
&& Product()
&& _sem.add_() )
|| And(()=>
Char('-')
&& S()
&& Product()
&& _sem.sub_() ) )
&& _sem.store_() );
}
class _Product{ //semantic rule related block using C# as host language (block can be implemented as nested struct)
internal _Product(calc0_direct parent){parent_=parent;}
calc0_direct parent_;
double v;
internal bool save_(){v= parent_.top.result;parent_.top.result=0; return true;}
internal bool mul_(){v*= parent_.top.result;parent_.top.result=0; return true;}
internal bool div_(){v/= parent_.top.result;parent_.top.result=0;return true;}
internal bool store_(){parent_.top.result= v;return true;}
}
public bool Product() /*Product
{ //semantic rule related block using C# as host language (block can be implemented as nested struct)
internal _Product(calc0_direct parent){parent_=parent;}
calc0_direct parent_;
double v;
internal bool save_(){v= parent_.top.result;parent_.top.result=0; return true;}
internal bool mul_(){v*= parent_.top.result;parent_.top.result=0; return true;}
internal bool div_(){v/= parent_.top.result;parent_.top.result=0;return true;}
internal bool store_(){parent_.top.result= v;return true;}
} :
Value save_
('*' S Value mul_
/'/' S Value div_)* store_ ;*/
{
var _sem= new _Product(this);
return And(()=>
Value()
&& _sem.save_()
&& OptRepeat(()=>
And(()=>
Char('*')
&& S()
&& Value()
&& _sem.mul_() )
|| And(()=>
Char('/')
&& S()
&& Value()
&& _sem.div_() ) )
&& _sem.store_() );
}
public bool Value() /*Value: Number S / '(' S Sum ')' S ;*/
{
return
And(()=> Number() && S() )
|| And(()=>
Char('(')
&& S()
&& Sum()
&& Char(')')
&& S() );
}
class _Number{ //semantic rule related block using C# as host language (block can be implemented as nested struct)
internal _Number(calc0_direct parent){parent_=parent;}
calc0_direct parent_;
internal string sNumber;
internal bool store_(){double.TryParse(sNumber,out parent_.top.result);return true;}
}
public bool Number() /*Number
{ //semantic rule related block using C# as host language (block can be implemented as nested struct)
internal _Number(calc0_direct parent){parent_=parent;}
calc0_direct parent_;
internal string sNumber;
internal bool store_(){double.TryParse(sNumber,out parent_.top.result);return true;}
}
: ([0-9]+ ('.' [0-9]+)?):sNumber store_ ;*/
{
var _sem= new _Number(this);
return And(()=>
Into(()=>
And(()=>
PlusRepeat(()=> In('0','9') )
&& Option(()=>
And(()=>
Char('.')
&& PlusRepeat(()=> In('0','9') ) ) ) ),out _sem.sNumber)
&& _sem.store_() );
}
public bool S() /*S: [ \n\r\t\v]* ;*/
{
return OptRepeat(()=> OneOf(" \n\r\t\v") );
}
#endregion Grammar Rules
}
}
| |
// 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.Specialized;
using System.Text;
using System.Net.Mail;
namespace System.Net.Mime
{
internal class MimeBasePart
{
internal const string DefaultCharSet = "utf-8";
private static readonly char[] s_decodeEncodingSplitChars = new char[] { '?', '\r', '\n' };
protected ContentType _contentType;
protected ContentDisposition _contentDisposition;
private HeaderCollection _headers;
internal MimeBasePart() { }
internal static bool ShouldUseBase64Encoding(Encoding encoding) =>
encoding == Encoding.Unicode || encoding == Encoding.UTF8 || encoding == Encoding.UTF32 || encoding == Encoding.BigEndianUnicode;
//use when the length of the header is not known or if there is no header
internal static string EncodeHeaderValue(string value, Encoding encoding, bool base64Encoding) =>
EncodeHeaderValue(value, encoding, base64Encoding, 0);
//used when the length of the header name itself is known (i.e. Subject : )
internal static string EncodeHeaderValue(string value, Encoding encoding, bool base64Encoding, int headerLength)
{
//no need to encode if it's pure ascii
if (IsAscii(value, false))
{
return value;
}
if (encoding == null)
{
encoding = Encoding.GetEncoding(DefaultCharSet);
}
EncodedStreamFactory factory = new EncodedStreamFactory();
IEncodableStream stream = factory.GetEncoderForHeader(encoding, base64Encoding, headerLength);
byte[] buffer = encoding.GetBytes(value);
stream.EncodeBytes(buffer, 0, buffer.Length);
return stream.GetEncodedString();
}
private static readonly char[] s_headerValueSplitChars = new char[] { '\r', '\n', ' ' };
private static readonly char[] s_questionMarkSplitChars = new char[] { '?' };
internal static string DecodeHeaderValue(string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
string newValue = string.Empty;
//split strings, they may be folded. If they are, decode one at a time and append the results
string[] substringsToDecode = value.Split(s_headerValueSplitChars, StringSplitOptions.RemoveEmptyEntries);
foreach (string foldedSubString in substringsToDecode)
{
//an encoded string has as specific format in that it must start and end with an
//'=' char and contains five parts, separated by '?' chars.
//the first and last part are therefore '=', the second part is the byte encoding (B or Q)
//the third is the unicode encoding type, and the fourth is encoded message itself. '?' is not valid inside of
//an encoded string other than as a separator for these five parts.
//If this check fails, the string is either not encoded or cannot be decoded by this method
string[] subStrings = foldedSubString.Split(s_questionMarkSplitChars);
if ((subStrings.Length != 5 || subStrings[0] != "=" || subStrings[4] != "="))
{
return value;
}
string charSet = subStrings[1];
bool base64Encoding = (subStrings[2] == "B");
byte[] buffer = Encoding.ASCII.GetBytes(subStrings[3]);
int newLength;
EncodedStreamFactory encoderFactory = new EncodedStreamFactory();
IEncodableStream s = encoderFactory.GetEncoderForHeader(Encoding.GetEncoding(charSet), base64Encoding, 0);
newLength = s.DecodeBytes(buffer, 0, buffer.Length);
Encoding encoding = Encoding.GetEncoding(charSet);
newValue += encoding.GetString(buffer, 0, newLength);
}
return newValue;
}
// Detect the encoding: "=?encoding?BorQ?content?="
// "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?="; // 3.5
// With the addition of folding in 4.0, there may be multiple lines with encoding, only detect the first:
// "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?=\r\n =?utf-8?B??=";
internal static Encoding DecodeEncoding(string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
string[] subStrings = value.Split(s_decodeEncodingSplitChars);
if ((subStrings.Length < 5 || subStrings[0] != "=" || subStrings[4] != "="))
{
return null;
}
string charSet = subStrings[1];
return Encoding.GetEncoding(charSet);
}
internal static bool IsAscii(string value, bool permitCROrLF)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
foreach (char c in value)
{
if (c > 0x7f)
{
return false;
}
if (!permitCROrLF && (c == '\r' || c == '\n'))
{
return false;
}
}
return true;
}
internal string ContentID
{
get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)]; }
set
{
if (string.IsNullOrEmpty(value))
{
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentID));
}
else
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)] = value;
}
}
}
internal string ContentLocation
{
get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)]; }
set
{
if (string.IsNullOrEmpty(value))
{
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentLocation));
}
else
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)] = value;
}
}
}
internal NameValueCollection Headers
{
get
{
//persist existing info before returning
if (_headers == null)
{
_headers = new HeaderCollection();
}
if (_contentType == null)
{
_contentType = new ContentType();
}
_contentType.PersistIfNeeded(_headers, false);
if (_contentDisposition != null)
{
_contentDisposition.PersistIfNeeded(_headers, false);
}
return _headers;
}
}
internal ContentType ContentType
{
get { return _contentType ?? (_contentType = new ContentType()); }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_contentType = value;
_contentType.PersistIfNeeded((HeaderCollection)Headers, true);
}
}
internal void PrepareHeaders(bool allowUnicode)
{
_contentType.PersistIfNeeded((HeaderCollection)Headers, false);
_headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), _contentType.Encode(allowUnicode));
if (_contentDisposition != null)
{
_contentDisposition.PersistIfNeeded((HeaderCollection)Headers, false);
_headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), _contentDisposition.Encode(allowUnicode));
}
}
internal virtual void Send(BaseWriter writer, bool allowUnicode)
{
throw new NotImplementedException();
}
internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback,
bool allowUnicode, object state)
{
throw new NotImplementedException();
}
internal void EndSend(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
LazyAsyncResult castedAsyncResult = asyncResult as MimePartAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndSend)));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
if (castedAsyncResult.Result is Exception)
{
throw (Exception)castedAsyncResult.Result;
}
}
internal class MimePartAsyncResult : LazyAsyncResult
{
internal MimePartAsyncResult(MimeBasePart part, object state, AsyncCallback callback) : base(part, state, callback)
{
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="DataServiceClientResponsePipelineConfiguration.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Client
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.OData.Core;
using Microsoft.OData.Client.Materialization;
/// <summary>
/// Class that is responsible for configuration of actions that are invoked from a response
/// </summary>
public class DataServiceClientResponsePipelineConfiguration
{
/// <summary> Actions to be run when reading start entry called </summary>
private readonly List<Action<ReadingEntryArgs>> readingStartEntryActions;
/// <summary> Actions to be run when reading end entry called </summary>
private readonly List<Action<ReadingEntryArgs>> readingEndEntryActions;
/// <summary> Actions to be run when reading start feed called </summary>
private readonly List<Action<ReadingFeedArgs>> readingStartFeedActions;
/// <summary> Actions to be run when reading end feed called </summary>
private readonly List<Action<ReadingFeedArgs>> readingEndFeedActions;
/// <summary> Actions to be run when reading start link called </summary>
private readonly List<Action<ReadingNavigationLinkArgs>> readingStartNavigationLinkActions;
/// <summary> Actions to be run when reading end link called </summary>
private readonly List<Action<ReadingNavigationLinkArgs>> readingEndNavigationLinkActions;
/// <summary> Actions to be run after an entry has been materialized </summary>
private readonly List<Action<MaterializedEntityArgs>> materializedEntityActions;
/// <summary> The message reader setting configurations. </summary>
private readonly List<Action<MessageReaderSettingsArgs>> messageReaderSettingsConfigurationActions;
/// <summary> The sender. </summary>
private readonly object sender;
/// <summary>
/// Creates a Data service client response pipeline class
/// </summary>
/// <param name="sender"> The sender for the Reading Atom event.</param>
internal DataServiceClientResponsePipelineConfiguration(object sender)
{
Debug.Assert(sender != null, "sender!= null");
this.sender = sender;
this.readingEndEntryActions = new List<Action<ReadingEntryArgs>>();
this.readingEndFeedActions = new List<Action<ReadingFeedArgs>>();
this.readingEndNavigationLinkActions = new List<Action<ReadingNavigationLinkArgs>>();
this.readingStartEntryActions = new List<Action<ReadingEntryArgs>>();
this.readingStartFeedActions = new List<Action<ReadingFeedArgs>>();
this.readingStartNavigationLinkActions = new List<Action<ReadingNavigationLinkArgs>>();
this.materializedEntityActions = new List<Action<MaterializedEntityArgs>>();
this.messageReaderSettingsConfigurationActions = new List<Action<MessageReaderSettingsArgs>>();
}
/// <summary>
/// Gets a value indicating whether this instance has handlers.
/// </summary>
/// <value>
/// <c>true</c> if this instance has handlers; otherwise, <c>false</c>.
/// </value>
internal bool HasConfigurations
{
get
{
return this.readingStartEntryActions.Count > 0 ||
this.readingEndEntryActions.Count > 0 ||
this.readingStartFeedActions.Count > 0 ||
this.readingEndFeedActions.Count > 0 ||
this.readingStartNavigationLinkActions.Count > 0 ||
this.readingEndNavigationLinkActions.Count > 0;
}
}
/// <summary>
/// Gets whether there is a reading entity handler
/// </summary>
internal bool HasReadingEntityHandlers
{
get
{
if (this.materializedEntityActions.Count > 0)
{
return true;
}
return false;
}
}
/// <summary>
/// Called when [reader settings created].
/// </summary>
/// <param name="messageReaderSettingsAction">The reader message settings configuration.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnMessageReaderSettingsCreated(Action<MessageReaderSettingsArgs> messageReaderSettingsAction)
{
WebUtil.CheckArgumentNull(messageReaderSettingsAction, "messageReaderSettingsAction");
this.messageReaderSettingsConfigurationActions.Add(messageReaderSettingsAction);
return this;
}
/// <summary>
/// Called when [read start entry].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnEntryStarted(Action<ReadingEntryArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.readingStartEntryActions.Add(action);
return this;
}
/// <summary>
/// Called when [read end entry].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnEntryEnded(Action<ReadingEntryArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.readingEndEntryActions.Add(action);
return this;
}
/// <summary>
/// Called when [read start feed].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnFeedStarted(Action<ReadingFeedArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.readingStartFeedActions.Add(action);
return this;
}
/// <summary>
/// Called when [read end feed].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnFeedEnded(Action<ReadingFeedArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.readingEndFeedActions.Add(action);
return this;
}
/// <summary>
/// Called when [read start navigation link].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnNavigationLinkStarted(Action<ReadingNavigationLinkArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.readingStartNavigationLinkActions.Add(action);
return this;
}
/// <summary>
/// Called when [read end navigation link].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnNavigationLinkEnded(Action<ReadingNavigationLinkArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.readingEndNavigationLinkActions.Add(action);
return this;
}
/// <summary>
/// Called when [entity materialized].
/// </summary>
/// <param name="action">The action.</param>
/// <returns>The response pipeline configuration.</returns>
public DataServiceClientResponsePipelineConfiguration OnEntityMaterialized(Action<MaterializedEntityArgs> action)
{
WebUtil.CheckArgumentNull(action, "action");
this.materializedEntityActions.Add(action);
return this;
}
/// <summary>
/// Executes actions that configure reader settings.
/// </summary>
/// <param name="readerSettings">The reader settings.</param>
internal void ExecuteReaderSettingsConfiguration(ODataMessageReaderSettingsBase readerSettings)
{
Debug.Assert(readerSettings != null, "readerSettings != null");
if (this.messageReaderSettingsConfigurationActions.Count > 0)
{
MessageReaderSettingsArgs args = new MessageReaderSettingsArgs(new DataServiceClientMessageReaderSettingsShim(readerSettings));
foreach (Action<MessageReaderSettingsArgs> readerSettingsConfigurationAction in this.messageReaderSettingsConfigurationActions)
{
readerSettingsConfigurationAction(args);
}
}
}
/// <summary>
/// Executes the on entry end actions.
/// </summary>
/// <param name="entry">The entry.</param>
internal void ExecuteOnEntryEndActions(ODataEntry entry)
{
// Be noticed that the entry could be null in some case, like expand.
if (this.readingEndEntryActions.Count > 0)
{
ReadingEntryArgs args = new ReadingEntryArgs(entry);
foreach (Action<ReadingEntryArgs> entryAction in this.readingEndEntryActions)
{
entryAction(args);
}
}
}
/// <summary>
/// Executes the on entry start actions.
/// </summary>
/// <param name="entry">The entry.</param>
internal void ExecuteOnEntryStartActions(ODataEntry entry)
{
// Be noticed that the entry could be null in some case, like expand.
if (this.readingStartEntryActions.Count > 0)
{
ReadingEntryArgs args = new ReadingEntryArgs(entry);
foreach (Action<ReadingEntryArgs> entryAction in this.readingStartEntryActions)
{
entryAction(args);
}
}
}
/// <summary>
/// Executes the on feed end actions.
/// </summary>
/// <param name="feed">The feed.</param>
internal void ExecuteOnFeedEndActions(ODataFeed feed)
{
Debug.Assert(feed != null, "entry != null");
if (this.readingEndFeedActions.Count > 0)
{
ReadingFeedArgs args = new ReadingFeedArgs(feed);
foreach (Action<ReadingFeedArgs> feedAction in this.readingEndFeedActions)
{
feedAction(args);
}
}
}
/// <summary>
/// Executes the on feed start actions.
/// </summary>
/// <param name="feed">The feed.</param>
internal void ExecuteOnFeedStartActions(ODataFeed feed)
{
Debug.Assert(feed != null, "feed != null");
if (this.readingStartFeedActions.Count > 0)
{
ReadingFeedArgs args = new ReadingFeedArgs(feed);
foreach (Action<ReadingFeedArgs> feedAction in this.readingStartFeedActions)
{
feedAction(args);
}
}
}
/// <summary>
/// Executes the on navigation end actions.
/// </summary>
/// <param name="link">The link.</param>
internal void ExecuteOnNavigationEndActions(ODataNavigationLink link)
{
Debug.Assert(link != null, "link != null");
if (this.readingEndNavigationLinkActions.Count > 0)
{
ReadingNavigationLinkArgs args = new ReadingNavigationLinkArgs(link);
foreach (Action<ReadingNavigationLinkArgs> navAction in this.readingEndNavigationLinkActions)
{
navAction(args);
}
}
}
/// <summary>
/// Executes the on navigation start actions.
/// </summary>
/// <param name="link">The link.</param>
internal void ExecuteOnNavigationStartActions(ODataNavigationLink link)
{
Debug.Assert(link != null, "link != null");
if (this.readingStartNavigationLinkActions.Count > 0)
{
ReadingNavigationLinkArgs args = new ReadingNavigationLinkArgs(link);
foreach (Action<ReadingNavigationLinkArgs> navAction in this.readingStartNavigationLinkActions)
{
navAction(args);
}
}
}
/// <summary>
/// Fires after the entry was materialized
/// </summary>
/// <param name="entry">The entry.</param>
/// <param name="entity">The entity.</param>
internal void ExecuteEntityMaterializedActions(ODataEntry entry, object entity)
{
Debug.Assert(entry != null, "entry != null");
Debug.Assert(entity != null, "entity != entity");
if (this.materializedEntityActions.Count > 0)
{
MaterializedEntityArgs args = new MaterializedEntityArgs(entry, entity);
foreach (Action<MaterializedEntityArgs> materializedEntryArgsAction in this.materializedEntityActions)
{
materializedEntryArgsAction(args);
}
}
}
/// <summary>
/// Fires the end entry events.
/// </summary>
/// <param name="entry">The entry.</param>
internal void FireEndEntryEvents(MaterializerEntry entry)
{
Debug.Assert(entry != null, "entry!=null");
if (this.HasReadingEntityHandlers)
{
this.ExecuteEntityMaterializedActions(entry.Entry, entry.ResolvedObject);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Orleans.GrainDirectory;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime.GrainDirectory
{
internal class LocalGrainDirectory : MarshalByRefObject, ILocalGrainDirectory, ISiloStatusListener
{
/// <summary>
/// list of silo members sorted by the hash value of their address
/// </summary>
private readonly List<SiloAddress> membershipRingList;
private readonly HashSet<SiloAddress> membershipCache;
private readonly AsynchAgent maintainer;
private readonly TraceLogger log;
private readonly SiloAddress seed;
internal ISiloStatusOracle Membership;
// Consider: move these constants into an apropriate place
internal const int HOP_LIMIT = 3; // forward a remote request no more than two times
private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(5); // Pause 5 seconds between forwards to let the membership directory settle down
protected SiloAddress Seed { get { return seed; } }
internal Logger Logger { get { return log; } } // logger is shared with classes that manage grain directory
internal bool Running;
internal SiloAddress MyAddress { get; private set; }
internal IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> DirectoryCache { get; private set; }
internal GrainDirectoryPartition DirectoryPartition { get; private set; }
public RemoteGrainDirectory RemGrainDirectory { get; private set; }
public RemoteGrainDirectory CacheValidator { get; private set; }
private readonly TaskCompletionSource<bool> stopPreparationResolver;
public Task StopPreparationCompletion { get { return stopPreparationResolver.Task; } }
internal OrleansTaskScheduler Scheduler { get; private set; }
internal GrainDirectoryHandoffManager HandoffManager { get; private set; }
internal ISiloStatusListener CatalogSiloStatusListener { get; set; }
private readonly CounterStatistic localLookups;
private readonly CounterStatistic localSuccesses;
private readonly CounterStatistic fullLookups;
private readonly CounterStatistic cacheLookups;
private readonly CounterStatistic cacheSuccesses;
private readonly CounterStatistic registrationsIssued;
private readonly CounterStatistic registrationsSingleActIssued;
private readonly CounterStatistic unregistrationsIssued;
private readonly CounterStatistic unregistrationsManyIssued;
private readonly IntValueStatistic directoryPartitionCount;
internal readonly CounterStatistic RemoteLookupsSent;
internal readonly CounterStatistic RemoteLookupsReceived;
internal readonly CounterStatistic LocalDirectoryLookups;
internal readonly CounterStatistic LocalDirectorySuccesses;
internal readonly CounterStatistic CacheValidationsSent;
internal readonly CounterStatistic CacheValidationsReceived;
internal readonly CounterStatistic RegistrationsLocal;
internal readonly CounterStatistic RegistrationsRemoteSent;
internal readonly CounterStatistic RegistrationsRemoteReceived;
internal readonly CounterStatistic RegistrationsSingleActLocal;
internal readonly CounterStatistic RegistrationsSingleActRemoteSent;
internal readonly CounterStatistic RegistrationsSingleActRemoteReceived;
internal readonly CounterStatistic UnregistrationsLocal;
internal readonly CounterStatistic UnregistrationsRemoteSent;
internal readonly CounterStatistic UnregistrationsRemoteReceived;
internal readonly CounterStatistic UnregistrationsManyRemoteSent;
internal readonly CounterStatistic UnregistrationsManyRemoteReceived;
public LocalGrainDirectory(Silo silo)
{
log = TraceLogger.GetLogger("Orleans.GrainDirectory.LocalGrainDirectory");
MyAddress = silo.LocalMessageCenter.MyAddress;
Scheduler = silo.LocalScheduler;
membershipRingList = new List<SiloAddress>();
membershipCache = new HashSet<SiloAddress>();
silo.OrleansConfig.OnConfigChange("Globals/Caching", () =>
{
lock (membershipCache)
{
DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(silo.GlobalConfig);
}
});
maintainer = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCacheMaintainer(this, DirectoryCache);
if (silo.GlobalConfig.SeedNodes.Count > 0)
{
seed = silo.GlobalConfig.SeedNodes.Contains(MyAddress.Endpoint) ? MyAddress : SiloAddress.New(silo.GlobalConfig.SeedNodes[0], 0);
}
stopPreparationResolver = new TaskCompletionSource<bool>();
DirectoryPartition = new GrainDirectoryPartition();
HandoffManager = new GrainDirectoryHandoffManager(this, silo.GlobalConfig);
RemGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceId);
CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorId);
// add myself to the list of members
AddServer(MyAddress);
Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) =>
String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode());
localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED);
localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES);
fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED);
RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT);
RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED);
LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED);
LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES);
cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED);
cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () =>
{
long delta1, delta2;
long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1);
long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2);
return String.Format("{0}, Delta={1}",
(curr2 != 0 ? (float)curr1 / (float)curr2 : 0)
,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0));
});
CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT);
CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED);
registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED);
RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL);
RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT);
RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED);
registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED);
RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL);
RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT);
RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED);
unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED);
UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL);
UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT);
UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED);
unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED);
UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT);
UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED);
directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count);
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor());
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100);
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => membershipRingList.Count == 0 ? 0 : ((float)100 / (float)membershipRingList.Count));
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => membershipRingList.Count);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () =>
{
lock (membershipCache)
{
return Utils.EnumerableToString(membershipRingList, siloAddressPrint);
}
});
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(FindPredecessors(MyAddress, 1), siloAddressPrint));
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(FindSuccessors(MyAddress, 1), siloAddressPrint));
}
public void Start()
{
Running = true;
if (maintainer != null)
{
maintainer.Start();
}
}
// Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised.
// This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of
// grains (for update purposes), which could cause application requests that require a new activation to be created to time out.
// The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes
// would receive successful responses but would not be reflected in the eventual state of the directory.
// It's easy to change this, if we think the trade-off is better the other way.
public void Stop(bool doOnStopHandoff)
{
// This will cause remote write requests to be forwarded to the silo that will become the new owner.
// Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the
// new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've
// begun stopping, which could cause them to not get handed off to the new owner.
Running = false;
if (doOnStopHandoff)
{
HandoffManager.ProcessSiloStoppingEvent();
}
else
{
MarkStopPreparationCompleted();
}
if (maintainer != null)
{
maintainer.Stop();
}
DirectoryCache.Clear();
}
internal void MarkStopPreparationCompleted()
{
stopPreparationResolver.TrySetResult(true);
}
internal void MarkStopPreparationFailed(Exception ex)
{
stopPreparationResolver.TrySetException(ex);
}
#region Handling membership events
protected void AddServer(SiloAddress silo)
{
lock (membershipCache)
{
if (membershipCache.Contains(silo))
{
// we have already cached this silo
return;
}
membershipCache.Add(silo);
// insert new silo in the sorted order
long hash = silo.GetConsistentHashCode();
// Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former.
// Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then
// 'index' will get 0, as needed.
int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
membershipRingList.Insert(index, silo);
HandoffManager.ProcessSiloAddEvent(silo);
if (log.IsVerbose) log.Verbose("Silo {0} added silo {1}", MyAddress, silo);
}
}
protected void RemoveServer(SiloAddress silo, SiloStatus status)
{
lock (membershipCache)
{
if (!membershipCache.Contains(silo))
{
// we have already removed this silo
return;
}
if (CatalogSiloStatusListener != null)
{
try
{
// only call SiloStatusChangeNotification once on the catalog and the order is important: call BEFORE updating membershipRingList.
CatalogSiloStatusListener.SiloStatusChangeNotification(silo, status);
}
catch (Exception exc)
{
log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception,
String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc);
}
}
// the call order is important
HandoffManager.ProcessSiloRemoveEvent(silo);
membershipCache.Remove(silo);
membershipRingList.Remove(silo);
AdjustLocalDirectory(silo);
AdjustLocalCache(silo);
if (log.IsVerbose) log.Verbose("Silo {0} removed silo {1}", MyAddress, silo);
}
}
/// <summary>
/// Adjust local directory following the removal of a silo by droping all activations located on the removed silo
/// </summary>
/// <param name="removedSilo"></param>
protected void AdjustLocalDirectory(SiloAddress removedSilo)
{
var activationsToRemove = (from pair in DirectoryPartition.GetItems()
from pair2 in pair.Value.Instances.Where(pair3 => pair3.Value.SiloAddress.Equals(removedSilo))
select new Tuple<GrainId, ActivationId>(pair.Key, pair2.Key)).ToList();
// drop all records of activations located on the removed silo
foreach (var activation in activationsToRemove)
{
DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2, true);
}
}
/// Adjust local cache following the removal of a silo by droping:
/// 1) entries that point to activations located on the removed silo
/// 2) entries for grains that are now owned by this silo (me)
/// 3) entries for grains that were owned by this removed silo - we currently do NOT do that.
/// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership).
/// We don't do that since first cache refresh handles that.
/// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo.
/// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner).
protected void AdjustLocalCache(SiloAddress removedSilo)
{
// remove all records of activations located on the removed silo
foreach (Tuple<GrainId, IReadOnlyList<Tuple<SiloAddress, ActivationId>>, int> tuple in DirectoryCache.KeyValues)
{
// 2) remove entries now owned by me (they should be retrieved from my directory partition)
if (MyAddress.Equals(CalculateTargetSilo(tuple.Item1)))
{
DirectoryCache.Remove(tuple.Item1);
}
// 1) remove entries that point to activations located on the removed silo
RemoveActivations(DirectoryCache, tuple.Item1, tuple.Item2, tuple.Item3, t => t.Item1.Equals(removedSilo));
}
}
internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--)
{
result.Add(membershipRingList[(i + numMembers) % numMembers]);
}
return result;
}
}
internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index + 1; i % numMembers != index && result.Count < count; i++)
{
result.Add(membershipRingList[i % numMembers]);
}
return result;
}
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (Equals(updatedSilo, MyAddress))
{
if (status == SiloStatus.Stopping || status.Equals(SiloStatus.ShuttingDown))
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(true), CacheValidator.SchedulingContext).Ignore();
}
else if (status == SiloStatus.Dead)
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(false), CacheValidator.SchedulingContext).Ignore();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => RemoveServer(updatedSilo, status), CacheValidator.SchedulingContext).Ignore();
}
else if (status.Equals(SiloStatus.Active)) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => AddServer(updatedSilo), CacheValidator.SchedulingContext).Ignore();
}
}
}
private bool IsValidSilo(SiloAddress silo)
{
if (Membership == null)
Membership = Silo.CurrentSilo.LocalSiloStatusOracle;
return Membership.IsFunctionalDirectory(silo);
}
#endregion
/// <summary>
/// Finds the silo that owns the directory information for the given grain ID.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="grainId"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
public SiloAddress CalculateTargetSilo(GrainId grainId, bool excludeThisSiloIfStopping = true)
{
// give a special treatment for special grains
if (grainId.IsSystemTarget)
{
if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress);
// every silo owns its system targets
return MyAddress;
}
if (Constants.SystemMembershipTableId.Equals(grainId))
{
if (Seed == null)
{
string grainName;
if (!Constants.TryGetSystemGrainName(grainId, out grainName))
grainName = "MembershipTableGrain";
var errorMsg = grainName + " cannot run without Seed node - please check your silo configuration file and make sure it specifies a SeedNode element. " +
" Alternatively, you may want to use AzureTable for LivenessType.";
throw new ArgumentException(errorMsg, "grainId = " + grainId);
}
// Directory info for the membership table grain has to be located on the primary (seed) node, for bootstrapping
if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a special grain {1}, returned {2}", MyAddress, grainId, Seed);
return Seed;
}
SiloAddress siloAddress;
int hash = unchecked((int)grainId.GetUniformHashCode());
lock (membershipCache)
{
if (membershipRingList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeThisSiloIfStopping && !Running ? null : MyAddress;
}
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = !Running && excludeThisSiloIfStopping;
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
siloAddress = membershipRingList.FindLast(siloAddr => (siloAddr.GetConsistentHashCode() <= hash) &&
(!siloAddr.Equals(MyAddress) || !excludeMySelf));
if (siloAddress == null)
{
// If not found in the traversal, last silo will do (we are on a ring).
// We checked above to make sure that the list isn't empty, so this should always be safe.
siloAddress = membershipRingList[membershipRingList.Count - 1];
// Make sure it's not us...
if (siloAddress.Equals(MyAddress) && excludeMySelf)
{
siloAddress = membershipRingList.Count > 1 ? membershipRingList[membershipRingList.Count - 2] : null;
}
}
}
if (log.IsVerbose2) log.Verbose2("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress.GetConsistentHashCode());
return siloAddress;
}
#region Implementation of ILocalGrainDirectory
public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription)
{
SiloAddress owner = CalculateTargetSilo(grainId);
if (owner == null)
{
// We don't know about any other silos, and we're stopping, so throw
throw new InvalidOperationException("Grain directory is stopping");
}
if (owner.Equals(MyAddress))
{
// if I am the owner, perform the operation locally
return null;
}
if (hopCount >= HOP_LIMIT)
{
// we are not forwarding because there were too many hops already
throw new OrleansException(string.Format("Silo {0} is not owner of {1}, cannot forward {2} to owner {3} because hop limit is reached", MyAddress, grainId, operationDescription, owner));
}
// forward to the silo that we think is the owner
return owner;
}
public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation, int hopCount)
{
var counterStatistic =
singleActivation
? (hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued)
: (hopCount > 0 ? this.RegistrationsRemoteReceived : this.registrationsIssued);
counterStatistic.Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync(recheck)");
}
if (forwardAddress == null)
{
(singleActivation ? RegistrationsSingleActLocal : RegistrationsLocal).Increment();
// we are the owner
var registrar = RegistrarManager.Instance.GetRegistrarForGrain(address.Grain);
return registrar.IsSynchronous ? registrar.Register(address, singleActivation)
: await registrar.RegisterAsync(address, singleActivation);
}
else
{
(singleActivation ? RegistrationsSingleActRemoteSent : RegistrationsRemoteSent).Increment();
// otherwise, notify the owner
AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, singleActivation, hopCount + 1);
if (singleActivation)
{
// Caching optimization:
// cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
if (result.Address == null) return result;
if (!address.Equals(result.Address) || !IsValidSilo(address.Silo)) return result;
var cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) };
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
else
{
if (IsValidSilo(address.Silo))
{
// Caching optimization:
// cache the result of a successfull RegisterActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
if (!DirectoryCache.LookUp(address.Grain, out cached))
{
cached = new List<Tuple<SiloAddress, ActivationId>>(1)
{
Tuple.Create(address.Silo, address.Activation)
};
}
else
{
var newcached = new List<Tuple<SiloAddress, ActivationId>>(cached.Count + 1);
newcached.AddRange(cached);
newcached.Add(Tuple.Create(address.Silo, address.Activation));
cached = newcached;
}
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
}
return result;
}
}
public Task UnregisterConditionallyAsync(ActivationAddress addr)
{
// This is a no-op if the lazy registration delay is zero or negative
return Silo.CurrentSilo.OrleansConfig.Globals.DirectoryLazyDeregistrationDelay <= TimeSpan.Zero ?
TaskDone.Done : UnregisterAsync(addr, false, 0);
}
public async Task UnregisterAsync(ActivationAddress address, bool force, int hopCount)
{
(hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment();
if (hopCount == 0)
InvalidateCacheEntry(address);
// see if the owner is somewhere else (returns null if we are owner)
var forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardaddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync(recheck)");
}
if (forwardaddress == null)
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = RegistrarManager.Instance.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
registrar.Unregister(address, force);
else
await registrar.UnregisterAsync(address, force);
}
else
{
UnregistrationsRemoteSent.Increment();
// otherwise, notify the owner
await GetDirectoryReference(forwardaddress).UnregisterAsync(address, force, hopCount + 1);
}
}
private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value)
{
if (dictionary == null)
dictionary = new Dictionary<K,List<V>>();
List<V> list;
if (! dictionary.TryGetValue(key, out list))
dictionary[key] = list = new List<V>();
list.Add(value);
}
// helper method to avoid code duplication inside UnregisterManyAsync
private void UnregisterOrPutInForwardList(IEnumerable<ActivationAddress> addresses, int hopCount,
ref Dictionary<SiloAddress, List<ActivationAddress>> forward, List<Task> tasks, string context)
{
foreach (var address in addresses)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, context);
if (forwardAddress != null)
AddToDictionary(ref forward, forwardAddress, address);
else
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = RegistrarManager.Instance.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
registrar.Unregister(address, true);
else
{
tasks.Add(registrar.UnregisterAsync(address, true));
}
}
}
}
public async Task UnregisterManyAsync(List<ActivationAddress> addresses, int hopCount)
{
(hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment();
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist = null;
var tasks = new List<Task>();
UnregisterOrPutInForwardList(addresses, hopCount, ref forwardlist, tasks, "UnregisterManyAsync");
// before forwarding to other silos, we insert a retry delay and re-check destination
if (hopCount > 0 && forwardlist != null)
{
await Task.Delay(RETRY_DELAY);
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist2 = null;
UnregisterOrPutInForwardList(forwardlist.SelectMany(kvp => kvp.Value), hopCount, ref forwardlist2, tasks, "UnregisterManyAsync(recheck)");
forwardlist = forwardlist2;
}
// forward the requests
if (forwardlist != null)
{
foreach (var kvp in forwardlist)
{
UnregistrationsManyRemoteSent.Increment();
tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, hopCount + 1));
}
}
// wait for all the requests to finish
await Task.WhenAll(tasks);
}
public bool LocalLookup(GrainId grain, out AddressesAndTag result)
{
localLookups.Increment();
SiloAddress silo = CalculateTargetSilo(grain, false);
// No need to check that silo != null since we're passing excludeThisSiloIfStopping = false
if (log.IsVerbose) log.Verbose("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo.GetConsistentHashCode());
// check if we own the grain
if (silo.Equals(MyAddress))
{
LocalDirectoryLookups.Increment();
result = GetLocalDirectoryData(grain);
if (result.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}=null", grain);
return false;
}
if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}={1}", grain, result.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
localSuccesses.Increment();
return true;
}
// handle cache
result = new AddressesAndTag();
cacheLookups.Increment();
result.Addresses = GetLocalCacheData(grain);
if (result.Addresses == null)
{
if (log.IsVerbose2) log.Verbose2("TryFullLookup else {0}=null", grain);
return false;
}
if (log.IsVerbose2) log.Verbose2("LocalLookup cache {0}={1}", grain, result.Addresses.ToStrings());
cacheSuccesses.Increment();
localSuccesses.Increment();
return true;
}
public AddressesAndTag GetLocalDirectoryData(GrainId grain)
{
var result = DirectoryPartition.LookUpGrain(grain);
if (result.Addresses != null)
result.Addresses = result.Addresses.Where(addr => IsValidSilo(addr.Silo)).ToList();
return result;
}
public List<ActivationAddress> GetLocalCacheData(GrainId grain)
{
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
return DirectoryCache.LookUp(grain, out cached) ?
cached.Select(elem => ActivationAddress.GetAddress(elem.Item1, grain, elem.Item2)).Where(addr => IsValidSilo(addr.Silo)).ToList() :
null;
}
public async Task<AddressesAndTag> LookupAsync(GrainId grainId, int hopCount = 0)
{
(hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
LocalDirectoryLookups.Increment();
var localResult = DirectoryPartition.LookUpGrain(grainId);
if (localResult.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}=none", grainId);
localResult.Addresses = new List<ActivationAddress>();
localResult.VersionTag = GrainInfo.NO_ETAG;
return localResult;
}
localResult.Addresses = localResult.Addresses.Where(addr => IsValidSilo(addr.Silo)).ToList();
if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}={1}", grainId, localResult.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
return localResult;
}
else
{
// Just a optimization. Why sending a message to someone we know is not valid.
if (!IsValidSilo(forwardAddress))
{
throw new OrleansException(String.Format("Current directory at {0} is not stable to perform the lookup for grainId {1} (it maps to {2}, which is not a valid silo). Retry later.", MyAddress, grainId, forwardAddress));
}
RemoteLookupsSent.Increment();
var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1);
// update the cache
result.Addresses = result.Addresses.Where(t => IsValidSilo(t.Silo)).ToList();
if (log.IsVerbose2) log.Verbose2("FullLookup remote {0}={1}", grainId, result.Addresses.ToStrings());
var entries = result.Addresses.Select(t => Tuple.Create(t.Silo, t.Activation)).ToList();
if (entries.Count > 0)
DirectoryCache.AddOrUpdate(grainId, entries, result.VersionTag);
return result;
}
}
public async Task DeleteGrainAsync(GrainId grainId, int hopCount)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
var registrar = RegistrarManager.Instance.GetRegistrarForGrain(grainId);
if (registrar.IsSynchronous)
registrar.Delete(grainId);
else
await registrar.DeleteAsync(grainId);
}
else
{
// otherwise, notify the owner
DirectoryCache.Remove(grainId);
await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1);
}
}
public void InvalidateCacheEntry(ActivationAddress activationAddress)
{
int version;
IReadOnlyList<Tuple<SiloAddress, ActivationId>> list;
var grainId = activationAddress.Grain;
var activationId = activationAddress.Activation;
// look up grainId activations
if (DirectoryCache.LookUp(grainId, out list, out version))
{
RemoveActivations(DirectoryCache, grainId, list, version, t => t.Item2.Equals(activationId));
}
}
/// <summary>
/// For testing purposes only.
/// Returns the silo that this silo thinks is the primary owner of directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public SiloAddress GetPrimaryForGrain(GrainId grain)
{
return CalculateTargetSilo(grain);
}
/// <summary>
/// For testing purposes only.
/// Returns the silos that this silo thinks hold copies of the directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public List<SiloAddress> GetSilosHoldingDirectoryInformationForGrain(GrainId grain)
{
var primary = CalculateTargetSilo(grain);
return FindPredecessors(primary, 1);
}
/// <summary>
/// For testing purposes only.
/// Returns the directory information held by the local silo for the provided grain ID.
/// The result will be null if no information is held.
/// </summary>
/// <param name="grain"></param>
/// <param name="isPrimary"></param>
/// <returns></returns>
public List<ActivationAddress> GetLocalDataForGrain(GrainId grain, out bool isPrimary)
{
var primary = CalculateTargetSilo(grain);
List<ActivationAddress> backupData = HandoffManager.GetHandedOffInfo(grain);
if (MyAddress.Equals(primary))
{
log.Assert(ErrorCode.DirectoryBothPrimaryAndBackupForGrain, backupData == null,
"Silo contains both primary and backup directory data for grain " + grain);
isPrimary = true;
return GetLocalDirectoryData(grain).Addresses;
}
isPrimary = false;
return backupData;
}
#endregion
public override string ToString()
{
var sb = new StringBuilder();
long localLookupsDelta;
long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta);
long localLookupsSucceededDelta;
long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta);
long fullLookupsDelta;
long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta);
long directoryPartitionSize = directoryPartitionCount.GetCurrentValue();
sb.AppendLine("Local Grain Directory:");
sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine();
sb.AppendLine(" Since last call:");
sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine();
if (localLookupsCurrent > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine();
sb.AppendLine(" Since start:");
sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine();
if (localLookupsCurrent > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine();
sb.Append(DirectoryCache.ToString());
return sb.ToString();
}
private long RingDistanceToSuccessor()
{
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
return distance;
}
private string RingDistanceToSuccessor_2()
{
const long ringSize = int.MaxValue * 2L;
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
double averageRingSpace = membershipRingList.Count == 0 ? 0 : (1.0 / (double)membershipRingList.Count);
return string.Format("RingDistance={0:X}, %Ring Space {1:0.00000}%, Average %Ring Space {2:0.00000}%",
distance, ((double)distance / (double)ringSize) * 100.0, averageRingSpace * 100.0);
}
private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2)
{
const long ringSize = int.MaxValue * 2L;
long hash1 = silo1.GetConsistentHashCode();
long hash2 = silo2.GetConsistentHashCode();
if (hash2 > hash1) return hash2 - hash1;
if (hash2 < hash1) return ringSize - (hash1 - hash2);
return 0;
}
public string RingStatusToString()
{
var sb = new StringBuilder();
sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine();
sb.AppendLine("Ring is:");
lock (membershipCache)
{
foreach (var silo in membershipRingList)
sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine();
}
sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine();
sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- "));
return sb.ToString();
}
internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo)
{
return InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo);
}
private static void RemoveActivations(IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> directoryCache, GrainId key, IReadOnlyList<Tuple<SiloAddress, ActivationId>> activations, int version, Func<Tuple<SiloAddress, ActivationId>, bool> doRemove)
{
int removeCount = activations.Count(doRemove);
if (removeCount == 0)
{
return; // nothing to remove, done here
}
if (activations.Count > removeCount) // still some left, update activation list. Note: Most of the time there should be only one activation
{
var newList = new List<Tuple<SiloAddress, ActivationId>>(activations.Count - removeCount);
newList.AddRange(activations.Where(t => !doRemove(t)));
directoryCache.AddOrUpdate(key, newList, version);
}
else // no activations left, remove from cache
{
directoryCache.Remove(key);
}
}
}
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.Storage;
using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using UnitTests.StorageTests.Relational.TestDataSets;
using Xunit;
namespace UnitTests.StorageTests.Relational
{
/// <summary>
/// The storage tests with assertions that should hold for any back-end.
/// </summary>
/// <remarks>This is not in an inheritance hierarchy to allow for cleaner separation for any framework
/// code and even testing the tests. The tests use unique news (Guids) so the storage doesn't need to be
/// cleaned until all the storage tests have been run.</remarks>
internal class CommonStorageTests
{
private readonly IInternalGrainFactory grainFactory;
/// <summary>
/// The storage provider under test.
/// </summary>
public IGrainStorage Storage { get; }
/// <summary>
/// The default constructor.
/// </summary>
/// <param name="grainFactory"></param>
/// <param name="storage"></param>
public CommonStorageTests(IInternalGrainFactory grainFactory, IGrainStorage storage)
{
this.grainFactory = grainFactory;
Storage = storage;
}
internal async Task PersistenceStorage_WriteReadWriteReadStatesInParallel(string prefix = nameof(this.PersistenceStorage_WriteReadWriteReadStatesInParallel), int countOfGrains = 100)
{
//As data is written and read the Version numbers (ETags) are as checked for correctness (they change).
//Additionally the Store_WriteRead tests does its validation.
var grainTypeName = GrainTypeGenerator.GetGrainType<Guid>();
int StartOfRange = 33900;
int CountOfRange = countOfGrains;
string grainIdTemplate = $"{prefix}-{{0}}";
//Since the version is NULL, storage provider tries to insert this data
//as new state. If there is already data with this class, the writing fails
//and the storage provider throws. Essentially it means either this range
//is ill chosen or the test failed due to another problem.
var grainStates = Enumerable.Range(StartOfRange, CountOfRange).Select(i => this.GetTestReferenceAndState(string.Format(grainIdTemplate, i), null)).ToList();
// Avoid parallelization of the first write to not stress out the system with deadlocks on INSERT
foreach (var grainData in grainStates)
{
//A sanity checker that the first version really has null as its state. Then it is stored
//to the database and a new version is acquired.
var firstVersion = grainData.Item2.ETag;
Assert.Null(firstVersion);
await Store_WriteRead(grainTypeName, grainData.Item1, grainData.Item2).ConfigureAwait(false);
var secondVersion = grainData.Item2.ETag;
Assert.NotEqual(firstVersion, secondVersion);
};
int MaxNumberOfThreads = Environment.ProcessorCount * 3;
// The purpose of Parallel.ForEach is to ensure the storage provider will be tested from
// multiple threads concurrently, as would happen in running system also.
// Nevertheless limit the degree of parallelization (concurrent threads) to
// avoid unnecessarily starving and growing the thread pool (which is very slow)
// if a few threads coupled with parallelization via tasks can force most concurrency
// scenarios.
Parallel.ForEach(grainStates, new ParallelOptions { MaxDegreeOfParallelism = MaxNumberOfThreads }, async grainData =>
{
// This loop writes the state consecutive times to the database to make sure its
// version is updated appropriately.
for(int k = 0; k < 10; ++k)
{
var versionBefore = grainData.Item2.ETag;
await RetryHelper.RetryOnExceptionAsync(5, RetryOperation.Sigmoid, async () =>
{
await Store_WriteRead(grainTypeName, grainData.Item1, grainData.Item2);
return Task.CompletedTask;
});
var versionAfter = grainData.Item2.ETag;
Assert.NotEqual(versionBefore, versionAfter);
}
});
}
/// <summary>
/// Writes to storage and tries to re-write the same state with NULL as ETag, as if the grain was just created.
/// </summary>
/// <returns>The <see cref="InconsistentStateException"/> thrown by the provider. This can be further inspected
/// by the storage specific asserts.</returns>
internal async Task<InconsistentStateException> PersistenceStorage_WriteDuplicateFailsWithInconsistentStateException()
{
//A grain with a random ID will be arranged to the database. Then its state is set to null to simulate the fact
//it is like a second activation after a one that has succeeded to write.
string grainTypeName = GrainTypeGenerator.GetGrainType<Guid>();
var inconsistentState = this.GetTestReferenceAndState(RandomUtilities.GetRandom<long>(), null);
var grainReference = inconsistentState.Item1;
var grainState = inconsistentState.Item2;
await Store_WriteRead(grainTypeName, inconsistentState.Item1, inconsistentState.Item2).ConfigureAwait(false);
grainState.ETag = null;
var exception = await Record.ExceptionAsync(() => Store_WriteRead(grainTypeName, grainReference, grainState)).ConfigureAwait(false);
Assert.NotNull(exception);
Assert.IsType<InconsistentStateException>(exception);
return (InconsistentStateException)exception;
}
/// <summary>
/// Writes a known inconsistent state to the storage and asserts an exception will be thrown.
/// </summary>
/// <returns>The <see cref="InconsistentStateException"/> thrown by the provider. This can be further inspected
/// by the storage specific asserts.</returns>
internal async Task<InconsistentStateException> PersistenceStorage_WriteInconsistentFailsWithInconsistentStateException()
{
//Some version not expected to be in the storage for this type and ID.
var inconsistentStateVersion = RandomUtilities.GetRandom<int>().ToString(CultureInfo.InvariantCulture);
var inconsistentState = this.GetTestReferenceAndState(RandomUtilities.GetRandom<long>(), inconsistentStateVersion);
string grainTypeName = GrainTypeGenerator.GetGrainType<Guid>();
var exception = await Record.ExceptionAsync(() => Store_WriteRead(grainTypeName, inconsistentState.Item1, inconsistentState.Item2)).ConfigureAwait(false);
Assert.NotNull(exception);
Assert.IsType<InconsistentStateException>(exception);
return (InconsistentStateException)exception;
}
/// <summary>
/// Writes a known inconsistent state to the storage and asserts an exception will be thrown.
/// </summary>
/// <returns></returns>
internal async Task PersistenceStorage_Relational_WriteReadIdCyrillic()
{
var grainTypeName = GrainTypeGenerator.GetGrainType<Guid>();
var grainReference = this.GetTestReferenceAndState(0, null);
var grainState = grainReference.Item2;
await Storage.WriteStateAsync(grainTypeName, grainReference.Item1, grainState).ConfigureAwait(false);
var storedGrainState = new GrainState<TestState1> { State = new TestState1() };
await Storage.ReadStateAsync(grainTypeName, grainReference.Item1, storedGrainState).ConfigureAwait(false);
Assert.Equal(grainState.ETag, storedGrainState.ETag);
Assert.Equal(grainState.State, storedGrainState.State);
}
/// <summary>
/// Writes to storage, reads back and asserts both the version and the state.
/// </summary>
/// <typeparam name="T">The grain state type.</typeparam>
/// <param name="grainTypeName">The type of the grain.</param>
/// <param name="grainReference">The grain reference as would be given by Orleans.</param>
/// <param name="grainState">The grain state the grain would hold and Orleans pass.</param>
/// <returns></returns>
internal async Task Store_WriteRead<T>(string grainTypeName, GrainReference grainReference, GrainState<T> grainState) where T : new()
{
await Storage.WriteStateAsync(grainTypeName, grainReference, grainState).ConfigureAwait(false);
var storedGrainState = new GrainState<T> { State = new T() };
await Storage.ReadStateAsync(grainTypeName, grainReference, storedGrainState).ConfigureAwait(false);
Assert.Equal(grainState.ETag, storedGrainState.ETag);
Assert.Equal(grainState.State, storedGrainState.State);
}
/// <summary>
/// Writes to storage, clears and reads back and asserts both the version and the state.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="grainTypeName">The type of the grain.</param>
/// <param name="grainReference">The grain reference as would be given by Orleans.</param>
/// <param name="grainState">The grain state the grain would hold and Orleans pass.</param>
/// <returns></returns>
internal async Task Store_WriteClearRead<T>(string grainTypeName, GrainReference grainReference, GrainState<T> grainState) where T : new()
{
//A legal situation for clearing has to be arranged by writing a state to the storage before
//clearing it. Writing and clearing both change the ETag, so they should differ.
await Storage.WriteStateAsync(grainTypeName, grainReference, grainState);
string writtenStateVersion = grainState.ETag;
await Storage.ClearStateAsync(grainTypeName, grainReference, grainState).ConfigureAwait(false);
string clearedStateVersion = grainState.ETag;
var storedGrainState = new GrainState<T> { State = new T() };
await Storage.ReadStateAsync(grainTypeName, grainReference, storedGrainState).ConfigureAwait(false);
Assert.NotEqual(writtenStateVersion, clearedStateVersion);
Assert.Equal(storedGrainState.State, Activator.CreateInstance<T>());
}
/// <summary>
/// Creates a new grain and a grain reference pair.
/// </summary>
/// <param name="grainId">The grain ID.</param>
/// <param name="version">The initial version of the state.</param>
/// <returns>A grain reference and a state pair.</returns>
internal Tuple<GrainReference, GrainState<TestState1>> GetTestReferenceAndState(long grainId, string version)
{
return Tuple.Create(this.grainFactory.GetGrain(GrainId.GetGrainId(UniqueKey.NewKey(grainId, UniqueKey.Category.Grain))), new GrainState<TestState1> { State = new TestState1(), ETag = version });
}
/// <summary>
/// Creates a new grain and a grain reference pair.
/// </summary>
/// <param name="grainId">The grain ID.</param>
/// <param name="version">The initial version of the state.</param>
/// <returns>A grain reference and a state pair.</returns>
internal Tuple<GrainReference, GrainState<TestState1>> GetTestReferenceAndState(string grainId, string version)
{
return Tuple.Create(this.grainFactory.GetGrain(GrainId.FromParsableString(GrainId.GetGrainId(RandomUtilities.NormalGrainTypeCode, grainId).ToParsableString())), new GrainState<TestState1> { State = new TestState1(), ETag = version });
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Runtime.Serialization;
using System.Configuration;
using System.Xml;
using System.Text;
using System.Resources;
using System.Globalization;
using System.Diagnostics;
using PHP.Core.Reflection;
#if SILVERLIGHT
using PHP.CoreCLR;
#else
using System.Web; // ReportError(config, HttpContext.Current.Response.Output, error, id, info, message);
#endif
namespace PHP.Core
{
#region Enumerations
/// <summary>
/// Types of errors caused by PHP class library functions.
/// </summary>
[Flags]
public enum PhpError : int
{
/// <summary>Error.</summary>
Error = 1,
/// <summary>Warning.</summary>
Warning = 2,
/// <summary>Notice.</summary>
Notice = 8,
/// <summary>User error.</summary>
UserError = 256,
/// <summary>User warning.</summary>
UserWarning = 512,
/// <summary>User notice.</summary>
UserNotice = 1024,
/// <summary>Parse error.</summary>
ParseError = 4,
/// <summary>Core error.</summary>
CoreError = 16,
/// <summary>Core warning.</summary>
CoreWarning = 32,
/// <summary>Compile error.</summary>
CompileError = 64,
/// <summary>Compile warning.</summary>
CompileWarning = 128,
/// <summary>Strict notice (PHP 5.0+).</summary>
Strict = 2048,
/// <summary>PHP 5.2+</summary>
RecoverableError = 4096,
/// <summary>Deprecated (PHP 5.3+)</summary>
Deprecated = 8192,
UserDeprecated = 16384,
}
/// <summary>
/// Sets of error types.
/// </summary>
[Flags]
public enum PhpErrorSet : int
{
/// <summary>Empty error set.</summary>
None = 0,
/// <summary>Standard errors used by Core and Class Library.</summary>
Standard = PhpError.Error | PhpError.Warning | PhpError.Notice | PhpError.Deprecated,
/// <summary>User triggered errors.</summary>
User = PhpError.UserError | PhpError.UserWarning | PhpError.UserNotice | PhpError.UserDeprecated,
/// <summary>Core system errors.</summary>
System = PhpError.ParseError | PhpError.CoreError | PhpError.CoreWarning | PhpError.CompileError | PhpError.CompileWarning | PhpError.RecoverableError,
/// <summary>All possible errors except for the strict ones.</summary>
AllButStrict = Standard | User | System,
/// <summary>All possible errors. 30719 in PHP 5.3</summary>
All = AllButStrict | PhpError.Strict,
/// <summary>Errors which can be handled by the user defined routine.</summary>
Handleable = (User | Standard) & ~PhpError.Error,
/// <summary>Errors which causes termination of a running script.</summary>
Fatal = PhpError.Error | PhpError.CompileError | PhpError.CoreError | PhpError.UserError
}
/// <summary>
/// Type of action being performed when PhpException static handlers (Throw, InvalidArgument, ...) are called.
/// </summary>
public enum PhpErrorAction
{
/// <summary>An action specified by the current configuration is taken.</summary>
Default,
/// <summary>An exception is thrown.</summary>
Throw,
/// <summary>Do nothing but setting the flag.</summary>
None
}
#endregion
/// <summary>
/// Represents information about an error got from the stack.
/// </summary>
public struct ErrorStackInfo
{
/// <summary>
/// The name of the source file.
/// </summary>
public string File;
/// <summary>
/// The name of the PHP function which caused an error.
/// </summary>
public string Caller;
/// <summary>
/// Whether a caller is a library function.
/// </summary>
public bool LibraryCaller;
/// <summary>
/// A number of a line in a source file where an error occured.
/// </summary>
public int Line;
/// <summary>
/// A number of a column in a source file where an error occured.
/// </summary>
public int Column;
/// <summary>
/// Initializes <see cref="ErrorStackInfo"/> by given values.
/// </summary>
/// <param name="file">Full path to a source file.</param>
/// <param name="caller">Name of a calling PHP funcion.</param>
/// <param name="line">Line in a source file.</param>
/// <param name="column">Column in a source file.</param>
/// <param name="libraryCaller">Whether a caller is a library function.</param>
public ErrorStackInfo(string file, string caller, int line, int column, bool libraryCaller)
{
File = file;
Caller = caller;
Line = line;
Column = column;
LibraryCaller = libraryCaller;
}
}
/// <summary>
/// Represents exceptions thrown by PHP class library functions.
/// </summary>
[Serializable]
[DebuggerNonUserCode]
public class PhpException : System.Exception
{
#region Frequently reported errors
/// <summary>
/// Invalid argument error.
/// </summary>
/// <param name="argument">The name of the argument being invalid.</param>
public static void InvalidArgument(string argument)
{
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument", argument));
}
/// <summary>
/// Invalid argument error with a description of a reason.
/// </summary>
/// <param name="argument">The name of the argument being invalid.</param>
/// <param name="message">The message - what is wrong with the argument. Must contain "{0}" which is replaced by argument's name.
/// </param>
public static void InvalidArgument(string argument, string message)
{
Throw(PhpError.Warning, String.Format(CoreResources.GetString("invalid_argument_with_message") + message, argument));
}
/// <summary>
/// Argument null error. Thrown when argument can't be null but it is.
/// </summary>
/// <param name="argument">The name of the argument.</param>
public static void ArgumentNull(string argument)
{
Throw(PhpError.Warning, CoreResources.GetString("argument_null", argument));
}
/// <summary>
/// Reference argument null error. Thrown when argument which is passed by reference is null.
/// </summary>
/// <param name="argument">The name of the argument.</param>
public static void ReferenceNull(string argument)
{
Throw(PhpError.Error, CoreResources.GetString("reference_null", argument));
}
/// <summary>
/// Called library function is not supported.
/// </summary>
public static void FunctionNotSupported()
{
Throw(PhpError.Warning, CoreResources.GetString("function_not_supported"));
}
/// <summary>
/// Called library function is not supported.
/// </summary>
/// <param name="function">Not supported function name.</param>
[Emitted]
public static void FunctionNotSupported(string/*!*/function)
{
Debug.Assert(!string.IsNullOrEmpty(function));
Throw(PhpError.Warning, CoreResources.GetString("notsupported_function_called", function));
}
/// <summary>
/// Calles library function is not supported.
/// </summary>
/// <param name="severity">A severity of the error.</param>
public static void FunctionNotSupported(PhpError severity)
{
Throw(severity, CoreResources.GetString("function_not_supported"));
}
///// <summary>
///// Called library function is deprecated.
///// </summary>
//public static void FunctionDeprecated()
//{
// ErrorStackInfo info = PhpStackTrace.TraceErrorFrame(ScriptContext.CurrentContext);
// FunctionDeprecated(info.LibraryCaller ? info.Caller : null);
//}
/// <summary>
/// Called library function is deprecated.
/// </summary>
public static void FunctionDeprecated(string functionName)
{
Throw(PhpError.Deprecated, CoreResources.GetString("function_is_deprecated", functionName));
}
/// <summary>
/// Calls by the Class Library methods which need variables but get a <b>null</b> reference.
/// </summary>
public static void NeedsVariables()
{
Throw(PhpError.Warning, CoreResources.GetString("function_needs_variables"));
}
/// <summary>
/// The value of an argument is not invalid but unsupported.
/// </summary>
/// <param name="argument">The argument which value is unsupported.</param>
/// <param name="value">The value which is unsupported.</param>
public static void ArgumentValueNotSupported(string argument, object value)
{
Throw(PhpError.Warning, CoreResources.GetString("argument_value_not_supported", value, argument));
}
/// <summary>
/// Throw by <see cref="PhpStack"/> when a peeked argument should be passed by reference but it is not.
/// </summary>
/// <param name="index">An index of the argument.</param>
/// <param name="calleeName">A name of the function or method being called. Can be a <B>null</B> reference.</param>
public static void ArgumentNotPassedByRef(int index, string calleeName)
{
if (calleeName != null)
Throw(PhpError.Error, CoreResources.GetString("argument_not_passed_byref_to", index, calleeName));
else
Throw(PhpError.Error, CoreResources.GetString("argument_not_passed_byref", index));
}
/// <summary>
/// Emitted to a user function/method call which has less actual arguments than it's expected to have.
/// </summary>
/// <param name="index">An index of the parameter.</param>
/// <param name="calleeName">A name of the function or method being called. Can be a <B>null</B> reference.</param>
[Emitted]
public static void MissingArgument(int index, string calleeName)
{
if (calleeName != null)
Throw(PhpError.Warning, CoreResources.GetString("missing_argument_for", index, calleeName));
else
Throw(PhpError.Warning, CoreResources.GetString("missing_argument", index));
}
/// <summary>
/// Emitted to a user function/method call which has less actual type arguments than it's expected to have.
/// </summary>
/// <param name="index">An index of the type parameter.</param>
/// <param name="calleeName">A name of the function or method being called. Can be a <B>null</B> reference.</param>
[Emitted]
public static void MissingTypeArgument(int index, string calleeName)
{
if (calleeName != null)
Throw(PhpError.Warning, CoreResources.GetString("missing_type_argument_for", index, calleeName));
else
Throw(PhpError.Warning, CoreResources.GetString("missing_type_argument", index));
}
[Emitted]
public static void MissingArguments(string typeName, string methodName, int actual, int required)
{
if (typeName != null)
{
if (methodName != null)
Throw(PhpError.Warning, CoreResources.GetString("too_few_method_params", typeName, methodName, required, actual));
else
Throw(PhpError.Warning, CoreResources.GetString("too_few_ctor_params", typeName, required, actual));
}
else
Throw(PhpError.Warning, CoreResources.GetString("too_few_function_params", methodName, required, actual));
}
public static void UnsupportedOperandTypes()
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("unsupported_operand_types"));
}
/// <summary>
/// Emitted to a library function call which has invalid actual argument count.
/// </summary>
[Emitted]
public static void InvalidArgumentCount(string typeName, string methodName)
{
if (methodName != null)
{
if (typeName != null)
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument_count_for_method", typeName, methodName));
else
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument_count_for_function", methodName));
}
else
Throw(PhpError.Warning, CoreResources.GetString("invalid_argument_count"));
}
/// <summary>
/// Emitted to the foreach statement if the variable to be enumerated doesn't implement
/// the <see cref="IPhpEnumerable"/> interface.
/// </summary>
[Emitted]
public static void InvalidForeachArgument()
{
Throw(PhpError.Warning, CoreResources.GetString("invalid_foreach_argument"));
}
/// <summary>
/// Emitted to the function call if an argument cannot be implicitly casted.
/// </summary>
/// <param name="argument">The argument which is casted.</param>
/// <param name="targetType">The type to which is casted.</param>
/// <param name="functionName">The name of the function called.</param>
[Emitted]
public static void InvalidImplicitCast(object argument, string targetType, string functionName)
{
Throw(PhpError.Warning, CoreResources.GetString("invalid_implicit_cast",
PhpVariable.GetTypeName(argument),
targetType,
functionName));
}
/// <summary>
/// Emitted to the code on the places where invalid number of breaking levels is used.
/// </summary>
/// <param name="levelCount">The number of levels.</param>
[Emitted]
public static void InvalidBreakLevelCount(int levelCount)
{
Throw(PhpError.Error, CoreResources.GetString("invalid_break_level_count", levelCount));
}
/// <summary>
/// Reported by operators when they found that a undefined variable is acceesed.
/// </summary>
/// <param name="name">The name of the variable.</param>
[Emitted]
public static void UndefinedVariable(string name)
{
Throw(PhpError.Notice, CoreResources.GetString("undefined_variable", name));
}
/// <summary>
/// Emitted instead of the assignment of to the "$this" variable.
/// </summary>
[Emitted]
public static void CannotReassignThis()
{
Throw(PhpError.Error, CoreResources.GetString("cannot_reassign_this"));
}
/// <summary>
/// An argument violates a type hint.
/// </summary>
/// <param name="argName">The name of the argument.</param>
/// <param name="typeName">The name of the hinted type.</param>
[Emitted]
public static void InvalidArgumentType(string argName, string typeName)
{
Throw(PhpError.Error, CoreResources.GetString("invalid_argument_type", argName, typeName));
}
/// <summary>
/// Array operators reports this error if an value of illegal type is used for indexation.
/// </summary>
public static void IllegalOffsetType()
{
Throw(PhpError.Warning, CoreResources.GetString("illegal_offset_type"));
}
/// <summary>
/// Array does not contain given <paramref name="key"/>.
/// </summary>
/// <param name="key">Key which was not found in the array.</param>
public static void UndefinedOffset(object key)
{
Throw(PhpError.Notice, CoreResources.GetString("undefined_offset", key));
}
/// <summary>
/// Emitted to the script's Main() routine. Thrown when an unexpected exception is catched.
/// </summary>
/// <param name="e">The catched exception.</param>
public static void InternalError(Exception e)
{
throw new PhpNetInternalException(e.Message, e);
}
/// <summary>
/// Reports an error when a variable should be PHP array but it is not.
/// </summary>
/// <param name="reference">Whether a reference modifier (=&) is used.</param>
/// <param name="var">The variable which was misused.</param>
/// <exception cref="PhpException"><paramref name="var"/> is <see cref="PhpArray"/> (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is scalar type (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is a string (Warning).</exception>
public static void VariableMisusedAsArray(object var, bool reference)
{
Debug.Assert(var != null);
DObject obj;
if ((obj = var as DObject) != null)
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("object_used_as_array", obj.TypeName));
}
else if (PhpVariable.IsString(var))
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString(reference ? "string_item_used_as_reference" : "string_used_as_array"));
}
else
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("scalar_used_as_array", PhpVariable.GetTypeName(var)));
}
}
/// <summary>
/// Reports an error when a variable should be PHP object but it is not.
/// </summary>
/// <param name="reference">Whether a reference modifier (=&) is used.</param>
/// <param name="var">The variable which was misused.</param>
/// <exception cref="PhpException"><paramref name="var"/> is <see cref="PhpArray"/> (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is scalar type (Warning).</exception>
/// <exception cref="PhpException"><paramref name="var"/> is a string (Warning).</exception>
public static void VariableMisusedAsObject(object var, bool reference)
{
Debug.Assert(var != null);
if (var is PhpArray)
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("array_used_as_object"));
}
else if (PhpVariable.IsString(var))
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString(reference ? "string_item_used_as_reference" : "string_used_as_object"));
}
else
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("scalar_used_as_object", PhpVariable.GetTypeName(var)));
}
}
/// <summary>
/// Thrown when "this" special variable is used out of class.
/// </summary>
[Emitted]
public static void ThisUsedOutOfObjectContext()
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("this_used_out_of_object"));
}
public static void UndeclaredStaticProperty(string className, string fieldName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("undeclared_static_property_accessed", className, fieldName));
}
[Emitted]
public static void StaticPropertyUnset(string className, string fieldName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("static_property_unset", className, fieldName));
}
[Emitted]
public static void UndefinedMethodCalled(string className, string methodName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("undefined_method_called", className, methodName));
}
public static void AbstractMethodCalled(string className, string methodName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("abstract_method_called", className, methodName));
}
public static void ConstantNotAccessible(string className, string constName, string context, bool isProtected)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isProtected ? "protected_constant_accessed" : "private_constant_accessed", className, constName, context));
}
public static void PropertyNotAccessible(string className, string fieldName, string context, bool isProtected)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isProtected ? "protected_property_accessed" : "private_property_accessed", className, fieldName, context));
}
public static void MethodNotAccessible(string className, string methodName, string context, bool isProtected)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isProtected ? "protected_method_called" : "private_method_called", className, methodName, context));
}
public static void CannotInstantiateType(string typeName, bool isInterface)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
isInterface ? "interface_instantiated" : "abstract_class_instantiated", typeName));
}
[Emitted]
public static void NoSuitableOverload(string className, string/*!*/ methodName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString(
(className != null) ? "no_suitable_method_overload" : "no_suitable_function_overload",
className, methodName));
}
[Emitted]
public static void PropertyTypeMismatch(string/*!*/ className, string/*!*/ propertyName)
{
PhpException.Throw(PhpError.Error, CoreResources.GetString("property_type_mismatch",
className, propertyName));
}
#endregion
#region Error handling stuff
/// <summary>
/// Delegate used to catch any thrown PHP exception. Used in compile time to catch PHP runtime exceptions.
/// </summary>
[ThreadStatic]
internal static Action<PhpError, string> ThrowCallbackOverride = null;
/// <summary>
/// Reports a PHP error.
/// </summary>
/// <param name="error">The error type</param>
/// <param name="message">The error message.</param>
public static void Throw(PhpError error, string message)
{
if (ThrowCallbackOverride != null)
{
ThrowCallbackOverride(error, message);
return;
}
ErrorStackInfo info = new ErrorStackInfo();
bool info_loaded = false;
// gets the current script context and config:
ScriptContext context = ScriptContext.CurrentContext;
LocalConfiguration config = context.Config;
// determines whether the error will be reported and whether it is handleable:
bool is_error_reported = ((PhpErrorSet)error & config.ErrorControl.ReportErrors) != 0 && !context.ErrorReportingDisabled;
bool is_error_handleable = ((PhpErrorSet)error & PhpErrorSet.Handleable & (PhpErrorSet)config.ErrorControl.UserHandlerErrors) != 0;
bool is_error_fatal = ((PhpErrorSet)error & PhpErrorSet.Fatal) != 0;
bool do_report = true;
// remember last error info
context.LastErrorType = error;
context.LastErrorMessage = message;
context.LastErrorFile = null; // only if we are getting ErrorStackInfo, see PhpStackTrace.TraceErrorFrame
context.LastErrorLine = 0; // only if we are getting ErrorStackInfo, see PhpStackTrace.TraceErrorFrame
// calls a user defined handler if available:
if (is_error_handleable && config.ErrorControl.UserHandler != null)
{
// loads stack info:
Func<ErrorStackInfo> func = () =>
{
if (!info_loaded)
{
info = PhpStackTrace.TraceErrorFrame(context, true);
info_loaded = true;
}
return info;
};
do_report = CallUserErrorHandler(context, error, func, message);
}
// reports error to output and logs:
if (do_report && is_error_reported &&
(config.ErrorControl.DisplayErrors || config.ErrorControl.EnableLogging)) // check if the error will be displayed to avoid stack trace loading
{
// loads stack info:
if (!info_loaded) { info = PhpStackTrace.TraceErrorFrame(context, false); info_loaded = true; }
ReportError(config, context.Output, error, -1, info, message);
}
// Throws an exception if the error is fatal and throwing is enabled.
// PhpError.UserError is also fatal, but can be cancelled by user handler => handler call must precede this line.
// Error displaying must also precede this line because the error should be displayed before an exception is thrown.
if (is_error_fatal && context.ThrowExceptionOnError)
{
// loads stack info:
if (!info_loaded) { info = PhpStackTrace.TraceErrorFrame(context, false); info_loaded = true; }
throw new PhpException(error, message, info);
}
}
/// <summary>
/// Reports an error to log file, event log and to output (as configured).
/// </summary>
private static void ReportError(LocalConfiguration config, TextWriter output, PhpError error, int id,
ErrorStackInfo info, string message)
{
string formatted_message = FormatErrorMessageOutput(config, error, id, info, message);
// logs error if logging is enabled:
if (config.ErrorControl.EnableLogging)
{
#if SILVERLIGHT
throw new NotSupportedException("Logging is not supported on Silverlight. Set EnableLogging to false.");
#else
// adds a message to log file:
if (config.ErrorControl.LogFile != null)
try
{
// <error>: <caller>(): <message> in <file> on line <line>
string caller = (info.Caller != null) ? (info.Caller + "(): ") : null;
string place = (info.Line > 0 && info.Column > 0) ? CoreResources.GetString("error_place", info.File, info.Line, info.Column) : null;
Logger.AppendLine(config.ErrorControl.LogFile, string.Concat(error, ": ", caller, message, place));
}
catch (Exception) { }
// adds a message to event log:
if (config.ErrorControl.SysLog)
try { Logger.AddToEventLog(message); }
catch (Exception) { }
#endif
}
// displays an error message if desired:
if (config.ErrorControl.DisplayErrors)
{
output.Write(config.ErrorControl.ErrorPrependString);
output.Write(formatted_message);
output.Write(config.ErrorControl.ErrorAppendString);
}
}
/// <summary>
/// Calls user error handler.
/// </summary>
/// <returns>Whether to report error by default handler (determined by handler's return value).</returns>
/// <exception cref="ScriptDiedException">Error handler dies.</exception>
private static bool CallUserErrorHandler(ScriptContext context, PhpError error, Func<ErrorStackInfo> info, string message)
{
LocalConfiguration config = context.Config;
try
{
object result = PhpVariable.Dereference(config.ErrorControl.UserHandler.Invoke(new PhpReference[]
{
new PhpReference((int)error),
new PhpReference(message),
new PhpReference(new LazyStackInfo(info, true)),
new PhpReference(new LazyStackInfo(info, false)),
new PhpReference() // global variables list is not supported
}));
// since PHP5 an error is reported by default error handler if user handler returns false:
return result is bool && (bool)result == false;
}
catch (ScriptDiedException)
{
// user handler has cancelled the error via script termination:
throw;
}
catch (PhpUserException)
{
// rethrow user exceptions:
throw;
}
catch (Exception)
{
}
return false;
}
/// <summary>
/// Reports error thrown from inside eval.
/// </summary>
internal static void ThrowByEval(PhpError error, string sourceFile, int line, int column, string message)
{
// obsolete:
// ErrorStackInfo info = new ErrorStackInfo(sourceFile,null,line,column,false);
//
// if (ScriptContext.CurrentContext.Config.ErrorControl.HtmlMessages)
// message = CoreResources.GetString("error_message_html_eval",message,info.Line,info.Column); else
// message = CoreResources.GetString("error_message_plain_eval",message,info.Line,info.Column);
Throw(error, message);
}
/// <summary>
/// Reports error thrown by compiler.
/// </summary>
internal static void ThrowByWebCompiler(PhpError error, int id, string sourceFile, int line, int column, string message)
{
ErrorStackInfo info = new ErrorStackInfo(sourceFile, null, line, column, false);
// gets the current script context and config:
LocalConfiguration config = Configuration.Local;
#if !SILVERLIGHT
ReportError(config, HttpContext.Current.Response.Output, error, id, info, message);
#else
ReportError(config, new StreamWriter(ScriptContext.CurrentContext.OutputStream), error, id, info, message);
#endif
if (((PhpErrorSet)error & PhpErrorSet.Fatal) != 0)
throw new PhpException(error, message, info);
}
/// <summary>
/// Get the error type text, to be displayed on output.
/// </summary>
/// <param name="error"></param>
/// <param name="id"></param>
/// <returns>Error text.</returns>
internal static string PhpErrorText(PhpError error, int id)
{
if (id > 0)
{
return String.Format("{0} ({1})", error, id);
}
else
{
switch (error)
{
// errors with spaces in the name
case PhpError.Strict:
return "Strict Standards";
// user errors reported as normal errors (without "User")
case PhpError.UserNotice:
return PhpError.Notice.ToString();
case PhpError.UserError:
return PhpError.Error.ToString();
case PhpError.UserWarning:
return PhpError.Warning.ToString();
// error string as it is
default:
return error.ToString(); ;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="info"></param>
/// <param name="config"></param>
/// <returns>Returns caller name with () or null. Formatted for the current output capabilities.</returns>
internal static string FormatErrorCallerName(ErrorStackInfo info, LocalConfiguration config)
{
if (info.Caller == null)
return null;
if (config.ErrorControl.HtmlMessages && config.ErrorControl.DocRefRoot != null && info.LibraryCaller)
{ // able to display HTML
return String.Format("<a href='{0}/function.{1}{2}'>{3}()</a>",
config.ErrorControl.DocRefRoot,
info.Caller.Replace('_', '-').ToLower(),
config.ErrorControl.DocRefExtension,
info.Caller);
}
else
{
return info.Caller + "()";
}
}
/// <summary>
/// Modifies the error message and caller display text, depends on error type.
/// In case of different PHP behavior.
/// </summary>
/// <param name="error">error type.</param>
/// <param name="message">Error message, in default without any change.</param>
/// <param name="caller">Caller text, in default will be modified to "foo(): ".</param>
internal static void FormatErrorMessageText(PhpError error, ref string message, ref string caller)
{
switch (error)
{
case PhpError.Deprecated:
case PhpError.UserNotice:
caller = null; // the caller is not displayed in PHP
return;
default:
if (caller != null)
caller += ": ";
return;
}
}
/// <summary>
/// Formats error message.
/// </summary>
/// <param name="config">A configuration.</param>
/// <param name="error">A type of the error.</param>
/// <param name="id">Error id or -1.</param>
/// <param name="info">A stack information about the error.</param>
/// <param name="message">A message.</param>
/// <returns>A formatted plain text or HTML message depending on settings in <paramref name="config"/>.</returns>
/// <exception cref="ArgumentNullException"><paramren name="config"/> is a <B>null</B> reference.</exception>
public static string FormatErrorMessageOutput(LocalConfiguration config, PhpError error, int id, ErrorStackInfo info, string message)
{
if (config == null)
throw new ArgumentNullException("config");
string error_str = PhpErrorText(error, id); // the error type (Warning, Error, ...)
bool show_place = info.Line > 0 && info.Column > 0; // we are able to report error position
string caller = FormatErrorCallerName(info, config); // current function name "foo()" or null
// change the message or caller, based on the error type
FormatErrorMessageText(error, ref message, ref caller);
// error message
string ErrorFormatString =
config.ErrorControl.HtmlMessages ?
(show_place ? CoreResources.error_message_html_debug : CoreResources.error_message_html) :
(show_place ? CoreResources.error_message_plain_debug : CoreResources.error_message_plain);
if (show_place)
return string.Format(ErrorFormatString,
error_str, caller, message, info.File, info.Line, info.Column);
else
return string.Format(ErrorFormatString,
error_str, caller, message);
}
/// <summary>
/// Converts exception message (ending by dot) to error message (not ending by a dot).
/// </summary>
/// <param name="exceptionMessage">The exception message.</param>
/// <returns>The error message.</returns>
/// <exception cref="ArgumentNullException"><paramref name="exceptionMessage"/> is a <B>null</B> reference.</exception>
public static string ToErrorMessage(string exceptionMessage)
{
if (exceptionMessage == null) throw new ArgumentNullException("exceptionMessage");
return exceptionMessage.TrimEnd(new char[] { '.' });
}
#endregion
#region Exception handling stuff
/// <summary>
/// Exception constructor.
/// </summary>
internal PhpException()
{
}
/// <summary>
/// Exception constructor.
/// </summary>
/// <param name="error">The type of PHP error.</param>
/// <param name="message">The error message.</param>
/// <param name="info">Information about an error gained from a stack.</param>
private PhpException(PhpError error, string message, ErrorStackInfo info)
: base(message)
{
this.info = info;
this.error = error;
}
/// <summary>
/// Error seriousness.
/// </summary>
public PhpError Error { get { return error; } }
private PhpError error;
/// <summary>
/// Error debug info (caller, source file, line and column).
/// </summary>
public ErrorStackInfo DebugInfo { get { return info; } }
private ErrorStackInfo info;
/// <summary>
/// Converts the exception to a string message.
/// </summary>
/// <returns>The formatted message.</returns>
public override string ToString()
{
return FormatErrorMessageOutput(ScriptContext.CurrentContext.Config, error, -1, info, Message);
}
#endregion
#region Serialization (CLR only)
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of the PhpException class with serialized data. This constructor is used
/// when an exception is thrown in a remotely called method. Such an exceptions needs to be serialized,
/// transferred back to the caller and then rethrown using this constructor.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data about the exception
/// being thrown.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or
/// destination.</param>
protected PhpException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.error = (PhpError)info.GetValue("error", typeof(PhpError));
this.info = new ErrorStackInfo(
(string)info.GetString("file"),
(string)info.GetString("caller"),
(int)info.GetInt32("line"),
(int)info.GetInt32("column"),
(bool)info.GetBoolean("libraryCaller"));
}
/// <summary>
/// Sets the SerializationInfo with information about the exception. This method is called when a skeleton
/// catches PhpException thrown in a remotely called method.
/// </summary>
/// <param name="info">The SerializationInfo that holds the serialized object data.</param>
/// <param name="context">The StreamingContext that contains contextual information about the source or
/// destination.</param>
[System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("error", error);
info.AddValue("caller", this.info.Caller);
info.AddValue("file", this.info.File);
info.AddValue("line", this.info.Line);
info.AddValue("column", this.info.Column);
}
#endif
#endregion
}
internal class LazyStackInfo : IPhpVariable
{
private PhpReference value;
private Func<ErrorStackInfo> info;
private readonly bool file;
private PhpReference Value
{
get
{
if (value == null)
value = file ? new PhpReference(info().File) : new PhpReference(info().Line);
return value;
}
}
public LazyStackInfo(Func<ErrorStackInfo> info, bool file)
{
this.info = info;
this.file = file;
}
public PhpTypeCode GetTypeCode()
{
return Value.GetTypeCode();
}
public double ToDouble()
{
return Value.ToDouble();
}
public int ToInteger()
{
return Value.ToInteger();
}
public long ToLongInteger()
{
return Value.ToLongInteger();
}
public bool ToBoolean()
{
return Value.ToBoolean();
}
public PhpBytes ToPhpBytes()
{
return Value.ToPhpBytes();
}
public Convert.NumberInfo ToNumber(out int intValue, out long longValue, out double doubleValue)
{
return Value.ToNumber(out intValue, out longValue, out doubleValue);
}
public string ToString(bool throwOnError, out bool success)
{
return ((IPhpConvertible)Value).ToString(throwOnError, out success);
}
public void Print(TextWriter output)
{
Value.Print(output);
}
public void Dump(TextWriter output)
{
Value.Dump(output);
}
public void Export(TextWriter output)
{
Value.Export(output);
}
public object DeepCopy()
{
return Value.DeepCopy();
}
public object Copy(CopyReason reason)
{
return this;
}
public int CompareTo(object obj)
{
return Value.CompareTo(obj);
}
public int CompareTo(object obj, IComparer comparer)
{
return Value.CompareTo(obj, comparer);
}
public bool IsEmpty()
{
return Value.IsEmpty();
}
public bool IsScalar()
{
return Value.IsScalar();
}
public string GetTypeName()
{
return Value.GetTypeName();
}
public override string ToString()
{
if (Value.Value == null)
return string.Empty;
return Value.Value.ToString();
}
}
internal static class ErrorSeverityHelper
{
public static PhpError ToPhpCompileError(this ErrorSeverity severity)
{
return (severity.Value == ErrorSeverity.Values.Warning)
? PhpError.CompileWarning
: PhpError.CompileError;
}
}
// TODO:
internal sealed class EvalErrorSink : ErrorSink
{
private readonly int firstLineColumnDisplacement;
public EvalErrorSink(int firstLineColumnDisplacement, WarningGroups disabledGroups, int[]/*!*/ disabledWarnings)
: base(disabledGroups, disabledWarnings)
{
this.firstLineColumnDisplacement = firstLineColumnDisplacement;
}
protected override bool Add(int id, string message, ErrorSeverity severity, int group, string/*!*/ fullPath,
ErrorPosition pos)
{
Debug.Assert(fullPath != null);
// first line column adjustment:
if (pos.FirstLine == 1) pos.FirstColumn += firstLineColumnDisplacement;
Debug.WriteLine("!!!3", message);
PhpException.ThrowByEval(severity.ToPhpCompileError(), fullPath, pos.FirstLine, pos.FirstColumn, message);
return true;
}
}
internal sealed class WebErrorSink : ErrorSink
{
public WebErrorSink(WarningGroups disabledGroups, int[]/*!*/ disabledWarnings)
: base(disabledGroups, disabledWarnings)
{
}
protected override bool Add(int id, string message, ErrorSeverity severity, int group, string/*!*/ fullPath,
ErrorPosition pos)
{
Debug.Assert(fullPath != null);
PhpException.ThrowByWebCompiler(severity.ToPhpCompileError(), id, fullPath, pos.FirstLine, pos.FirstColumn, message);
return true;
}
}
/// <summary>
/// Thrown when data are not found found in call context or are not valid.
/// </summary>
[Serializable]
public class InvalidCallContextDataException : ApplicationException
{
internal InvalidCallContextDataException(string slot)
: base(CoreResources.GetString("invalid_call_context_data", slot)) { }
}
/// <summary>
/// Thrown by exit/die language constructs to cause immediate termination of a script being executed.
/// </summary>
[Serializable]
public class ScriptDiedException : ApplicationException
{
internal ScriptDiedException(object status)
{
this.status = status;
}
internal ScriptDiedException() : this(255) { }
public object Status { get { return status; } set { status = value; } }
private object status;
#region Serializable
#if !SILVERLIGHT
public ScriptDiedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
this.Status = info.GetValue("Status", typeof(object));
}
}
[System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
if (info != null)
{
info.AddValue("Status", Status);
}
}
#endif
#endregion
}
/// <summary>
/// Thrown when user attempts to create two types with same name in one assembly.
/// </summary>
internal class DuplicateTypeNames : ApplicationException
{
public DuplicateTypeNames(string name)
{
this.name = name;
}
public readonly string name;
}
/// <summary>
/// Thrown when an unexpected exception is thrown during a script execution.
/// </summary>
[Serializable]
public class PhpNetInternalException : ApplicationException
{
internal PhpNetInternalException(string message, Exception inner) : base(message, inner) { }
#if !SILVERLIGHT
protected PhpNetInternalException(SerializationInfo info, StreamingContext context) : base(info, context) { }
#endif
/// <summary>
/// Exception details. Contains also details of <see cref="Exception.InnerException"/> to pass this into event logs.
/// </summary>
public override string Message
{
get
{
StringBuilder result = new StringBuilder(base.Message);
//for (var ex = this.InnerException; ex != null; ex = ex.InnerException)
var ex = this.InnerException;
if (ex != null)
{
result.AppendLine();
result.AppendFormat("InnerException: {0}\nat {1}\n", ex.Message, ex.StackTrace);
}
return result.ToString();
}
}
}
/// <summary>
/// Holder for an instance of <see cref="Library.SPL.Exception"/>.
/// For internal purposes only.
/// </summary>
public class PhpUserException : ApplicationException
{
public readonly Library.SPL.Exception UserException;
public PhpUserException(Library.SPL.Exception inner)
: base(Convert.ObjectToString(inner.getMessage(ScriptContext.CurrentContext)))
{
UserException = inner;
}
}
/// <summary>
/// An implementation of a method doesn't behave correctly.
/// </summary>
public class InvalidMethodImplementationException : ApplicationException
{
public InvalidMethodImplementationException(string methodName)
: base(CoreResources.GetString("invalid_method_implementation", methodName))
{ }
}
}
| |
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace Elasticsearch.Client
{
public partial class ElasticsearchClient
{
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePut(string snapshot, string repository, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePutAsync(string snapshot, string repository, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePut(string snapshot, string repository, Stream body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePutAsync(string snapshot, string repository, Stream body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePut(string snapshot, string repository, byte[] body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePutAsync(string snapshot, string repository, byte[] body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePutString(string snapshot, string repository, string body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePutStringAsync(string snapshot, string repository, string body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("PUT", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePost(string snapshot, string repository, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePostAsync(string snapshot, string repository, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePost(string snapshot, string repository, Stream body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePostAsync(string snapshot, string repository, Stream body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePost(string snapshot, string repository, byte[] body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePostAsync(string snapshot, string repository, byte[] body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public HttpResponseMessage SnapshotCreatePostString(string snapshot, string repository, string body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return mConnection.Execute("POST", uri, body);
}
///<summary><see href="http://www.elastic.co/guide/en/elasticsearch/reference/master/modules-snapshots.html"/></summary>
///<param name="snapshot">A snapshot name</param>
///<param name="repository">A repository name</param>
///<param name="body">The snapshot definition</param>
///<param name="options">The function to set optional url parameters.</param>
public async Task<HttpResponseMessage> SnapshotCreatePostStringAsync(string snapshot, string repository, string body, Func<SnapshotCreateParameters, SnapshotCreateParameters> options = null)
{
var uri = string.Format("/_0/{1}/{0}", snapshot, repository);
if (options != null)
{
uri = options.Invoke(new SnapshotCreateParameters()).GetUri(uri);
}
return await mConnection.ExecuteAsync("POST", uri, body);
}
}
}
| |
// 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.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
internal class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase
{
[Fact]
public void Never()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object F = 1;
object P { get { return 3; } }
}
class P
{
public P(C c) { }
public object G = 2;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object Q { get { return 4; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("new C()", value);
Verify(evalResult,
EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("G", "2", "object {int}", "new P(new C()).G"),
EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
children = GetChildren(children[1]);
Verify(children,
EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DebuggerBrowsableAttributes are not inherited.
/// </summary>
[Fact]
public void Never_OverridesAndImplements()
{
var source =
@"using System.Diagnostics;
interface I
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P1 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object P2 { get; }
object P3 { get; }
object P4 { get; }
}
abstract class A
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P5 { get; }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal virtual object P6 { get { return 0; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal abstract object P7 { get; }
internal abstract object P8 { get; }
}
class B : A, I
{
public object P1 { get { return 1; } }
object I.P2 { get { return 2; } }
object I.P3 { get { return 3; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object I.P4 { get { return 4; } }
internal override object P5 { get { return 5; } }
internal override object P6 { get { return 6; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P7 { get { return 7; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal override object P8 { get { return 8; } }
}
class C
{
I o = new B();
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("c", value);
Verify(evalResult,
EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable));
children = GetChildren(children[0]);
Verify(children,
EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly),
EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly),
EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly),
EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly),
EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly));
}
/// <summary>
/// DkmClrDebuggerBrowsableAttributes are obtained from the
/// containing type and associated with the member name. For
/// explicit interface implementations, the name will include
/// namespace and type.
/// </summary>
[Fact]
public void Never_ExplicitNamespaceGeneric()
{
var source =
@"using System.Diagnostics;
namespace N1
{
namespace N2
{
class A<T>
{
internal interface I<U>
{
T P { get; }
U Q { get; }
}
}
}
class B : N2.A<object>.I<int>
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object N2.A<object>.I<int>.P { get { return 1; } }
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int Q { get { return 2; } }
}
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("N1.B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{N1.B}", "N1.B", "o"));
}
[Fact]
public void RootHidden()
{
var source =
@"using System.Diagnostics;
struct S
{
internal S(int[] x, object[] y) : this()
{
this.F = x;
this.Q = y;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int[] F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal int P { get { return this.F.Length; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object[] Q { get; private set; }
}
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly B G = new B { H = 4 };
}
class B
{
internal object H;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeA = assembly.GetType("A");
var value = CreateDkmClrValue(
value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }),
type: new DkmClrType((TypeImpl)typeS),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.F[0]"),
EvalResult("[1]", "2", "int", "o.F[1]"),
EvalResult("[0]", "3", "object {int}", "o.Q[0]"),
EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[3]),
EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H"));
}
[Fact]
public void RootHidden_Exception()
{
var source =
@"using System;
using System.Diagnostics;
class E : Exception
{
}
class F : E
{
object G = 1;
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
object P { get { throw new F(); } }
}";
using (new EnsureEnglishUICulture())
{
var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children[1],
EvalResult("G", "1", "object {int}", null));
Verify(children[7],
EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null,
DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly));
}
}
}
/// <summary>
/// Value should not be expandable if all members are marked
/// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)].
/// </summary>
[WorkItem(934800)]
[Fact(Skip = "934800")]
public void RootHidden_Empty()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F1 = new C();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F2 = new C();
}
class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F3 = new object();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly object F4 = null;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o"));
}
[Fact]
public void DebuggerBrowsable_GenericType()
{
var source =
@"using System.Diagnostics;
class C<T>
{
internal C(T f, T g)
{
this.F = f;
this.G = g;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal readonly T F;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal readonly T G;
}
struct S
{
internal S(object o)
{
this.O = o;
}
internal readonly object O;
}";
var assembly = GetAssembly(source);
var typeS = assembly.GetType("S");
var typeC = assembly.GetType("C`1").MakeGenericType(typeS);
var value = CreateDkmClrValue(
value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)),
type: new DkmClrType((TypeImpl)typeC),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly));
}
[Fact]
public void RootHidden_ExplicitImplementation()
{
var source =
@"using System.Diagnostics;
interface I<T>
{
T P { get; }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
T Q { get; }
}
class A
{
internal object F;
}
class B : I<A>
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
A I<A>.P { get { return new A() { F = 1 }; } }
A I<A>.Q { get { return new A() { F = 2 }; } }
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"),
EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F"));
}
[Fact]
public void RootHidden_ProxyType()
{
var source =
@"using System.Diagnostics;
[DebuggerTypeProxy(typeof(P))]
class A
{
internal A(int f)
{
this.F = f;
}
internal int F;
}
class P
{
private readonly A a;
public P(A a)
{
this.a = a;
}
public object Q { get { return this.a.F; } }
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object R { get { return this.a.F + 1; } }
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F = new A(1);
internal object G = new A(3);
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("B");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[1]),
EvalResult("F", "1", "int", "((A)o.F).F"));
Verify(GetChildren(children[2]),
EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
}
[Fact]
public void RootHidden_Recursive()
{
var source =
@"using System.Diagnostics;
class A
{
internal A(object o)
{
this.F = o;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal object F;
}
class B
{
internal B(object o)
{
this.F = o;
}
internal object F;
}";
var assembly = GetAssembly(source);
var typeA = assembly.GetType("A");
var typeB = assembly.GetType("B");
var value = CreateDkmClrValue(
value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))),
type: new DkmClrType((TypeImpl)typeA),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F"));
}
[Fact]
public void RootHidden_OnStaticMembers()
{
var source =
@"using System.Diagnostics;
class A
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object F = new B();
}
class B
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
internal static object P { get { return new C(); } }
internal static object G = 1;
}
class C
{
internal static object Q { get { return 3; } }
internal object H = 2;
}";
var assembly = GetAssembly(source);
var type = assembly.GetType("A");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[0]);
Verify(children,
EvalResult("G", "1", "object {int}", "B.G"),
EvalResult("H", "2", "object {int}", "((C)B.P).H"),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class));
children = GetChildren(children[2]);
Verify(children,
EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly));
}
// Dev12 exposes the contents of RootHidden members even
// if the members are private (e.g.: ImmutableArray<T>).
[Fact]
public void RootHidden_OnNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class C<T>
{
public C(params T[] items)
{
this.items = items;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private T[] items;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(1, 2, 3),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "int", "o.items[0]"),
EvalResult("[1]", "2", "int", "o.items[1]"),
EvalResult("[2]", "3", "int", "o.items[2]"));
}
// Dev12 does not merge "Static members" (or "Non-Public
// members") across multiple RootHidden members. In
// other words, there may be multiple "Static members" (or
// "Non-Public members") rows within the same container.
[Fact]
public void RootHidden_WithStaticAndNonPublicMembers()
{
var source =
@"using System.Diagnostics;
public class A
{
public static int PA { get { return 1; } }
internal int FA = 2;
}
public class B
{
internal int PB { get { return 3; } }
public static int FB = 4;
}
public class C
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly object FA = new A();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public object PB { get { return new B(); } }
public static int PC { get { return 5; } }
internal int FC = 6;
}";
var assembly = GetAssembly(source);
var runtime = new DkmClrRuntimeInstance(new Assembly[0]);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type),
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers));
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data),
EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class),
EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
Verify(GetChildren(children[0]),
EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[1]),
EvalResult("FA", "2", "int", "((A)o.FA).FA"));
Verify(GetChildren(children[2]),
EvalResult("FB", "4", "int", "B.FB"));
Verify(GetChildren(children[3]),
EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[4]),
EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly));
Verify(GetChildren(children[5]),
EvalResult("FC", "6", "int", "o.FC"));
}
[Fact]
public void ConstructedGenericType()
{
var source = @"
using System.Diagnostics;
public class C<T>
{
public T X;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Y;
}
";
var assembly = GetAssembly(source);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: type,
evalFlags: DkmEvaluationResultFlags.None);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(evalResult),
EvalResult("X", "0", "int", "o.X"));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using FSLib = Microsoft.FSharp.Compiler.AbstractIL.Internal.Library;
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
internal class Transactional
{
/// Run 'stepWithEffect' followed by continuation 'k', but if the continuation later fails with
/// an exception, undo the original effect by running 'compensatingEffect'.
/// Note: if 'compensatingEffect' throws, it masks the original exception.
/// Note: This is a monadic bind where the first two arguments comprise M<A>.
public static B Try<A, B>(Func<A> stepWithEffect, Action<A> compensatingEffect, Func<A, B> k)
{
var stepCompleted = false;
var allOk = false;
A a = default(A);
try
{
a = stepWithEffect();
stepCompleted = true;
var r = k(a);
allOk = true;
return r;
}
finally
{
if (!allOk && stepCompleted)
{
compensatingEffect(a);
}
}
}
// if A == void, this is the overload
public static B Try<B>(Action stepWithEffect, Action compensatingEffect, Func<B> k)
{
return Try(
() => { stepWithEffect(); return 0; },
(int dummy) => { compensatingEffect(); },
(int dummy) => { return k(); });
}
// if A & B are both void, this is the overload
public static void Try(Action stepWithEffect, Action compensatingEffect, Action k)
{
Try(
() => { stepWithEffect(); return 0; },
(int dummy) => { compensatingEffect(); },
(int dummy) => { k(); return 0; });
}
}
[CLSCompliant(false)]
[ComVisible(true)]
public class FileNode : HierarchyNode
{
private static Dictionary<string, int> extensionIcons;
/// <summary>
/// overwrites of the generic hierarchyitem.
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public override string Caption
{
get
{
// Use LinkedIntoProjectAt property if available
string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt);
if (caption == null || caption.Length == 0)
{
// Otherwise use filename
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
caption = Path.GetFileName(caption);
}
return caption;
}
}
public override int ImageIndex
{
get
{
// Check if the file is there.
if (!this.CanShowDefaultIcon())
{
return (int)ProjectNode.ImageName.MissingFile;
}
//Check for known extensions
int imageIndex;
string extension = System.IO.Path.GetExtension(this.FileName);
if ((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex)))
{
// Missing or unknown extension; let the base class handle this case.
return base.ImageIndex;
}
// The file type is known and there is an image for it in the image list.
return imageIndex;
}
}
public override Guid ItemTypeGuid
{
get { return VSConstants.GUID_ItemType_PhysicalFile; }
}
public override int MenuCommandId
{
get { return VsMenus.IDM_VS_CTXT_ITEMNODE; }
}
public override string Url
{
get
{
string path = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
if (String.IsNullOrEmpty(path))
{
return String.Empty;
}
Url url;
if (Path.IsPathRooted(path))
{
// Use absolute path
url = new Microsoft.VisualStudio.Shell.Url(path);
}
else
{
// Path is relative, so make it relative to project path
url = new Url(this.ProjectMgr.BaseURI, path);
}
return url.AbsoluteUrl;
}
}
static FileNode()
{
// Build the dictionary with the mapping between some well known extensions
// and the index of the icons inside the standard image list.
extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm);
extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass);
extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService);
extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl);
extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage);
extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig);
extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile);
extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap);
extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon);
extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap);
extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB);
extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR);
extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile);
extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema);
extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile);
extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX);
extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK);
}
/// <summary>
/// Constructor for the FileNode
/// </summary>
/// <param name="root">Root of the hierarchy</param>
/// <param name="element">Associated project element</param>
internal FileNode(ProjectNode root, ProjectElement element, uint? hierarchyId = null)
: base(root, element, hierarchyId)
{
if (this.ProjectMgr.NodeHasDesigner(this.ItemNode.GetMetadata(ProjectFileConstants.Include)))
{
this.HasDesigner = true;
}
}
public virtual string RelativeFilePath
{
get
{
return PackageUtilities.MakeRelativeIfRooted(this.Url, this.ProjectMgr.BaseURI);
}
}
public override NodeProperties CreatePropertiesObject()
{
return new FileNodeProperties(this);
}
public override object GetIconHandle(bool open)
{
int index = this.ImageIndex;
if (NoImage == index)
{
// There is no image for this file; let the base class handle this case.
return base.GetIconHandle(open);
}
// Return the handle for the image.
return this.ProjectMgr.ImageHandler.GetIconHandle(index);
}
/// <summary>
/// Get an instance of the automation object for a FileNode
/// </summary>
/// <returns>An instance of the Automation.OAFileNode if succeeded</returns>
public override object GetAutomationObject()
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Renames a file node.
/// </summary>
/// <param name="label">The new name.</param>
/// <returns>An errorcode for failure or S_OK.</returns>
/// <exception cref="InvalidOperationException">if the file cannot be validated</exception>
/// <devremark>
/// We are going to throw instaed of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
/// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
/// Also the automation methods are also calling SetEditLabel
/// </devremark>
public override int SetEditLabel(string label)
{
// IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
// expected that we can be called with a label which is the same as the current
// label and this should not be considered a NO-OP.
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
// Validate the filename.
if (String.IsNullOrEmpty(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
else if (label.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
else if (Utilities.IsFileNameInvalid(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
for (HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling)
{
if (n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0)
{
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileOrFolderAlreadyExists, CultureInfo.CurrentUICulture), label));
}
}
string fileName = Path.GetFileNameWithoutExtension(label);
// If there is no filename or it starts with a leading dot issue an error message and quit.
if (String.IsNullOrEmpty(fileName) || fileName[0] == '.')
{
throw new InvalidOperationException(SR.GetString(SR.FileNameCannotContainALeadingPeriod, CultureInfo.CurrentUICulture));
}
// Verify that the file extension is unchanged
string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));
if (String.Compare(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase) != 0)
{
// Don't prompt if we are in automation function.
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
// Prompt to confirm that they really want to change the extension of the file
string message = SR.GetString(SR.ConfirmExtensionChange, CultureInfo.CurrentUICulture, new string[] { label });
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if (shell == null)
{
return VSConstants.E_FAIL;
}
if (!PromptYesNoWithYesSelected(message, null, OLEMSGICON.OLEMSGICON_INFO, shell))
{
// The user cancelled the confirmation for changing the extension.
// Return S_OK in order not to show any extra dialog box
return VSConstants.S_OK;
}
}
}
// Build the relative path by looking at folder names above us as one scenarios
// where we get called is when a folder above us gets renamed (in which case our path is invalid)
HierarchyNode parent = this.Parent;
while (parent != null && (parent is FolderNode))
{
strRelPath = Path.Combine(parent.Caption, strRelPath);
parent = parent.Parent;
}
var result = SetEditLabel(label, strRelPath);
return result;
}
// Implementation of functionality from Microsoft.VisualStudio.Shell.VsShellUtilities.PromptYesNo
// Difference: Yes button is default
private static bool PromptYesNoWithYesSelected(string message, string title, OLEMSGICON icon, IVsUIShell uiShell)
{
Guid emptyGuid = Guid.Empty;
int result = 0;
ThreadHelper.Generic.Invoke(() =>
{
ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(0u, ref emptyGuid, title, message, null, 0u, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, icon, 0, out result));
});
return result == (int)NativeMethods.IDYES;
}
public override string GetMkDocument()
{
Debug.Assert(this.Url != null, "No url specified for this node");
return this.Url;
}
/// <summary>
/// Delete the item corresponding to the specified path from storage.
/// </summary>
/// <param name="path"></param>
public override void DeleteFromStorage(string path)
{
if (FSLib.Shim.FileSystem.SafeExists(path))
{
File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly.
File.Delete(path);
}
}
/// <summary>
/// Rename the underlying document based on the change the user just made to the edit label.
/// </summary>
public int SetEditLabel(string label, string relativePath)
{
int returnValue = VSConstants.S_OK;
uint oldId = this.ID;
string strSavePath = Path.GetDirectoryName(relativePath);
string newRelPath = Path.Combine(strSavePath, label);
if (!Path.IsPathRooted(relativePath))
{
strSavePath = Path.Combine(Path.GetDirectoryName(this.ProjectMgr.BaseURI.Uri.LocalPath), strSavePath);
}
string newName = Path.Combine(strSavePath, label);
if (NativeMethods.IsSamePath(newName, this.Url))
{
// If this is really a no-op, then nothing to do
if (String.Compare(newName, this.Url, StringComparison.Ordinal) == 0)
return VSConstants.S_FALSE;
}
else
{
// If the renamed file already exists then quit (unless it is the result of the parent having done the move).
if (IsFileOnDisk(newName)
&& (IsFileOnDisk(this.Url)
|| String.Compare(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.Ordinal) != 0))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, CultureInfo.CurrentUICulture), label));
}
else if (newName.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
}
string oldName = this.Url;
// must update the caption prior to calling RenameDocument, since it may
// cause queries of that property (such as from open editors).
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
RenameDocument(oldName, newName);
// Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale
// hierarchy item id.
if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED)
{
return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE;
}
return returnValue;
}
/// <summary>
/// Returns a specific Document manager to handle files
/// </summary>
/// <returns>Document manager object</returns>
internal override DocumentManager GetDocumentManager()
{
return new FileDocumentManager(this);
}
/// <summary>
/// Called by the drag&drop implementation to ask the node
/// which is being dragged/droped over which nodes should
/// process the operation.
/// This allows for dragging to a node that cannot contain
/// items to let its parent accept the drop, while a reference
/// node delegate to the project and a folder/project node to itself.
/// </summary>
/// <returns></returns>
public override HierarchyNode GetDragTargetHandlerNode()
{
Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode");
HierarchyNode handlerNode = this;
while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode))
handlerNode = handlerNode.Parent;
if (handlerNode == null)
handlerNode = this.ProjectMgr;
return handlerNode;
}
public override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Exec on special filenode commands
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
IVsWindowFrame windowFrame = null;
switch ((VsCommands)cmd)
{
case VsCommands.ViewCode:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.ViewForm:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.Open:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show);
case VsCommands.OpenWith:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show);
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch ((VsCommands)cmd)
{
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.ViewCode:
case VsCommands.Open:
case VsCommands.OpenWith:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if (cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else
{
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
public override void DoDefaultAction()
{
CCITracing.TraceCall();
FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager;
Debug.Assert(manager != null, "Could not get the FileDocumentManager");
manager.Open(false, false, WindowFrameShowAction.Show);
}
/// <summary>
/// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
/// </summary>
/// <param name="docData">A pointer to the document in the rdt</param>
/// <param name="newFilePath">The new file path to the document</param>
/// <returns></returns>
public override int AfterSaveItemAs(IntPtr docData, string newFilePath)
{
if (String.IsNullOrEmpty(newFilePath))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newFilePath");
}
int returnCode = VSConstants.S_OK;
newFilePath = newFilePath.Trim();
//Identify if Path or FileName are the same for old and new file
string newDirectoryName = Path.GetDirectoryName(newFilePath);
Uri newDirectoryUri = new Uri(newDirectoryName);
string newCanonicalDirectoryName = newDirectoryUri.LocalPath;
newCanonicalDirectoryName = newCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string oldCanonicalDirectoryName = new Uri(Path.GetDirectoryName(this.GetMkDocument())).LocalPath;
oldCanonicalDirectoryName = oldCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string errorMessage = String.Empty;
bool isSamePath = NativeMethods.IsSamePath(newCanonicalDirectoryName, oldCanonicalDirectoryName);
bool isSameFile = NativeMethods.IsSamePath(newFilePath, this.Url);
// Currently we do not support if the new directory is located outside the project cone
string projectCannonicalDirecoryName = new Uri(this.ProjectMgr.ProjectFolder).LocalPath;
projectCannonicalDirecoryName = projectCannonicalDirecoryName.TrimEnd(Path.DirectorySeparatorChar);
if (!isSamePath && newCanonicalDirectoryName.IndexOf(projectCannonicalDirecoryName, StringComparison.OrdinalIgnoreCase) == -1)
{
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LinkedItemsAreNotSupported, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
//Get target container
HierarchyNode targetContainer = null;
if (isSamePath)
{
targetContainer = this.Parent;
}
else if (NativeMethods.IsSamePath(newCanonicalDirectoryName, projectCannonicalDirecoryName))
{
//the projectnode is the target container
targetContainer = this.ProjectMgr;
}
else
{
//search for the target container among existing child nodes
targetContainer = this.ProjectMgr.FindChild(newDirectoryName);
if (targetContainer != null && (targetContainer is FileNode))
{
// We already have a file node with this name in the hierarchy.
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
}
if (targetContainer == null)
{
// Add a chain of subdirectories to the project.
string relativeUri = PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, newDirectoryUri);
Debug.Assert(!String.IsNullOrEmpty(relativeUri) && relativeUri != newDirectoryUri.LocalPath, "Could not make pat distance of " + this.ProjectMgr.BaseURI.Uri.LocalPath + " and " + newDirectoryUri);
targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
}
Debug.Assert(targetContainer != null, "We should have found a target node by now");
//Suspend file changes while we rename the document
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
string oldName = Path.Combine(this.ProjectMgr.ProjectFolder, oldrelPath);
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
// Rename the node.
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
// Check if the file name was actually changed.
// In same cases (e.g. if the item is a file and the user has changed its encoding) this function
// is called even if there is no real rename.
var oldParent = this.Parent;
if (!isSameFile || (oldParent.ID != targetContainer.ID))
{
// The path of the file is changed or its parent is changed; in both cases we have
// to rename the item.
this.RenameFileNode(oldName, newFilePath, targetContainer.ID);
OnInvalidateItems(oldParent);
// This is what othe project systems do; for the purposes of source control, the old file is removed, and a new file is added
// (althought the old file stays on disk!)
this.ProjectMgr.Tracker.OnItemRemoved(oldName, VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_NoFlags);
this.ProjectMgr.Tracker.OnItemAdded(newFilePath, VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags);
}
}
catch (Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newFilePath, oldrelPath);
throw;
}
finally
{
sfc.Resume();
}
return returnCode;
}
/// <summary>
/// Determines if this is node a valid node for painting the default file icon.
/// </summary>
/// <returns></returns>
public override bool CanShowDefaultIcon()
{
string moniker = this.GetMkDocument();
if (String.IsNullOrEmpty(moniker) || !FSLib.Shim.FileSystem.SafeExists(moniker))
{
return false;
}
return true;
}
public virtual string FileName
{
get
{
return this.Caption;
}
set
{
this.SetEditLabel(value);
}
}
/// <summary>
/// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented.
/// </summary>
/// <param name="showMessage">true if user should be presented for UI in case the file is not present</param>
/// <returns>true if file is on disk</returns>
public virtual bool IsFileOnDisk(bool showMessage)
{
bool fileExist = IsFileOnDisk(this.Url);
if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ItemDoesNotExistInProjectDirectory, CultureInfo.CurrentUICulture), this.Caption);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
return fileExist;
}
/// <summary>
/// Determine if the file represented by "path" exist in storage.
/// Override this method if your files are not persisted on disk.
/// </summary>
/// <param name="path">Url representing the file</param>
/// <returns>True if the file exist</returns>
public virtual bool IsFileOnDisk(string path)
{
return FSLib.Shim.FileSystem.SafeExists(path);
}
/// <summary>
/// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
/// </summary>
/// <param name="oldFileName">The old file name.</param>
/// <param name="newFileName">The new file name</param>
/// <param name="newParentId">The new parent id of the item.</param>
/// <returns>The newly added FileNode.</returns>
/// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
public virtual FileNode RenameFileNode(string oldFileName, string newFileName, uint newParentId)
{
if (string.Compare(oldFileName, newFileName, StringComparison.Ordinal) == 0)
{
// We do not want to rename the same file
return null;
}
string[] file = new string[1];
file[0] = newFileName;
VSADDRESULT[] result = new VSADDRESULT[1];
Guid emptyGuid = Guid.Empty;
FileNode childAdded = null;
string originalInclude = this.ItemNode.Item.UnevaluatedInclude;
return Transactional.Try(
// Action
() =>
{
// It's unfortunate that MPF implements rename in terms of AddItemWithSpecific. Since this
// is the case, we have to pass false to prevent AddITemWithSpecific to fire Add events on
// the IVsTrackProjectDocuments2 tracker. Otherwise, clients listening to this event
// (SCCI, for example) will be really confused.
using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
{
var currentId = this.ID;
// actual deletion is delayed until all checks are passed
Func<uint> getIdOfExistingItem =
() =>
{
this.OnItemDeleted();
this.Parent.RemoveChild(this);
return currentId;
};
// raises OnItemAdded inside
ErrorHandler.ThrowOnFailure(this.ProjectMgr.AddItemWithSpecific(newParentId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 0, file, IntPtr.Zero, 0, ref emptyGuid, null, ref emptyGuid, result, false, getIdOfExistingItem));
childAdded = this.ProjectMgr.FindChild(newFileName) as FileNode;
Debug.Assert(childAdded != null, "Could not find the renamed item in the hierarchy");
}
},
// Compensation
() =>
{
// it failed, but 'this' is dead and 'childAdded' is here to stay, so fix the latter back
using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
{
childAdded.ItemNode.Rename(originalInclude);
childAdded.ItemNode.RefreshProperties();
}
},
// Continuation
() =>
{
// Since this node has been removed all of its state is zombied at this point
// Do not call virtual methods after this point since the object is in a deleted state.
// Remove the item created by the add item. We need to do this otherwise we will have two items.
// Please be aware that we have not removed the ItemNode associated to the removed file node from the hierrachy.
// What we want to achieve here is to reuse the existing build item.
// We want to link to the newly created node to the existing item node and addd the new include.
//temporarily keep properties from new itemnode since we are going to overwrite it
string newInclude = childAdded.ItemNode.Item.UnevaluatedInclude;
string dependentOf = childAdded.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
childAdded.ItemNode.RemoveFromProjectFile();
// Assign existing msbuild item to the new childnode
childAdded.ItemNode = this.ItemNode;
childAdded.ItemNode.Item.ItemType = this.ItemNode.ItemName;
childAdded.ItemNode.Item.Xml.Include = newInclude;
if (!string.IsNullOrEmpty(dependentOf))
childAdded.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, dependentOf);
childAdded.ItemNode.RefreshProperties();
// Extensibilty events has rename
this.ProjectMgr.ExtensibilityEventsHelper.FireItemRenamed(childAdded, Path.GetFileName(originalInclude));
//Update the new document in the RDT.
try
{
DocumentManager.RenameDocument(this.ProjectMgr.Site, oldFileName, newFileName, childAdded.ID);
// The current automation node is renamed, but the hierarchy ID is now pointing to the old item, which
// is invalid. Update it.
this.ID = childAdded.ID;
//Update FirstChild
childAdded.FirstChild = this.FirstChild;
//Update ChildNodes
SetNewParentOnChildNodes(childAdded);
RenameChildNodes(childAdded);
return childAdded;
}
finally
{
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, childAdded.ID, EXPANDFLAGS.EXPF_SelectItem);
}
});
}
/// <summary>
/// Rename all childnodes
/// </summary>
/// <param name="parentNode">The newly added Parent node.</param>
public virtual void RenameChildNodes(FileNode parentNode)
{
foreach (HierarchyNode child in GetChildNodes())
{
FileNode childNode = child as FileNode;
if (null == childNode)
{
continue;
}
string newfilename;
if (childNode.HasParentNodeNameRelation)
{
string relationalName = childNode.Parent.GetRelationalName();
string extension = childNode.GetRelationNameExtension();
newfilename = relationalName + extension;
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename);
}
else
{
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.Caption);
}
childNode.RenameDocument(childNode.GetMkDocument(), newfilename);
//We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed
//which happens if the is no name relation between the parent and the child
string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
if (!string.IsNullOrEmpty(dependentOf))
{
childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include));
}
}
}
/// <summary>
/// Tries recovering from a rename failure.
/// </summary>
/// <param name="fileThatFailed"> The file that failed to be renamed.</param>
/// <param name="originalFileName">The original filenamee</param>
public virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName)
{
// TODO does this do anything useful? did it ever change in the first place?
if (this.ItemNode != null && !String.IsNullOrEmpty(originalFileName))
{
this.ItemNode.Rename(originalFileName);
this.ItemNode.RefreshProperties();
}
}
public override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage)
{
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
/// <summary>
/// This should be overriden for node that are not saved on disk
/// </summary>
/// <param name="oldName">Previous name in storage</param>
/// <param name="newName">New name in storage</param>
public virtual void RenameInStorage(string oldName, string newName)
{
File.Move(oldName, newName);
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")]
public override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags)
{
if (this.ExcludeNodeFromScc)
{
return;
}
if (files == null)
{
throw new ArgumentNullException("files");
}
if (flags == null)
{
throw new ArgumentNullException("flags");
}
foreach (HierarchyNode node in this.GetChildNodes())
{
files.Add(node.GetMkDocument());
}
}
/// <summary>
/// Get's called to rename the eventually running document this hierarchyitem points to
/// </summary>
/// returns FALSE if the doc can not be renamed
public bool RenameDocument(string oldName, string newName)
{
IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null) return false;
IntPtr docData = IntPtr.Zero;
IVsHierarchy pIVsHierarchy;
uint itemId;
uint uiVsDocCookie;
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr))
{
// Don't rename it if it wasn't opened by us.
return false;
}
// ask other potentially running packages
if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag))
{
return false;
}
// Allow the user to "fix" the project by renaming the item in the hierarchy
// to the real name of the file on disk.
bool shouldRenameInStorage = IsFileOnDisk(oldName) || !IsFileOnDisk(newName);
Transactional.Try(
// Action
() => { if (shouldRenameInStorage) RenameInStorage(oldName, newName); },
// Compensation
() => { if (shouldRenameInStorage) RenameInStorage(newName, oldName); },
// Continuation
() =>
{
string newFileName = Path.GetFileName(newName);
string oldCaption = this.Caption;
Transactional.Try(
// Action
() => DocumentManager.UpdateCaption(this.ProjectMgr.Site, newFileName, docData),
// Compensation
() => DocumentManager.UpdateCaption(this.ProjectMgr.Site, oldCaption, docData),
// Continuation
() =>
{
bool caseOnlyChange = NativeMethods.IsSamePath(oldName, newName);
if (!caseOnlyChange)
{
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
this.RenameFileNode(oldName, newName);
}
else
{
this.RenameCaseOnlyChange(newFileName);
}
bool extensionWasChanged = (0 != String.Compare(Path.GetExtension(oldName), Path.GetExtension(newName), StringComparison.OrdinalIgnoreCase));
if (extensionWasChanged)
{
// Update the BuildAction
this.ItemNode.ItemName = this.ProjectMgr.DefaultBuildAction(newName);
}
this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
});
});
}
finally
{
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
sfc.Resume(); // can throw, e.g. when RenameFileNode failed, but file was renamed on disk and now editor cannot find file
}
return true;
}
private FileNode RenameFileNode(string oldFileName, string newFileName)
{
return this.RenameFileNode(oldFileName, newFileName, this.Parent.ID);
}
/// <summary>
/// Renames the file node for a case only change.
/// </summary>
/// <param name="newFileName">The new file name.</param>
private void RenameCaseOnlyChange(string newFileName)
{
//Update the include for this item.
string include = this.ItemNode.Item.UnevaluatedInclude;
if (String.Compare(include, newFileName, StringComparison.OrdinalIgnoreCase) == 0)
{
this.ItemNode.Item.Xml.Include = newFileName;
}
else
{
string includeDir = Path.GetDirectoryName(include);
this.ItemNode.Item.Xml.Include = Path.Combine(includeDir, newFileName);
}
this.ItemNode.RefreshProperties();
this.ReDraw(UIHierarchyElement.Caption);
this.RenameChildNodes(this);
// Refresh the property browser.
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if (shell == null)
{
throw new InvalidOperationException();
}
shell.RefreshPropertyBrowser(0);
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem);
}
/// <summary>
/// Update the ChildNodes after the parent node has been renamed
/// </summary>
/// <param name="newFileNode">The new FileNode created as part of the rename of this node</param>
private void SetNewParentOnChildNodes(FileNode newFileNode)
{
foreach (HierarchyNode childNode in GetChildNodes())
{
childNode.Parent = newFileNode;
}
}
private List<HierarchyNode> GetChildNodes()
{
List<HierarchyNode> childNodes = new List<HierarchyNode>();
HierarchyNode childNode = this.FirstChild;
while (childNode != null)
{
childNodes.Add(childNode);
childNode = childNode.NextSibling;
}
return childNodes;
}
public override __VSPROVISIONALVIEWINGSTATUS ProvisionalViewingStatus =>
IsFileOnDisk(false)
? __VSPROVISIONALVIEWINGSTATUS.PVS_Enabled
: __VSPROVISIONALVIEWINGSTATUS.PVS_Disabled;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.